agentix-cli 0.100.0 → 0.101.1

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 (111) hide show
  1. package/apps/mac-voice/Sources/AgentXVoice/BubbleMotion.swift +36 -0
  2. package/apps/mac-voice/Sources/AgentXVoice/Character.swift +21 -7
  3. package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +30 -9
  4. package/apps/mac-voice/Sources/AgentXVoice/PanelAnswer.swift +13 -5
  5. package/apps/mac-voice/Sources/AgentXVoice/PanelBubble.swift +37 -0
  6. package/apps/mac-voice/Sources/AgentXVoice/PillPlacement.swift +23 -3
  7. package/apps/mac-voice/Sources/AgentXVoice/SettingsWindow.swift +1 -1
  8. package/apps/mac-voice/Sources/AgentXVoice/Surface.swift +13 -0
  9. package/apps/mac-voice/Sources/AgentXVoice/main.swift +2 -2
  10. package/dist/{App-XLQDP26J.js → App-EYUDDF6K.js} +2 -2
  11. package/dist/{ChatApp-DRDUXZ66.js → ChatApp-F5LZLBI3.js} +2 -2
  12. package/dist/{agent-QHM3J2XS.js → agent-XF3BWMOB.js} +2 -2
  13. package/dist/{board-dashboard-R6ZTCTSI.js → board-dashboard-TVSOWW32.js} +4 -4
  14. package/dist/{chunk-DRUEPGLP.js → chunk-5UO6BBDG.js} +2 -2
  15. package/dist/{chunk-S2GPUSBU.js → chunk-AYNZAOJN.js} +2 -2
  16. package/dist/chunk-ECM2QEXF.js +54 -0
  17. package/dist/chunk-ECM2QEXF.js.map +1 -0
  18. package/dist/{chunk-J64VIHL5.js → chunk-EEZI2K7S.js} +2 -2
  19. package/dist/{chunk-BERHVF3T.js → chunk-EXPIKLUN.js} +2 -2
  20. package/dist/{chunk-6BZMRVKJ.js → chunk-GOPJG2RG.js} +177 -177
  21. package/dist/chunk-GOPJG2RG.js.map +1 -0
  22. package/dist/{chunk-Z4FY64BS.js → chunk-GSFB46YC.js} +2 -2
  23. package/dist/{chunk-OFVMUBIP.js → chunk-HMDM5MCR.js} +2 -2
  24. package/dist/{chunk-SJMOZY7Y.js → chunk-HQJW3BC5.js} +2 -2
  25. package/dist/{chunk-B32A6OOY.js → chunk-MWLX3QCD.js} +47 -47
  26. package/dist/chunk-MWLX3QCD.js.map +1 -0
  27. package/dist/{chunk-VBFXUZTY.js → chunk-N57ES35J.js} +2 -2
  28. package/dist/{chunk-GJ5EJVMZ.js → chunk-PYCTWI2I.js} +2 -2
  29. package/dist/{chunk-IQJ7UZVV.js → chunk-QRD3ZG27.js} +2 -2
  30. package/dist/{chunk-DXJRMPGH.js → chunk-RWSCQMLD.js} +2 -2
  31. package/dist/{chunk-YYCFI4VP.js → chunk-S337S2M7.js} +2 -2
  32. package/dist/{chunk-BHKWXFJD.js → chunk-TXFIMVVF.js} +5 -5
  33. package/dist/{chunk-LXJGLNVG.js → chunk-V6W3FFW7.js} +2 -2
  34. package/dist/{chunk-4BCAH7XI.js → chunk-XO55WKCX.js} +2 -2
  35. package/dist/{chunk-J4JVKVEK.js → chunk-Y6POV2X5.js} +2 -2
  36. package/dist/{chunk-BTLW2RML.js → chunk-YOCQ2MWL.js} +2 -2
  37. package/dist/{chunk-JZJ7AZJD.js → chunk-ZJXDBVBT.js} +2 -2
  38. package/dist/cli.js +1 -1
  39. package/dist/{client-BLUCLNIS.js → client-526OCGWD.js} +2 -2
  40. package/dist/config-HCJ5NZW5.js +2 -0
  41. package/dist/config-mutator-PGR2OGWC.js +2 -0
  42. package/dist/{doctor-XGQW5SMD.js → doctor-AC5ONEO2.js} +2 -2
  43. package/dist/index.d.ts +9 -9
  44. package/dist/index.js +1 -1
  45. package/dist/{program-CH5QSA7K.js → program-2G53UFIU.js} +16 -16
  46. package/dist/program-2G53UFIU.js.map +1 -0
  47. package/dist/{promote-K5LP5Q6Z.js → promote-CNKIINYK.js} +2 -2
  48. package/dist/{query-LHXSINM2.js → query-A2N2LIR7.js} +2 -2
  49. package/dist/{registry-OQUO6NCW.js → registry-REKWHOHS.js} +2 -2
  50. package/dist/{request-planner-TW5OCKTF.js → request-planner-MS5BS6HY.js} +2 -2
  51. package/dist/{review-candidates-EFELFOSY.js → review-candidates-2F4QK6QQ.js} +2 -2
  52. package/dist/{routing-TSRZLD7B.js → routing-SU5Q4IPM.js} +2 -2
  53. package/dist/schedule-tool-24KHZY2Z.js +2 -0
  54. package/dist/scheduler-ALDZOUKJ.js +2 -0
  55. package/dist/{seat-NIPWHLKC.js → seat-PZBFMYQL.js} +2 -2
  56. package/dist/{select-UAKDLN76.js → select-D3XOFXA5.js} +2 -2
  57. package/dist/{set-enabled-74DLXMSM.js → set-enabled-DNDRQ3CZ.js} +2 -2
  58. package/dist/{tool-TEGHFORD.js → tool-FB6SPVIS.js} +2 -2
  59. package/dist/{tool-CEBL57UW.js → tool-RRGOHJW6.js} +2 -2
  60. package/dist/wiki-3DH2QYTX.js +2 -0
  61. package/package.json +1 -1
  62. package/dist/chunk-6BZMRVKJ.js.map +0 -1
  63. package/dist/chunk-B32A6OOY.js.map +0 -1
  64. package/dist/chunk-JREA25GJ.js +0 -54
  65. package/dist/chunk-JREA25GJ.js.map +0 -1
  66. package/dist/config-ZUMI4IY4.js +0 -2
  67. package/dist/config-mutator-S3CD2IWQ.js +0 -2
  68. package/dist/program-CH5QSA7K.js.map +0 -1
  69. package/dist/schedule-tool-JUHRVU5D.js +0 -2
  70. package/dist/scheduler-EHJPTULN.js +0 -2
  71. package/dist/wiki-WOK4SCB7.js +0 -2
  72. /package/dist/{App-XLQDP26J.js.map → App-EYUDDF6K.js.map} +0 -0
  73. /package/dist/{ChatApp-DRDUXZ66.js.map → ChatApp-F5LZLBI3.js.map} +0 -0
  74. /package/dist/{agent-QHM3J2XS.js.map → agent-XF3BWMOB.js.map} +0 -0
  75. /package/dist/{board-dashboard-R6ZTCTSI.js.map → board-dashboard-TVSOWW32.js.map} +0 -0
  76. /package/dist/{chunk-DRUEPGLP.js.map → chunk-5UO6BBDG.js.map} +0 -0
  77. /package/dist/{chunk-S2GPUSBU.js.map → chunk-AYNZAOJN.js.map} +0 -0
  78. /package/dist/{chunk-J64VIHL5.js.map → chunk-EEZI2K7S.js.map} +0 -0
  79. /package/dist/{chunk-BERHVF3T.js.map → chunk-EXPIKLUN.js.map} +0 -0
  80. /package/dist/{chunk-Z4FY64BS.js.map → chunk-GSFB46YC.js.map} +0 -0
  81. /package/dist/{chunk-OFVMUBIP.js.map → chunk-HMDM5MCR.js.map} +0 -0
  82. /package/dist/{chunk-SJMOZY7Y.js.map → chunk-HQJW3BC5.js.map} +0 -0
  83. /package/dist/{chunk-VBFXUZTY.js.map → chunk-N57ES35J.js.map} +0 -0
  84. /package/dist/{chunk-GJ5EJVMZ.js.map → chunk-PYCTWI2I.js.map} +0 -0
  85. /package/dist/{chunk-IQJ7UZVV.js.map → chunk-QRD3ZG27.js.map} +0 -0
  86. /package/dist/{chunk-DXJRMPGH.js.map → chunk-RWSCQMLD.js.map} +0 -0
  87. /package/dist/{chunk-YYCFI4VP.js.map → chunk-S337S2M7.js.map} +0 -0
  88. /package/dist/{chunk-BHKWXFJD.js.map → chunk-TXFIMVVF.js.map} +0 -0
  89. /package/dist/{chunk-LXJGLNVG.js.map → chunk-V6W3FFW7.js.map} +0 -0
  90. /package/dist/{chunk-4BCAH7XI.js.map → chunk-XO55WKCX.js.map} +0 -0
  91. /package/dist/{chunk-J4JVKVEK.js.map → chunk-Y6POV2X5.js.map} +0 -0
  92. /package/dist/{chunk-BTLW2RML.js.map → chunk-YOCQ2MWL.js.map} +0 -0
  93. /package/dist/{chunk-JZJ7AZJD.js.map → chunk-ZJXDBVBT.js.map} +0 -0
  94. /package/dist/{client-BLUCLNIS.js.map → client-526OCGWD.js.map} +0 -0
  95. /package/dist/{config-ZUMI4IY4.js.map → config-HCJ5NZW5.js.map} +0 -0
  96. /package/dist/{config-mutator-S3CD2IWQ.js.map → config-mutator-PGR2OGWC.js.map} +0 -0
  97. /package/dist/{doctor-XGQW5SMD.js.map → doctor-AC5ONEO2.js.map} +0 -0
  98. /package/dist/{promote-K5LP5Q6Z.js.map → promote-CNKIINYK.js.map} +0 -0
  99. /package/dist/{query-LHXSINM2.js.map → query-A2N2LIR7.js.map} +0 -0
  100. /package/dist/{registry-OQUO6NCW.js.map → registry-REKWHOHS.js.map} +0 -0
  101. /package/dist/{request-planner-TW5OCKTF.js.map → request-planner-MS5BS6HY.js.map} +0 -0
  102. /package/dist/{review-candidates-EFELFOSY.js.map → review-candidates-2F4QK6QQ.js.map} +0 -0
  103. /package/dist/{routing-TSRZLD7B.js.map → routing-SU5Q4IPM.js.map} +0 -0
  104. /package/dist/{schedule-tool-JUHRVU5D.js.map → schedule-tool-24KHZY2Z.js.map} +0 -0
  105. /package/dist/{scheduler-EHJPTULN.js.map → scheduler-ALDZOUKJ.js.map} +0 -0
  106. /package/dist/{seat-NIPWHLKC.js.map → seat-PZBFMYQL.js.map} +0 -0
  107. /package/dist/{select-UAKDLN76.js.map → select-D3XOFXA5.js.map} +0 -0
  108. /package/dist/{set-enabled-74DLXMSM.js.map → set-enabled-DNDRQ3CZ.js.map} +0 -0
  109. /package/dist/{tool-TEGHFORD.js.map → tool-FB6SPVIS.js.map} +0 -0
  110. /package/dist/{tool-CEBL57UW.js.map → tool-RRGOHJW6.js.map} +0 -0
  111. /package/dist/{wiki-WOK4SCB7.js.map → wiki-3DH2QYTX.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{c as le,d as K,e as E,f as Y,g as D}from"./chunk-N7HKIMMR.js";import{a as se,b as de}from"./chunk-DG5I6PPM.js";import{e as j,g as oe,n as ie,p as J}from"./chunk-E5OV6RTG.js";import{a as ae,b as re}from"./chunk-DRUEPGLP.js";import{a as ne}from"./chunk-J64VIHL5.js";import{M as ee,T as _e,ba as q,da as te,ea as U,ha as F,t as L,u as Z,x as Pe}from"./chunk-JREA25GJ.js";import{existsSync as M,readFileSync as he,writeFileSync as ve,appendFileSync as Ue,mkdirSync as We}from"fs";import{dirname as Oe,resolve as P}from"path";import{fileURLToPath as Be}from"url";import{hostname as He}from"os";import{spawn as Le}from"child_process";F();import{existsSync as pe,readFileSync as ce,writeFileSync as G,copyFileSync as ze}from"fs";import{resolve as ge}from"path";function W(e,t={}){let n=t.configPath||ge(process.cwd(),"agentx.json");if(!pe(n))throw new Error(`agentx.json not found at ${n}`);let a=JSON.parse(ce(n,"utf-8")),r=e(a),o=typeof r=="string"?{summary:r}:r,s=JSON.stringify(a,null,2)+`
1
+ import{c as le,d as K,e as E,f as Y,g as D}from"./chunk-N7HKIMMR.js";import{a as se,b as de}from"./chunk-DG5I6PPM.js";import{e as j,g as oe,n as ie,p as J}from"./chunk-E5OV6RTG.js";import{a as ae,b as re}from"./chunk-5UO6BBDG.js";import{a as ne}from"./chunk-EEZI2K7S.js";import{L as ee,S as _e,aa as q,ca as te,da as U,ga as F,s as L,t as Z,w as Pe}from"./chunk-ECM2QEXF.js";import{existsSync as M,readFileSync as he,writeFileSync as ve,appendFileSync as Ue,mkdirSync as We}from"fs";import{dirname as Oe,resolve as P}from"path";import{fileURLToPath as Be}from"url";import{hostname as He}from"os";import{spawn as Le}from"child_process";F();import{existsSync as pe,readFileSync as ce,writeFileSync as G,copyFileSync as ze}from"fs";import{resolve as ge}from"path";function W(e,t={}){let n=t.configPath||ge(process.cwd(),"agentx.json");if(!pe(n))throw new Error(`agentx.json not found at ${n}`);let a=JSON.parse(ce(n,"utf-8")),r=e(a),o=typeof r=="string"?{summary:r}:r,s=JSON.stringify(a,null,2)+`
2
2
  `,l=n+".tmp";G(l,s,"utf-8");try{JSON.parse(ce(l,"utf-8"))}catch(p){throw new Error(`config did not round-trip cleanly: ${p.message}`)}let i;return t.skipBackup||(i=`${n}.bak.${Date.now()}`,ze(n,i)),G(n,s,"utf-8"),t.skipReload||De().catch(()=>{}),{summary:o.summary,payload:o.payload,backupPath:i}}function me(e,t={}){let n=t.configPath||ge(process.cwd(),"agentx.json");if(pe(n)&&!t.overwrite)throw new Error(`agentx.json already exists at ${n}. Pass overwrite=true to replace it.`);return G(n,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:n}}async function De(){try{let t=U().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${t}/reload`,{method:"POST"}).catch(()=>null)}catch{}}function ue(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",a=`<header class="ax-topbar">
4
4
  <div class="ax-topbar__left">
@@ -741,4 +741,4 @@ tr:hover td { background: var(--bg-hover); }
741
741
  ORDER BY started_at DESC, rowid DESC LIMIT ?`).all(t,Math.max(1,Math.min(n,500))).map(r=>({taskId:r.task_id,agentId:r.agent_id,channel:r.channel,chatId:r.chat_id,status:r.status,startedAt:r.started_at,finishedAt:r.finished_at??null,messagePreview:r.message_preview}))}function lt(e){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'requests'").get()?e.prepare("PRAGMA table_info(requests)").all().some(a=>a.name==="person"):!1}function $e(e,t,n,a,...r){return lt(e)?e.prepare(`SELECT id, state, channel, agent_id, text, created_at FROM requests
742
742
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
743
743
  ${a}`).all(t,...n,...r).map(s=>({id:s.id,state:s.state,channel:s.channel,agentId:s.agent_id,text:s.text,createdAt:s.created_at})):[]}function sn(e,t){return $e(e,t,L,"ORDER BY created_at")}function dn(e,t,n=50){return $e(e,t,[...L,...Z],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}_e();var Q="member:",ct=90,pt="members",gt="tailscale-user-login",mt=400,ut=60*60*1e3;function ft(e){let t=e.scopes.find(n=>n.startsWith(Q));return t?t.slice(Q.length):null}function Ae(e,t){if(!e)return null;let n=t.verify(e),a=n?ft(n):null;return n&&a?{rec:n,personId:a}:null}function un(e,t){let n=e.people().find(l=>l.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:a,record:r}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${Q}${n.id}`],expiresInDays:ct}),{code:o,expiresAt:s}=e.codes.create({token:a,tokenId:r.id,name:n.id});return e.members.log({person:n.id,device:r.id,event:"invited"}),{ok:!0,code:o,expiresAt:s,tokenId:r.id,person:n}}var ht="The private network says someone else is connecting from this machine. Ask the owner for a new code.",vt="Too many machines are waiting for the owner's answer. Try again later.",Se=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function Ie(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function bt(e){if(!Ie(e))return null;let t=Se(e,gt).toLowerCase();return t?t.slice(0,80):null}function xt(e){let t=e.socket?.remoteAddress||"unknown";if(!Ie(e))return t;let n=Se(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function yt(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function kt(e){return e.identities.map(ee).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function fn(e,t){let n=Date.now(),a=t.now??Date.now,r=t.log??(m=>console.log(m)),o=xt(e),s=t.limiter.retryAfter(o);if(s>0)return r(`[member] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let l=null,i="";try{let m=await ie(e,2048);l=m.code,i=yt(m.machine)}catch{}let p=t.codes.redeem(l),g=p?Ae(p.token,t.tokens):null;if(await $t(n,t.minMs??mt),!p||!g)return t.limiter.fail(o),r(`[member] pair-code failed from ${o}`),{status:401,body:{error:J}};t.limiter.succeed(o);let{rec:f,personId:d}=g,h=t.people().find(m=>m.id===d);if(!h)return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:"person no longer listed"}),r(`[member] pair-code for ${d} refused from ${o}: person no longer listed`),{status:403,body:{error:J}};let u=bt(e),A=kt(h);if(A.length&&(!u||!A.includes(u)))return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:`network login ${u??"missing"}; expected ${A.join(" or ")}`}),r(`[member] ${d}: pairing from ${o} refused: the network says "${u??"nobody"}", expected ${A.join(" or ")}`),{status:403,body:{error:ht}};let x=i||"Unnamed machine",y=h.name.slice(0,40),v=oe(t.root,{title:`New machine for ${y}`,ask:`From ${o}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${x}". Let it see ${y}'s own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:pt},{now:a()});return v.ok?(t.members.add({tokenId:f.id,personId:d,name:x,state:"pending",cardId:v.card.id,address:o,...u?{network:u}:{},createdAt:new Date(a()).toISOString()}),t.members.log({person:d,device:f.id,event:"paired",address:o,detail:x}),r(`[member] ${d} paired "${x}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:d,name:x,state:"pending"},token:p.token}):(t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:v.error}),r(`[member] ${d}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:vt}})}var H="this machine is not paired",wt="waiting for the owner to approve this machine";function Ee(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function hn(e,t){return t.state==="pending"&&t.cardId?Ee(j(e,t.cardId)):null}function vn(e,t,n){let a=t.now??Date.now,r=t.log??(g=>console.log(g)),o=Ae(e,t.tokens);if(!o)return{ok:!1,status:401,error:H};let{rec:s,personId:l}=o,i=t.members.byToken(s.id);if(!i||i.state==="removed"||i.personId!==l)return{ok:!1,status:401,error:H};if(t.people&&!t.people().some(g=>g.id===l))return Ce(t,s.id,"person no longer listed"),r(`[member] ${l}: "${i.name}" ended: person no longer listed`),{ok:!1,status:401,error:H};if(i.state==="pending"){let g=i.cardId?j(t.root,i.cardId):null,f=Ee(g);if(f==="yes")i=t.members.update(s.id,{state:"active",approvedAt:new Date(a()).toISOString()})??i,t.members.log({person:l,device:s.id,event:"approved",detail:g?.decided_by}),r(`[member] ${l}: "${i.name}" approved`);else if(f==="no"){let d=g?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(s.id),t.members.update(s.id,{state:"removed",removedAt:new Date(a()).toISOString(),removedReason:d}),t.members.log({person:l,device:s.id,event:"refused",detail:d}),r(`[member] ${l}: "${i.name}" refused: ${d}`),{ok:!1,status:401,error:H}}else return{ok:!1,status:403,error:wt,waiting:!0}}let p=i.lastSeenAt?Date.parse(i.lastSeenAt):0;return n&&(a()-p>=ut||i.lastAddress!==n)&&(i=t.members.update(s.id,{lastSeenAt:new Date(a()).toISOString(),lastAddress:n})??i,t.members.log({person:l,device:s.id,event:"signed-in",address:n})),{ok:!0,device:i,personId:l,rec:s}}function Ce(e,t,n="removed by the owner"){let a=e.members.byToken(t);if(!a)return null;e.tokens.revoke(t);let r=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:a.personId,device:t,event:"removed",detail:n}),r}function bn(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Ce(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function $t(e,t){let n=e+t-Date.now();n>0&&await new Promise(a=>setTimeout(a,n))}var Te=["gitlab","github"];function At(e,t,n){let a=String(t||"").trim().toLowerCase();if(!Te.includes(a))throw new Error(`Request status works on ${Te.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let r=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...r,a])]:r.filter(o=>o!==a),`request status on ${a} is ${n?"on":"off"}`}function kn(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function wn(e){let{summary:t}=W(n=>At(n,e?.channel,!!e?.enabled));return{summary:t}}var St="https://ntfy.sh";function An(e){return{enabled:!!e?.enabled,server:e?.server||St,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Sn(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let a=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(a))throw new Error("ntfy server must be an http(s) URL");n.server=a}if("topic"in t){let a=String(t.topic).trim();if(!a)throw new Error("ntfy topic cannot be empty");n.topic=a}if("token"in t){let a=String(t.token??"").trim();a?n.token=a:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{W as a,be as b,Bt as c,Ht as d,Lt as e,Kt as f,Yt as g,Gt as h,on as i,sn as j,dn as k,ct as l,un as m,xt as n,fn as o,hn as p,vn as q,Ce as r,bn as s,Te as t,At as u,kn as v,wn as w,An as x,Sn as y,st as z,nn as A};
744
- //# sourceMappingURL=chunk-VBFXUZTY.js.map
744
+ //# sourceMappingURL=chunk-N57ES35J.js.map
@@ -1,5 +1,5 @@
1
- import{ea as m,ha as b}from"./chunk-JREA25GJ.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
1
+ import{da as m,ga as b}from"./chunk-ECM2QEXF.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
2
2
 
3
3
  `))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
4
4
  `))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
5
- //# sourceMappingURL=chunk-GJ5EJVMZ.js.map
5
+ //# sourceMappingURL=chunk-PYCTWI2I.js.map
@@ -1,8 +1,8 @@
1
- import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-LXJGLNVG.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-DRUEPGLP.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
1
+ import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-V6W3FFW7.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-5UO6BBDG.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
2
2
  `)}async function k(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(u){return`Could not notify the operator (${u?.message??u}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),u=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let p=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(p).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>Q(i,f,u)).join(`
3
3
  `):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!h.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||q;if(!B(g))return`Error: unknown timezone "${g}".`;let d=o||_(i.matched,f);if(!R(d))return`Error: invalid id "${d}" (letters, digits, "-" and "_" only).`;if(p[d])return`Error: a schedule "${d}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:u.toISOString()},L=b({parsed:i,agent:f,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),v=await m(U=>I(U,`crons.${d}`,L));if(!v.success)return`Error: ${v.error}`;let N=w(E(i.cron,g,u),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${d}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${f}`,$?`Notify: ${$.channel} ${$.chatId}`:"Notify: none",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${d}`,`Reject: agentx schedule reject ${d}`].join(`
4
4
  `),H=await k(h,t,G);return[`Requested schedule "${d}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
5
5
  `)}if(!o)return`Error: ${r} needs \`id\`.`;let c=p[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let d=await m($=>P($,`crons.${o}`));return d.success?`Withdrew the pending request "${o}".`:`Error: ${d.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:u.toISOString()},l=await m(d=>{if(!x(d,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(d,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${S(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,u),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
6
6
  `),g=await k(h,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
7
7
  `)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),u=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),p=s(n.accountId);return{agentId:t,channel:u,chatId:h,...p?{accountId:p}:{}}}export{re as a,oe as b};
8
- //# sourceMappingURL=chunk-IQJ7UZVV.js.map
8
+ //# sourceMappingURL=chunk-QRD3ZG27.js.map
@@ -1,4 +1,4 @@
1
- import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as gt}from"./chunk-FX3D7YON.js";import{a as ne,b as We}from"./chunk-FCPTN6NF.js";import{o as we,p as He}from"./chunk-5MUJZODV.js";import{ga as Ze,ha as et}from"./chunk-JREA25GJ.js";import{a as ot,b as st,c as it,d as at,e as ct,f as ut,g as lt,h as dt,i as pt,j as mt,k as bt,l as ft}from"./chunk-RGDKHYY2.js";import{a as E,b as Ke,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function yt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import ht from"better-sqlite3";import{createHash as wt}from"crypto";import{mkdirSync as Tt}from"fs";import{dirname as Et,resolve as kt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function xt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function St(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&_t(e),t<2&&Rt(e),t<3&&At(e)}function At(e){e.exec(`
1
+ import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as gt}from"./chunk-FX3D7YON.js";import{a as ne,b as We}from"./chunk-FCPTN6NF.js";import{o as we,p as He}from"./chunk-5MUJZODV.js";import{fa as Ze,ga as et}from"./chunk-ECM2QEXF.js";import{a as ot,b as st,c as it,d as at,e as ct,f as ut,g as lt,h as dt,i as pt,j as mt,k as bt,l as ft}from"./chunk-RGDKHYY2.js";import{a as E,b as Ke,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function yt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import ht from"better-sqlite3";import{createHash as wt}from"crypto";import{mkdirSync as Tt}from"fs";import{dirname as Et,resolve as kt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function xt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function St(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&_t(e),t<2&&Rt(e),t<3&&At(e)}function At(e){e.exec(`
2
2
  ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
3
3
  INSERT INTO schema_version (v) VALUES (3);
4
4
  `)}function Rt(e){e.exec(`
@@ -111,4 +111,4 @@ import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";im
111
111
  `)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${h}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let x=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=x.answer,x.repaired&&(L=!0)}return{model:a,answers:M,usage:y,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Vt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:U,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:U}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===U),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function zt(e,t,r,n,o){let s=[r,ae(t)].join(`
112
112
  `),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Jt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Gt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Bt,qt,Xt,Ue,$t,be=E(()=>{"use strict";He();Fe();gt();j();Y();v();z();Bt="claude-code",qt="claude-haiku-4-5-20251001",Xt=24e3,Ue=2e3,$t=3e4});import{readFileSync as Yt}from"fs";import{homedir as Kt}from"os";import{join as Ht}from"path";function N(e={}){let t=(e.baseUrl??Wt).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??en,s=e.maxChoiceOptions??tn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),sn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=an(a.abortSignal,a.timeoutMs??e.timeoutMs??Zt);try{let b={"Content-Type":"application/json"},y=on(e.apiKeyEnv,e.apiKeyFile);y&&(b.Authorization=`Bearer ${y}`);let w=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:rn(a.questions)}),signal:g}),g);if(!w.ok){let k=await w.text().catch(()=>"");throw new Error(`${n} ${w.status}: ${k.slice(0,300)}`)}let f=await qe(w.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
113
113
  ${F(m.error)}`);let h=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let x=_(q,h[k]);M[k]=x.answer,x.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function rn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:nn[n.type]};return t}function on(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Ht(Kt(),t.slice(2)):t;if(!Z.has(n))try{let o=Yt(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function sn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function an(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Wt,Zt,en,tn,nn,Z,fe=E(()=>{"use strict";j();v();z();Y();Wt="http://127.0.0.1:8000/v1",Zt=3e4,en=6e3,tn=50;nn={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};Ke(Xe,{DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>U,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>yt,agreement:()=>ot,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>dt,askSeat:()=>mn,band:()=>Ie,bootstrapInterval:()=>mt,brier:()=>ct,buildDesign:()=>ve,calibrationReport:()=>bt,choice:()=>nt,compareCalibrators:()=>Dt,confidenceFor:()=>re,configureDecisions:()=>un,coverageCurve:()=>lt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>dn,describeIssues:()=>F,ece:()=>it,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>pt,getDecisionBackend:()=>D,getSeatMode:()=>ze,labelsOf:()=>S,listDecisionBackends:()=>Ee,logLoss:()=>ut,logit:()=>le,mce:()=>at,measureConsistency:()=>jt,normalizeDistribution:()=>xe,normalizedNegEntropy:()=>oe,noul:()=>tt,pMax:()=>Se,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>pn,registerBuiltinDecisionBackends:()=>cn,registerDecisionBackend:()=>R,reliabilityBins:()=>st,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>ln,score:()=>rt,seatEnvVar:()=>Ve,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function cn(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();ft();Me();je();Je();pe();be();fe();C();pe();be();fe()});function un(e){T={...ye,...T,...e},ee=!0}function ln(){T={...ye,seats:{}},ee=!1}function bn(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(et(),he(Ze)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}T={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function dn(){return T}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return fn.includes(t)?t:null}function Ve(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function ze(e,t=process.env){bn();let r=ge(t[Ve(e)]);return r||(T.enabled?ge(T.seats[e]?.mode)??"off":"off")}function pn(e,t,r=!1){if(!(!e||!T.store))try{T.store.recordOutcome(e,t,r)}catch{}}async function mn(e,t,r,n={}){let o=ze(e);if(o==="off")return null;let s=T.seats[e]??{mode:o},i=n.backend??s.backend??T.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs}),l=gn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return yn(e,o,t,r,i,n,s,a,u),hn(e,i,u),null}}function gn(e,t,r,n,o,s,i){if(!T.store)return null;try{return T.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:Ye(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function yn(e,t,r,n,o,s,i,a,u){if(T.store)try{T.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:Ye(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function Ye(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function hn(e,t,r){let n=Date.now();n-Ge<6e4||(Ge=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var ye,T,ee,fn,Ge,Je=E(()=>{C();V();ye={enabled:!1,defaultBackend:"local",seats:{},store:null},T={...ye},ee=!1;fn=["off","shadow","active"];Ge=0});export{D as a,Ee as b,C as c,I as d,V as e,Dt as f,Me as g,jt as h,je as i,me as j,Un as k,Fe as l,cn as m,$e as n,un as o,ln as p,dn as q,ge as r,Ve as s,ze as t,pn as u,mn as v,Je as w};
114
- //# sourceMappingURL=chunk-DXJRMPGH.js.map
114
+ //# sourceMappingURL=chunk-RWSCQMLD.js.map
@@ -1,4 +1,4 @@
1
- import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-DP7RTNDM.js";import{a as E}from"./chunk-S2GPUSBU.js";import{b as L}from"./chunk-CECHWYJ2.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c=""){return Z(r,s,t,o,i,c)}function Z(n,r,s,t,o,i=""){let c=r?`
1
+ import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-DP7RTNDM.js";import{a as E}from"./chunk-AYNZAOJN.js";import{b as L}from"./chunk-CECHWYJ2.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c=""){return Z(r,s,t,o,i,c)}function Z(n,r,s,t,o,i=""){let c=r?`
2
2
  ## Worldview
3
3
 
4
4
  ${r}
@@ -240,4 +240,4 @@ ${g}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
240
240
  Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let u=[{role:"user",content:n}];s&&(u.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),u.push({role:"user",content:`Your previous response failed validation: ${s}
241
241
  Re-emit the FULL corrected JSON object.`}));let g=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:u}),signal:i.signal});if(!g.ok){let a=await g.text().catch(()=>"");throw new Error(`anthropic API ${g.status}: ${a.slice(0,500)}`)}let l=await g.json(),e=(Array.isArray(l.content)?l.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
242
242
  `).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...m)=>t(m.map(String).join(" "))),p=c.rebuildIndex(),u=z(r),g=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(g,p,u,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let l=p.articles.map(m=>({title:m.title,path:m.path,type:m.type})),d=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,l,d);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,l,d);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(m=>m.candidates),w=new Set(y.map(m=>m.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(m=>[m.stamp,m]));for(let m of f.articles){let A=c.readArticle(m.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${m.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(m.promotedFrom,T),S={id:Y(o,m.path),createdAt:v,status:"pending",article:m,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:m.path,title:m.title,type:m.type,stamps:m.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of m.promotedFrom)k.push({stamp:X,decision:"proposed",article:m.path,proposal:S.id,at:v})}for(let m of f.skipped)k.push({stamp:m.stamp,decision:"skipped",reason:m.reason,at:v}),i.skipped.push(m);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let u=s.now??Date.now(),g=new Date(u).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??g,lastUpdated:g,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let d=new Date(u).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:d}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:d};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
243
- //# sourceMappingURL=chunk-YYCFI4VP.js.map
243
+ //# sourceMappingURL=chunk-S337S2M7.js.map
@@ -1,4 +1,4 @@
1
- import{B as Ns,a as ys,b as bs,d as xs,f as Fe,l as _s,s as Es,u as Ds,z as Os}from"./chunk-BERHVF3T.js";import{a as fs}from"./chunk-GLQLCBJS.js";import{b as ws}from"./chunk-DP7RTNDM.js";import{a as Ps}from"./chunk-W4YR2RO2.js";import{b as ks,c as Bt,d as Ss,e as vs,h as Cs}from"./chunk-J4JVKVEK.js";import{a as hs}from"./chunk-J64VIHL5.js";import{a as jt,b as Ts}from"./chunk-J3SOEFRE.js";import{a as Ut,b as Is}from"./chunk-SIU6STB2.js";import{e as As,i as $s,j as Ms,k as Rs}from"./chunk-X5C5W3E4.js";import{a as ss}from"./chunk-Z4FY64BS.js";import{a as rs,c as os}from"./chunk-MYVHVJWZ.js";import{a as is,b as as,c as cs,d as ds,f as us}from"./chunk-DWADWDMU.js";import{a as ls,b as gs}from"./chunk-23A5K5UW.js";import{g as ps,h as ms}from"./chunk-4BCAH7XI.js";import{a as at,c as Le}from"./chunk-2GIDVZ4H.js";import{q as es,t as ts,v as xe,w as ns}from"./chunk-DXJRMPGH.js";import{a as Ne,b as it,f as Ht}from"./chunk-72SZI2UW.js";import{a as we,b as Dt}from"./chunk-FCPTN6NF.js";import{c as Bn,d as Wn}from"./chunk-QOYAX2FT.js";import{e as me}from"./chunk-DSYKYZMT.js";import{B as Ft,D as oi,F as Qn,J as ii,P as zn,Q as Xn,R as Oe,S as Yn,T as Vn,V as Zn,ha as ai,z as Jn}from"./chunk-JREA25GJ.js";import{a as Lt,i as ri}from"./chunk-RJ7DASOU.js";import{g as Nt,h as si}from"./chunk-BRK6M6LA.js";import{a as qn,b as oe,c as Kn,d as Gn,e as Ot}from"./chunk-2QNT5JDS.js";ns();Ht();var Ls="session-continuity",Fs={continues:Ne("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:Ne("Does the new request refer to something stated earlier in the conversation?")};function Hs(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Wt(s.message,1200),previousRequest:s.previousMessage?Wt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Wt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function js(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 Wt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{execa as ht}from"execa";import{spawn as ci}from"node:child_process";import{createHash as di}from"node:crypto";import{createInterface as ui}from"node:readline";var de=class extends Error{},li=s=>ci("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),qt=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(),ui({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{B as Ns,a as ys,b as bs,d as xs,f as Fe,l as _s,s as Es,u as Ds,z as Os}from"./chunk-EXPIKLUN.js";import{a as fs}from"./chunk-GLQLCBJS.js";import{b as ws}from"./chunk-DP7RTNDM.js";import{a as Ps}from"./chunk-W4YR2RO2.js";import{b as ks,c as Bt,d as Ss,e as vs,h as Cs}from"./chunk-Y6POV2X5.js";import{a as hs}from"./chunk-EEZI2K7S.js";import{a as jt,b as Ts}from"./chunk-J3SOEFRE.js";import{a as Ut,b as Is}from"./chunk-SIU6STB2.js";import{e as As,i as $s,j as Ms,k as Rs}from"./chunk-X5C5W3E4.js";import{a as ss}from"./chunk-GSFB46YC.js";import{a as rs,c as os}from"./chunk-MYVHVJWZ.js";import{a as is,b as as,c as cs,d as ds,f as us}from"./chunk-DWADWDMU.js";import{a as ls,b as gs}from"./chunk-23A5K5UW.js";import{g as ps,h as ms}from"./chunk-XO55WKCX.js";import{a as at,c as Le}from"./chunk-2GIDVZ4H.js";import{q as es,t as ts,v as xe,w as ns}from"./chunk-RWSCQMLD.js";import{a as Ne,b as it,f as Ht}from"./chunk-72SZI2UW.js";import{a as we,b as Dt}from"./chunk-FCPTN6NF.js";import{c as Bn,d as Wn}from"./chunk-QOYAX2FT.js";import{e as me}from"./chunk-DSYKYZMT.js";import{A as Ft,C as oi,E as Qn,I as ii,O as zn,P as Xn,Q as Oe,R as Yn,S as Vn,U as Zn,ga as ai,y as Jn}from"./chunk-ECM2QEXF.js";import{a as Lt,i as ri}from"./chunk-RJ7DASOU.js";import{g as Nt,h as si}from"./chunk-BRK6M6LA.js";import{a as qn,b as oe,c as Kn,d as Gn,e as Ot}from"./chunk-2QNT5JDS.js";ns();Ht();var Ls="session-continuity",Fs={continues:Ne("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:Ne("Does the new request refer to something stated earlier in the conversation?")};function Hs(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Wt(s.message,1200),previousRequest:s.previousMessage?Wt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Wt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function js(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 Wt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{execa as ht}from"execa";import{spawn as ci}from"node:child_process";import{createHash as di}from"node:crypto";import{createInterface as ui}from"node:readline";var de=class extends Error{},li=s=>ci("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),qt=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(),ui({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()}},Kt=class{constructor(e=li,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=di("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([f],[b])=>f.localeCompare(b))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new de("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 f=[...this.entries].find(([,b])=>!b.connection.busy);if(!f)throw new de("Codex warm process capacity reached");f[1].connection.close(),this.entries.delete(f[0])}try{r={fingerprint:n,connection:new qt(e,this.launchProcess)}}catch{throw new de("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,d="",c,l,u,p=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let h=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),k=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 f={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",{...f,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(k),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let I=new Promise((E,_)=>{i.failTurn=_,i.notify=(C,O)=>{if(O?.threadId!==l)return;let F=O.item,D={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...O,type:C.replace("/","."),...F?{item:{...F,type:D[F.type]||F.type}}:{}}),C==="item/completed"&&F?.type==="agentMessage"&&F.phase==="final_answer"&&(c=F.text),C==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=O.delta,e.onDelta?.(O.delta,d)),C==="thread/tokenUsage/updated"){let L=O.tokenUsage.last,H=L.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-H),outputTokens:(u?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+H,cacheCreateTokens:(u?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}C==="turn/completed"&&(O.turn.status==="completed"?E():_(new Error(O.turn.error?.message||`Codex turn ${O.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:c??d,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(f){if(i.close(),!a&&!e.signal?.aborted)throw new de(f.message);return{content:d,codexSessionId:l,usage:u,error:f.message,duration:Date.now()-t}}finally{clearTimeout(k),clearTimeout(h),e.signal?.removeEventListener("abort",y),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())}}},Us=new Kt;import{execFile as Pi}from"child_process";import{StringDecoder as We}from"string_decoder";import{mkdtempSync as or,readFileSync as ir,rmSync as ar}from"fs";import{join as pt}from"path";import{tmpdir as cr}from"os";function ct(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 c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[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),d=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"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===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"||d===529||d===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"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,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 dt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var Bs=null;function ut(){return Bs}function od(s){Bs=s}function He(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function gi(s,e){if(s.state()==="busy")return null;let n=s.snapshot(),r=s.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?n.claudeSessionId&&n.claudeSessionId!==e.resumeSessionId?`session changed (${n.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:n.claudeSessionId?"session rotated":null}var Te=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Ws=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=He(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=gi(r,t);if(!a)return r.claim?.(),r;this.handles.delete(n),this.handleWorkspace.delete(n),this.cfg.log(`[process-registry] respawning ${n}: ${a}`),r.kill(a).catch(()=>{})}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 Te(`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 Te(`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=He(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=He(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=He(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=He(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(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";n.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as pi}from"child_process";import{existsSync as mi,readFileSync as hi}from"fs";import{resolve as fi}from"path";function yi(s){let e=fi(s,"CLAUDE.md");if(!mi(e))return null;try{let t=hi(e,"utf8");return us(t)}catch{return null}}var bi=20*60*1e3,wi=5e3,je=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ue=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function xi(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var qs=class{constructor(e={}){this.opts=e}spawn(e,t){return new Gt(e,t,this.opts)}},Gt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=pi(r,o,{cwd:t.workspace,env:Le(xi({...process.env},e),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:yi(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 d=this.waiters.splice(0);for(let c of d)c(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??bi,d=o+a,c=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new je(a));try{for(;;){let l=d-Date.now();if(l<=0)throw c();let u=await this.nextEvent(l);if(u===null&&this.killReason)throw new Ue(this.killReason);if(u===null&&!this.exited)throw c();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);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)},wi);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"}}};Ot();ri();Dt();import{resolve as Ks,join as Gs}from"path";var Ti=4e3;function lt(s){try{let e=Gs(Ks(s.root),".agentx","db.sqlite"),t=Lt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=we(),r=s.input.command?s.input.command.slice(0,Ti):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -27,7 +27,7 @@ ${s}`}function Ei(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
27
27
  `,u)}};_.stdout?.on("data",v=>{D+=H.write(v);let w=D.split(`
28
28
  `);D=w.pop()||"";for(let x of w)K(x)}),_.stderr?.on("data",v=>{L+=j.write(v)});let A=await _;if(i&&i.removeEventListener("abort",F),D+=H.end(),D.trim()&&K(D),L+=j.end(),C)return{content:"",error:O||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:y};if(A.exitCode!==0||h){let v=A,w;return v.timedOut?w=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:h?w=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+L)?w=nr():w=L.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Q(w),duration:Date.now()-d,usage:p,opencodeSessionId:y}}return f=!1,{content:u.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||s.model,opencodeSessionId:y}}catch(I){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let E=/ENOENT|spawn opencode/i.test(I?.message||"")?nr():I?.message;return{content:u,...Q(E||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:y}}finally{b?.(),k?.release(f)}}async function qi(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=le(s,e,n),d="",c=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of c)l.type==="result"&&l.subtype==="success"&&(d=l.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...Q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Ki(s,e,t,n,r,o,i,a,d){let c=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,y=()=>{let f=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(f))}catch{}};a&&(a.aborted?y():a.addEventListener("abort",y,{once:!0}));let h=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);h.unref?.();let k=()=>({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()-c});try{let f=s.provider||"claude-code",b=n?`${n}
29
29
 
30
- ${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),_=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=ds(s),O=Object.keys(C).length>0,F={task:b,cwd:s.workspace,provider:f,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:_,providerOpts:o,abortSignal:u.signal,mcpServers:O?C:void 0};if(r){let{generateStream:K}=await import("./agent-QHM3J2XS.js"),A="",v,w,x,N;for await(let M of K(F)){if(d)try{d(M)}catch{}if(M.type==="text_delta")A+=M.text,r(M.text,A);else if(M.type==="thinking_delta")M.text&&i&&i(M.text);else if(M.type==="generate_result"){if(M.result.content&&M.result.content!==A){let V=M.result.content.slice(A.length);V?(A=M.result.content,r(V,A)):A=M.result.content}v=M.result.tokensUsed,M.result.inputTokens!=null&&(w=M.result.inputTokens),M.result.outputTokens!=null&&(x=M.result.outputTokens)}else if(M.type==="done"){if(M.result.content&&M.result.content!==A){let V=M.result.content.slice(A.length);V?(A=M.result.content,r(V,A)):A=M.result.content}M.result.tokensUsed!=null&&(v=M.result.tokensUsed)}else M.type==="error"&&(N=M.error)}return N&&!A?p?k():N==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${N}`),duration:Date.now()-c}:((w===void 0||x===void 0)&&v&&(w=Math.round(v*.7),x=v-w),{content:A||"Done.",tokensUsed:v,usage:w!==void 0||x!==void 0?{inputTokens:w||0,outputTokens:x||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:D}=await import("./agent-QHM3J2XS.js"),L=await D(F),H=L.inputTokens,j=L.outputTokens;if((H===void 0||j===void 0)&&L.tokensUsed){let K=L.tokensUsed;H=Math.round(K*.7),j=K-H}return{content:L.content||"Done.",tokensUsed:L.tokensUsed,usage:H!==void 0||j!==void 0?{inputTokens:H||0,outputTokens:j||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(f){return p?k():f?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${f.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",y)}}var Gi=1e3;async function Ji(s,e){let t=Promise.resolve(s).then(i=>({kind:"exit",r:i})),n,r=e.then(()=>new Promise(i=>{n=setTimeout(()=>i({kind:"grace"}),Gi),n.unref?.()})),o=await Promise.race([t,r]);return n&&clearTimeout(n),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Qi(s,e,t,n,r,o,i){let a=ut();if(!a)return null;let d=Date.now(),{channel:c,chatId:l}=yt(e.context),u={agentId:e.agentId,channel:c,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,y=!1;try{let A=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:c,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),y=a.list().length>A}catch(A){return A instanceof Te,null}y&&Vt(e.agentId,s,e.model,n,"persistent");let h=le(s,e,t),k="",f,b,I,E,_,C,O,F="",D="",L=A=>{if(!i||!A)return;let v;if(D&&A.startsWith(D)?v=A.slice(D.length):v=F&&!F.endsWith(`
30
+ ${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),_=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=ds(s),O=Object.keys(C).length>0,F={task:b,cwd:s.workspace,provider:f,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:_,providerOpts:o,abortSignal:u.signal,mcpServers:O?C:void 0};if(r){let{generateStream:K}=await import("./agent-XF3BWMOB.js"),A="",v,w,x,N;for await(let M of K(F)){if(d)try{d(M)}catch{}if(M.type==="text_delta")A+=M.text,r(M.text,A);else if(M.type==="thinking_delta")M.text&&i&&i(M.text);else if(M.type==="generate_result"){if(M.result.content&&M.result.content!==A){let V=M.result.content.slice(A.length);V?(A=M.result.content,r(V,A)):A=M.result.content}v=M.result.tokensUsed,M.result.inputTokens!=null&&(w=M.result.inputTokens),M.result.outputTokens!=null&&(x=M.result.outputTokens)}else if(M.type==="done"){if(M.result.content&&M.result.content!==A){let V=M.result.content.slice(A.length);V?(A=M.result.content,r(V,A)):A=M.result.content}M.result.tokensUsed!=null&&(v=M.result.tokensUsed)}else M.type==="error"&&(N=M.error)}return N&&!A?p?k():N==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${N}`),duration:Date.now()-c}:((w===void 0||x===void 0)&&v&&(w=Math.round(v*.7),x=v-w),{content:A||"Done.",tokensUsed:v,usage:w!==void 0||x!==void 0?{inputTokens:w||0,outputTokens:x||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:D}=await import("./agent-XF3BWMOB.js"),L=await D(F),H=L.inputTokens,j=L.outputTokens;if((H===void 0||j===void 0)&&L.tokensUsed){let K=L.tokensUsed;H=Math.round(K*.7),j=K-H}return{content:L.content||"Done.",tokensUsed:L.tokensUsed,usage:H!==void 0||j!==void 0?{inputTokens:H||0,outputTokens:j||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(f){return p?k():f?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${f.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",y)}}var Gi=1e3;async function Ji(s,e){let t=Promise.resolve(s).then(i=>({kind:"exit",r:i})),n,r=e.then(()=>new Promise(i=>{n=setTimeout(()=>i({kind:"grace"}),Gi),n.unref?.()})),o=await Promise.race([t,r]);return n&&clearTimeout(n),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Qi(s,e,t,n,r,o,i){let a=ut();if(!a)return null;let d=Date.now(),{channel:c,chatId:l}=yt(e.context),u={agentId:e.agentId,channel:c,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,y=!1;try{let A=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:c,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),y=a.list().length>A}catch(A){return A instanceof Te,null}y&&Vt(e.agentId,s,e.model,n,"persistent");let h=le(s,e,t),k="",f,b,I,E,_,C,O,F="",D="",L=A=>{if(!i||!A)return;let v;if(D&&A.startsWith(D)?v=A.slice(D.length):v=F&&!F.endsWith(`
31
31
  `)?`
32
32
 
33
33
  ${A}`:A,D=A,!!v){F+=v;try{i(v,F)}catch{}}},H=!1,j=()=>{H=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?j():o.addEventListener("abort",j,{once:!0}));let K=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:A})){if(K=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let w=v.raw.message?.content??[];for(let N of w)N.type==="text"&&typeof N.text=="string"?(k=N.text,L(N.text)):N.type==="tool_use"&&(D="");let x=v.raw.message?.usage;if(x){let N=(x.input_tokens||0)+(x.cache_read_input_tokens||0)+(x.cache_creation_input_tokens||0);N>0&&(E=N)}}if(v.type==="result"){let w=v.raw;if(w.is_error){let x=Q(typeof w.result=="string"?w.result:"claude error");f=x.error,b=x.errorKind}else typeof w.result=="string"&&w.result.length>0&&(k=w.result,F||L(w.result));typeof w.session_id=="string"&&(O=w.session_id),w.usage&&(I={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(_=w.num_turns),typeof w.message?.model=="string"?C=w.message.model:typeof w.model=="string"&&(C=w.model)}}}catch(A){if(H)f="task cancelled by operator",b="cancelled";else if(K)if(A instanceof Ue)f=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,b="interrupted";else if(A instanceof je){let v=Q(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);f=v.error,b=v.errorKind}else{let v=Q(`persistent claude process error: ${A?.message||String(A)}`);f=v.error,b=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",j),null}finally{o&&o.removeEventListener("abort",j)}return H&&!f&&(f="task cancelled by operator",b="cancelled"),{content:H?"":k,error:f,errorKind:b,duration:Date.now()-d,usage:I,contextTokens:E,numTurns:_,billedModel:C,claudeSessionId:O}}function yr(s){let e=oe(s.autonomy);if(!e&&!s.personLimits)return{args:[]};if(!s.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?zs(s.autonomy,s.agentId,s.taskId):{args:[]};return"error"in t||!s.personLimits?t:er(t.args,s.taskId,s.agentId)}function zi(s){return oe(s.autonomy)||!!s.personLimits}async function Xi(s,e,t,n,r,o,i){let a=oe(e.autonomy)?e.autonomy:void 0,d=a&&Xs(a,s.tier)||e.personLimits&&tr(s.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:c,message:a?`${Gn(a)}
@@ -131,7 +131,7 @@ Agent: ${t.slice(0,1e3)}`}],{model:Ia,maxTokens:512})).content.trim().match(/\[[
131
131
  `)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(c){i={content:"",error:c?.message??String(c)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,n,r);if(d){let c=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${c}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let c=i.error?Fe(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";ks().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:c,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(c){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${c?.message??c}`)}return i}async executeInternal(e,t,n,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=oe(e.autonomy),a=Yn(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:Br().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(d){let g=await d;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let c=this.agents.get(e.agentId);if(!c){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(S=>S.id===e.agentId));if(g){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${g.peer}"`);try{let m=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(g.peer,e.message,e.agentId,{timeoutMs:m}),viaMesh:g.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${g.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:l,chatId:u}=yt(e.context),p;if(c.activeTasks>=c.def.maxConcurrent)if(l==="api"||l==="app"||l==="a2a"||l==="mcp"||l==="reminder"||l==="events"||l==="guest"||i){let g=Date.now(),m=25*6e4,S=500;for(;c.activeTasks>=c.def.maxConcurrent;){if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(P=>setTimeout(P,S))}}else if(l==="voice"){let g=Date.now(),m=25*6e4,S=`${e.agentId}\0${u}`;for(;this.messageQueue.isBusy(e.agentId,l,u)||this.voiceClaims.has(S);){if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(m/6e4)}m`};await new Promise(P=>setTimeout(P,500))}p=S,this.voiceClaims.add(S)}else{let g=c.def.queueMode||"collect",m=this.messageQueue.enqueue(e.agentId,l,u,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:l,chatId:u,originalContext:e.context,queuedAt:e.queuedAt});if(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let S=this.messageQueue.pendingCount(e.agentId,l,u);return X().emit("task:queued",{agentId:e.agentId,channel:l,chatId:u,at:new Date().toISOString(),sender:Ft(e.context),humanRoot:Nt(e.context)}),this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${S}) behind=${c.runningTasks.map(P=>P.id).join(",")||"-"} chat=${l}:${u} at=${new Date().toISOString()}`),{content:"",error:xs(m,S)}}}let y=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(g,m)=>{this.log(`[${e.agentId}] ${g} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/1e3))}s`)}});if(p&&this.voiceClaims.delete(p),!y.ok)return this.log(`[${e.agentId}] ${y.reason}`),{content:"",error:y.reason};if(e.queuedAt!==void 0){let g=Er(e.queuedAt);g&&(e.message=`${g}
132
132
  ${e.message}`),e.queuedAt=void 0}c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let h={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};c.runningTasks.push(h),e.runningTaskId=h.id;let k=zn(this.config.people,e.context);if(e.context&&(k?e.context.person=k.id:delete e.context.person),this.runningContexts.set(h.id,e.context??{}),e.onStart)try{e.onStart(h.id)}catch{}let f=new AbortController;this.taskAborts.set(h.id,{agentId:e.agentId,channel:h.channel,chatId:typeof h.chatId=="string"?h.chatId:"",originalMessage:e.message||"",controller:f});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(h.id,b);let I=g=>{if(g){b.buffer+=g,b.buffer.length>Mo&&(b.buffer=b.buffer.slice(b.buffer.length-Mo));for(let m of b.subscribers)try{m(g)}catch{}}},E=we();e.taskId=E;let _=new Map,C=(g,m,S)=>{try{X().emit("task:step",{taskId:E,agentId:e.agentId,name:"pipeline",action:g,status:S,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},O=0,F=!1,D=()=>{F||(F=!0,O&&C("first-event",O,"ok"))},L;if(t){let g=Xc();L=m=>{D();let S=g(m);if(S&&I(S),_o(E,e.agentId,m),Po(_,m),cn(m,void 0,e.model||c.def.model),r)try{r(m)}catch{}}}else L=g=>{if(D(),_o(E,e.agentId,g),Po(_,g),cn(g,void 0,e.model||c.def.model),r)try{r(g)}catch{}};let H=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,j=H?setTimeout(()=>f.abort(new Error(`timed out after ${Math.round(H/1e3)}s`)),H):void 0;j?.unref?.();let K=(c.def.preSpawnTimeoutSec??Wc)*1e3,A=setTimeout(()=>{f.abort(new Error(`timed out before spawn after ${Math.round(K/1e3)}s in step "${h.step??"start"}"`))},K);A.unref?.();let v=()=>{A&&clearTimeout(A),A=void 0},w=()=>`task=${h.id} chat=${l}:${u} at=${new Date().toISOString()}`,x;f.signal.addEventListener("abort",()=>{let g=ze(f.signal).message;/^timed out/.test(g)&&(x=h.step??"start"),this.log(`[${e.agentId}] task ${h.id} aborted in step "${h.step??"start"}" \u2014 ${g} ${w()}`)},{once:!0});let N=g=>{h.step=g,this.log(`[${e.agentId}] step ${g} ${w()}`)},M=(g,m,S=0)=>{if(f.signal.aborted)return Promise.reject(ze(f.signal));N(g),(g==="agent"||g==="workflow-auto-run")&&(v(),O=Date.now());let P=Date.now(),W=Ao(m(),jc[g]??0,g);return Co(W,f.signal,S).then(B=>(C(g,P,"ok"),B),B=>{throw C(g,P,"error"),B instanceof Re&&this.log(`[${e.agentId}] ${B.message}; continuing without it ${w()}`),B})},V=async(g,m,S,P=0)=>{try{return await M(g,m,P)}catch(W){if(W instanceof Re)return S();throw W}},wn=!1,xn=g=>{if(wn)return;wn=!0,this.runReleases.delete(h.id),j&&clearTimeout(j),v(),c.activeTasks--;let m=c.runningTasks.findIndex(S=>S.id===h.id);m!==-1&&c.runningTasks.splice(m,1),this.runningContexts.delete(h.id),this.taskAborts.delete(h.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
133
133
  [task finished]
134
- `)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),Uc).unref?.();try{let S=b.endedAt,P={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-h.startedAt.getTime(),ok:!g?.error,error:g?.error,...x?{status:"timeout",step:x}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let B=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,l,u).then(S=>{if(S.length===0)return;this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${h.id} chat=${l}:${u} at=${new Date().toISOString()}`);let P=Date.now(),W=()=>X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:P,at:new Date().toISOString()});for(let B of S){let ee=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:ee,queuedAt:B.queuedAt??B.timestamp}).then($=>(Fe($.error)||W(),this.postQueuedResponseToChannel(e.agentId,ee,$)),$=>{throw W(),$}).catch($=>{this.log(`[${e.agentId}] queued message failed: ${$.message}`)})}}).catch(S=>{X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(h.id,xn),this.messageQueue.markRunning(e.agentId,l,u),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${w()}`);let T=e.context?.channel||"api",{evaluateRequest:Oo,selectRequestContext:No}=await import("./request-planner-TW5OCKTF.js"),pe=await V("request-gate",()=>Oo(e.message,e.agentId,T),()=>({active:!1,preprocess:!1}));pe.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let R=u,vt=e.context?.sender||"User",ne=c.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,T,R),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${T}:${R}`),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"stale",at:new Date().toISOString()})),e.freshSession||await V("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,T,R,e.seedHistory),()=>{});let Lo=[...this.sessions.getSession(e.agentId,T,R).messages].reverse().find(g=>g.role==="agent")?.content;vo({agent:e.agentId,channel:T,chatId:R,message:e.message,previousReply:Lo,taskId:E}),this.sessions.addUserMessage(e.agentId,T,R,vt,e.message);let Tn=Date.now();X().emit("task:started",{agentId:e.agentId,channel:T,chatId:R,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Tn).toISOString(),taskId:E,resumeOrigin:Pr(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Ft(e.context),...k?{person:k}:{},humanRoot:Nt(e.context),pickup:Jn(e.context),operator:Qn(e.context)});let Y,Ct,kn=this.classifier;if(kn&&T!=="a2a"&&!ne){N("classify");let g=Date.now();Ct=kn.classify({text:e.message,channel:T,sender:e.context?.sender,chatId:R,agentId:e.agentId}).then(m=>{Y=m||void 0,Y?.path?.length&&(h.intentPath=Y.path.slice()),C("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),C("classify",g,"error")})}let In=async g=>{if(!Ct)return;let m;await Promise.race([Ct,new Promise(S=>{m=setTimeout(S,g),m.unref?.()})]),m&&clearTimeout(m)};await In(Oc);let _e=this.config.workflows?.matching,be;if(this.config.workflows?.enabled&&_e?.enabled&&!i)try{let g=new _s({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Es({agentId:e.agentId,channel:T,message:e.message,intentPath:Y?.path},g.list());m&&m.confidence>=_e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${_e.mode} reasons=${m.reasons.join(",")||"n/a"}`),_e.mode==="auto"&&m.confidence>=_e.autoRunThreshold&&(this.workflowAutoRunner?be={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let Fo=this.wikiHub.getAgentWiki(e.agentId),Sn=this.memoryStore.findRelevant(e.message,e.agentId,ne?3:8),vn=this.memoryStore.buildContext(Sn),Cn=this.memoryStore.contextFacts(Sn),Ho=this.patternStore.findRelevant(e.message,e.agentId,5),jo=this.patternStore.buildContext(Ho),An="";if(!ne)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),S=await M("skills",()=>g(c.def.workspace)),P=e.personLimits?.skills??[],W=P.length?S.filter(B=>!P.some(ee=>Oe(ee,B.frontmatter.name))):S;An=m(W,e.message)}catch{}let U=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,T,R):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,T,R):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,T,R):void 0;if(U&&this.sessions.isSessionStale(e.agentId,T,R)&&(this.log(`[${e.agentId}] session stale for ${T}:${R}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"stale"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"stale",at:new Date().toISOString()}),U=void 0),U&&this.sessions.shouldRotateByTierTwo(e.agentId,T,R)){let g=this.sessions.getLastTurnContextTokens(e.agentId,T,R);this.log(`[${e.agentId}] tier-2 rotation for ${T}:${R} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),U=void 0}if(U&&this.sessions.shouldRotateByTurns(e.agentId,T,R)){let g=this.sessions.getTurnCount(e.agentId,T,R);this.log(`[${e.agentId}] max-turns rotation for ${T}:${R} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"max-turns",at:new Date().toISOString()}),U=void 0}if(U&&c.def.tier==="claude-code"){let g=U;await V("rotate",()=>this.maybeRotateForContinuity(e,c,T,R,g),()=>!1)&&(U=void 0)}try{let g=await M("compact",()=>this.sessions.compactIfNeeded(e.agentId,T,R,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",S=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${T}:${R} (quality: ${m}%, ${S} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let P=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Uo=process.env.AGENTX_CONTEXT_SURGERY==="1",Bo=ne?{maxMessages:8,maxChars:2400}:Uo&&$o(T,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Wo=!U&&!ne?Jc(Fo,e.agentId):void 0,Ve=U?void 0:this.sessions.buildHistoryContext(e.agentId,T,R,Bo),qo=U?void 0:this.sessions.getRotationMemo(e.agentId,T,R)??void 0,$n,Mn=[];if(this.config.procedures?.injection?.enabled&&!U&&!ne)try{let g=new Qe({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=gn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){$n=pn(m),Mn=m.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of m)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(me&&me.cat)try{let m=this.sessions.getSession(e.agentId,T,R).messages,S=m[0],P=m[m.length-1],W=Ve===void 0?`resume=${U?U.slice(0,8):"?"} (no rebuild)`:`fresh history=${Ve.length}c/${Ve.split(`
134
+ `)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),Uc).unref?.();try{let S=b.endedAt,P={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-h.startedAt.getTime(),ok:!g?.error,error:g?.error,...x?{status:"timeout",step:x}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let B=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,l,u).then(S=>{if(S.length===0)return;this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${h.id} chat=${l}:${u} at=${new Date().toISOString()}`);let P=Date.now(),W=()=>X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:P,at:new Date().toISOString()});for(let B of S){let ee=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:ee,queuedAt:B.queuedAt??B.timestamp}).then($=>(Fe($.error)||W(),this.postQueuedResponseToChannel(e.agentId,ee,$)),$=>{throw W(),$}).catch($=>{this.log(`[${e.agentId}] queued message failed: ${$.message}`)})}}).catch(S=>{X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(h.id,xn),this.messageQueue.markRunning(e.agentId,l,u),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${w()}`);let T=e.context?.channel||"api",{evaluateRequest:Oo,selectRequestContext:No}=await import("./request-planner-MS5BS6HY.js"),pe=await V("request-gate",()=>Oo(e.message,e.agentId,T),()=>({active:!1,preprocess:!1}));pe.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let R=u,vt=e.context?.sender||"User",ne=c.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,T,R),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${T}:${R}`),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"stale",at:new Date().toISOString()})),e.freshSession||await V("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,T,R,e.seedHistory),()=>{});let Lo=[...this.sessions.getSession(e.agentId,T,R).messages].reverse().find(g=>g.role==="agent")?.content;vo({agent:e.agentId,channel:T,chatId:R,message:e.message,previousReply:Lo,taskId:E}),this.sessions.addUserMessage(e.agentId,T,R,vt,e.message);let Tn=Date.now();X().emit("task:started",{agentId:e.agentId,channel:T,chatId:R,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Tn).toISOString(),taskId:E,resumeOrigin:Pr(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Ft(e.context),...k?{person:k}:{},humanRoot:Nt(e.context),pickup:Jn(e.context),operator:Qn(e.context)});let Y,Ct,kn=this.classifier;if(kn&&T!=="a2a"&&!ne){N("classify");let g=Date.now();Ct=kn.classify({text:e.message,channel:T,sender:e.context?.sender,chatId:R,agentId:e.agentId}).then(m=>{Y=m||void 0,Y?.path?.length&&(h.intentPath=Y.path.slice()),C("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),C("classify",g,"error")})}let In=async g=>{if(!Ct)return;let m;await Promise.race([Ct,new Promise(S=>{m=setTimeout(S,g),m.unref?.()})]),m&&clearTimeout(m)};await In(Oc);let _e=this.config.workflows?.matching,be;if(this.config.workflows?.enabled&&_e?.enabled&&!i)try{let g=new _s({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Es({agentId:e.agentId,channel:T,message:e.message,intentPath:Y?.path},g.list());m&&m.confidence>=_e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${_e.mode} reasons=${m.reasons.join(",")||"n/a"}`),_e.mode==="auto"&&m.confidence>=_e.autoRunThreshold&&(this.workflowAutoRunner?be={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let Fo=this.wikiHub.getAgentWiki(e.agentId),Sn=this.memoryStore.findRelevant(e.message,e.agentId,ne?3:8),vn=this.memoryStore.buildContext(Sn),Cn=this.memoryStore.contextFacts(Sn),Ho=this.patternStore.findRelevant(e.message,e.agentId,5),jo=this.patternStore.buildContext(Ho),An="";if(!ne)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),S=await M("skills",()=>g(c.def.workspace)),P=e.personLimits?.skills??[],W=P.length?S.filter(B=>!P.some(ee=>Oe(ee,B.frontmatter.name))):S;An=m(W,e.message)}catch{}let U=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,T,R):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,T,R):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,T,R):void 0;if(U&&this.sessions.isSessionStale(e.agentId,T,R)&&(this.log(`[${e.agentId}] session stale for ${T}:${R}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"stale"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"stale",at:new Date().toISOString()}),U=void 0),U&&this.sessions.shouldRotateByTierTwo(e.agentId,T,R)){let g=this.sessions.getLastTurnContextTokens(e.agentId,T,R);this.log(`[${e.agentId}] tier-2 rotation for ${T}:${R} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),U=void 0}if(U&&this.sessions.shouldRotateByTurns(e.agentId,T,R)){let g=this.sessions.getTurnCount(e.agentId,T,R);this.log(`[${e.agentId}] max-turns rotation for ${T}:${R} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"max-turns",at:new Date().toISOString()}),U=void 0}if(U&&c.def.tier==="claude-code"){let g=U;await V("rotate",()=>this.maybeRotateForContinuity(e,c,T,R,g),()=>!1)&&(U=void 0)}try{let g=await M("compact",()=>this.sessions.compactIfNeeded(e.agentId,T,R,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",S=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${T}:${R} (quality: ${m}%, ${S} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let P=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Uo=process.env.AGENTX_CONTEXT_SURGERY==="1",Bo=ne?{maxMessages:8,maxChars:2400}:Uo&&$o(T,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Wo=!U&&!ne?Jc(Fo,e.agentId):void 0,Ve=U?void 0:this.sessions.buildHistoryContext(e.agentId,T,R,Bo),qo=U?void 0:this.sessions.getRotationMemo(e.agentId,T,R)??void 0,$n,Mn=[];if(this.config.procedures?.injection?.enabled&&!U&&!ne)try{let g=new Qe({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=gn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){$n=pn(m),Mn=m.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of m)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(me&&me.cat)try{let m=this.sessions.getSession(e.agentId,T,R).messages,S=m[0],P=m[m.length-1],W=Ve===void 0?`resume=${U?U.slice(0,8):"?"} (no rebuild)`:`fresh history=${Ve.length}c/${Ve.split(`
135
135
  `).length}L`,B=`[${e.agentId}] ${T}:${R} ${W} | session.messages=${m.length}`+(m.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${P.timestamp.slice(11,19)}(${P.role}:${(P.content||"").slice(0,40).replace(/\n/g," ")})`:"");me.cat("context",B)}catch(g){me.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Rn;if(c.def.contextReferences&&!U)try{let g=c.def.workspace,m=this.referencesCache.get(g);if(!m){let[P,W]=await M("references",()=>Promise.all([jt(c.def.workspace),Ut(c.def.workspace)]));if(P.byId.size===0&&W.recipes.length===0){let[B,ee]=await M("references",()=>Promise.all([jt(process.cwd()),Ut(process.cwd())]));m={refs:B,recipes:ee}}else m={refs:P,recipes:W};this.referencesCache.set(g,m)}let S=Is({agentId:e.agentId,intentTags:Y?.path,message:e.message},m.recipes,m.refs);S.cards.length>0&&(Rn=Ts(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Pn=this.sessions.getCrossSessionSummary(e.agentId,T,R,e.message),_n,Ze=Tr(e.message);if(Ze)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:T,chatId:R,lookbackDays:Ze.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${Ze.lookbackDays}d on this chat (cue-triggered)]`],S=[...g.turns].sort((P,W)=>P.ts.localeCompare(W.ts));for(let P of S){let W=P.ts.slice(11,16)+" "+P.day,B=P.role==="user"?P.senderName||"User":P.senderName||"Agent";m.push(`${W} ${B}: ${P.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),_n=m.join(`
136
136
  `),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ze.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Ko=ne?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",En,Dn,On=!1;if(Ko==="planner"&&!pe.active&&T!=="voice"&&T!=="desktop"){try{let{planContext:g}=await import("./context-planner-JU7CNXCB.js"),m=await M("plan-context",()=>g({agentId:e.agentId,channel:T,chatId:R,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(On=!0,En=m.sessionHistory,vn=m.memoryContext,Cn=m.memoryFacts,Pn=m.crossChatContext,Dn=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}On&&U&&(this.sessions.clearClaudeSessionId(e.agentId,T,R),U=void 0)}let At=`${e.agentId}:${T}:${R}`,et=cs(e.message);et&&(et==="default"?(this.activeSouls.delete(At),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(At,et),this.log(`[${e.agentId}] Soul switched to: ${et}`)));let Go=this.activeSouls.get(At),Jo=is(c.def.workspace,Go),Qo=as(Jo),zo=this.agentMemory.indexMarkdown(e.agentId),Xo=c.def.tier==="claude-code"||c.def.tier==="codex-cli"?`[Operating principle]
137
137
  Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",Yo=Yc(c.def.richMessages,T),Nn="";if(c.def.workspace){let g=G(c.def.workspace,"CLAUDE.md");if(te(g))try{let m=Xe(g,"utf-8");Nn=`[Project CLAUDE.md]
@@ -144,9 +144,9 @@ ${$}`),m+=$.length}catch{}}}let Vo=$t.length>0?$t.join(`
144
144
 
145
145
  `):"",Mt=[c.def.systemPrompt||"",Xo,Yo,Nn,Vo,Qo||"",zo||""].filter(g=>g.trim().length>0).join(`
146
146
 
147
- `)||void 0,Rt={channel:T,chatId:R,channelScope:e.context?.group?"group":T==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,T),systemPrompt:c.def.systemPrompt,sender:vt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ne||$o(T,c.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ne?void 0:jo||void 0,procedureContext:$n,references:Rn,skillInjection:An||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:En??Ve,memoryContext:vn||void 0,crossChatContext:Pn||void 0,longMemoryRecall:_n||void 0,wikiContext:Wo,handoverNote:this.buildHandoverNote(e.agentId,T,R),rotationMemo:qo,eventDigest:U?void 0:Gc(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Os(T,!U,c.def.richMessages);return g?Qc(c.def.workspace,g):void 0})(),intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},nt=pe.active&&pe.preprocess?await V("select-context",()=>No(Rt),()=>({input:Rt,excluded:[]})):{input:Rt,excluded:[]};nt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${nt.excluded.join(", ")}`);let st=Rr(nt.input,ne?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Zo=fs(st,{memory:Cn,procedures:Mn,wikiContext:nt.input.wikiContext}),Pt=(st?.length??0)+(Mt?.length??0)+(e.message?.length??0),rt={history:st?.length??0,sysPrompt:Mt?.length??0,message:e.message?.length??0},Ln=ro(e.agentId,T,R);oo(Ln,Pt,rt);let Fn=io(Ln);Fn&&this.log(`[${e.agentId}] ${Fn}`),Pt>16e3&&this.log(`[${e.agentId}] large context for ${T}:${R}: ${Pt} bytes (history=${rt.history}, sysPrompt=${rt.sysPrompt}, message=${rt.message})`);let _t,Hn=ss(c.def.tier,this.config.decisions.routing);if(!e.model&&Hn&&(!pe.active||pe.preprocess))try{let{routeTaskModel:g}=await import("./routing-TSRZLD7B.js"),m=await M("route-model",()=>g({message:e.message,agent:e.agentId,channel:T,isFollowUp:!!U,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,T,R),cheapModel:Hn}));m.downgraded&&(_t=m.model,this.log(`[${e.agentId}] ${m.reason}`))}catch{}let ei={...e,systemPromptAppend:Mt,..._t?{model:_t}:{}},se,jn=!1,Un=ko({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:c.def.maxExecutionMinutes??20}),ti=L;L=g=>{Un.observe(g),ti?.(g)};try{let g=this.workflowAutoRunner;if(be&&g){let q=be;try{let z=await M("workflow-auto-run",()=>g({workflowId:q.workflowId,agentId:e.agentId,channel:T,chatId:R,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:T,chatId:R,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:q.workflowId,matchConfidence:q.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${be.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:"",duration:0,metadata:{handledByWorkflow:be.workflowId,workflowRunId:z.runId,workflowMatchConfidence:be.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(c.def.tier==="claude-code"){N("dispatch-gate");let q=c.def.persistentProcess?ut():null,z=q!=null&&q.hasLive({agentId:e.agentId,channel:T,chatId:R}),ce=!!U||z,re=[Wr(ce),no(ce,void 0,e.model||c.def.model)].find(De=>De&&De.abort);if(re){c.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${re.reason}`);let De={content:"",error:re.message,duration:0};if(!t){b.buffer=`[error] ${re.message}`;for(let ni of b.subscribers)try{ni(b.buffer)}catch{}}return se=De,De}Qr();let Ee=so();Ee&&this.log(`[${e.agentId}] ${Ee}`)}let m=c.def.tier==="claude-code",S=m?t:(q,z)=>{q&&I(q),t&&t(q,z)},P=!1,W=m?n:q=>{q&&(P?I(q):(I(`\u{1F4AD} ${q}`),P=!0)),n&&n(q)},B=()=>{P&&(I(`
147
+ `)||void 0,Rt={channel:T,chatId:R,channelScope:e.context?.group?"group":T==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,T),systemPrompt:c.def.systemPrompt,sender:vt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ne||$o(T,c.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ne?void 0:jo||void 0,procedureContext:$n,references:Rn,skillInjection:An||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:En??Ve,memoryContext:vn||void 0,crossChatContext:Pn||void 0,longMemoryRecall:_n||void 0,wikiContext:Wo,handoverNote:this.buildHandoverNote(e.agentId,T,R),rotationMemo:qo,eventDigest:U?void 0:Gc(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Os(T,!U,c.def.richMessages);return g?Qc(c.def.workspace,g):void 0})(),intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},nt=pe.active&&pe.preprocess?await V("select-context",()=>No(Rt),()=>({input:Rt,excluded:[]})):{input:Rt,excluded:[]};nt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${nt.excluded.join(", ")}`);let st=Rr(nt.input,ne?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Zo=fs(st,{memory:Cn,procedures:Mn,wikiContext:nt.input.wikiContext}),Pt=(st?.length??0)+(Mt?.length??0)+(e.message?.length??0),rt={history:st?.length??0,sysPrompt:Mt?.length??0,message:e.message?.length??0},Ln=ro(e.agentId,T,R);oo(Ln,Pt,rt);let Fn=io(Ln);Fn&&this.log(`[${e.agentId}] ${Fn}`),Pt>16e3&&this.log(`[${e.agentId}] large context for ${T}:${R}: ${Pt} bytes (history=${rt.history}, sysPrompt=${rt.sysPrompt}, message=${rt.message})`);let _t,Hn=ss(c.def.tier,this.config.decisions.routing);if(!e.model&&Hn&&(!pe.active||pe.preprocess))try{let{routeTaskModel:g}=await import("./routing-SU5Q4IPM.js"),m=await M("route-model",()=>g({message:e.message,agent:e.agentId,channel:T,isFollowUp:!!U,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,T,R),cheapModel:Hn}));m.downgraded&&(_t=m.model,this.log(`[${e.agentId}] ${m.reason}`))}catch{}let ei={...e,systemPromptAppend:Mt,..._t?{model:_t}:{}},se,jn=!1,Un=ko({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:c.def.maxExecutionMinutes??20}),ti=L;L=g=>{Un.observe(g),ti?.(g)};try{let g=this.workflowAutoRunner;if(be&&g){let q=be;try{let z=await M("workflow-auto-run",()=>g({workflowId:q.workflowId,agentId:e.agentId,channel:T,chatId:R,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:T,chatId:R,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:q.workflowId,matchConfidence:q.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${be.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:"",duration:0,metadata:{handledByWorkflow:be.workflowId,workflowRunId:z.runId,workflowMatchConfidence:be.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(c.def.tier==="claude-code"){N("dispatch-gate");let q=c.def.persistentProcess?ut():null,z=q!=null&&q.hasLive({agentId:e.agentId,channel:T,chatId:R}),ce=!!U||z,re=[Wr(ce),no(ce,void 0,e.model||c.def.model)].find(De=>De&&De.abort);if(re){c.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${re.reason}`);let De={content:"",error:re.message,duration:0};if(!t){b.buffer=`[error] ${re.message}`;for(let ni of b.subscribers)try{ni(b.buffer)}catch{}}return se=De,De}Qr();let Ee=so();Ee&&this.log(`[${e.agentId}] ${Ee}`)}let m=c.def.tier==="claude-code",S=m?t:(q,z)=>{q&&I(q),t&&t(q,z)},P=!1,W=m?n:q=>{q&&(P?I(q):(I(`\u{1F4AD} ${q}`),P=!0)),n&&n(q)},B=()=>{P&&(I(`
148
148
  `),P=!1)},ee=m?S:S?(q,z)=>{B(),S(q,z)}:void 0,$=await M("agent",()=>br(c.def,ei,this.providers,ee,st,U,L,f.signal,W),Bc);if(!$.error){let q=zc(c.def.toolUseRequired,_);if(q){let z=Array.from(_.entries()).map(([ce,ot])=>`${ce}=${ot}`).join(", ")||"none";$.error=`tool_required_not_called: ${q} (invoked: ${z})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${q}, observed ${z}`)}}let Et=this.interruptedRuns.get(h.id);Et&&($.content="",$.error=Et,$.errorKind="interrupted"),se=$;let ae=$.usage?$r($.usage):void 0;if(jn=!0,X().emit("task:completed",{taskId:E,agentId:e.agentId,channel:T,chatId:R,durationMs:Date.now()-Tn,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:Et?!0:void 0,inputTokens:ae?.inputTokens,outputTokens:ae?.outputTokens,cacheReadTokens:ae?.cacheReadTokens,cacheCreateTokens:ae?.cacheCreateTokens,tier2InputTokens:ae?.tier2InputTokens,tier2OutputTokens:ae?.tier2OutputTokens,tier2CacheReadTokens:ae?.tier2CacheReadTokens,tier2CacheCreateTokens:ae?.tier2CacheCreateTokens,resumed:!!U,resumeSessionId:U||void 0,jevArm:pe.arm,numTurns:$.numTurns,injectedContext:Zo,finalResponse:$.content||void 0,billedModel:$.billedModel||c.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let q=$.error?`[error] ${$.error}`:$.content;b.buffer=q;for(let z of b.subscribers)try{z(q)}catch{}}if($.error)c.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,T,R,$.content),So({agent:e.agentId,channel:T,chatId:R,request:e.message,reply:$.content,taskId:E}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,T,R,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,T,R,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,T,R,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,T,R,$.usage,$.contextTokens),$.usage){let re=$.contextTokens,Ee=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(re??Ee)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${T}:${R}: context=${re??"n/a"} tokens (cumulative turn total=${Ee}) \u2014 next turn will rotate`)}if(ls({channel:T,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await In(Nc);try{let re=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:re,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:T,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
149
149
 
150
150
  Agent: ${$.content}`,meta:Kc(Y,e.context)})}catch{}gs(e.agentId,e.message,$.content,{channel:T,chatId:R,sender:vt},this.memoryStore).catch(()=>{}),Lr(e.agentId,e.message,$.content,{channel:T,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=$.billedModel||e.model||c.def.model,ce=e.context?.channel,ot=ce&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ce}:${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,z,ce,ot),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${w()}`)}return $}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=ct(g.message);return se={content:"",error:dt(m),errorKind:m.kind},se}finally{if(Un.stop(),!jn)try{X().emit("task:completed",{taskId:E,agentId:e.agentId,channel:l,chatId:u,durationMs:Date.now()-h.startedAt.getTime(),error:se?.error||(f.signal.aborted?ze(f.signal).message:"run ended before completion"),errorKind:se?.errorKind,interrupted:this.interruptedRuns.has(h.id)?!0:void 0,at:new Date().toISOString()})}catch{}xn(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);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=G(process.cwd(),Pe,this.safe(e.agentId),t);te(n)||Lc(n,{recursive:!0});let r=G(n,`${this.safe(e.id)}.json`);Hc(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=G(process.cwd(),Pe,this.safe(e));if(!te(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let d=new Date(n).toISOString().slice(0,10),c=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[c,d]){let p=G(a,u);if(te(p))try{for(let y of ie(p)){if(!y.endsWith(".json"))continue;let h=y.split("-")[0],k=parseInt(h,10);if(!Number.isFinite(k)||k<i||k>n)continue;let f=Math.floor((n-k)/36e5),b=t-1-f;b>=0&&b<t&&o[b]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Pe);if(!te(e))return 0;let t=0;for(let n of ie(e)){let r=G(e,n),o;try{o=ie(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),d;try{d=ie(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let l=JSON.parse(Xe(G(a,c),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let p=u.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=qc){let t=G(process.cwd(),Pe);if(!te(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ie(t)){let i=G(t,o),a;try{a=ie(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=n))try{Fc(G(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=G(process.cwd(),Pe,this.safe(e));if(!te(n))return[];let r=ie(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=G(n,i),d;try{d=ie(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let l=JSON.parse(Xe(G(a,c),"utf-8")),{transcript:u,responseText:p,...y}=l;o.push(y)}catch{}}}return o}getTaskRecord(e,t){let n=G(process.cwd(),Pe,this.safe(e));if(!te(n))return null;let r=this.safe(t),o=ie(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(n,i,`${r}.json`);if(te(a))try{return JSON.parse(Xe(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=Ps();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.errorKind==="interrupted"||Fe(n.error))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}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}findRunningTurn(e,t={}){let n=this.agents.get(e);if(!n)return null;let r;if(t.taskId)r=n.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=n.runningTasks.filter(a=>{let d=yt(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(n=>n.id)}:null}isChatBusy(e,t,n){return this.messageQueue.isBusy(e,t,n)}runningIntentPath(e,t,n){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==n||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}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}}interruptRunning(e){let t=0;for(let[n,r]of this.taskAborts){this.interruptedRuns.set(n,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${n} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:d,originalMessage:c}=o,l=o.controller.signal.aborted,u=!1;l&&c&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,d,c)),this.messageQueue.enqueue(i,a,d,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:n}});let p=this.messageQueue.pendingCount(i,a,d),y=!1;if(r.replace){let h=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(h))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${h}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:y,edited:u,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,d=i.chatId;return new Promise(c=>{let l=!1,u=p=>{l||(l=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>u({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{Fe(p.error)?u({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>u({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}};function Yc(s,e){return s===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
151
151
  `)}export{Us as a,od as b,Ws as c,yi as d,qs as e,lt as f,yd as g,Td as h,kd as i,Ad as j,yt as k,Fi as l,hr as m,Wi as n,qi as o,Ki as p,br as q,bt as r,wt as s,ba as t,su as u,ru as v,rn as w,X as x,Fr as y,$a as z,_a as A,Ur as B,Tu as C,Br as D,Gr as E,Vr as F,Ou as G,Zr as H,Qe as I,Tc as J,kc as K,Ic as L,Sc as M,vc as N,gn as O,ag as P,cg as Q,Kc as R,Gc as S,Jc as T,bn as U,Ro as V,Po as W,zc as X,_o as Y,Eo as Z,Yc as _};
152
- //# sourceMappingURL=chunk-BHKWXFJD.js.map
152
+ //# sourceMappingURL=chunk-TXFIMVVF.js.map
@@ -1,2 +1,2 @@
1
- import{q as p}from"./chunk-J4JVKVEK.js";import{b as i,c as u,d as l,e as c}from"./chunk-DRUEPGLP.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
2
- //# sourceMappingURL=chunk-LXJGLNVG.js.map
1
+ import{q as p}from"./chunk-Y6POV2X5.js";import{b as i,c as u,d as l,e as c}from"./chunk-5UO6BBDG.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
2
+ //# sourceMappingURL=chunk-V6W3FFW7.js.map
@@ -1,6 +1,6 @@
1
- import{a as O,b as $,c as U,d as T,e as j}from"./chunk-WPNRDEHW.js";import{t as R,v as E,w as W}from"./chunk-DXJRMPGH.js";import{a as z,b as C,f as V}from"./chunk-72SZI2UW.js";import{a as B,b as re}from"./chunk-FX3D7YON.js";import{o as J,p as te}from"./chunk-5MUJZODV.js";V();var we="wiki-rerank",be=30,se=900;function xe(a){let e=a.excerptChars??se;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ne(t.excerpt,e)}))}}function Se(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:z("Do any of the candidates answer the query?")}}function Ne(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ne(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},G=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as M,appendFileSync as ie,existsSync as S,mkdirSync as F,renameSync as oe,statSync as Q}from"fs";import{resolve as A,dirname as X}from"path";import{createHash as ae}from"crypto";var _=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),F(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=O.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{M(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{M(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=O.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);Y(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),Y(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let g=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){g=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=g;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,g=p+1;break}}if(!d&&g<r.levels.length&&(d=r.levels[g].id,g++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${g}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let u={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(u),o.push(u)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=$.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
1
+ import{a as O,b as $,c as U,d as T,e as j}from"./chunk-WPNRDEHW.js";import{t as R,v as E,w as W}from"./chunk-RWSCQMLD.js";import{a as z,b as C,f as V}from"./chunk-72SZI2UW.js";import{a as B,b as re}from"./chunk-FX3D7YON.js";import{o as J,p as te}from"./chunk-5MUJZODV.js";V();var we="wiki-rerank",be=30,se=900;function xe(a){let e=a.excerptChars??se;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ne(t.excerpt,e)}))}}function Se(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:z("Do any of the candidates answer the query?")}}function Ne(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ne(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},G=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as M,appendFileSync as ie,existsSync as S,mkdirSync as F,renameSync as oe,statSync as Q}from"fs";import{resolve as A,dirname as X}from"path";import{createHash as ae}from"crypto";var _=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),F(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=O.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{M(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{M(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=O.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);Y(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),Y(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let g=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){g=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=g;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,g=p+1;break}}if(!d&&g<r.levels.length&&(d=r.levels[g].id,g++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${g}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let u={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(u),o.push(u)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=$.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
2
  `,n=this.classificationsPath();return S(n)||F(X(n),{recursive:!0}),ie(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=$.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=$.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[ce(e.text),e.channel??""].join("");return ae("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=U.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function Y(a,e){F(X(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;M(t,JSON.stringify(e,null,2)),oe(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of G)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of G)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function ce(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}re();te();W();import{createHash as me}from"crypto";V();W();var P="intent-path",de=.5,le=.3;function pe(a){return{message:fe(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function Z(a,e){let t={};for(let r of a)t[r.id]=he(r);return C(t,e)}function ge(a){return{category:Z(a,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function ue(a){return{verb:Z(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function D(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=pe(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await E(P,n,ge(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=de,b=[c.choice],g=e.filter(m=>m.parentId===c.choice);if(g.length>=2){let m=t.incumbent?.[0]===c.choice,d=await E(P,{...n,category:c.choice},ue(g),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;l=Math.min(l,f.pMax),h=h&&f.pMax>=le,b.push(f.choice)}else g.length===1&&b.push(g[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function he(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function fe(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=J(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:q(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},g=new Set(o.map(u=>u.id)),m=s.map((u,p)=>g.has(u)?-1:p).filter(u=>u>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let u=m.length===0,p=m.length===1&&m[0]===s.length-1;d=u||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(u){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(u?.message||u).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:q(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await D(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&D(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
5
  `),i=await this.callProvider(o),s=B(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=ee(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??ee(d);if(!v)continue;let u={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(u[p]=y);!u.name&&d!==v&&(u.name=d.trim()),b[v]=u}let g={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(g.input=s.leaf.input),typeof s.leaf.output=="string"&&(g.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:g}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function ee(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return me("sha1").update(a.join("")).digest("hex").slice(0,16)}function q(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function ve(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{we as a,be as b,xe as c,Se as d,Ne as e,x as f,_ as g,L as h,q as i,ve as j};
6
- //# sourceMappingURL=chunk-4BCAH7XI.js.map
6
+ //# sourceMappingURL=chunk-XO55WKCX.js.map
@@ -1,4 +1,4 @@
1
- import{b as S,c as O}from"./chunk-DRUEPGLP.js";import{a as I,b as X}from"./chunk-FCPTN6NF.js";import{a as F,b as oe}from"./chunk-7I7IEX4S.js";import{d as M}from"./chunk-QIJLFPWE.js";import{execFile as Le}from"child_process";import{writeFileSync as ee,mkdirSync as w,existsSync as b,readFileSync as $e}from"fs";import{resolve as _}from"path";var ce=["off","shadow","authoritative"],ae={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},de="INTENT_LEDGER_MODE";function B(n,e=process.env){let t=P(e[ae[n]]);if(t)return t;let i=P(e[de]);return i||"off"}function P(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return ce.includes(e)?e:null}X();import ue from"better-sqlite3";import{existsSync as Pe,mkdirSync as le}from"fs";import{dirname as ge,resolve as me}from"path";var T=class{db;path;constructor(e={}){this.path=me(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),le(ge(this.path),{recursive:!0}),this.db=new ue(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),fe(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let i=this.findEventBySourceId(e.source,e.sourceEventId);if(i)return i}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
1
+ import{b as S,c as O}from"./chunk-5UO6BBDG.js";import{a as I,b as X}from"./chunk-FCPTN6NF.js";import{a as F,b as oe}from"./chunk-7I7IEX4S.js";import{d as M}from"./chunk-QIJLFPWE.js";import{execFile as Le}from"child_process";import{writeFileSync as ee,mkdirSync as w,existsSync as b,readFileSync as $e}from"fs";import{resolve as _}from"path";var ce=["off","shadow","authoritative"],ae={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},de="INTENT_LEDGER_MODE";function B(n,e=process.env){let t=P(e[ae[n]]);if(t)return t;let i=P(e[de]);return i||"off"}function P(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return ce.includes(e)?e:null}X();import ue from"better-sqlite3";import{existsSync as Pe,mkdirSync as le}from"fs";import{dirname as ge,resolve as me}from"path";var T=class{db;path;constructor(e={}){this.path=me(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),le(ge(this.path),{recursive:!0}),this.db=new ue(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),fe(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let i=this.findEventBySourceId(e.source,e.sourceEventId);if(i)return i}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
2
2
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let i=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
3
3
  FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return i?U(i):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
4
4
  FROM intent_events WHERE id = ?`).get(e);return t?U(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
@@ -123,4 +123,4 @@ ${r.prompt}`,r.maxOutputTokens),agentId:r.agent,autonomy:r.autonomy,timeoutMinut
123
123
  `);return t.length<=e?t.join(`
124
124
  `):t.slice(-e).join(`
125
125
  `)}function Ce(n,e,t){return new Promise((i,r)=>{Le("/bin/sh",["-c",n],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(s,c,o)=>{if(s&&s.killed){r(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}i({stdout:String(c??""),stderr:String(o??""),code:s?typeof s.code=="number"?s.code:1:0})})})}export{T as a,G as b,it as c,De as d,rt as e,st as f,$ as g,Q as h,B as i,je as j,V as k,K as l,at as m,Ae as n,ne as o,ie as p,re as q,we as r,C as s};
126
- //# sourceMappingURL=chunk-J4JVKVEK.js.map
126
+ //# sourceMappingURL=chunk-Y6POV2X5.js.map