agentix-cli 0.135.0 → 0.135.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 (98) hide show
  1. package/dist/{absorb-eval-WY3YMLS4.js → absorb-eval-YT5TOTC7.js} +2 -2
  2. package/dist/{agent-3R5NY7I3.js → agent-DRUIMWF5.js} +2 -2
  3. package/dist/{board-dashboard-U3ZSCO62.js → board-dashboard-2524GN5N.js} +2 -2
  4. package/dist/chunk-32LIPTHM.js +55 -0
  5. package/dist/chunk-32LIPTHM.js.map +1 -0
  6. package/dist/{chunk-5NT44FKL.js → chunk-3D5XUOBL.js} +2 -2
  7. package/dist/{chunk-EEBK4F6E.js → chunk-3F4GPRGQ.js} +2 -2
  8. package/dist/{chunk-BQIWMQNU.js → chunk-H4NSB54D.js} +2 -2
  9. package/dist/chunk-MTX4UPNB.js +3 -0
  10. package/dist/chunk-MTX4UPNB.js.map +1 -0
  11. package/dist/{chunk-NY7NHGVT.js → chunk-MUVE3UAS.js} +2 -2
  12. package/dist/chunk-MWNCS57L.js +2 -0
  13. package/dist/chunk-MWNCS57L.js.map +1 -0
  14. package/dist/{chunk-GSKJ57XY.js → chunk-NG72DYJR.js} +80 -80
  15. package/dist/chunk-NG72DYJR.js.map +1 -0
  16. package/dist/{chunk-ZGVVYJIK.js → chunk-R6ECKZLE.js} +2 -2
  17. package/dist/{chunk-MI7WOGH6.js → chunk-R6KLH34H.js} +2 -2
  18. package/dist/{chunk-RGZARSHV.js → chunk-ROLSSYXE.js} +1 -1
  19. package/dist/{chunk-RGZARSHV.js.map → chunk-ROLSSYXE.js.map} +1 -1
  20. package/dist/{chunk-YA3P77LV.js → chunk-SKSYII3K.js} +2 -2
  21. package/dist/{chunk-6WF56ME6.js → chunk-SN7YH4E4.js} +2 -2
  22. package/dist/{chunk-RVEMX5MJ.js → chunk-TTG3ZW3W.js} +2 -2
  23. package/dist/{chunk-ZFRXFUP7.js → chunk-UTW56K5I.js} +2 -2
  24. package/dist/{chunk-H6VWU2HN.js → chunk-UXOGNBGL.js} +2 -2
  25. package/dist/{chunk-L5UGH4T4.js → chunk-WYEWNN76.js} +3 -3
  26. package/dist/{chunk-LU7GDHGD.js → chunk-ZEAT2B5B.js} +2 -2
  27. package/dist/cli.js +1 -1
  28. package/dist/{contributions-KLRJ4ZXV.js → contributions-ZD6ZGTJR.js} +2 -2
  29. package/dist/enrich-EFIPWA3P.js +16 -0
  30. package/dist/{enrich-ZB5I7KHN.js.map → enrich-EFIPWA3P.js.map} +1 -1
  31. package/dist/event-levels-7CY7AJLY.js +3 -0
  32. package/dist/event-levels-7CY7AJLY.js.map +1 -0
  33. package/dist/{hub-TILTOOSS.js → hub-MVX3U6A2.js} +2 -2
  34. package/dist/index.js +1 -1
  35. package/dist/load-LQ2I2PQI.js +2 -0
  36. package/dist/model-call-J7JATTMW.js +2 -0
  37. package/dist/{program-U3HJY7E5.js → program-WOQXOAYQ.js} +194 -194
  38. package/dist/program-WOQXOAYQ.js.map +1 -0
  39. package/dist/{promote-RHVZB2QZ.js → promote-X2XQEEQP.js} +2 -2
  40. package/dist/push-bridge-325SXDGN.js +1 -1
  41. package/dist/query-RRHYPXOM.js +2 -0
  42. package/dist/query-runs-WYRNBLLC.js +6 -0
  43. package/dist/query-runs-WYRNBLLC.js.map +1 -0
  44. package/dist/{query-settings-2MGUS6AY.js → query-settings-WKVLQEVZ.js} +2 -2
  45. package/dist/{registry-LZLIPP7N.js → registry-VXK36CCL.js} +2 -2
  46. package/dist/score-LNJ46A67.js +3 -0
  47. package/dist/score-LNJ46A67.js.map +1 -0
  48. package/dist/types-YZX46RES.js +2 -0
  49. package/dist/{wiki-GCRRINW3.js → wiki-QZ7XNAMJ.js} +2 -2
  50. package/dist/wiki-enrich-PMG4T6PP.js +2 -0
  51. package/package.json +1 -1
  52. package/dist/chunk-GSKJ57XY.js.map +0 -1
  53. package/dist/chunk-JRS5QRZG.js +0 -2
  54. package/dist/chunk-JRS5QRZG.js.map +0 -1
  55. package/dist/chunk-JTDUTCUE.js +0 -3
  56. package/dist/chunk-JTDUTCUE.js.map +0 -1
  57. package/dist/chunk-WWDYDLY2.js +0 -55
  58. package/dist/chunk-WWDYDLY2.js.map +0 -1
  59. package/dist/enrich-ZB5I7KHN.js +0 -16
  60. package/dist/event-levels-CQWHSLMT.js +0 -3
  61. package/dist/event-levels-CQWHSLMT.js.map +0 -1
  62. package/dist/load-EOZUZK7U.js +0 -2
  63. package/dist/model-call-PKV5UAQ7.js +0 -2
  64. package/dist/program-U3HJY7E5.js.map +0 -1
  65. package/dist/query-OZXZVLO7.js +0 -2
  66. package/dist/query-runs-7VX3YAC3.js +0 -4
  67. package/dist/query-runs-7VX3YAC3.js.map +0 -1
  68. package/dist/score-DZGPLHCL.js +0 -3
  69. package/dist/score-DZGPLHCL.js.map +0 -1
  70. package/dist/types-LJZ2YY5W.js +0 -2
  71. package/dist/wiki-enrich-P5TNWACZ.js +0 -2
  72. /package/dist/{absorb-eval-WY3YMLS4.js.map → absorb-eval-YT5TOTC7.js.map} +0 -0
  73. /package/dist/{agent-3R5NY7I3.js.map → agent-DRUIMWF5.js.map} +0 -0
  74. /package/dist/{board-dashboard-U3ZSCO62.js.map → board-dashboard-2524GN5N.js.map} +0 -0
  75. /package/dist/{chunk-5NT44FKL.js.map → chunk-3D5XUOBL.js.map} +0 -0
  76. /package/dist/{chunk-EEBK4F6E.js.map → chunk-3F4GPRGQ.js.map} +0 -0
  77. /package/dist/{chunk-BQIWMQNU.js.map → chunk-H4NSB54D.js.map} +0 -0
  78. /package/dist/{chunk-NY7NHGVT.js.map → chunk-MUVE3UAS.js.map} +0 -0
  79. /package/dist/{chunk-ZGVVYJIK.js.map → chunk-R6ECKZLE.js.map} +0 -0
  80. /package/dist/{chunk-MI7WOGH6.js.map → chunk-R6KLH34H.js.map} +0 -0
  81. /package/dist/{chunk-YA3P77LV.js.map → chunk-SKSYII3K.js.map} +0 -0
  82. /package/dist/{chunk-6WF56ME6.js.map → chunk-SN7YH4E4.js.map} +0 -0
  83. /package/dist/{chunk-RVEMX5MJ.js.map → chunk-TTG3ZW3W.js.map} +0 -0
  84. /package/dist/{chunk-ZFRXFUP7.js.map → chunk-UTW56K5I.js.map} +0 -0
  85. /package/dist/{chunk-H6VWU2HN.js.map → chunk-UXOGNBGL.js.map} +0 -0
  86. /package/dist/{chunk-L5UGH4T4.js.map → chunk-WYEWNN76.js.map} +0 -0
  87. /package/dist/{chunk-LU7GDHGD.js.map → chunk-ZEAT2B5B.js.map} +0 -0
  88. /package/dist/{contributions-KLRJ4ZXV.js.map → contributions-ZD6ZGTJR.js.map} +0 -0
  89. /package/dist/{hub-TILTOOSS.js.map → hub-MVX3U6A2.js.map} +0 -0
  90. /package/dist/{load-EOZUZK7U.js.map → load-LQ2I2PQI.js.map} +0 -0
  91. /package/dist/{model-call-PKV5UAQ7.js.map → model-call-J7JATTMW.js.map} +0 -0
  92. /package/dist/{promote-RHVZB2QZ.js.map → promote-X2XQEEQP.js.map} +0 -0
  93. /package/dist/{query-OZXZVLO7.js.map → query-RRHYPXOM.js.map} +0 -0
  94. /package/dist/{query-settings-2MGUS6AY.js.map → query-settings-WKVLQEVZ.js.map} +0 -0
  95. /package/dist/{registry-LZLIPP7N.js.map → registry-VXK36CCL.js.map} +0 -0
  96. /package/dist/{types-LJZ2YY5W.js.map → types-YZX46RES.js.map} +0 -0
  97. /package/dist/{wiki-GCRRINW3.js.map → wiki-QZ7XNAMJ.js.map} +0 -0
  98. /package/dist/{wiki-enrich-P5TNWACZ.js.map → wiki-enrich-PMG4T6PP.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as Re}from"./chunk-GTJIKXDB.js";import{q as Kt}from"./chunk-S2GAEH2F.js";import{a as w}from"./chunk-7LN4VKDU.js";import{a as ne}from"./chunk-IMLAPB7G.js";import{b as Jt}from"./chunk-WCXXXAHV.js";import{f as Yt,g as Ae,i as V,j as q,l as Zt}from"./chunk-AKLZ4YO2.js";import{t as Xt,u as Gt}from"./chunk-5NT44FKL.js";import{d as Ht,e as zt}from"./chunk-AQASR6KR.js";import{X as Nt,Z as te,_ as ve,aa as $e,b as Se}from"./chunk-QDWEM4DG.js";import{a as Vt,b as qt,d as Bt}from"./chunk-Y4CYQV7G.js";import{a as Lt,b as Ot}from"./chunk-SHEUCITK.js";import{g as Mt,h as jt,i as Wt,k as Ft,l as Ut}from"./chunk-FWDRBUMS.js";import{q as Pt}from"./chunk-SSQMFHSM.js";import{a as Ct,b as Dt}from"./chunk-LUYN6RAC.js";import{A as Rt,B as _t,ha as xe,n as ee,o as St,oa as It,p as vt,pa as Et,q as Jr,xa as Tt,y as $t,z as At}from"./chunk-DYGQF3MI.js";import{a as we,h as Yr}from"./chunk-BRK6M6LA.js";import{f as ke,n as Zr}from"./chunk-UIBUZ2N3.js";import{existsSync as Qr,readdirSync as ei,readFileSync as ti,statSync as ni}from"fs";import{resolve as ri}from"path";function Qt(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],l=a.filter(f=>n-f.at<=r),c=a.filter(f=>n-f.at>r&&n-f.at<=r*2),u=l.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:g,lastRunAt:p,recent:l.length,prior:c.length,failed:u,paused:d}}).sort((o,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[o.state]-l[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var re=new Map;function Ea(t,e=1e3){if(!Qr(t))return[];let n=ei(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=ri(t,s);return{path:o,mtime:ni(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of re.keys())i.has(s)||re.delete(s);let r=[];for(let{path:s,mtime:o}of n){let a=re.get(s);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let l=ii(s,o);re.set(s,{mtime:o,summary:l}),l&&r.push(l)}return r}function ii(t,e){try{let n=ti(t,"utf-8").split(`
1
+ import{a as Re}from"./chunk-GTJIKXDB.js";import{a as w}from"./chunk-7LN4VKDU.js";import{a as ne}from"./chunk-IMLAPB7G.js";import{q as Kt}from"./chunk-S2GAEH2F.js";import{b as Jt}from"./chunk-WCXXXAHV.js";import{f as Yt,g as Ae,i as V,j as q,l as Zt}from"./chunk-AKLZ4YO2.js";import{t as Xt,u as Gt}from"./chunk-3D5XUOBL.js";import{d as Ht,e as zt}from"./chunk-AQASR6KR.js";import{X as Nt,Z as te,_ as ve,aa as $e,b as Se}from"./chunk-QDWEM4DG.js";import{a as Vt,b as qt,d as Bt}from"./chunk-Y4CYQV7G.js";import{a as Lt,b as Ot}from"./chunk-SHEUCITK.js";import{g as Mt,h as jt,i as Wt,k as Ft,l as Ut}from"./chunk-FWDRBUMS.js";import{q as Pt}from"./chunk-SSQMFHSM.js";import{a as Ct,b as Dt}from"./chunk-LUYN6RAC.js";import{A as Rt,B as _t,ha as xe,n as ee,o as St,oa as It,p as vt,pa as Et,q as Jr,xa as Tt,y as $t,z as At}from"./chunk-DYGQF3MI.js";import{a as we,h as Yr}from"./chunk-BRK6M6LA.js";import{f as ke,n as Zr}from"./chunk-UIBUZ2N3.js";import{existsSync as Qr,readdirSync as ei,readFileSync as ti,statSync as ni}from"fs";import{resolve as ri}from"path";function Qt(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],l=a.filter(f=>n-f.at<=r),c=a.filter(f=>n-f.at>r&&n-f.at<=r*2),u=l.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:g,lastRunAt:p,recent:l.length,prior:c.length,failed:u,paused:d}}).sort((o,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[o.state]-l[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var re=new Map;function Ea(t,e=1e3){if(!Qr(t))return[];let n=ei(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=ri(t,s);return{path:o,mtime:ni(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of re.keys())i.has(s)||re.delete(s);let r=[];for(let{path:s,mtime:o}of n){let a=re.get(s);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let l=ii(s,o);re.set(s,{mtime:o,summary:l}),l&&r.push(l)}return r}function ii(t,e){try{let n=ti(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let i=JSON.parse(n[0]),r=i.run?.workflowId;if(!r)return null;let s=i.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),l=a.status??a.run?.status;if(l){s=l;break}}return{workflowId:r,status:s,at:e}}catch{return null}}var si={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},oi=(t,e,n)=>{try{return Pt(t,e,n)}catch{return null}},en=864e5;function Pa(t){let e=t.now??Date.now(),n={...si,...t.thresholds},i=t.nextFire??oi,r=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],c=a.timezone||"UTC",u=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),d=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,k.text),trigger:{schedule:$(a.schedule,k.text),timezone:c},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?_e(a.nextRun)??_e(i(a.schedule,new Date(e),c)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:pi(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:tn(u),sampledRuns:l.length,flags:[],attention:null};p.flags=nn(p,u,a.schedule,c,null,e,n,i),r.push(rn(p))}let s=new Map(Qt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let l=o.get(a.workflowId);l?l.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(I=>I.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},u=a.state||"active",d=u==="active",p=(o.get(a.id)??[]).slice().sort((I,ye)=>ye.at-I.at),g=p.map(I=>({at:I.at,status:ci(I.status)})),f=g[0],h=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",C=typeof c.timezone=="string"?c.timezone:"UTC",M={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,k.text),trigger:h?{schedule:$(b,k.text),timezone:C}:{event:$(typeof c.event=="string"?c.event:"",k.text),filters:di(c.filter,a)},agent:ui(a),enabled:d,state:u,nextRunAt:h&&d&&b?_e(i(b,new Date(e),C)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let I=g.find(ye=>ye.status==="success");return I?new Date(I.at).toISOString():null})(),consecutiveFailures:tn(g),sampledRuns:p.length,flags:[],attention:null},Q=Date.parse(a.updated||a.created||"");M.flags=h?nn(M,g,b,C,Number.isFinite(Q)?Q:null,e,n,i):ai(M,s.get(a.id)?.state==="dormant",Number.isFinite(Q)?Q:null,e,n),r.push(rn(M))}return r.sort(li).slice(0,k.routines)}function tn(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function nn(t,e,n,i,r,s,o,a){let l=[],c=e.length?e[0].at:null;if(!t.enabled){let p=on(c,r,s,o);return p&&l.push(p),l}if(t.consecutiveFailures>=o.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let u=new Date(c),d=null;for(let p=0;p<o.missedFires&&(d=a(n,u,i),!!d);p++)u=d;return d&&s>d.getTime()+o.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${o.missedFires} scheduled fires missed`}),l}function ai(t,e,n,i,r){let s=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=on(o,n,i,r);return a&&s.push(a),s}return t.consecutiveFailures>=r.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function on(t,e,n,i){let r=Math.max(t??0,e??0);return r&&n-r<i.disabledDays*en?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/en)} days`:"Disabled and never ran"}}function rn(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var sn={critical:0,warning:1,info:2};function li(t,e){let n=t.attention?sn[t.attention]:3,i=e.attention?sn[e.attention]:3;return n-i||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ci(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function ui(t){if(t.ownerAgent)return $(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),k.text):null}function di(t,e){let n=[],i=e?.project;if(i&&n.push($(`project=${i}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,s]of Object.entries(t)){let o=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];o.length&&n.push($(`${r}=${o.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function _e(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function pi(t,e){return t===void 0?void 0:$(t,e)}import{existsSync as H,readdirSync as Pi,readFileSync as Ni}from"fs";import{resolve as R}from"path";import{randomBytes as cn}from"crypto";import{existsSync as fi,mkdirSync as mi,readdirSync as hi,readFileSync as bi,renameSync as un,unlinkSync as yi,writeFileSync as wi}from"fs";import{resolve as dn}from"path";function an(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var gi=t=>t.trim().split(`
3
3
  `).pop()?.slice(0,300)||"no output";async function ln(t,e,n,i=Re){let r=await i(t.bin,[...an(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return r.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${gi(r.stderr||r.stdout)}`}}async function Oa(t,e,n,i,r=Re){return(await r(t.bin,[...an(t),"--read-only","media","download","--chat",e,"--id",n,"--output",i],{timeoutMs:12e4})).code===0}var ki=2e3,xi=t=>ln(t.wacli,t.to,t.text);function Ie(t){return dn(t,".agentx","whatsapp-triage","drafts")}var Si=t=>/^[a-z0-9-]{8,64}$/.test(t),ie=(t,e)=>dn(Ie(t),`${e}.json`);function pn(t,e){mi(Ie(t),{recursive:!0});let n=ie(t,e.id),i=`${n}.${process.pid}.tmp`;wi(i,JSON.stringify(e,null,2)+`
4
4
  `,{mode:384}),un(i,n)}function Va(t,e,n=Date.now()){let i=e.text.trim().slice(0,ki);if(!i)throw new Error("empty draft");let r={...e,text:i,id:`${n.toString(36)}-${cn(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return pn(t,r),r}function se(t,e){if(!Si(e))return null;try{return JSON.parse(bi(ie(t,e),"utf-8"))}catch{return null}}function gn(t,e){let n=Ie(t);return fi(n)?hi(n).filter(i=>i.endsWith(".json")).map(i=>se(t,i.slice(0,-5))).filter(i=>!!i&&(!e||i.status===e)).sort((i,r)=>i.created_at.localeCompare(r.created_at)):[]}async function fn(t,e,n,i={}){let r=se(t,e);if(!r||r.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${ie(t,e)}.${process.pid}.${cn(3).toString("hex")}.claim`;try{un(ie(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let o={...r,decided_by:i.by??"operator",decided_at:new Date(i.now??Date.now()).toISOString()};if(n==="no")o.status="rejected";else{let a=await(i.send??xi)(r).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?o.status="sent":(o.status="failed",o.error=a.error)}pn(t,o);try{yi(s)}catch{}return o.status==="failed"?{ok:!1,error:o.error??"send failed"}:{ok:!0,draft:o}}import{mkdirSync as vi,readFileSync as $i,renameSync as Ai,writeFileSync as Ri}from"fs";import{resolve as _i}from"path";function mn(t){return _i(Ae(t),"_state.json")}function A(t){try{let e=JSON.parse($i(mn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function B(t,e){vi(Ae(t),{recursive:!0});let n=mn(t),i=`${n}.${process.pid}.tmp`;Ri(i,JSON.stringify(e,null,2)+`
@@ -529,4 +529,4 @@ Document the arguments, commands, or files the skill expects. Example:
529
529
  claude-code ${xt(t)} --arg value
530
530
  \`\`\`
531
531
  `}Tt();var zr={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Xr(t){return{...zr,...t??{},regions:{...t?.regions??{}},buffer:{...zr.buffer,...t?.buffer??{}}}}function td(t){try{return Xr(Et(t).screen)}catch{return Xr(void 0)}}var Ra=/^[a-z][\w-]*$/,Gr=["window","screen","menubar","notifications"];function Z(t,e,n,i){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${i}`);return r}var be=(t,e)=>Z(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Kr(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function nd(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=be(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=be(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=be(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=Z(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=Z(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[s,o]of Object.entries(e.regions)){if(!Ra.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);o===null?delete r[s]:r[s]=Kr(o)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,s={...n.buffer??{}};"enabled"in r&&(s.enabled=!!r.enabled),"seconds"in r&&(s.seconds=Z(r.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in r&&(s.fps=Z(r.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in r&&(s.maxPixels=be(r.maxPixels,"buffer.maxPixels")),"region"in r&&(s.region=String(r.region).trim()),n.buffer=s}let i=n.buffer?.region;if(i!==void 0&&!Gr.includes(i)&&!n.regions?.[i])try{Kr(i)}catch{throw new Error(`buffer.region "${i}" is not a region \u2014 use ${[...Gr,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Qt as a,Ea as b,tt as c,Ks as d,Js as e,mc as f,hc as g,bc as h,ar as i,wc as j,xc as k,D as l,lr as m,k as n,Pa as o,Oa as p,xi as q,Va as r,fn as s,A as t,Xa as u,Ga as v,Ya as w,oe as x,Za as y,xn as z,il as A,z as B,wl as C,kl as D,_n as E,cr as F,$c as G,_c as H,vr as I,eu as J,tu as K,au as L,qo as M,lu as N,Sl as O,vl as P,$l as Q,Al as R,Rl as S,_l as T,El as U,Tl as V,Wl as W,Me as X,Fl as Y,Ul as Z,X as _,G as $,Ko as aa,bu as ba,yu as ca,wu as da,ku as ea,ct as fa,xu as ga,Fe as ha,Ue as ia,pe as ja,ms as ka,bs as la,zl as ma,qe as na,Be as oa,ys as pa,ws as qa,Xn as ra,Yn as sa,Xl as ta,Ss as ua,Gl as va,Ts as wa,Ps as xa,He as ya,Ls as za,Zn as Aa,P as Ba,Lr as Ca,Or as Da,Mr as Ea,_u as Fa,ia as Ga,Wr as Ha,Fr as Ia,ju as Ja,Wu as Ka,ka as La,Fu as Ma,Vr as Na,ge as Oa,oc as Pa,ir as Qa,ze as Ra,Qe as Sa,gc as Ta,Bu as Ua,Hu as Va,zu as Wa,Xu as Xa,Gu as Ya,Ku as Za,Ju as _a,Yu as $a,Zu as ab,zr as bb,Xr as cb,td as db,Gr as eb,nd as fb};
532
- //# sourceMappingURL=chunk-ZGVVYJIK.js.map
532
+ //# sourceMappingURL=chunk-R6ECKZLE.js.map
@@ -1,4 +1,4 @@
1
- import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-ROH45HXN.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-TILTOOSS.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-EOZUZK7U.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-ZB5I7KHN.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-ZB5I7KHN.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
1
+ import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-ROH45HXN.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-MVX3U6A2.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-LQ2I2PQI.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-EFIPWA3P.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-EFIPWA3P.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
2
2
  `).slice(0,12).map(n=>` | ${n}`).join(`
3
3
  `)))}u.outcomes.length===0&&console.log(t.dim(" nothing to do: no entity of these types changed since the last run (--force redoes them)")),console.log(t.dim(` spent $${u.costUsd.toFixed(3)} of $${w}${u.capped?" \xB7 stopped at the cap":""}`))})}export{N as a,I as b};
4
- //# sourceMappingURL=chunk-MI7WOGH6.js.map
4
+ //# sourceMappingURL=chunk-R6KLH34H.js.map
@@ -1,2 +1,2 @@
1
1
  var e=["minor","normal","major"];export{e as a};
2
- //# sourceMappingURL=chunk-RGZARSHV.js.map
2
+ //# sourceMappingURL=chunk-ROLSSYXE.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/wiki/ontology/types.ts"],"sourcesContent":["// --- Wiki ontology types (#811) ---\n//\n// The ontology says what kinds of things the wiki holds (types grouped\n// into pillars), how they relate (properties), how important an event is,\n// and how each type's page is viewed (lenses). Every value here comes\n// from `ontology.yaml` in the wiki root, falling back to the generic\n// defaults in `defaults.ts`. Nothing about a particular organisation\n// belongs in code.\n\nexport type Importance = \"minor\" | \"normal\" | \"major\"\n\nexport const IMPORTANCE_LEVELS: readonly Importance[] = [\"minor\", \"normal\", \"major\"] as const\n\nexport interface PillarDef {\n id: string\n label: string\n /** One line under the pillar title. */\n description?: string\n /** Icon name from the view's small built-in icon set. */\n icon?: string\n /** Shown in the sidebar. A fallback pillar such as Topics sets false. */\n sidebar?: boolean\n}\n\nexport interface TypeDef {\n id: string\n label: string\n plural?: string\n pillar: string\n /** schema.org class, shown as a hint on the page. */\n schema?: string\n icon?: string\n /** Panels the page opens with, in order. */\n lens?: LensPanel[]\n}\n\nexport interface PropertyDef {\n id: string\n /** Read from the subject: \"Person — role at → Organization\". */\n label: string\n /** Read from the value's side: \"Organization — people ← Person\". */\n inverse?: string\n /** Wikidata property id, kept as a mapping hint. */\n wikidata?: string\n /** Types the value is expected to be. Informational. */\n range?: string[]\n /** Types the subject may be. A lens shows other subjects' statements\n * through the inverse; `wiki enrich` writes it only on these (#820). */\n domain?: string[]\n}\n\nexport type PanelSource = \"statements\" | \"linked\" | \"history\" | \"discussed\" | \"readings\" | \"notes\"\n\nexport interface LensPanel {\n /** Panel id. Used in the zoom URL, so keep it short and stable. */\n panel: string\n title?: string\n /** Where items come from. Inferred from the other fields when omitted. */\n source?: PanelSource\n /** Properties to show (statements panels). `related` covers plain links. */\n from?: string | string[]\n /** Keep only items whose other end has one of these types. */\n types?: string[]\n /** Items shown at the overview level (Z2). The full list is Z3. */\n show?: number\n group_by?: \"role\" | \"property\"\n display?: \"list\" | \"timeline\"\n /** History: importance levels shown unfolded. */\n importance?: Importance[]\n /** History: levels folded under a count. */\n fold?: Importance\n /** History: repeated minor events shown as one recurring line. */\n rollup?: { min: number; days: number }\n /** Readings: only the latest value per metric. */\n latest?: boolean\n /** `owner` marks the panel as private to the owner. */\n access?: \"owner\"\n}\n\nexport interface ClassifyRule {\n /** Type the matching page gets. */\n type: string\n /** Match when the page's legacy `type` is one of these. */\n legacy?: string[]\n /** Match when the page path starts with one of these folders. */\n path?: string[]\n /** Match when the page has any of these tags. */\n tags?: string[]\n /** Case-insensitive regular expression on the title. */\n title?: string\n}\n\n/** Gives an event its importance without a model call (#811). */\nexport interface ImportanceRule {\n level: Importance\n /** Case-insensitive regular expression on the event title. */\n title?: string\n /** Match when the event page has any of these tags. */\n tags?: string[]\n}\n\nexport interface Ontology {\n version: number\n pillars: PillarDef[]\n types: TypeDef[]\n properties: PropertyDef[]\n importance: {\n default: Importance\n /** Who may set `major`: \"owner\" means agents can only propose it. */\n major_set_by: \"owner\" | \"anyone\"\n rollup: { min: number; days: number }\n /** Tried in order by `wiki events` before it asks a model. The first\n * match wins. */\n rules?: ImportanceRule[]\n }\n sidebar: {\n pins_max: number\n /** Page titles the owner pinned, in order. */\n pins: string[]\n }\n /** Rules that give a page a type, tried in order. The first match wins. */\n classify: ClassifyRule[]\n /** Type for pages no rule matches. */\n fallback_type: string\n /** Extra names of the fleet's agents, for agents that run on another\n * node or answer to a persona name (#819). The node's own agent ids,\n * configured names and persona names are found without this. */\n agent_names?: string[]\n}\n\n/** One typed fact about a page: subject (the page) → property → value. */\nexport interface WikiStatement {\n property: string\n /** A page title (becomes a link) or a literal value. */\n value: string\n role?: string\n since?: string\n until?: string\n /** Metric name for readings (disk_used, uptime). */\n metric?: string\n /** When a reading was taken. */\n at?: string\n /** Where it comes from: entry id, document, gazette reference, article. */\n source?: string\n access?: \"public\" | \"shared\" | \"private\"\n status?: \"proposed\" | \"confirmed\"\n confirmed_by?: string\n checked_at?: string\n /** The job that wrote it, e.g. \"wiki-enrich\"; its next run replaces it. */\n by?: string\n note?: string\n}\n"],"mappings":"AAWO,IAAMA,EAA2C,CAAC,QAAS,SAAU,OAAO","names":["IMPORTANCE_LEVELS"]}
1
+ {"version":3,"sources":["../src/wiki/ontology/types.ts"],"sourcesContent":["// --- Wiki ontology types (#811) ---\n//\n// The ontology says what kinds of things the wiki holds (types grouped\n// into pillars), how they relate (properties), how important an event is,\n// and how each type's page is viewed (lenses). Every value here comes\n// from `ontology.yaml` in the wiki root, falling back to the generic\n// defaults in `defaults.ts`. Nothing about a particular organisation\n// belongs in code.\n\nexport type Importance = \"minor\" | \"normal\" | \"major\"\n\nexport const IMPORTANCE_LEVELS: readonly Importance[] = [\"minor\", \"normal\", \"major\"] as const\n\nexport interface PillarDef {\n id: string\n label: string\n /** One line under the pillar title. */\n description?: string\n /** Icon name from the view's small built-in icon set. */\n icon?: string\n /** Shown in the sidebar. A fallback pillar such as Topics sets false. */\n sidebar?: boolean\n}\n\nexport interface TypeDef {\n id: string\n label: string\n plural?: string\n pillar: string\n /** schema.org class, shown as a hint on the page. */\n schema?: string\n icon?: string\n /** Panels the page opens with, in order. */\n lens?: LensPanel[]\n}\n\nexport interface PropertyDef {\n id: string\n /** Read from the subject: \"Person — role at → Organization\". */\n label: string\n /** Read from the value's side: \"Organization — people ← Person\". */\n inverse?: string\n /** Wikidata property id, kept as a mapping hint. */\n wikidata?: string\n /** Types the value is expected to be. Informational. */\n range?: string[]\n /** Types the subject may be. A lens shows other subjects' statements\n * through the inverse; `wiki enrich` writes it only on these (#820). */\n domain?: string[]\n}\n\nexport type PanelSource = \"statements\" | \"linked\" | \"history\" | \"discussed\" | \"readings\" | \"notes\"\n\nexport interface LensPanel {\n /** Panel id. Used in the zoom URL, so keep it short and stable. */\n panel: string\n title?: string\n /** Where items come from. Inferred from the other fields when omitted. */\n source?: PanelSource\n /** Properties to show (statements panels). `related` covers plain links. */\n from?: string | string[]\n /** Keep only items whose other end has one of these types. */\n types?: string[]\n /** Items shown at the overview level (Z2). The full list is Z3. */\n show?: number\n group_by?: \"role\" | \"property\"\n display?: \"list\" | \"timeline\"\n /** History: importance levels shown unfolded. */\n importance?: Importance[]\n /** History: levels folded under a count. */\n fold?: Importance\n /** History: repeated minor events shown as one recurring line. */\n rollup?: { min: number; days: number }\n /** Readings: only the latest value per metric. */\n latest?: boolean\n /** `owner` marks the panel as private to the owner. */\n access?: \"owner\"\n}\n\nexport interface ClassifyRule {\n /** Type the matching page gets. */\n type: string\n /** Match when the page's legacy `type` is one of these. */\n legacy?: string[]\n /** Match when the page path starts with one of these folders. */\n path?: string[]\n /** Match when the page has any of these tags. */\n tags?: string[]\n /** Case-insensitive regular expression on the title. */\n title?: string\n}\n\n/** Gives an event its importance without a model call (#811). */\nexport interface ImportanceRule {\n level: Importance\n /** Case-insensitive regular expression on the event title. */\n title?: string\n /** Match when the event page has any of these tags. */\n tags?: string[]\n /** Case-insensitive regular expression on the title that stops the rule. */\n unless?: string\n}\n\nexport interface Ontology {\n version: number\n pillars: PillarDef[]\n types: TypeDef[]\n properties: PropertyDef[]\n importance: {\n default: Importance\n /** Who may set `major`: \"owner\" means agents can only propose it. */\n major_set_by: \"owner\" | \"anyone\"\n rollup: { min: number; days: number }\n /** Tried in order by `wiki events` before it asks a model. The first\n * match wins. */\n rules?: ImportanceRule[]\n }\n sidebar: {\n pins_max: number\n /** Page titles the owner pinned, in order. */\n pins: string[]\n }\n /** Rules that give a page a type, tried in order. The first match wins. */\n classify: ClassifyRule[]\n /** Type for pages no rule matches. */\n fallback_type: string\n /** Extra names of the fleet's agents, for agents that run on another\n * node or answer to a persona name (#819). The node's own agent ids,\n * configured names and persona names are found without this. */\n agent_names?: string[]\n}\n\n/** One typed fact about a page: subject (the page) → property → value. */\nexport interface WikiStatement {\n property: string\n /** A page title (becomes a link) or a literal value. */\n value: string\n role?: string\n since?: string\n until?: string\n /** Metric name for readings (disk_used, uptime). */\n metric?: string\n /** When a reading was taken. */\n at?: string\n /** Where it comes from: entry id, document, gazette reference, article. */\n source?: string\n access?: \"public\" | \"shared\" | \"private\"\n status?: \"proposed\" | \"confirmed\"\n confirmed_by?: string\n checked_at?: string\n /** The job that wrote it, e.g. \"wiki-enrich\"; its next run replaces it. */\n by?: string\n note?: string\n}\n"],"mappings":"AAWO,IAAMA,EAA2C,CAAC,QAAS,SAAU,OAAO","names":["IMPORTANCE_LEVELS"]}
@@ -1,4 +1,4 @@
1
- import{c as L}from"./chunk-JRS5QRZG.js";import{a as H}from"./chunk-4LWFJ4MZ.js";import{c as N}from"./chunk-BIJHMWXK.js";import{b as J}from"./chunk-QD6IICK7.js";var X="note:",v=e=>e.startsWith(X);function Ne(e){let t=new Set(e.types),s=new Map;for(let o of H(e.dir).notes)!o.type||!t.has(o.type)||!o.description&&!o.body||J(`${o.description}
1
+ import{c as L}from"./chunk-MWNCS57L.js";import{a as H}from"./chunk-4LWFJ4MZ.js";import{c as N}from"./chunk-BIJHMWXK.js";import{b as J}from"./chunk-QD6IICK7.js";var X="note:",v=e=>e.startsWith(X);function Ne(e){let t=new Set(e.types),s=new Map;for(let o of H(e.dir).notes)!o.type||!t.has(o.type)||!o.description&&!o.body||J(`${o.description}
2
2
  ${o.body}`)||s.set(`${X}${o.file}`,o);let n=[],i=new Map;for(let[o,r]of s)n.push({path:o,title:r.name,type:"note",tags:[r.type],owner:e.owner,lastUpdated:r.checked}),i.set(o,r.description||r.body.split(`
3
3
  `)[0]);return{pool:n,summaries:i,read(o){let r=s.get(o);return r?ie(o,r,e.owner):null}}}function ie(e,t,s){let n=t.checked?`Checked: ${t.checked}`:"Checked: not recorded",i=t.source?`Source: ${t.source}`:"Source: not recorded",o=t.checked??t.updated?.slice(0,10)??"";return{path:e,content:`${i}
4
4
  ${n}
@@ -84,4 +84,4 @@ Question: ${e}
84
84
  ${t.map(n=>`- ${n.line}`).join(`
85
85
  `)}
86
86
  `}async function Qe(e,t,s,n,i){let o={selectorMs:0,planMs:0,liveMs:0,synthesisMs:0,selectorOutput:""},r=(u,y)=>({status:u,basis:"pages",answer:"",picked:[],live:[],liveAsked:0,error:y,trace:o}),a=()=>`${(i.now?.()??new Date).toISOString().slice(0,16).replace("T"," ")} UTC`,c=async u=>{if(!ee(n.live))return r("no-candidates",u);let y=[],x=0;try{let w=Date.now(),C=await te(e,n.live,i.call,i.timeoutMs);if(o.planMs=Date.now()-w,x=C.length,C.length===0)return r("no-candidates",u);w=Date.now(),y=await q(C,n.live,i.fetch),o.liveMs=Date.now()-w}catch(w){return i.log("source search failed:",w?.message),r("no-candidates",u)}let P=y.filter(w=>!w.line.endsWith(W));if(P.length===0)return{...r("no-candidates",`${u} The source search found no issue.`),live:y,liveAsked:x};let B=Date.now();try{let w=await i.call(Me(e,P,a()),n.answerModel,i.timeoutMs*2);return o.synthesisMs=Date.now()-B,{status:"ok",basis:"search",answer:w.trim(),picked:[],live:P,liveAsked:x,trace:o}}catch(w){return o.synthesisMs=Date.now()-B,i.log("answer failed:",w?.message),{status:"error",basis:"search",answer:"",picked:[],live:P,liveAsked:x,error:`Synthesis: ${w?.message||"unknown"}`,trace:o}}},d=t.pool.filter(u=>t.readable.has(u.path)),g=d.filter(u=>!u.path.startsWith("@")&&!v(u.path)),m=d.filter(u=>u.path.startsWith("@")),l=d.filter(u=>v(u.path)),h=[...M(e,g,s,n.candidates).map(u=>g[u]),...M(e,l,s,n.noteCandidates).map(u=>l[u]),...M(e,m,s,n.sharedCandidates).map(u=>m[u])];if(h.length===0)return c("No page shares a word with the question.");let p=Date.now(),R;try{o.selectorOutput=await i.call(Le(e,h,s,n.maxPages),n.navigatorModel,i.timeoutMs),R=Ae(o.selectorOutput,h.length,n.maxPages)}catch(u){return i.log("navigator failed:",u?.message),r("error",`Selector: ${u?.message||"unknown"}`)}finally{o.selectorMs=Date.now()-p}let $=[];for(let u of R){let y=t.read(h[u].path);y&&$.push({...y,hop:0})}if($.length===0)return c("No page was picked for the question.");let V=xe(e,$,t,s,n),Y=Pe([...$,...V],s,n.pageChars);$.push(...V.map(({chars:u,...y})=>y));let A=[],E=0;if(U(n.live))try{p=Date.now();let u=await ne(e,Y,n.live,i.call,i.timeoutMs);o.planMs=Date.now()-p,E=u.length,p=Date.now(),A=await q(u,n.live,i.fetch),o.liveMs=Date.now()-p}catch(u){i.log("live read failed:",u?.message)}p=Date.now();try{let u=await i.call(_e(e,Y,A,a(),$.some(y=>v(y.path))),n.answerModel,i.timeoutMs*2);return o.synthesisMs=Date.now()-p,{status:"ok",basis:"pages",answer:u.trim(),picked:$,live:A,liveAsked:E,trace:o}}catch(u){return o.synthesisMs=Date.now()-p,i.log("answer failed:",u?.message),{status:"error",basis:"pages",answer:"",picked:$,live:A,liveAsked:E,error:`Synthesis: ${u?.message||"unknown"}`,trace:o}}}export{v as a,Ne as b,Ie as c,Fe as d,Qe as e};
87
- //# sourceMappingURL=chunk-YA3P77LV.js.map
87
+ //# sourceMappingURL=chunk-SKSYII3K.js.map
@@ -1,4 +1,4 @@
1
- import{a as h}from"./chunk-NY7NHGVT.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
1
+ import{a as h}from"./chunk-MUVE3UAS.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
2
2
  `),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
3
3
  `),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
4
- //# sourceMappingURL=chunk-6WF56ME6.js.map
4
+ //# sourceMappingURL=chunk-SN7YH4E4.js.map
@@ -1,4 +1,4 @@
1
- import{c as w}from"./chunk-ZFRXFUP7.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
1
+ import{c as w}from"./chunk-UTW56K5I.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
2
2
  ${a.content}`),t.previous??""].join(`
3
3
  `),l=u.toLowerCase(),d=$(u),p=new Set(d.urls.map(y)),g=new Set(d.numbers),n=$(t.content),c=[];for(let a of n.commits)j(l,a,d.commits)||c.push(`commit ${a}`);for(let a of n.urls)!p.has(y(a))&&!l.includes(y(a))&&c.push(`link ${a}`);for(let a of n.numbers)/^\d{1,2}$/.test(a)||!g.has(a)&&!l.includes(a)&&c.push(`number ${a}`);let h=[];for(let a of s){let m=$(a.content);if(m.commits.length===0&&m.urls.length===0)continue;let v=o(a.id),S=(v.length>0?v:[t.content]).join(`
4
4
  `).toLowerCase(),x=$(S);for(let b of m.commits)j(S,b,x.commits)||h.push({entry:a.id,fact:`commit ${b}`});for(let b of m.urls)S.includes(y(b))||h.push({entry:a.id,fact:`link ${b}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:i,weakSources:e,ungrounded:c,lost:h}}function U(t,r){let o=r.toLowerCase(),s=w(r).commits,i=[];for(let e of t){let u=w(e.content),l=[...u.commits.filter(d=>!j(o,d,s)).map(d=>`commit ${d}`),...u.urls.filter(d=>!o.includes(y(d))).map(d=>`link ${d}`)];l.length>0&&i.push({entry:e.id,facts:l})}return i}var P=new Set("the and for with from into of on in at to by an a".split(" "));function L(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!P.has(r)&&!R.has(r)))}function M(t,r){if(t.size===0||r.size===0)return 0;let o=0;for(let s of t)r.has(s)&&o++;return o/(t.size+r.size-o)}function D(t,r,o={}){let s=o.titleMin??.75,i=o.sourcesMin??.5,e=t.map(l=>({...l,tt:L(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let d=l+1;d<e.length;d++){let p=e[l],g=e[d];if(r&&!r.has(p.path)&&!r.has(g.path))continue;let n=(p.type??"")===(g.type??"")?M(p.tt,g.tt):0;if(n>=s){u.push({a:p.path,b:g.path,reason:"title",score:n});continue}if(p.ss.size>=2&&g.ss.size>=2){let c=M(p.ss,g.ss);c>=i&&u.push({a:p.path,b:g.path,reason:"sources",score:c})}}return u.sort((l,d)=>d.score-l.score||l.a.localeCompare(d.a))}var A=4e3;function J(t,r){let o=r.map(i=>{let e=i.content.length>A?`${i.content.slice(0,A)}
@@ -33,4 +33,4 @@ Reply with JSON only, no fencing:
33
33
  {"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function z(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=l=>Array.isArray(l)?l.map(d=>String(d)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,i=s(r.claims);if(Number.isNaN(i))return null;let e=Math.min(i,Number.isNaN(s(r.supported))?i-o(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:i,supported:Math.max(0,e),unsupported:o(r.unsupported),contradicted:o(r.contradicted),offSubject:o(r.off_subject??r.offSubject),missing:o(r.missing),verdict:u}:null}function I(t,r,o,s=[],i=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,d=new Set;for(let n of t)for(let c of n.lost)l.add(c.entry),d.add(`${c.entry}|${c.fact}`);let p=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(c=>c.path===n))),g={sample:{articles:t.length,seed:o.seed,since:o.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,c)=>n+c.missingSources.length,0),weakSources:t.reduce((n,c)=>n+c.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,c)=>n+c.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:d.size},duplicates:{pairs:r.length,articlesInPair:p.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,i).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(c=>({path:n.path,...c}))).slice(0,i),weak:t.filter(n=>n.weakSources.length>0).slice(0,i).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,i),uncited:(e?.lost??[]).slice(0,i).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,i).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(a=>a.verdict),c=n.reduce((a,m)=>a+m.claims,0),h=n.reduce((a,m)=>a+m.supported,0);g.judge={judged:n.length,claims:c,supported:h,supportRate:c>0?h/c:1,unsupported:n.reduce((a,m)=>a+m.unsupported.length,0),contradicted:n.reduce((a,m)=>a+m.contradicted.length,0),articlesWithWrongMerge:n.filter(a=>a.offSubject.length>0).length,missingFacts:n.reduce((a,m)=>a+m.missing.length,0),verdicts:{good:n.filter(a=>a.verdict==="good").length,minor:n.filter(a=>a.verdict==="minor").length,major:n.filter(a=>a.verdict==="major").length}}}return g}var f=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function O(t){let r=t.sample.articles,o=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${f(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(W*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${f(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${f(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${f(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&o.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;o.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${f(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${f(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,i=(e,u)=>{u.length!==0&&o.push("",`## ${e}`,"",...u)};return i("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),i("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),i("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),i("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),i("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),i("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),o.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),o.join(`
34
34
  `)+`
35
35
  `}function V(t){if(!t||typeof t!="object")return{};let r=t,o=r.usage??{},s=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(o.input_tokens),outputTokens:s(o.output_tokens),cacheReadTokens:s(o.cache_read_input_tokens),cacheWriteTokens:s(o.cache_creation_input_tokens)}}function C(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function Y(t){let r=new Map,o=i=>{let e=i||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let i of t)i.kind==="call"?o(i.label).calls.push(i):i.kind==="run"&&o(i.label).runs.push(i);let s=[];for(let[i,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,c)=>n-c),d;if(u.length>0)d=u.reduce((n,c)=>n+(Date.parse(c.endedAt)-Date.parse(c.startedAt)),0);else{let n=e.map(h=>Date.parse(h.at)-h.wallMs),c=e.map(h=>Date.parse(h.at));d=Math.max(...c)-Math.min(...n)}let p=e.reduce((n,c)=>n+c.entries,0),g=e.reduce((n,c)=>n+(c.costUsd??0),0);s.push({label:i,calls:e.length,failed:e.filter(n=>n.failed).length,entries:p,articles:e.reduce((n,c)=>n+c.articles,0),refused:e.reduce((n,c)=>n+c.refused,0),heldCited:e.reduce((n,c)=>n+(c.heldCited??0),0),wallMs:d,callMsP50:C(l,.5),callMsP95:C(l,.95),prepMs:e.reduce((n,c)=>n+(c.prepMs??0),0),costUsd:g,costPerEntry:p>0?g/p:0,entriesPerMinute:d>0?p/d*6e4:0,promptChars:e.reduce((n,c)=>n+c.promptChars,0)})}return s.sort((i,e)=>i.label.localeCompare(e.label))}export{T as a,_ as b,k as c,E as d,W as e,N as f,U as g,D as h,A as i,J as j,z as k,I as l,O as m,V as n,Y as o};
36
- //# sourceMappingURL=chunk-RVEMX5MJ.js.map
36
+ //# sourceMappingURL=chunk-TTG3ZW3W.js.map
@@ -1,4 +1,4 @@
1
- import{c as g}from"./chunk-WWDYDLY2.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
1
+ import{e as g}from"./chunk-32LIPTHM.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
2
2
  `)}).join(`
3
3
 
4
4
  ---
@@ -14,4 +14,4 @@ These ${e.length} articles were found by searching the wiki for each entry below
14
14
 
15
15
  ${i}
16
16
  `}var d=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,y=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,w=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,k=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,C=/^\s*\d+[.)]\s/gm;function A(e){let i=[...e.matchAll(d)].map(s=>s[0].replace(/[.,;:!?'"]+$/,"")),r=[...e.matchAll(y)].map(s=>s[1].trim()),n=e.replace(d," ").replace(y," ").replace(C," "),o=[...n.matchAll(w)].map(s=>s[0].toLowerCase()),c=[...n.replace(w," ").matchAll(k)].map(s=>v(s[0]));return{commits:m(o),urls:m(i),wikilinks:m(r),numbers:m(c)}}function R(e,i){let r=A(e),n=A(i),o=i.toLowerCase(),a=[];for(let t of r.commits)!o.includes(t)&&!n.commits.some(l=>l.startsWith(t)||t.startsWith(l))&&a.push(`commit ${t}`);let c=t=>t.toLowerCase().replace(/\/+$/,""),s=new Set(n.urls.map(c));for(let t of r.urls)s.has(c(t))||a.push(`link ${t}`);let f=new Set(n.wikilinks.map(t=>t.toLowerCase()));for(let t of r.wikilinks)f.has(t.toLowerCase())||a.push(`link [[${t}]]`);let h=new Set(n.numbers);for(let t of r.numbers)h.has(t)||a.push(`number ${t}`);return a}function v(e){return/^\d{1,3}(,\d{3})+$/.test(e)?e.replace(/,/g,""):e}function m(e){return[...new Set(e)]}function L(e,i){if(i.some(n=>n.path===e.path))return e.path;let r=b(e.title);return r?i.find(n=>b(n.title)===r)?.path??e.path:e.path}function b(e){return(e||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}export{$ as a,x as b,A as c,R as d,L as e};
17
- //# sourceMappingURL=chunk-ZFRXFUP7.js.map
17
+ //# sourceMappingURL=chunk-UTW56K5I.js.map
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-LZLIPP7N.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-VXK36CCL.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-H6VWU2HN.js.map
126
+ //# sourceMappingURL=chunk-UXOGNBGL.js.map
@@ -1,4 +1,4 @@
1
- import{$ as $r,H as mr,I as hr,J as yr,L as wr,M as br,N as xr,O as Ir,R as Sr,S as Tr,V as kr,W as vr,a as Zs,b as er,ba as Ar,d as nr,f as ze,l as kt,m as pr,t as vt,v as fr}from"./chunk-QDWEM4DG.js";import{a as Vs}from"./chunk-QSKG754X.js";import{b as tr}from"./chunk-MEFPXHQJ.js";import{a as gr}from"./chunk-W4YR2RO2.js";import{b as rr,c as pn,d as ir,e as Tt,h as ar}from"./chunk-SSQMFHSM.js";import{e as Xs,f as Ys}from"./chunk-36AXN6ZB.js";import{a as ln,b as sr}from"./chunk-J3SOEFRE.js";import{a as gn,b as or}from"./chunk-SIU6STB2.js";import{e as dr,i as cr,j as ur,k as lr}from"./chunk-X5C5W3E4.js";import{a as zs}from"./chunk-6WF56ME6.js";import{g as Js,h as Qs}from"./chunk-ERULJ2ZL.js";import{c as Ns,f as Ls}from"./chunk-K445URSN.js";import{s as Ds,v as St,w as Os,y as ye,z as un}from"./chunk-4XMALK7X.js";import{a as Qe,b as Ee,f as It}from"./chunk-72SZI2UW.js";import{a as _e,b as rn}from"./chunk-FCPTN6NF.js";import{a as Fs,c as Us}from"./chunk-MYVHVJWZ.js";import{d as De,h as Ae}from"./chunk-6TURWSMN.js";import{a as Hs,b as Bs,c as js,d as Ws,l as qs}from"./chunk-AV7T3SYT.js";import{a as Gs,b as Ks}from"./chunk-Y5MFVVTM.js";import{c as Ss,d as Ts}from"./chunk-QOYAX2FT.js";import{e as $e}from"./chunk-DSYKYZMT.js";import{D as As,F as dn,H as ka,K as Cs,O as va,U as Ms,V as cn,W as Ps,X as Je,Y as Rs,Z as _s,da as Es,xa as $a}from"./chunk-DYGQF3MI.js";import{g as Ke,h as Sa}from"./chunk-BRK6M6LA.js";import{f as an,n as Ta}from"./chunk-UIBUZ2N3.js";import{a as ks,b as le,c as vs,d as $s,e as on}from"./chunk-2QNT5JDS.js";un();It();var $t="tool-set",Cr=["answer","code","full"],Mr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Aa=.1;function Rr(n){return{task:Pr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Pr(n.agentPrompt,600)}:{}}}var _r={bundle:Ee({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Er(n,e=Aa){let s=n?.bundle?.probabilities;if(!s)return"full";let r=fn(s.answer),o=fn(s.code),i=fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Dr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Mr.answer.includes(t))?"answer":e.every(t=>Mr.code.includes(t))?"code":"full"}function Or(n,e){return Cr.indexOf(n)<Cr.indexOf(e)}function fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Pr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Nr=!1;function Lr(n,e){let t=St($t);if(t!=="off")return t==="active"&&!Nr&&(Nr=!0,e(`[decisions] seat "${$t}" is set to active, but only shadow is built: it records and changes nothing`)),ye($t,Rr(n),_r,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Er(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Fr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Dr(r);Os(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Or(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Ca(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Ur(n,e){let t=Ca(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function mn(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}un();It();var Hr="session-continuity",Br={continues:Qe("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:Qe("Does the new request refer to something stated earlier in the conversation?")};function jr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:hn(n.message,1200),previousRequest:n.previousMessage?hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Wr(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ot}from"execa";import{spawn as Ma}from"node:child_process";import{createHash as Pa}from"node:crypto";import{createInterface as Ra}from"node:readline";var we=class extends Error{},_a=n=>Ma("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),yn=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(),Ra({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{$ as $r,H as mr,I as hr,J as yr,L as wr,M as br,N as xr,O as Ir,R as Sr,S as Tr,V as kr,W as vr,a as Zs,b as er,ba as Ar,d as nr,f as ze,l as kt,m as pr,t as vt,v as fr}from"./chunk-QDWEM4DG.js";import{a as Vs}from"./chunk-QSKG754X.js";import{b as tr}from"./chunk-MEFPXHQJ.js";import{a as gr}from"./chunk-W4YR2RO2.js";import{b as rr,c as pn,d as ir,e as Tt,h as ar}from"./chunk-SSQMFHSM.js";import{e as Xs,f as Ys}from"./chunk-36AXN6ZB.js";import{a as ln,b as sr}from"./chunk-J3SOEFRE.js";import{a as gn,b as or}from"./chunk-SIU6STB2.js";import{e as dr,i as cr,j as ur,k as lr}from"./chunk-X5C5W3E4.js";import{a as zs}from"./chunk-SN7YH4E4.js";import{g as Js,h as Qs}from"./chunk-ERULJ2ZL.js";import{c as Ns,f as Ls}from"./chunk-K445URSN.js";import{s as Ds,v as St,w as Os,y as ye,z as un}from"./chunk-4XMALK7X.js";import{a as Qe,b as Ee,f as It}from"./chunk-72SZI2UW.js";import{a as _e,b as rn}from"./chunk-FCPTN6NF.js";import{a as Fs,c as Us}from"./chunk-MYVHVJWZ.js";import{d as De,h as Ae}from"./chunk-6TURWSMN.js";import{a as Hs,b as Bs,c as js,d as Ws,l as qs}from"./chunk-AV7T3SYT.js";import{a as Gs,b as Ks}from"./chunk-Y5MFVVTM.js";import{c as Ss,d as Ts}from"./chunk-QOYAX2FT.js";import{e as $e}from"./chunk-DSYKYZMT.js";import{D as As,F as dn,H as ka,K as Cs,O as va,U as Ms,V as cn,W as Ps,X as Je,Y as Rs,Z as _s,da as Es,xa as $a}from"./chunk-DYGQF3MI.js";import{g as Ke,h as Sa}from"./chunk-BRK6M6LA.js";import{f as an,n as Ta}from"./chunk-UIBUZ2N3.js";import{a as ks,b as le,c as vs,d as $s,e as on}from"./chunk-2QNT5JDS.js";un();It();var $t="tool-set",Cr=["answer","code","full"],Mr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Aa=.1;function Rr(n){return{task:Pr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Pr(n.agentPrompt,600)}:{}}}var _r={bundle:Ee({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Er(n,e=Aa){let s=n?.bundle?.probabilities;if(!s)return"full";let r=fn(s.answer),o=fn(s.code),i=fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Dr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Mr.answer.includes(t))?"answer":e.every(t=>Mr.code.includes(t))?"code":"full"}function Or(n,e){return Cr.indexOf(n)<Cr.indexOf(e)}function fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Pr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Nr=!1;function Lr(n,e){let t=St($t);if(t!=="off")return t==="active"&&!Nr&&(Nr=!0,e(`[decisions] seat "${$t}" is set to active, but only shadow is built: it records and changes nothing`)),ye($t,Rr(n),_r,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Er(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Fr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Dr(r);Os(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Or(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Ca(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Ur(n,e){let t=Ca(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function mn(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}un();It();var Hr="session-continuity",Br={continues:Qe("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:Qe("Does the new request refer to something stated earlier in the conversation?")};function jr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:hn(n.message,1200),previousRequest:n.previousMessage?hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Wr(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ot}from"execa";import{spawn as Ma}from"node:child_process";import{createHash as Pa}from"node:crypto";import{createInterface as Ra}from"node:readline";var we=class extends Error{},_a=n=>Ma("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),yn=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(),Ra({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 s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},wn=class{constructor(e=_a,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}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 s=Pa("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[P])=>w.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new we("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let w=[...this.entries].find(([,P])=>!P.connection.busy);if(!w)throw new we("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:s,connection:new yn(e,this.launchProcess)}}catch{throw new we("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,g,m,h=!1,p=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",p,{once:!0});let x=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),S=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let w={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(S),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let _=new Promise((L,M)=>{i.failTurn=M,i.notify=(D,U)=>{if(U?.threadId!==u)return;let N=U.item,q={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...U,type:D.replace("/","."),...N?{item:{...N,type:q[N.type]||N.type}}:{}}),D==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),D==="item/agentMessage/delta"&&(h||(h=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=U.delta,e.onDelta?.(U.delta,c)),D==="thread/tokenUsage/updated"){let H=U.tokenUsage.last;m=H.inputTokens;let K=H.cachedInputTokens||0;g={inputTokens:(g?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-K),outputTokens:(g?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(g?.cacheReadTokens||0)+K,cacheCreateTokens:(g?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}D==="turn/completed"&&(U.turn.status==="completed"?L():M(new Error(U.turn.error?.message||`Codex turn ${U.turn.status}`)))}});return _.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await _,{content:d??c,codexSessionId:u,billedModel:e.model,usage:g,contextTokens:m,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new we(w.message);return{content:c,codexSessionId:u,usage:g,contextTokens:m,error:w.message,duration:Date.now()-t}}finally{clearTimeout(S),clearTimeout(x),e.signal?.removeEventListener("abort",p),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())}}},qr=new wn;import{execFile as Za}from"child_process";import{StringDecoder as et}from"string_decoder";import{mkdtempSync as co,readFileSync as uo,rmSync as lo}from"fs";import{join as Et}from"path";import{tmpdir as go}from"os";function At(n){let e=(n||"").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 d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[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]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Ct(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Mt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var Gr=null;function Pt(){return Gr}function fl(n){Gr=n}function Xe(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function Ea(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var Oe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},Kr=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 s=Xe(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Ea(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${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 Oe(`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 Oe(`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(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Xe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Xe(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Xe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=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<s&&(s=i,t=o)}if(!t)return!1;let r=Xe(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,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.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),s.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(s.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Da}from"child_process";import{randomUUID as Oa}from"crypto";import{existsSync as Na,readFileSync as La}from"fs";import{resolve as Fa}from"path";function Ua(n){let e=Fa(n,"CLAUDE.md");if(!Na(e))return null;try{let t=La(e,"utf8");return qs(t)}catch{return null}}var Ha=20*60*1e3,Ba=5e3,Ye=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ve=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function ja(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var Jr=class{constructor(e={}){this.opts=e}spawn(e,t){return new bn(e,t,this.opts)}},bn=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=Da(r,o,{cwd:t.workspace,env:Ae(ja({...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:Ua(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(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;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(h=>{t=h}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),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=Oa(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
3
3
  `);let c=e.deadlineMs??Ha,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new Ye(c)),g=!1,m=null;try{for(;;){let h=d-Date.now();if(h<=0)throw u();let p=await this.nextEvent(h);if(p===null&&this.killReason)throw new Ve(this.killReason);if(p===null&&!this.exited)throw u();if(p===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!g){if(p.type==="user"&&p.uuid===i)g=!0,m&&(yield{type:m.type,raw:m});else if(p.type==="system"&&p.subtype==="init")m=p;else if(p.type==="result"){m=null;let x=typeof p.result=="string"?p.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${x.length} chars): ${x.slice(0,120)}`)}continue}if(yield{type:p.type,raw:p},p.type==="result"){this.onResultEvent(p);return}}}finally{let h=this.snap.state==="busy";this.snap={...this.snap,...h?{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 s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Ba);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];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),e.extraArgs&&t.push(...e.extraArgs),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 s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}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 s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=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:s,state:"idle"}}};on();Ta();rn();import{resolve as Qr,join as zr}from"path";var Wa=4e3;function Rt(n){try{let e=zr(Qr(n.root),".agentx","db.sqlite"),t=an({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=_e(),r=n.input.command?n.input.command.slice(0,Wa):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -31,7 +31,7 @@ ${n}`}function td(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
31
31
  `,g)}};L.stdout?.on("data",T=>{N+=H.write(T);let b=N.split(`
32
32
  `);N=b.pop()||"";for(let O of b)X(O)}),L.stderr?.on("data",T=>{q+=K.write(T)});let A=await L;if(i&&i.removeEventListener("abort",U),N+=H.end(),N.trim()&&X(N),q+=K.end(),M)return{content:"",error:D||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if(A.exitCode!==0||p){let T=A,b;return T.timedOut?b=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?b=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+q)?b=oo():b=q.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...V(b),duration:Date.now()-c,usage:m,opencodeSessionId:h}}return S=!1,{content:g.trim(),duration:Date.now()-c,usage:m,billedModel:e.model||n.model,opencodeSessionId:h}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(P?.message||"")?oo():P?.message;return{content:g,...V(_||"OpenCode failed"),duration:Date.now()-c,usage:m,opencodeSessionId:h}}finally{w?.(),x?.release(S)}}async function gd(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=xe(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function pd(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),g=new AbortController,m=!1,h=()=>{let S=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{g.abort(new Error(S))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let p=setTimeout(()=>{m=!0;try{g.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);p.unref?.();let x=()=>({content:"",...V(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let S=n.provider||"claude-code",w=s?`${s}
33
33
 
34
- ${e.message}`:e.message,P=e.context?.sender,_=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),L=e.context?.channel==="web-chat"&&_?{userId:P,agentId:e.agentId||"acme-public"}:void 0,M=Ws(n),D=Object.keys(M).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:L,providerOpts:o,abortSignal:g.signal,mcpServers:D?M:void 0};if(r){let{generateStream:X}=await import("./agent-3R5NY7I3.js"),A="",T,b,O,B;for await(let C of X(U)){if(c)try{c(C)}catch{}if(C.type==="text_delta")A+=C.text,r(C.text,A);else if(C.type==="thinking_delta")C.text&&i&&i(C.text);else if(C.type==="generate_result"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}T=C.result.tokensUsed,C.result.inputTokens!=null&&(b=C.result.inputTokens),C.result.outputTokens!=null&&(O=C.result.outputTokens)}else if(C.type==="done"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}C.result.tokensUsed!=null&&(T=C.result.tokensUsed)}else C.type==="error"&&(B=C.error)}return B&&!A?m?x():B==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${B}`),duration:Date.now()-d}:((b===void 0||O===void 0)&&T&&(b=Math.round(T*.7),O=T-b),{content:A||"Done.",tokensUsed:T,usage:b!==void 0||O!==void 0?{inputTokens:b||0,outputTokens:O||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:N}=await import("./agent-3R5NY7I3.js"),q=await N(U),H=q.inputTokens,K=q.outputTokens;if((H===void 0||K===void 0)&&q.tokensUsed){let X=q.tokensUsed;H=Math.round(X*.7),K=X-H}return{content:q.content||"Done.",tokensUsed:q.tokensUsed,usage:H!==void 0||K!==void 0?{inputTokens:H||0,outputTokens:K||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(S){return m?x():S?.message==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${S.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var In=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},fd=1e3;async function md(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),fd),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function hd(n,e,t,s,r,o,i){let a=Pt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Lt(e.context),g={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(g,"freshSession=true")}catch{}let m,h=!1;try{let A=a.list().length;m=a.acquire(g,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>A}catch(A){return A instanceof Oe,null}h&&vn(e.agentId,n,e.model,s,"persistent");let p=xe(n,e,t),x="",S,w,P,_,L,M,D,U="",N="",q=A=>{if(!i||!A)return;let T;if(N&&A.startsWith(N)?T=A.slice(N.length):T=U&&!U.endsWith(`
34
+ ${e.message}`:e.message,P=e.context?.sender,_=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),L=e.context?.channel==="web-chat"&&_?{userId:P,agentId:e.agentId||"acme-public"}:void 0,M=Ws(n),D=Object.keys(M).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:L,providerOpts:o,abortSignal:g.signal,mcpServers:D?M:void 0};if(r){let{generateStream:X}=await import("./agent-DRUIMWF5.js"),A="",T,b,O,B;for await(let C of X(U)){if(c)try{c(C)}catch{}if(C.type==="text_delta")A+=C.text,r(C.text,A);else if(C.type==="thinking_delta")C.text&&i&&i(C.text);else if(C.type==="generate_result"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}T=C.result.tokensUsed,C.result.inputTokens!=null&&(b=C.result.inputTokens),C.result.outputTokens!=null&&(O=C.result.outputTokens)}else if(C.type==="done"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}C.result.tokensUsed!=null&&(T=C.result.tokensUsed)}else C.type==="error"&&(B=C.error)}return B&&!A?m?x():B==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${B}`),duration:Date.now()-d}:((b===void 0||O===void 0)&&T&&(b=Math.round(T*.7),O=T-b),{content:A||"Done.",tokensUsed:T,usage:b!==void 0||O!==void 0?{inputTokens:b||0,outputTokens:O||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:N}=await import("./agent-DRUIMWF5.js"),q=await N(U),H=q.inputTokens,K=q.outputTokens;if((H===void 0||K===void 0)&&q.tokensUsed){let X=q.tokensUsed;H=Math.round(X*.7),K=X-H}return{content:q.content||"Done.",tokensUsed:q.tokensUsed,usage:H!==void 0||K!==void 0?{inputTokens:H||0,outputTokens:K||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(S){return m?x():S?.message==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${S.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var In=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},fd=1e3;async function md(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),fd),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function hd(n,e,t,s,r,o,i){let a=Pt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Lt(e.context),g={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(g,"freshSession=true")}catch{}let m,h=!1;try{let A=a.list().length;m=a.acquire(g,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>A}catch(A){return A instanceof Oe,null}h&&vn(e.agentId,n,e.model,s,"persistent");let p=xe(n,e,t),x="",S,w,P,_,L,M,D,U="",N="",q=A=>{if(!i||!A)return;let T;if(N&&A.startsWith(N)?T=A.slice(N.length):T=U&&!U.endsWith(`
35
35
  `)?`
36
36
 
37
37
  ${A}`:A,N=A,!!T){U+=T;try{i(T,U)}catch{}}},H=!1,K=()=>{H=!0,a.kill(g,"operator-cancel").catch(()=>{})};o&&(o.aborted?K():o.addEventListener("abort",K,{once:!0}));let X=!1;try{let A=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of m.runTurn({message:p,taskId:e.taskId??"unknown",deadlineMs:A})){if(X=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let b=T.raw.message?.content??[];for(let B of b)B.type==="text"&&typeof B.text=="string"?(x=B.text,q(B.text)):B.type==="tool_use"&&(N="");let O=T.raw.message?.usage;if(O){let B=(O.input_tokens||0)+(O.cache_read_input_tokens||0)+(O.cache_creation_input_tokens||0);B>0&&(_=B)}}if(T.type==="result"){let b=T.raw;if(b.is_error){let O=V(typeof b.result=="string"?b.result:"claude error");S=O.error,w=O.errorKind}else typeof b.result=="string"&&b.result.length>0&&(x=b.result,U||q(b.result));typeof b.session_id=="string"&&(D=b.session_id),b.usage&&(P={inputTokens:b.usage.input_tokens||0,outputTokens:b.usage.output_tokens||0,cacheReadTokens:b.usage.cache_read_input_tokens||0,cacheCreateTokens:b.usage.cache_creation_input_tokens||0}),typeof b.num_turns=="number"&&(L=b.num_turns),typeof b.message?.model=="string"?M=b.message.model:typeof b.model=="string"?M=b.model:M=Mt(b.modelUsage)||M}}}catch(A){if(H)S="task cancelled by operator",w="cancelled";else if(X)if(A instanceof Ve)S=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,w="interrupted";else if(A instanceof Ye){let T=V(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);S=T.error,w=T.errorKind}else{let T=V(`persistent claude process error: ${A?.message||String(A)}`);S=T.error,w=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(g,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",K),null}finally{o&&o.removeEventListener("abort",K)}return H&&!S&&(S="task cancelled by operator",w="cancelled"),{content:H?"":x,error:S,errorKind:w,duration:Date.now()-c,usage:P,contextTokens:_,numTurns:L,billedModel:M,claudeSessionId:D}}function Io(n){let e=le(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?Vr(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:so(t.args,n.taskId,n.agentId)}function yd(n){return le(n.autonomy)||!!n.personLimits}async function wd(n,e,t,s,r,o,i){let a=le(e.autonomy)?e.autonomy:void 0,c=a&&Zr(a,n.tier)||e.personLimits&&ro(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${$s(a)}
@@ -157,4 +157,4 @@ ${ve}`),f+=ve.length}catch{}}}let ya=Vt.length>0?Vt.join(`
157
157
 
158
158
  Agent: ${$.content}`,meta:Ku(ee,e.context)})}catch{}Ks(e.agentId,e.message,$.content,{channel:y,chatId:I,sender:zt},this.memoryStore).catch(()=>{}),No(e.agentId,e.message,$.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=$.billedModel||e.model||d.def.model,he=e.context?.channel,bt=he&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${he}:${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,J,he,bt),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${O()}`)}return $}catch(l){d.errors++,this.log(`[${e.agentId}] unexpected error: ${l.message}`);let f=At(l.message);return re={content:"",error:Ct(f),errorKind:f.kind},re}finally{if(xs.stop(),Is&&ae&&Te)try{let l=re?.usage,f=Sr(Te,ae,{error:re?re.error||void 0:S.signal.aborted?Re(S.signal).message:"run ended before completion",canceled:Tr(re?.errorKind)||this.stoppedRuns.has(p.id)||this.interruptedRuns.has(p.id)||!re&&S.signal.aborted,durationMs:Date.now()-p.startedAt.getTime(),...l?{inputTokens:l.inputTokens,outputTokens:l.outputTokens}:{},readOnly:nn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(l){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${l?.message||l}`)}se(re),Kn(re)}}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:this.withWorkflowSteps(e.runningTasks),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:kr(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=Q(process.cwd(),je,this.safe(e.agentId),t);de(s)||Ou(s,{recursive:!0});let r=Q(s,`${this.safe(e.id)}.json`);Lu(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=Q(process.cwd(),je,this.safe(e));if(!de(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let g of[d,c]){let m=Q(a,g);if(de(m))try{for(let h of ge(m)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],x=parseInt(p,10);if(!Number.isFinite(x)||x<i||x>s)continue;let S=Math.floor((s-x)/36e5),w=t-1-S;w>=0&&w<t&&o[w]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=Q(process.cwd(),je);if(!de(e))return 0;let t=0;for(let s of ge(e)){let r=Q(e,s),o;try{o=ge(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=Q(r,i),c;try{c=ge(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(it(Q(a,d),"utf-8")),g=(u.responseText||u.error||"").trim();if(!g)continue;let m=g.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:m,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Gu){let t=Q(process.cwd(),je);if(!de(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ge(t)){let i=Q(t,o),a;try{a=ge(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Nu(Q(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=Q(process.cwd(),je,this.safe(e));if(!de(s))return[];let r=ge(s).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=Q(s,i),c;try{c=ge(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(it(Q(a,d),"utf-8")),{transcript:g,responseText:m,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=Q(process.cwd(),je,this.safe(e));if(!de(s))return null;let r=this.safe(t),o=ge(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=Q(s,i,`${r}.json`);if(de(a))try{return JSON.parse(it(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=gr();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||ze(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Lt(a);return c.channel===t.channel&&c.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,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let r=[...this.taskAborts].filter(([,o])=>o.agentId===e.agentId&&o.channel===e.channel&&o.chatId===e.chatId).map(([o])=>o);t=r.length===1?r[0]:void 0}let s=t?this.taskAborts.get(t):void 0;return!t||!s?null:{taskId:t,traceId:s.traceId,agentId:s.agentId,channel:s.channel,chatId:s.chatId,sender:s.sender,rootId:s.rootId,originalMessage:s.originalMessage,origin:s.origin??null,...s.workflowRunId?{workflowRunId:s.workflowRunId}:{}}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,g=!1;u&&d&&(g=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let m=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:m,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let h=this.messageQueue.pendingCount(i,a,c);Z().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(m).toISOString(),sender:{name:s},humanRoot:!1,person:Ms(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:m});let p=!1;if(r.replace){let x=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(x))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${x}`),p=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${h}${g?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:p,edited:g,pending:h}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,g=m=>{u||(u=!0,d(m))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:m=>g({ok:!0,agentId:e,channel:a,chatId:c,taskId:m,queued:!1})}).then(m=>{ze(m.error)?g({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):m.error?g({ok:!1,status:500,error:m.error||"run did not start"}):g({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:m.viaAttachedSession?"attached":"other"})}).catch(m=>g({ok:!1,status:500,error:m?.message??String(m)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Zu(n,e){return n===!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(`
159
159
  `)}export{qr as a,fl as b,Kr as c,Ua as d,Jr as e,Rt as f,Al as g,Rl as h,_l as i,Ll as j,Lt as k,id as l,bo as m,ld as n,gd as o,pd as p,So as q,Ft as r,Ut as s,Dd as t,lg as u,gg as v,Rn as w,Z as x,Lo as y,qd as z,Qd as A,Ho as B,Mg as C,Bo as D,Go as E,Yo as F,Wg as G,Vo as H,jt as I,Qg as J,zg as K,ot as L,Zc as M,eu as N,tu as O,nu as P,su as Q,Fn as R,Hu as S,Bu as T,Ff as U,Uf as V,Ku as W,Ju as X,zu as Y,Gn as Z,Ji as _,Qi as $,Yu as aa,zi as ba,Xi as ca,Zu as da};
160
- //# sourceMappingURL=chunk-L5UGH4T4.js.map
160
+ //# sourceMappingURL=chunk-WYEWNN76.js.map
@@ -1,6 +1,6 @@
1
- import{d as h}from"./chunk-ZFRXFUP7.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
1
+ import{d as h}from"./chunk-UTW56K5I.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
2
2
  `),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
3
3
  `).filter(o=>o.trim()).length,a=c.split(`
4
4
  `).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
5
5
  `))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
6
- //# sourceMappingURL=chunk-LU7GDHGD.js.map
6
+ //# sourceMappingURL=chunk-ZEAT2B5B.js.map
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-U3HJY7E5.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
2
+ import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-WOQXOAYQ.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
3
3
  //# sourceMappingURL=cli.js.map
@@ -1,4 +1,4 @@
1
- import{a as ee}from"./chunk-LU7GDHGD.js";import"./chunk-ZFRXFUP7.js";import{f as Q,k as V}from"./chunk-QSKG754X.js";import{c as O}from"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import{b as X}from"./chunk-KEXBEUSU.js";import"./chunk-WWDYDLY2.js";import"./chunk-YA3P77LV.js";import"./chunk-ERULJ2ZL.js";import"./chunk-WPNRDEHW.js";import"./chunk-JRS5QRZG.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-4XMALK7X.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DYGQF3MI.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
1
+ import{a as ee}from"./chunk-ZEAT2B5B.js";import"./chunk-UTW56K5I.js";import{f as Q,k as V}from"./chunk-QSKG754X.js";import{c as O}from"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import{b as X}from"./chunk-KEXBEUSU.js";import"./chunk-32LIPTHM.js";import"./chunk-SKSYII3K.js";import"./chunk-ERULJ2ZL.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-4XMALK7X.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DYGQF3MI.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
2
2
  `),se(t,n)}function ie(n){return{agents:E(w(S(n),"state.json"),{agents:{}}).agents??{}}}function ye(n){let r=w(S(n),"pending");return z(r)?re(r).filter(t=>t.endsWith(".json")).sort().map(t=>E(w(r,t),null)).filter(t=>!!t):[]}function G(n){return w(S(n),"held.json")}function K(n,r={}){let t=E(G(n),[]);return r.all?t:t.filter(a=>a.status==="held")}function _e(n){let r=w(S(n),"reports");if(!z(r))return null;let t=re(r).filter(a=>a.endsWith(".json")).sort().pop();return t?E(w(r,t),null):null}function ke(n,r,t,a={}){let o=ie(r).agents[t],c=a.now??Date.now(),e=a.since??o?.lastRunAt??new Date(c-864e5).toISOString(),d=e.slice(0,10),u=new Set(o?.processed??[]),s=[];for(let g of n.getAgentEntries(t))g.date<d||u.has(g.id)||s.push({id:g.id,at:g.date,kind:"chat",title:[g.source,g.sourceContext].filter(Boolean).join(" \xB7 "),text:g.content});if(a.db){let g=Date.parse(e);for(let l of V(a.db,{agentId:t,since:Number.isFinite(g)?g:void 0,limit:500})){if(l.status==="in-flight"||u.has(l.taskId))continue;let k=(Q(a.db,l.taskId)?.steps??[]).filter(b=>b.name==="tool_use"||b.action).slice(0,be).map(b=>`- ${b.action??b.name}${b.inputSummary?` ${x(b.inputSummary,160)}`:""}${b.outputSummary?` \u2192 ${x(b.outputSummary,240)}`:""}${b.error?` \u2717 ${x(b.error,120)}`:""}`),y=[`Request: ${x(l.originalMessage??l.messagePreview??"",600)}`,k.length?`Tool calls:
3
3
  ${k.join(`
4
4
  `)}`:"",l.finalResponse?`Reply: ${x(l.finalResponse,800)}`:""].filter(Boolean).join(`
@@ -54,4 +54,4 @@ _Sources: ${t.sources.join("; ")}._`,a);return n.writeArticle(r,{title:t.title,.
54
54
  `).replace(/\n{3,}/g,`
55
55
 
56
56
  `).trim(),superseded:d}}function Ce(n){let r=n.previous?` (previously: ${n.previous})`:"";return`- **${n.attribute}:** ${n.value} \u2014 ${n.source}; checked ${n.checkedAt.slice(0,10)} by ${n.by}${r}`}function Re(n){let r=n.match(/^- \*\*.+?:\*\* (.*?) — .*?; checked (\S+) by \S+(?: \(previously: (.*)\))?$/);return r?{value:r[1],checkedAt:r[2],...r[3]?{previous:r[3]}:{}}:void 0}function J(n,r){return`contribution:${n}@${r.slice(0,10)}`}var Te={person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"};function de(n,r,t){let a=r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"page",o=t?Te[t]:"contributions",c=`${o}/${a}.md`;for(let e=2;n.readArticle(c);e++)c=`${o}/${a}-${e}.md`;return c}export{_ as DEFAULT_CONTRIBUTION_LIMITS,B as FACTS_HEADING,ue as applyFactLines,De as approveHeld,xe as buildContributionPrompt,S as contributionsDir,_e as latestReport,K as listHeld,ye as listPendingBatches,Be as mergeContributions,W as pageKey,Ae as parseContributionPatches,ke as pendingWork,Se as possibleDuplicate,Fe as rejectHeld,ce as replaceOnce,Me as runContribution};
57
- //# sourceMappingURL=contributions-KLRJ4ZXV.js.map
57
+ //# sourceMappingURL=contributions-ZD6ZGTJR.js.map
@@ -0,0 +1,16 @@
1
+ import{a as Y,k as I,l as M,m as _}from"./chunk-H4NSB54D.js";import{f as G,g as N}from"./chunk-MTX4UPNB.js";import{f as y}from"./chunk-QAWKN2N4.js";import"./chunk-IMLAPB7G.js";import{b as C}from"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QIJLFPWE.js";import{createHash as L}from"crypto";import{existsSync as J,mkdirSync as V,readFileSync as B,writeFileSync as q}from"fs";import{resolve as P}from"path";var D="wiki-enrich",$e=["person","organization","project","place","device","server","app","domain","account"],K=new Set(["person","organization","project","place"]),F=3500,Q=700;function X(e,n){let i=e.ontology.types.find(r=>r.id===n)?.lens??[],t=new Map;for(let r of i)if(N(r)==="statements")for(let s of G(r)){if(s==="related"||t.has(s))continue;let l=e.ontology.properties.find(u=>u.id===s);l?.domain&&!l.domain.includes(n)||t.set(s,l?.label??s.replace(/_/g," "))}return t}function H(e,n,i){let t=y(n.title);return t.length<4?[]:[...e.entities.values()].filter(r=>r.type===i&&r.id!==n.id&&` ${y(r.title)} `.includes(` ${t} `))}function T(e){return e.access==="public"?null:new Set([e.owner,...e.access==="shared"?e.sharedWith??[]:[]])}function Z(e,n){let i=T(e);if(!i)return!0;let t=T(n);return!!t&&[...t].every(r=>i.has(r))}function ee(e,n,i,t){let r=a=>!t||Z(a.article.meta,t.article.meta),s=a=>a.pages.some(r),l=n.pages.filter(r),u=t?[...new Set(l.flatMap(a=>a.article.meta.sources??[]))]:n.sources,p=Y(e,n,null).filter(s),f=a=>[...new Map(a.map(g=>[g.id,g])).values()],w=f([...p.filter(a=>a.type==="event"),...H(e,n,"event").filter(s)]).sort((a,g)=>(g.date||"").localeCompare(a.date||"")).slice(0,30),o=f([...p.filter(a=>a.type==="project"),...H(e,n,"project").filter(s)]).slice(0,12),d=p.filter(a=>a.type!=="event"&&a.type!=="project").filter(s).filter(a=>n.type!=="person"||K.has(a.type)).slice(0,40),v=i(u).sort((a,g)=>g.date.localeCompare(a.date)).slice(0,14),c=X(e,n.type),m=new Map;for(let a of c.keys()){let g=e.ontology.properties.find(h=>h.id===a)?.range;g?.length&&m.set(a,g)}return{entity:n,pages:l,properties:c,ranges:m,neighbours:d,events:w,projects:o,entries:v,sources:u,mentions:te(e,n,12,r)}}function te(e,n,i=12,t=()=>!0){let r=[n.title,...n.pages.flatMap(p=>p.article.meta.aliases??[])].filter(p=>p.trim().length>=3);if(r.length===0)return[];let s=r.map(p=>p.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),l=new RegExp(`(^|[^\\p{L}\\p{N}])(${s.join("|")})(?=$|[^\\p{L}\\p{N}])`,"iu"),u=[];for(let p of e.entities.values())if(!(p.id===n.id||p.type==="event"))for(let f of p.pages){if(!t(f))continue;let w=I(f.article.content),o=l.exec(w);if(!o)continue;let d=Math.max(0,o.index-250);u.push({page:f,excerpt:w.slice(d,o.index+450).replace(/\s+/g," ").trim(),at:f.article.meta.lastUpdated||""});break}return u.sort((p,f)=>f.at.localeCompare(p.at)).slice(0,i).map(({page:p,excerpt:f})=>({page:p,excerpt:f}))}function ne(e){let n=[...e.pages.map(i=>`${i.agentId}/${i.article.path}`),...e.sources,...e.events.map(i=>i.id),...e.projects.map(i=>i.id),...e.mentions.map(i=>`${i.page.agentId}/${i.page.article.path}`)].sort();return L("sha1").update(n.join(`
2
+ `)).digest("hex").slice(0,16)}var O=(e,n)=>e.length>n?`${e.slice(0,n)}\u2026`:e;function se(e,n,i){let t=e.entity,r=[`You are bringing one wiki page up to date. Today is ${i}.`,`Subject: "${t.title}" (${n}).`,"","## What the agents' pages say"];for(let s of e.pages)r.push(`### page ${s.agentId}/${s.article.path} (updated ${s.article.meta.lastUpdated||"?"})`,O(I(s.article.content),F),"");if(e.mentions.length){r.push("## Other pages that name the subject");for(let s of e.mentions)r.push(`### page ${s.page.agentId}/${s.page.article.path}: "${s.page.article.meta.title}"`,s.excerpt,"")}r.push("## Source entries (newest first)");for(let s of e.entries)r.push(`### entry ${s.id} (${s.date}, ${s.agentId}, ${s.source})`,O(s.content.trim(),Q),"");return r.push("## Event pages",...e.events.map(s=>`- ${s.date||"?"} \xB7 ${s.title}`),""),r.push("## Project pages",...e.projects.map(s=>`- ${s.title}`),""),r.push("## Other pages it may name",...e.neighbours.map(s=>`- ${s.title} (${s.type})`),""),r.push(`## Properties you may use (the subject is always ${t.title})`,...[...e.properties].map(([s,l])=>`- ${s}: "${t.title} ${l} <value>"${e.ranges.get(s)?`, value is a ${e.ranges.get(s).join(" or ")}`:""}`),""),r.push("## Task","Return one JSON object and nothing else:",'{"overview": "\u2026", "statements": [{"property": "\u2026", "value": "\u2026", "role": "\u2026", "since": "YYYY-MM-DD", "until": "YYYY-MM-DD", "source": "\u2026"}], "history": ["event page title"], "projects": ["project page title"]}',"","Rules:",`- overview: 3 to 6 full sentences telling the story of the relationship: who ${t.title} is to us, how it started, what changed, and where it stands now, with dates. Plain prose. Link pages as [[Exact Title]] only when the title is listed above. Never stop mid-sentence.`,"- statements: only facts the pages or entries state. Use only the listed properties. value is a listed page title when it names one, else a short literal. role, since and until only when stated.","- source: the entry id, the page (agent/path) or the event title the fact comes from. A statement without one of these is dropped.","- Do not list an AI agent or bot as a person's relation.","- history: titles of the listed event pages that are about the subject. projects: listed project titles it takes part in.","- Leave out anything you could not verify. Do not write 'unknown' or 'not captured' as a fact.","- Write in the language the pages are written in."),r.join(`
3
+ `)}function ie(e){let n=e.match(/```(?:json)?\s*\n([\s\S]*?)\n```/),i=n?n[1]:e.slice(e.indexOf("{"),e.lastIndexOf("}")+1);try{let t=JSON.parse(i);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}var z=/^\d{4}-\d{2}(-\d{2})?$/,E=e=>typeof e=="string"?e.trim():"";function re(e,n,i){let t=[],r=n.entity,s=E(e.overview);if(s&&!/[.!?؟)»"']$/.test(s)){let o=Math.max(s.lastIndexOf(". "),s.lastIndexOf("? "),s.lastIndexOf("! "));s=o>0?s.slice(0,o+1):"",t.push("overview: unfinished last sentence removed")}let l=[...n.entries.map(o=>o.id),...n.pages.map(o=>`${o.agentId}/${o.article.path}`),...n.pages.map(o=>o.article.path),...n.mentions.map(o=>`${o.page.agentId}/${o.page.article.path}`),...n.mentions.map(o=>o.page.article.path),...n.events.map(o=>o.title)],u=[],p=new Set;for(let o of Array.isArray(e.statements)?e.statements:[]){let d=o??{},v=E(d.property),c=E(d.value),m=E(d.source),a=`${v} ${c}`;if(!n.properties.has(v)){t.push(`${a}: property not allowed`);continue}if(!c||/^(unknown|not (given|known|captured|recorded))\b/i.test(c)){t.push(`${a}: no value`);continue}if(!m||!l.some(k=>m.includes(k))){t.push(`${a}: source not among those given`);continue}let g=i.names.get(y(c)),h=g?i.entities.get(g):void 0;if(h?.id===r.id){t.push(`${a}: points at itself`);continue}if(r.type==="person"&&h?.type==="agent"){t.push(`${a}: an agent is not a person's relation`);continue}let j=n.ranges.get(v);if(j&&h&&!j.includes(h.type)){t.push(`${a}: value is a ${h.type}, expected ${j.join(" or ")}`);continue}let A=`${v}
4
+ ${y(c)}`;if(p.has(A))continue;p.add(A);let $={property:v,value:h?.title??c,source:O(m,200)},W=E(d.role);W&&($.role=O(W,80)),z.test(E(d.since))&&($.since=E(d.since)),z.test(E(d.until))&&($.until=E(d.until)),u.push($)}let f=new Map([...n.events,...n.projects].map(o=>[y(o.title),o.title])),w=[];for(let o of[...Array.isArray(e.history)?e.history:[],...Array.isArray(e.projects)?e.projects:[]]){let d=f.get(y(E(o).replace(/^\d{4}-\d{2}-\d{2}\s*·\s*/,"")));d&&!w.includes(d)?w.push(d):!d&&E(o)&&t.push(`link ${E(o)}: no such page`)}return{overview:s,statements:u,links:w,dropped:t}}function oe(e,n){let i=`## Overview
5
+
6
+ ${n.trim()}
7
+
8
+ ${M}
9
+ `,t=_(e);if(t){let r=e.slice(t.end,t.after)===M,s=/^#{1,2}[ \t]/m.test(e.slice(t.end,t.end+4)),u=(r||s&&I(e).length<=F?e.slice(t.after):e.slice(t.textStart)).trim();return`${e.slice(0,t.start)}${i}${u?`
10
+ ${u}
11
+ `:""}`}return`${i}
12
+ ${e.trim()}
13
+ `}function ae(e,n,i){let t=p=>`${p.property}
14
+ ${y(p.value)}`,r=(e.statements??[]).filter(p=>p.by!==D),s=new Set(r.map(t)),l=[...r,...n.statements.filter(p=>!s.has(t(p))).map(p=>({...p,checked_at:i,by:D}))],u=[...new Set([...e.related??[],...n.links])];return{...e,statements:l.length?l:void 0,related:u.length?u:void 0,lastUpdated:i}}function ce(e,n){return n.pages.filter(i=>!e.syncedFrom(i.agentId)).sort((i,t)=>(t.article.meta.sources?.length??0)-(i.article.meta.sources?.length??0)||t.article.content.length-i.article.content.length)[0]}var pe={person:"people",organization:"organizations",project:"projects",place:"places"};function we(e,n,i,t,r){let s=n.replace(/\s+/g," ").trim(),l=e.getAgentWiki(t);if(l.listAllArticles().some(w=>y(w.meta.title)===y(s)))return null;let u=`${pe[i]??`${i}s`}/${y(s).replace(/ /g,"-").slice(0,80)||"page"}.md`,p=C(i)?i:void 0,f={title:s,type:p,class:i,tags:[],owner:t,access:"shared",created:r,lastUpdated:r,sources:[]};return l.writeArticle(u,f,`${s}.
15
+ `,t)?u:null}function ke(e){let n=P(e,"_enrich","state.json");if(!J(n))return{entities:{}};try{let i=JSON.parse(B(n,"utf-8"));return i&&typeof i.entities=="object"?i:{entities:{}}}catch{return{entities:{}}}}function Ee(e,n){V(P(e,"_enrich"),{recursive:!0}),q(P(e,"_enrich","state.json"),JSON.stringify(n,null,2))}async function be(e,n,i,t,r){let s=new Set(t.types),l=new Set(t.only.map(y)),u=c=>c.sources.length+c.pages.length,p=c=>r.entities[c.id]?.failures??0,f=[...n.entities.values()].filter(c=>s.has(c.type)).filter(c=>l.size===0||l.has(y(c.id))||l.has(y(c.title))).sort((c,m)=>p(c)-p(m)||u(m)-u(c)),w=c=>e.getSharedStore().readEntries(c),o={outcomes:[],costUsd:0,capped:!1},d=0,v=(c,m,a,g=!1)=>{if(t.dryRun)return;let h=r.entities[c];r.entities[c]=g?{fingerprint:h?.fingerprint??"",at:new Date().toISOString(),costUsd:a,failures:(h?.failures??0)+1}:{fingerprint:m,at:new Date().toISOString(),costUsd:a},t.save?.(r)};for(let c of f){if(d>=t.max)break;let m={entity:c.id,title:c.title,statements:0,links:0,overview:!1,costUsd:0,dropped:[]},a=ce(e,c);if(!a){o.outcomes.push({...m,status:"no-page"});continue}let g=ee(n,c,w,a),h=ne(g);if(!t.force&&r.entities[c.id]?.fingerprint===h){l.size&&o.outcomes.push({...m,status:"unchanged"});continue}if(o.costUsd>=t.maxCostUsd){o.capped=!0;break}d++;let j=n.ontology.types.find(S=>S.id===c.type)?.label??c.type,A=`${a.agentId}/${a.article.path}`,$;try{$=await i(se(g,j,t.today))}catch(S){o.outcomes.push({...m,page:A,status:"failed",dropped:[S.message.slice(0,200)]}),v(c.id,h,0,!0);continue}o.costUsd+=$.costUsd;let W=ie($.text),k={...m,page:A,status:"no-reply",costUsd:$.costUsd};if(!W){o.outcomes.push(k),v(c.id,h,$.costUsd);continue}let b=re(W,g,n);if(Object.assign(k,{statements:b.statements.length,links:b.links.length,overview:!!b.overview,dropped:b.dropped}),!b.overview&&b.statements.length===0&&b.links.length===0){k.status="nothing-new",o.outcomes.push(k),v(c.id,h,$.costUsd);continue}let U=S=>b.overview?oe(S.content,b.overview):S.content;if(t.dryRun){o.outcomes.push({...k,status:"dry-run",preview:U(a.article),facts:b.statements});continue}let x=e.getAgentWiki(a.agentId),R=x.readArticle(a.article.path);if(!(!!R&&x.writeArticle(a.article.path,ae(R.meta,b,t.today),U(R),R.meta.owner||a.agentId))){k.status="failed",k.dropped.push(R?"write refused":"the page was moved or removed during the run"),o.outcomes.push(k),v(c.id,h,$.costUsd,!0);continue}x.rebuildIndex(),v(c.id,h,$.costUsd),k.status="written",o.outcomes.push(k)}return o}export{D as ENRICH_BY,$e as ENRICH_TYPES,se as buildEnrichPrompt,re as checkEnrichment,we as createEntityPage,ee as enrichContext,ne as fingerprint,X as lensProperties,ke as loadEnrichState,te as mentionsOf,ae as mergedMeta,ie as parseEnrichReply,Z as readableAlongside,be as runEnrich,Ee as saveEnrichState,ce as targetPage,oe as withOverview};
16
+ //# sourceMappingURL=enrich-EFIPWA3P.js.map