agentix-cli 0.52.1 → 0.54.0
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.
- package/dist/{App-X6FGYBLX.js → App-VRTLAPRF.js} +2 -2
- package/dist/{ChatApp-XMUOXQ2M.js → ChatApp-YENWPZT4.js} +2 -2
- package/dist/{agent-KKVMU3VB.js → agent-HVUGHYBF.js} +2 -2
- package/dist/{board-dashboard-KETIFTBD.js → board-dashboard-3XJVYDB3.js} +729 -191
- package/dist/board-dashboard-3XJVYDB3.js.map +1 -0
- package/dist/chunk-2D3RYIDU.js +3 -0
- package/dist/chunk-2D3RYIDU.js.map +1 -0
- package/dist/{chunk-H7R3F2CO.js → chunk-2TJYZF4E.js} +2 -2
- package/dist/chunk-33QV5O6P.js +7 -0
- package/dist/chunk-33QV5O6P.js.map +1 -0
- package/dist/{chunk-MHBUAU2B.js → chunk-37EABIOJ.js} +2 -2
- package/dist/chunk-3RCFUIYR.js +29 -0
- package/dist/chunk-3RCFUIYR.js.map +1 -0
- package/dist/{chunk-B5UA3X6E.js → chunk-3W2KMI5O.js} +2 -2
- package/dist/{chunk-3IUU4YFI.js → chunk-4FFWNPFX.js} +5 -5
- package/dist/chunk-4FFWNPFX.js.map +1 -0
- package/dist/{chunk-7BQQWI4T.js → chunk-4HNHHKJF.js} +2 -2
- package/dist/chunk-6JHA3ZE6.js +1111 -0
- package/dist/chunk-6JHA3ZE6.js.map +1 -0
- package/dist/{chunk-76NNONUJ.js → chunk-BKDUCPZ3.js} +2 -2
- package/dist/{chunk-64UYAWAK.js → chunk-BMSPRUEJ.js} +33 -33
- package/dist/chunk-BMSPRUEJ.js.map +1 -0
- package/dist/{chunk-NKSCUCVZ.js → chunk-ENRJ2QEH.js} +2 -2
- package/dist/{chunk-AWRRBNWQ.js → chunk-HQMISQ7L.js} +2 -2
- package/dist/{chunk-E57WKMRR.js → chunk-KLDGJSR5.js} +2 -2
- package/dist/{ntfy-ZY2NPGBA.js → chunk-KZKDVIOE.js} +3 -3
- package/dist/chunk-KZKDVIOE.js.map +1 -0
- package/dist/{chunk-7NF45XCM.js → chunk-M67AN4J7.js} +2 -2
- package/dist/{chunk-WKTFP3SK.js → chunk-NO2HOK4B.js} +2 -2
- package/dist/chunk-QD6IICK7.js +2 -0
- package/dist/chunk-QD6IICK7.js.map +1 -0
- package/dist/{chunk-QDPLR3SB.js → chunk-QX4R5WY7.js} +2 -2
- package/dist/{chunk-QZ4M2KAC.js → chunk-QYHABRLM.js} +2 -2
- package/dist/{chunk-AKAM4BNC.js → chunk-TLFJVLVQ.js} +166 -160
- package/dist/chunk-TLFJVLVQ.js.map +1 -0
- package/dist/{chunk-YS3Z2Z64.js → chunk-UYMK3XNB.js} +44 -45
- package/dist/chunk-UYMK3XNB.js.map +1 -0
- package/dist/{chunk-7M7VJMGP.js → chunk-WLRHL2P7.js} +2 -2
- package/dist/chunk-WWMFNLKD.js +10 -0
- package/dist/chunk-WWMFNLKD.js.map +1 -0
- package/dist/{chunk-YPPTPBBV.js → chunk-XWU7O3S5.js} +2 -2
- package/dist/{chunk-XOUIZBAQ.js → chunk-ZOJUHPD5.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-N4XQEAVL.js +2 -0
- package/dist/{compaction-NWPBPWY2.js → compaction-H5U32UU6.js} +2 -2
- package/dist/{config-FGCJVXYX.js → config-KHKIY6LI.js} +2 -2
- package/dist/config-mutator-ZZKFQ7HJ.js +2 -0
- package/dist/doctor-QICAXIQB.js +2 -0
- package/dist/index.d.ts +130 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/memory-extract-F76BE6KA.js +2 -0
- package/dist/ntfy-52EXHVMD.js +2 -0
- package/dist/program-ZWNGK3RB.js +2 -0
- package/dist/{promote-NBFF7ZIW.js → promote-H6ZHJXTY.js} +2 -2
- package/dist/push-HEDA6P3B.js +2 -0
- package/dist/push-HEDA6P3B.js.map +1 -0
- package/dist/push-keys-2DTD7YNQ.js +2 -0
- package/dist/push-store-LXTYULUF.js +2 -0
- package/dist/query-FTE4FLYK.js +2 -0
- package/dist/registry-HDOFVNRK.js +2 -0
- package/dist/{request-planner-ZEXFARZE.js → request-planner-ABD4WIGM.js} +2 -2
- package/dist/{review-candidates-F2HNH2TZ.js → review-candidates-B6574GOJ.js} +2 -2
- package/dist/{routing-XSRZ7V23.js → routing-BGKZOHOA.js} +2 -2
- package/dist/schedule-tool-UDHXTKWV.js +2 -0
- package/dist/scheduler-NQM3HVUY.js +2 -0
- package/dist/scheduler-NQM3HVUY.js.map +1 -0
- package/dist/{seat-IPDLEUI5.js → seat-VGST5AQB.js} +2 -2
- package/dist/seat-VGST5AQB.js.map +1 -0
- package/dist/{select-BYOX63CR.js → select-Y7SBUCGJ.js} +2 -2
- package/dist/set-enabled-ARKMDLXN.js +2 -0
- package/dist/set-enabled-ARKMDLXN.js.map +1 -0
- package/dist/{tool-WW4YCMSP.js → tool-5EVYUN2G.js} +2 -2
- package/dist/wiki-GREI2TSP.js +2 -0
- package/dist/wiki-GREI2TSP.js.map +1 -0
- package/package.json +3 -1
- package/dist/board-dashboard-KETIFTBD.js.map +0 -1
- package/dist/chunk-3IUU4YFI.js.map +0 -1
- package/dist/chunk-64UYAWAK.js.map +0 -1
- package/dist/chunk-6BXKZY76.js +0 -7
- package/dist/chunk-6BXKZY76.js.map +0 -1
- package/dist/chunk-7PK32QT5.js +0 -1107
- package/dist/chunk-7PK32QT5.js.map +0 -1
- package/dist/chunk-AKAM4BNC.js.map +0 -1
- package/dist/chunk-HRBKSZ34.js +0 -2
- package/dist/chunk-HRBKSZ34.js.map +0 -1
- package/dist/chunk-WCNKTV6G.js +0 -28
- package/dist/chunk-WCNKTV6G.js.map +0 -1
- package/dist/chunk-YS3Z2Z64.js.map +0 -1
- package/dist/client-AVQSLPIZ.js +0 -2
- package/dist/config-mutator-5JSG3CHW.js +0 -2
- package/dist/doctor-VITHTLEC.js +0 -2
- package/dist/memory-extract-MGGXIZTE.js +0 -2
- package/dist/ntfy-ZY2NPGBA.js.map +0 -1
- package/dist/program-MNFDOQGQ.js +0 -2
- package/dist/query-XCXR57IV.js +0 -2
- package/dist/registry-5ZP3ZNSH.js +0 -2
- package/dist/schedule-tool-AKCVLCWK.js +0 -2
- package/dist/scheduler-BEGZJWJU.js +0 -2
- package/dist/wiki-IVJJQUKB.js +0 -2
- /package/dist/{App-X6FGYBLX.js.map → App-VRTLAPRF.js.map} +0 -0
- /package/dist/{ChatApp-XMUOXQ2M.js.map → ChatApp-YENWPZT4.js.map} +0 -0
- /package/dist/{agent-KKVMU3VB.js.map → agent-HVUGHYBF.js.map} +0 -0
- /package/dist/{chunk-H7R3F2CO.js.map → chunk-2TJYZF4E.js.map} +0 -0
- /package/dist/{chunk-MHBUAU2B.js.map → chunk-37EABIOJ.js.map} +0 -0
- /package/dist/{chunk-B5UA3X6E.js.map → chunk-3W2KMI5O.js.map} +0 -0
- /package/dist/{chunk-7BQQWI4T.js.map → chunk-4HNHHKJF.js.map} +0 -0
- /package/dist/{chunk-76NNONUJ.js.map → chunk-BKDUCPZ3.js.map} +0 -0
- /package/dist/{chunk-NKSCUCVZ.js.map → chunk-ENRJ2QEH.js.map} +0 -0
- /package/dist/{chunk-AWRRBNWQ.js.map → chunk-HQMISQ7L.js.map} +0 -0
- /package/dist/{chunk-E57WKMRR.js.map → chunk-KLDGJSR5.js.map} +0 -0
- /package/dist/{chunk-7NF45XCM.js.map → chunk-M67AN4J7.js.map} +0 -0
- /package/dist/{chunk-WKTFP3SK.js.map → chunk-NO2HOK4B.js.map} +0 -0
- /package/dist/{chunk-QDPLR3SB.js.map → chunk-QX4R5WY7.js.map} +0 -0
- /package/dist/{chunk-QZ4M2KAC.js.map → chunk-QYHABRLM.js.map} +0 -0
- /package/dist/{chunk-7M7VJMGP.js.map → chunk-WLRHL2P7.js.map} +0 -0
- /package/dist/{chunk-YPPTPBBV.js.map → chunk-XWU7O3S5.js.map} +0 -0
- /package/dist/{chunk-XOUIZBAQ.js.map → chunk-ZOJUHPD5.js.map} +0 -0
- /package/dist/{client-AVQSLPIZ.js.map → client-N4XQEAVL.js.map} +0 -0
- /package/dist/{compaction-NWPBPWY2.js.map → compaction-H5U32UU6.js.map} +0 -0
- /package/dist/{config-FGCJVXYX.js.map → config-KHKIY6LI.js.map} +0 -0
- /package/dist/{config-mutator-5JSG3CHW.js.map → config-mutator-ZZKFQ7HJ.js.map} +0 -0
- /package/dist/{doctor-VITHTLEC.js.map → doctor-QICAXIQB.js.map} +0 -0
- /package/dist/{memory-extract-MGGXIZTE.js.map → memory-extract-F76BE6KA.js.map} +0 -0
- /package/dist/{program-MNFDOQGQ.js.map → ntfy-52EXHVMD.js.map} +0 -0
- /package/dist/{promote-NBFF7ZIW.js.map → program-ZWNGK3RB.js.map} +0 -0
- /package/dist/{query-XCXR57IV.js.map → promote-H6ZHJXTY.js.map} +0 -0
- /package/dist/{registry-5ZP3ZNSH.js.map → push-keys-2DTD7YNQ.js.map} +0 -0
- /package/dist/{routing-XSRZ7V23.js.map → push-store-LXTYULUF.js.map} +0 -0
- /package/dist/{schedule-tool-AKCVLCWK.js.map → query-FTE4FLYK.js.map} +0 -0
- /package/dist/{scheduler-BEGZJWJU.js.map → registry-HDOFVNRK.js.map} +0 -0
- /package/dist/{request-planner-ZEXFARZE.js.map → request-planner-ABD4WIGM.js.map} +0 -0
- /package/dist/{review-candidates-F2HNH2TZ.js.map → review-candidates-B6574GOJ.js.map} +0 -0
- /package/dist/{seat-IPDLEUI5.js.map → routing-BGKZOHOA.js.map} +0 -0
- /package/dist/{wiki-IVJJQUKB.js.map → schedule-tool-UDHXTKWV.js.map} +0 -0
- /package/dist/{select-BYOX63CR.js.map → select-Y7SBUCGJ.js.map} +0 -0
- /package/dist/{tool-WW4YCMSP.js.map → tool-5EVYUN2G.js.map} +0 -0
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{chmodSync as n,existsSync as s,mkdirSync as i,readFileSync as u,writeFileSync as o}from"fs";import{dirname as c,resolve as y}from"path";var g=".agentx/push-keys.json";function K(e=g,r=process.cwd()){return y(r,e)}function f(e){if(!s(e))return null;try{let r=JSON.parse(u(e,"utf-8"));return typeof r?.publicKey=="string"&&typeof r?.privateKey=="string"?r:null}catch{return null}}function a(e,r){let t={...r,createdAt:new Date().toISOString()};return i(c(e),{recursive:!0}),o(e,JSON.stringify(t,null,2)+`
|
|
2
|
+
`,{encoding:"utf-8",mode:384}),n(e,384),t}export{g as a,K as b,f as c,a as d};
|
|
3
|
+
//# sourceMappingURL=chunk-2D3RYIDU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/channels/push-keys.ts"],"sourcesContent":["import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\n\n// --- VAPID keys for Web Push ---\n//\n// The key pair identifies this node to the phone's push service. It lives in\n// its own file (channels.push.keysFile, default .agentx/push-keys.json next\n// to the device tokens), never in agentx.json, so sharing or committing the\n// config can't leak the private key. `agentx app push-keys` writes it once;\n// replacing it cuts off every phone until each turns notifications on again.\n\nexport const DEFAULT_PUSH_KEYS_FILE = \".agentx/push-keys.json\"\n\nexport interface PushKeys {\n publicKey: string\n privateKey: string\n createdAt: string\n}\n\nexport function pushKeysPath(file: string = DEFAULT_PUSH_KEYS_FILE, baseDir: string = process.cwd()): string {\n return resolve(baseDir, file)\n}\n\n/** The saved key pair, or null when the file is missing or unreadable. */\nexport function readPushKeys(path: string): PushKeys | null {\n if (!existsSync(path)) return null\n try {\n const k = JSON.parse(readFileSync(path, \"utf-8\"))\n return typeof k?.publicKey === \"string\" && typeof k?.privateKey === \"string\" ? k : null\n } catch {\n return null\n }\n}\n\n/** Writes the key pair readable by the owner only. */\nexport function writePushKeys(path: string, keys: { publicKey: string; privateKey: string }): PushKeys {\n const out: PushKeys = { ...keys, createdAt: new Date().toISOString() }\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(out, null, 2) + \"\\n\", { encoding: \"utf-8\", mode: 0o600 })\n chmodSync(path, 0o600)\n return out\n}\n"],"mappings":"AAAA,OAAS,aAAAA,EAAW,cAAAC,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,KAC9E,OAAS,WAAAC,EAAS,WAAAC,MAAe,OAU1B,IAAMC,EAAyB,yBAQ/B,SAASC,EAAaC,EAAeF,EAAwBG,EAAkB,QAAQ,IAAI,EAAW,CAC3G,OAAOJ,EAAQI,EAASD,CAAI,CAC9B,CAGO,SAASE,EAAaC,EAA+B,CAC1D,GAAI,CAACX,EAAWW,CAAI,EAAG,OAAO,KAC9B,GAAI,CACF,IAAMC,EAAI,KAAK,MAAMV,EAAaS,EAAM,OAAO,CAAC,EAChD,OAAO,OAAOC,GAAG,WAAc,UAAY,OAAOA,GAAG,YAAe,SAAWA,EAAI,IACrF,MAAE,CACA,OAAO,IACT,CACF,CAGO,SAASC,EAAcF,EAAcG,EAA2D,CACrG,IAAMC,EAAgB,CAAE,GAAGD,EAAM,UAAW,IAAI,KAAK,EAAE,YAAY,CAAE,EACrE,OAAAb,EAAUG,EAAQO,CAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EAC5CR,EAAcQ,EAAM,KAAK,UAAUI,EAAK,KAAM,CAAC,EAAI;AAAA,EAAM,CAAE,SAAU,QAAS,KAAM,GAAM,CAAC,EAC3FhB,EAAUY,EAAM,GAAK,EACdI,CACT","names":["chmodSync","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","resolve","DEFAULT_PUSH_KEYS_FILE","pushKeysPath","file","baseDir","readPushKeys","path","k","writePushKeys","keys","out"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-
|
|
1
|
+
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-QYHABRLM.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-4HNHHKJF.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
|
|
2
2
|
`)}async function k(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(u){return`Could not notify the operator (${u?.message??u}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),u=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let p=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(p).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>Q(i,f,u)).join(`
|
|
3
3
|
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!h.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||q;if(!B(g))return`Error: unknown timezone "${g}".`;let d=o||_(i.matched,f);if(!R(d))return`Error: invalid id "${d}" (letters, digits, "-" and "_" only).`;if(p[d])return`Error: a schedule "${d}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:u.toISOString()},L=b({parsed:i,agent:f,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),v=await m(U=>I(U,`crons.${d}`,L));if(!v.success)return`Error: ${v.error}`;let N=w(E(i.cron,g,u),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${d}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${f}`,$?`Notify: ${$.channel} ${$.chatId}`:"Notify: none",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${d}`,`Reject: agentx schedule reject ${d}`].join(`
|
|
4
4
|
`),H=await k(h,t,G);return[`Requested schedule "${d}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=p[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let d=await m($=>P($,`crons.${o}`));return d.success?`Withdrew the pending request "${o}".`:`Error: ${d.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:u.toISOString()},l=await m(d=>{if(!x(d,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(d,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${S(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,u),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await k(h,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
7
|
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),u=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),p=s(n.accountId);return{agentId:t,channel:u,chatId:h,...p?{accountId:p}:{}}}export{re as a,oe as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-2TJYZF4E.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{g as j,h as x,o as O,p as I}from"./chunk-S7CVSKOX.js";import{m as S,p as L}from"./chunk-4FFWNPFX.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as E,constants as T,existsSync as y,readFileSync as b,readdirSync as $,statSync as B}from"fs";import{join as P,resolve as m}from"path";import{homedir as M}from"os";import{createRequire as X}from"module";import{execFile as _}from"child_process";var q=(n,t)=>new Promise(e=>{try{_(n,t,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),R="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function N(n={}){if((n.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let t=n.helper===void 0?I():n.helper;if(!t)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(n.run??q)(t,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:t,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:t,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:R}:i.alertStyle==="none"?{state:"hidden",path:t,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:R}:{state:"ready",path:t,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:t,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(n={}){let t=[];await G(t),V(t);let e=K(t);return e&&U(t,e),e&&Q(t,e),e&&Y(t,e),e&&ee(t,e),e&&ne(t,e),e&&await F(t,e),e&&Z(t,e),n.running!==!1&&e&&await te(t,e),{checks:t,summary:W(t)}}var we=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async n=>{let{checks:t,summary:e}=await J({running:n.running!==!1});n.json?process.stdout.write(JSON.stringify({checks:t,summary:e},null,2)+`
|
|
2
|
+
`):ie(t),process.exit(e.errors>0?1:0)});async function F(n,t,e=N){if(!O(t.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&n.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function Z(n,t,e=process.platform,i=s=>{try{return E(s,T.X_OK),!0}catch{return!1}}){let s=t.reminders;if(!s?.enabled)return;if(e!=="darwin"){n.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let r=s.command||"remindctl",a=r.includes("/")?i(r)?r:null:x(r,process.env.PATH||"",i);n.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(s.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${r} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function G(n){let t=Number(process.versions.node.split(".")[0]);n.push({severity:t==22?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:t==22?void 0:"AgentX requires Node 22.x.",fix:t==22?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return h(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
|
|
3
|
+
`)[0]}catch{return null}},i=e("npm");n.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let s=e("claude");if(s){let l;try{l=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else n.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let l;try{l=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else n.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else n.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{X(import.meta.url)("better-sqlite3"),n.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){n.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function V(n){if(process.platform!=="darwin")return;let t=P(M(),"Library/LaunchAgents"),e=[];try{e=$(t).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return E(s,T.X_OK),!0}catch{return!1}};for(let s of e){let r=j(b(P(t,s),"utf-8")),a=x("ffmpeg",r,i);n.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${s})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${s} sets PATH to ${r}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function K(n){let t=m(process.cwd(),"agentx.json");if(!y(t))return n.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${t}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(t,"utf-8"))}catch(a){return n.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(t),n.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){n.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let r=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function U(n,t){let e=new Set;if(C(t,e),e.size===0){n.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=m(process.cwd(),".env"),s={};if(y(i))for(let l of b(i,"utf-8").split(/\r?\n/)){let u=l.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);u&&(s[u[1]]=u[2])}let r=[],a=[];for(let l of e){let u=process.env[l]??s[l];u===void 0?r.push(l):(!u.trim()||/^["']?\s*["']?$/.test(u))&&a.push(l)}r.length===0&&a.length===0?n.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&n.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),a.length>0&&n.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(n,t){if(typeof n=="string")for(let e of n.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))t.add(e[1]);else if(Array.isArray(n))for(let e of n)C(e,t);else if(n&&typeof n=="object")for(let e of Object.values(n))C(e,t)}function Q(n,t){let e=[];for(let[i,s]of Object.entries(t.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{B(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?n.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):n.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
4
|
+
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function Y(n,t){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(t.agents||{})){if(!r.workspace)continue;let a=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let l of["settings.json","settings.local.json"]){let u=m(a,".claude",l);if(!y(u))continue;let w;try{w=JSON.parse(b(u,"utf-8"))}catch(d){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${d.message}`});continue}let k=w.env||{};for(let[d,p]of Object.entries(k)){if(typeof p!="string")continue;let g=p.match(e);g&&i.push({severity:"fail",agent:s,msg:`${l} env.${d} contains unexpanded ${[...new Set(g)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let o=k.PATH;if(typeof o=="string"){let d=o.split(":").filter(Boolean);d.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let c=w.permissions;if(c&&typeof c=="object"&&"allow"in c){let d=c.allow,p=c.deny;Array.isArray(d)&&d.length===0&&Array.isArray(p)&&p.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){n.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(t.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)n.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function ee(n,t){let e=t.webhooks??[],i=[],s=m(process.cwd(),t.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let o of $(s))o.endsWith(".json")&&!o.startsWith("_")&&!o.endsWith(".disabled.json")&&r.add(o.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let o of e){if(!o.enabled||!a.has(o.source))continue;!(o.triggers&&Object.keys(o.triggers).length>0)&&!o.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${o.id}" (${o.source} -> ${o.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let o of e)if(!(!o.enabled||!o.triggers)){for(let[c,d]of Object.entries(o.triggers))r.size>0&&!r.has(d)&&i.push({severity:"fail",title:`webhook "${o.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${t.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});o.defaultWorkflow&&r.size>0&&!r.has(o.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${o.id}".defaultWorkflow -> "${o.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let o of $(s))if(!(!o.endsWith(".json")||o.startsWith("_")||o.endsWith(".disabled.json")))try{let c=JSON.parse(b(m(s,o),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${c.id??o}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((t.mesh?.peers??[]).map(o=>o.name));for(let o of e)!o.enabled||!o.node||l.has(o.node)||i.push({severity:"fail",title:`webhook "${o.id}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let o of e){if(!o.enabled)continue;let c=`${o.source}:${o.agentId}`,d=u.get(c);d?i.push({severity:"warn",title:`webhook entries "${d}" and "${o.id}" both enabled for ${o.source} -> ${o.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(c,o.id)}let w=new Set(Object.keys(t.agents??{}));for(let o of t.channels?.gitlab?.agentMappings??[])if(o?.agentId){if(o.node){l.has(o.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${o.agentId}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}w.has(o.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${o.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[o,c]of Object.entries(t.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||i.push({severity:"fail",title:`telegram account "${o}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${o}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let k=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[o,c]of Object.entries(t.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let g of d){let A=`${g.kind}::${g.label}`;p.has(A)&&i.push({severity:"warn",title:`agents.${o}.integrations: duplicate (${g.kind}, ${g.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(A),k.has(g.kind)||i.push({severity:"warn",title:`agents.${o}.integrations: unknown kind "${g.kind}" on integration "${g.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let H=g.credentials||{};for(let[D,v]of Object.entries(H))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${o}.integrations[${g.kind}/${g.label}].${D} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){n.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(t.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)n.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}async function te(n,t){let e=t.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};t.dashboard?.token&&(i.Authorization=`Bearer ${t.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(r),!a.ok){n.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();n.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e})}catch{n.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function ne(n,t){let e=Object.entries(t.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
|
+
`)[0]||null}catch{i=null}if(i){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else n.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){n.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=m(r.workspace,".codegraph","codegraph.db");y(a)?n.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):n.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function W(n){return{errors:n.filter(t=>t.severity==="fail").length,warnings:n.filter(t=>t.severity==="warn").length,ok:n.filter(t=>t.severity==="ok").length}}function ie(n){console.log(),console.log(f.bold(" agentx doctor")),console.log();let t=new Map;for(let i of n)t.has(i.group)||t.set(i.group,[]),t.get(i.group).push(i);for(let[i,s]of t){console.log(f.bold(" "+i));for(let r of s){let a=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${r.title}`),r.detail&&console.log(f.dim(" "+r.detail.replace(/\n/g,`
|
|
6
|
+
`))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=W(n);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{N as a,J as b,we as c,F as d,Z as e};
|
|
7
|
+
//# sourceMappingURL=chunk-33QV5O6P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/doctor.ts","../src/notify/helper-status.ts"],"sourcesContent":["import { Command } from \"commander\"\nimport chalk from \"chalk\"\nimport { execFileSync } from \"child_process\"\nimport { accessSync, constants, existsSync, readFileSync, readdirSync, statSync } from \"fs\"\nimport { join, resolve } from \"path\"\nimport { homedir } from \"os\"\nimport { createRequire } from \"module\"\nimport { loadDaemonConfig } from \"@/daemon/config\"\nimport { findOnPath, plistPathEnv } from \"@/desktop/install\"\nimport { localSettings } from \"@/notify/local\"\nimport { helperStatus } from \"@/notify/helper-status\"\n\n// --- agentx doctor ---\n//\n// Pre-flight health check. Catches the common \"why isn't it working\" reasons\n// before the operator hits them at runtime:\n// - wrong Node version\n// - invalid / missing agentx.json\n// - agents with claude-code tier but no claude CLI installed\n// - ${FOO} references in agentx.json that have no matching env var\n// - agent workspace dirs that don't exist\n// - daemon reachable? (when --check-running, default true)\n//\n// Exit code: 0 if clean, 1 if any error, 0 if only warnings (so CI won't block\n// on advisory checks).\n\nexport type Severity = \"ok\" | \"warn\" | \"fail\"\n\nexport interface Check {\n severity: Severity\n group: string\n title: string\n detail?: string\n fix?: string\n}\n\n/** Run every preflight check and return the result as data. Exposed so\n * the dashboard's /admin/doctor route can render the same checks the\n * `agentx doctor` CLI prints — without spawning a child process. */\nexport async function runDoctorChecks(\n opts: { running?: boolean } = {},\n): Promise<{ checks: Check[]; summary: { errors: number; warnings: number; ok: number } }> {\n const checks: Check[] = []\n await runEnvChecks(checks)\n runDesktopChecks(checks)\n const cfg = runConfigChecks(checks)\n if (cfg) runReferenceChecks(checks, cfg)\n if (cfg) runWorkspaceChecks(checks, cfg)\n if (cfg) runWorkspaceSettingsChecks(checks, cfg)\n if (cfg) runRoutingChecks(checks, cfg)\n if (cfg) runCodegraphChecks(checks, cfg)\n if (cfg) await runNotificationChecks(checks, cfg)\n if (cfg) runReminderChecks(checks, cfg)\n if (opts.running !== false && cfg) await runRuntimeChecks(checks, cfg)\n return { checks, summary: summarize(checks) }\n}\n\nexport const doctor = new Command()\n .name(\"doctor\")\n .description(\"pre-flight health check: Node, config, credentials, daemon\")\n .option(\"--no-running\", \"skip the live daemon probe\")\n .option(\"--json\", \"emit machine-readable JSON (stable shape for CI)\")\n .action(async (opts) => {\n const { checks, summary } = await runDoctorChecks({ running: opts.running !== false })\n if (opts.json) {\n process.stdout.write(JSON.stringify({ checks, summary }, null, 2) + \"\\n\")\n } else {\n printHumanReport(checks)\n }\n process.exit(summary.errors > 0 ? 1 : 0)\n })\n\n// ---------------------------------------------------------------------------\n// Checks\n// ---------------------------------------------------------------------------\n\n/** On a Mac with banners on: can AgentX Helper post them with its icon? */\nexport async function runNotificationChecks(checks: Check[], cfg: any, status = helperStatus): Promise<void> {\n if (!localSettings(cfg.notifications?.local).banner) return\n const helper = await status()\n if (helper.state === \"unsupported\") return\n checks.push({\n severity: helper.state === \"ready\" ? \"ok\" : \"warn\",\n group: \"Notifications\",\n title: helper.message,\n detail: helper.path,\n fix: helper.fix,\n })\n}\n\n/** reminders.enabled: macOS only, and the daemon needs remindctl. */\nexport function runReminderChecks(\n checks: Check[],\n cfg: any,\n platform: NodeJS.Platform = process.platform,\n isExecutable: (file: string) => boolean = (file) => { try { accessSync(file, constants.X_OK); return true } catch { return false } },\n): void {\n const r = cfg.reminders\n if (!r?.enabled) return\n if (platform !== \"darwin\") {\n checks.push({\n severity: \"warn\",\n group: \"Reminders\",\n title: \"Reminders hand-back unavailable on this machine\",\n detail: \"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.\",\n fix: \"Set reminders.enabled to false here, or enable it on the Mac node instead.\",\n })\n return\n }\n const command = r.command || \"remindctl\"\n const found = command.includes(\"/\") ? (isExecutable(command) ? command : null) : findOnPath(command, process.env.PATH || \"\", isExecutable)\n checks.push(found\n ? { severity: \"ok\", group: \"Reminders\", title: `Watching ${(r.lists || []).join(\", \")} for due reminders`, detail: found }\n : {\n severity: \"fail\",\n group: \"Reminders\",\n title: `${command} not found`,\n detail: \"The daemon reads Apple Reminders through remindctl.\",\n fix: \"brew install steipete/tap/remindctl, or set reminders.command to its full path.\",\n })\n}\n\nasync function runEnvChecks(checks: Check[]): Promise<void> {\n const nodeMajor = Number(process.versions.node.split(\".\")[0])\n checks.push({\n severity: nodeMajor == 22 ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: `Node.js ${process.versions.node}`,\n detail: nodeMajor == 22 ? undefined : \"AgentX requires Node 22.x.\",\n fix: nodeMajor == 22 ? undefined : \"Install Node 22 (nvm install 22 && nvm use 22)\",\n })\n\n const which = (bin: string): string | null => {\n try { return execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [bin], { encoding: \"utf-8\" }).trim().split(\"\\n\")[0] }\n catch { return null }\n }\n const npmPath = which(\"npm\")\n checks.push({\n severity: npmPath ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: npmPath ? \"npm on PATH\" : \"npm not found\",\n detail: npmPath || undefined,\n })\n\n // Claude CLI is only required if the config references claude-code agents;\n // we report it advisory here and promote to fail in the config step below.\n const claudePath = which(\"claude\")\n if (claudePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"claude\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `claude CLI ${ver || \"installed\"}`, detail: claudePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"claude CLI not on PATH\",\n detail: \"Only required for agents on the claude-code tier.\",\n fix: \"See https://docs.anthropic.com/en/docs/claude-code\",\n })\n }\n\n const codexPath = which(\"codex\")\n if (codexPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codex\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `codex CLI ${ver || \"installed\"}`, detail: codexPath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"codex CLI not on PATH\",\n detail: \"Only required for agents on the codex-cli tier.\",\n fix: \"Install with `npm i -g @openai/codex`.\",\n })\n }\n\n const openCodePath = which(\"opencode\")\n if (openCodePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"opencode\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `opencode CLI ${ver || \"installed\"}`, detail: openCodePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"opencode CLI not on PATH\",\n detail: \"Only required for agents on the opencode tier.\",\n fix: \"Install from https://opencode.ai/docs/.\",\n })\n }\n\n try {\n createRequire(import.meta.url)(\"better-sqlite3\")\n checks.push({\n severity: \"ok\",\n group: \"Environment\",\n title: `better-sqlite3 loads for Node ${process.version}`,\n detail: `NODE_MODULE_VERSION ${process.versions.modules}`,\n })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Environment\",\n title: \"better-sqlite3 native binding does not load\",\n detail: e?.message ?? String(e),\n fix: `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`,\n })\n }\n}\n\n/** The desktop app's login item runs with only the PATH its plist sets, so\n * check that local Whisper's ffmpeg is reachable there, not in this shell. */\nfunction runDesktopChecks(checks: Check[]): void {\n if (process.platform !== \"darwin\") return\n // Older installs used another label; apps/mac-voice/install.sh keeps it.\n const agents = join(homedir(), \"Library/LaunchAgents\")\n let names: string[] = []\n try { names = readdirSync(agents).filter(n => /agentx\\.voice.*\\.plist$/.test(n)) } catch { return }\n const isExecutable = (file: string) => { try { accessSync(file, constants.X_OK); return true } catch { return false } }\n for (const name of names) {\n const path = plistPathEnv(readFileSync(join(agents, name), \"utf-8\"))\n const ffmpeg = findOnPath(\"ffmpeg\", path, isExecutable)\n checks.push(ffmpeg\n ? { severity: \"ok\", group: \"Desktop\", title: \"ffmpeg reachable by the desktop app\", detail: `${ffmpeg} (${name})` }\n : {\n severity: \"warn\",\n group: \"Desktop\",\n title: \"ffmpeg not reachable by the desktop app\",\n detail: `Local Whisper transcription fails without it. ${name} sets PATH to ${path}.`,\n fix: \"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install.\",\n })\n }\n}\n\nfunction runConfigChecks(checks: Check[]): any {\n const cfgPath = resolve(process.cwd(), \"agentx.json\")\n if (!existsSync(cfgPath)) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json not found\",\n detail: `Looked in ${cfgPath}`,\n fix: \"Run `agentx setup` to create one via the web wizard.\",\n })\n return null\n }\n let cfg: any\n try { cfg = JSON.parse(readFileSync(cfgPath, \"utf-8\")) }\n catch (e: any) {\n checks.push({ severity: \"fail\", group: \"Config\", title: \"agentx.json is not valid JSON\", detail: e.message })\n return null\n }\n try {\n // Full schema validation — catches missing required fields.\n loadDaemonConfig(cfgPath)\n checks.push({ severity: \"ok\", group: \"Config\", title: `agentx.json valid (${Object.keys(cfg.agents || {}).length} agents, ${Object.keys(cfg.crons || {}).length} schedules)` })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json failed schema validation\",\n detail: e.message,\n fix: \"Open /admin → Advanced tab to edit and re-save.\",\n })\n }\n const claudeCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"claude-code\")\n if (claudeCodeAgents.length > 0) {\n const hasClaude = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"claude\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasClaude) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${claudeCodeAgents.length} agent(s) use claude-code tier but claude CLI is missing`,\n detail: claudeCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk.\",\n })\n }\n }\n const codexCliAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"codex-cli\")\n if (codexCliAgents.length > 0) {\n const hasCodex = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codex\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasCodex) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${codexCliAgents.length} agent(s) use codex-cli tier but codex CLI is missing`,\n detail: codexCliAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code.\",\n })\n }\n }\n const openCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"opencode\")\n if (openCodeAgents.length > 0) {\n const hasOpenCode = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"opencode\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasOpenCode) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${openCodeAgents.length} agent(s) use opencode tier but OpenCode CLI is missing`,\n detail: openCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier.\",\n })\n }\n }\n return cfg\n}\n\nfunction runReferenceChecks(checks: Check[], cfg: any): void {\n // Parse ${VAR} references out of the config (recursively) and verify each\n // one has a matching value in .env or process.env.\n const refs = new Set<string>()\n collectEnvRefs(cfg, refs)\n if (refs.size === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: \"No ${VAR} references in agentx.json\" })\n return\n }\n const envFile = resolve(process.cwd(), \".env\")\n const envFromFile: Record<string, string> = {}\n if (existsSync(envFile)) {\n for (const line of readFileSync(envFile, \"utf-8\").split(/\\r?\\n/)) {\n const m = line.match(/^\\s*([A-Z_][A-Z0-9_]*)\\s*=\\s*(.*)$/i)\n if (m) envFromFile[m[1]] = m[2]\n }\n }\n const missing: string[] = []\n const empty: string[] = []\n for (const name of refs) {\n const raw = process.env[name] ?? envFromFile[name]\n if (raw === undefined) missing.push(name)\n else if (!raw.trim() || /^[\"']?\\s*[\"']?$/.test(raw)) empty.push(name)\n }\n if (missing.length === 0 && empty.length === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: `${refs.size} env reference(s) resolved` })\n } else {\n if (missing.length > 0) {\n checks.push({\n severity: \"fail\",\n group: \"Secrets\",\n title: `${missing.length} env var(s) referenced in agentx.json but missing`,\n detail: missing.join(\", \"),\n fix: `Add to .env — e.g. ${missing[0]}=<value>`,\n })\n }\n if (empty.length > 0) {\n checks.push({\n severity: \"warn\",\n group: \"Secrets\",\n title: `${empty.length} env var(s) set but empty`,\n detail: empty.join(\", \"),\n })\n }\n }\n}\n\nfunction collectEnvRefs(node: unknown, into: Set<string>): void {\n if (typeof node === \"string\") {\n for (const m of node.matchAll(/\\$\\{([A-Z_][A-Z0-9_]*)\\}/g)) into.add(m[1])\n } else if (Array.isArray(node)) {\n for (const item of node) collectEnvRefs(item, into)\n } else if (node && typeof node === \"object\") {\n for (const v of Object.values(node)) collectEnvRefs(v, into)\n }\n}\n\nfunction runWorkspaceChecks(checks: Check[], cfg: any): void {\n const missing: string[] = []\n for (const [id, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const abs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n try {\n const st = statSync(abs)\n if (!st.isDirectory()) missing.push(`${id}: ${abs} (exists but not a directory)`)\n } catch { missing.push(`${id}: ${abs}`) }\n }\n if (missing.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspaces\", title: \"All agent workspace folders exist\" })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Workspaces\",\n title: `${missing.length} agent workspace(s) missing`,\n detail: missing.join(\"\\n \"),\n fix: \"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them.\",\n })\n }\n}\n\n// Audit each agent's .claude/settings.json for known traps:\n// - unexpanded ${VAR} literals in env values (Claude Code does NOT expand them)\n// - env.PATH missing /usr/bin or /bin (basic utils unreachable)\n// - JSON syntax errors\n// - permissions.allow: [] explicitly empty alongside non-empty deny\n// Each finding is FAIL severity for the ${VAR} / PATH cases (these break the\n// agent's Bash tool entirely), WARN for the lockdown case.\nfunction runWorkspaceSettingsChecks(checks: Check[], cfg: any): void {\n const VAR_RE = /\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}/g\n const findings: Array<{ severity: Severity; agent: string; msg: string }> = []\n\n for (const [agentId, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const wsAbs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n for (const fname of [\"settings.json\", \"settings.local.json\"]) {\n const p = resolve(wsAbs, \".claude\", fname)\n if (!existsSync(p)) continue\n let data: any\n try {\n data = JSON.parse(readFileSync(p, \"utf-8\"))\n } catch (e: any) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname}: JSON parse error — ${e.message}` })\n continue\n }\n const env = (data.env || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(env)) {\n if (typeof v !== \"string\") continue\n const unexpanded = v.match(VAR_RE)\n if (unexpanded) {\n findings.push({\n severity: \"fail\",\n agent: agentId,\n msg: `${fname} env.${k} contains unexpanded ${[...new Set(unexpanded)].join(\",\")} — Claude Code does NOT expand \\${VAR} in settings.json (use a fully-literal value)`,\n })\n }\n }\n const pathVal = env.PATH\n if (typeof pathVal === \"string\") {\n const parts = pathVal.split(\":\").filter(Boolean)\n if (!parts.includes(\"/usr/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /usr/bin — cat/head/sh/which will fail` })\n }\n if (!parts.includes(\"/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /bin — ls/cp/mv will fail` })\n }\n }\n const perms = data.permissions\n if (perms && typeof perms === \"object\" && \"allow\" in perms) {\n const allow = perms.allow\n const deny = perms.deny\n if (Array.isArray(allow) && allow.length === 0 && Array.isArray(deny) && deny.length > 0) {\n findings.push({\n severity: \"warn\",\n agent: agentId,\n msg: `${fname} permissions.allow is explicitly [] with ${deny.length} deny rules — agent may be locked out (omit the key to use defaults instead)`,\n })\n }\n }\n }\n }\n\n if (findings.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspace settings\", title: `All ${Object.keys(cfg.agents || {}).length} agent .claude/settings.json files clean` })\n return\n }\n for (const f of findings) {\n checks.push({\n severity: f.severity,\n group: \"Workspace settings\",\n title: `${f.agent}: ${f.msg}`,\n fix: f.severity === \"fail\" ? \"Edit .claude/settings.json — replace ${VAR} with the literal value or omit the key to inherit.\" : \"Either remove the empty allow list or populate it.\",\n })\n }\n}\n\n// Surface routing / dispatch fragilities the recurring-patches plan\n// cataloged: webhook entries that route many event-types to a single\n// handler (github, gitlab), trigger maps pointing at workflow ids that\n// don't exist, mesh `node` fields naming peers that aren't configured,\n// gitlab agentMappings referencing unknown agents, and the very common\n// \"I edited agentx.json but didn't reload\" pitfall.\nfunction runRoutingChecks(checks: Check[], cfg: any): void {\n const webhooks = (cfg.webhooks ?? []) as Array<{\n id: string\n source: string\n agentId: string\n enabled: boolean\n node?: string\n secretEnv?: string\n triggers?: Record<string, string>\n defaultWorkflow?: string\n }>\n const findings: Array<{ severity: Severity; title: string; fix?: string }> = []\n\n // Build the set of known workflow ids. Workflows live as JSON files under\n // `workflows.dir` (default .agentx/workflows/). The id is the filename\n // sans extension; we don't need to parse the contents for this check.\n const workflowDir = resolve(process.cwd(), cfg.workflows?.dir || \".agentx/workflows\")\n const knownWorkflows = new Set<string>()\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (f.endsWith(\".json\") && !f.startsWith(\"_\") && !f.endsWith(\".disabled.json\")) {\n knownWorkflows.add(f.replace(/\\.json$/, \"\"))\n }\n }\n }\n } catch { /* directory not yet populated; checks below tolerate empty set */ }\n\n // 1. Multi-event-type sources (github, gitlab) without a triggers map.\n // Without it, every inbound event hits the same agent and the\n // duplicate-firing class of bug returns. Surface as REVIEW (warn) —\n // operators may genuinely want a single-handler setup, but they\n // should opt in by setting `defaultWorkflow` explicitly.\n const multiEventSources = new Set([\"github\", \"gitlab\"])\n for (const w of webhooks) {\n if (!w.enabled) continue\n if (!multiEventSources.has(w.source)) continue\n const hasTriggers = w.triggers && Object.keys(w.triggers).length > 0\n if (!hasTriggers && !w.defaultWorkflow) {\n findings.push({\n severity: \"warn\",\n title: `webhook \"${w.id}\" (${w.source} -> ${w.agentId}) has no triggers map; every event-type collapses to the bound agent`,\n fix: `Add a triggers map: { \"issues.opened\": \"wf-id\", \"pull_request.synchronize\": \"wf-id\" } — or set defaultWorkflow.`,\n })\n }\n }\n\n // 2. Trigger map references workflow ids that don't exist on disk.\n // Hard-fails the dispatch at runtime (and silently — dispatcher just\n // logs \"workflow not found\" and bails). Surface here as FAIL.\n for (const w of webhooks) {\n if (!w.enabled || !w.triggers) continue\n for (const [eventType, workflowId] of Object.entries(w.triggers)) {\n if (knownWorkflows.size > 0 && !knownWorkflows.has(workflowId)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".triggers[\"${eventType}\"] -> \"${workflowId}\" — no such workflow under ${cfg.workflows?.dir || \".agentx/workflows\"}`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n if (w.defaultWorkflow && knownWorkflows.size > 0 && !knownWorkflows.has(w.defaultWorkflow)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".defaultWorkflow -> \"${w.defaultWorkflow}\" — no such workflow`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n\n // 2b. Incoherent workflow lifecycle: status=active says \"reviewed, ship\n // it\" while state=quarantined means the runtime refuses to dispatch\n // it (conflict detector parked it). The two axes are independent\n // (state is the only dispatch gate — see workflowSchema), so this\n // combo silently looks live while never firing.\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (!f.endsWith(\".json\") || f.startsWith(\"_\") || f.endsWith(\".disabled.json\")) continue\n try {\n const wf = JSON.parse(readFileSync(resolve(workflowDir, f), \"utf-8\"))\n if (wf?.status === \"active\" && wf?.state === \"quarantined\") {\n findings.push({\n severity: \"warn\",\n title: `workflow \"${wf.id ?? f}\" is status=active but state=quarantined — it looks live but will never dispatch`,\n fix: `Resolve the conflict the detector flagged, then set state back to \"active\" (or set status to \"review\" while parked).`,\n })\n }\n } catch { /* unparseable file is caught by workflow validate */ }\n }\n }\n } catch { /* directory races are non-fatal for doctor */ }\n\n // 3. Mesh-routed webhooks naming peers that don't exist.\n const peers = new Set<string>(((cfg.mesh?.peers ?? []) as Array<{ name: string }>).map(p => p.name))\n for (const w of webhooks) {\n if (!w.enabled || !w.node) continue\n if (!peers.has(w.node)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\" routes to mesh peer \"${w.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or remove the node field on the webhook.`,\n })\n }\n }\n\n // 4. Two enabled webhook entries collide on (source, agentId): the\n // Phase 3 dispatcher takes the first match, the second is silently\n // ignored — operators rarely realize.\n const seen = new Map<string, string>()\n for (const w of webhooks) {\n if (!w.enabled) continue\n const key = `${w.source}:${w.agentId}`\n const prior = seen.get(key)\n if (prior) {\n findings.push({\n severity: \"warn\",\n title: `webhook entries \"${prior}\" and \"${w.id}\" both enabled for ${w.source} -> ${w.agentId}; only the first is dispatched`,\n fix: `Disable one entry, or merge their triggers maps into a single entry.`,\n })\n } else {\n seen.set(key, w.id)\n }\n }\n\n // 5. GitLab agentMappings referencing agent ids that aren't in agents.\n // A mapping with `node:` set is a cross-mesh route — the agent lives\n // on a remote peer, not locally — so missing-from-agents is correct\n // and not a finding. We still warn when `node` names a peer that\n // isn't configured (caught by check #3 above for webhooks; same\n // invariant should hold for agentMappings).\n const agentIds = new Set(Object.keys(cfg.agents ?? {}))\n for (const m of (cfg.channels?.gitlab?.agentMappings ?? [])) {\n if (!m?.agentId) continue\n if (m.node) {\n // Cross-mesh route — verify the named peer exists.\n if (!peers.has(m.node)) {\n findings.push({\n severity: \"fail\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" routes to mesh peer \"${m.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or drop the node field on the mapping.`,\n })\n }\n continue\n }\n if (!agentIds.has(m.agentId)) {\n findings.push({\n severity: \"warn\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" — no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,\n fix: `Add the agent to agents.*, set node:\"<peer>\" if the agent lives remotely, or remove the mapping.`,\n })\n }\n }\n\n // 6. Telegram accounts without an agentBinding silently drop every DM.\n for (const [acctId, acct] of Object.entries((cfg.channels?.telegram?.accounts ?? {}) as Record<string, { agentBinding?: string }>)) {\n if (!acct.agentBinding) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\" has no agentBinding; every DM to this bot will drop`,\n fix: `Set agentBinding to a valid agent id.`,\n })\n } else if (!agentIds.has(acct.agentBinding)) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\".agentBinding -> \"${acct.agentBinding}\" — no such agent in agents.*`,\n fix: `Fix the agentBinding or define the agent in agents.*.`,\n })\n }\n }\n\n // 7. Per-agent integrations: missing env vars + unknown kinds + duplicates.\n // The new agents[].integrations[] block declares third-party credentials\n // (telegram-bot, hubspot, gitlab-user, gmail, ...). Doctor scans for:\n // - duplicate (kind, label) on the same agent (config integrity)\n // - tokenEnv refs that don't exist in process.env (latent failure)\n // - kinds outside the canonical INTEGRATION_KINDS set (typos)\n // Failures are warnings, not blocking — credentials may be set on the\n // daemon process and absent from the doctor's local shell.\n const KNOWN_KINDS = new Set([\n \"telegram-bot\", \"whatsapp\", \"slack-bot\", \"discord-bot\",\n \"gitlab-user\", \"github-user\",\n \"gmail\", \"hotmail\", \"smtp\",\n \"hubspot\", \"salesforce\", \"pipedrive\", \"odoo\",\n \"trello\", \"linear\", \"asana\", \"jira\", \"notion\",\n \"stripe\", \"sentry\", \"vercel\", \"twilio\", \"custom\",\n ])\n for (const [agentId, a] of Object.entries((cfg.agents ?? {}) as Record<string, any>)) {\n const list = (a.integrations as any[] | undefined) ?? []\n if (!list.length) continue\n const seen = new Set<string>()\n for (const i of list) {\n const key = `${i.kind}::${i.label}`\n if (seen.has(key)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: duplicate (${i.kind}, ${i.label})`,\n fix: `Remove the duplicate or rename one. (kind, label) must be unique per agent.`,\n })\n }\n seen.add(key)\n if (!KNOWN_KINDS.has(i.kind)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: unknown kind \"${i.kind}\" on integration \"${i.label}\"`,\n fix: `Use a canonical kind from INTEGRATION_KINDS, or \"custom\" for ad-hoc services.`,\n })\n }\n const creds = (i.credentials || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(creds)) {\n if (typeof v === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(v) && !process.env[v]) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations[${i.kind}/${i.label}].${k} -> $${v} but env var is unset (in this shell)`,\n fix: `Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`,\n })\n }\n }\n }\n }\n\n // (Removed: the \"agentx.json newer than daemon pid\" check produced\n // false positives because the pid file is only rewritten on start,\n // not on hot-reload. The signal-to-noise was too low. A future check\n // can query /reload's `lastReload` timestamp via the daemon API\n // instead of using filesystem mtimes.)\n\n if (findings.length === 0) {\n checks.push({\n severity: \"ok\",\n group: \"Routing\",\n title: `${webhooks.length} webhook(s), ${Object.keys(cfg.channels?.telegram?.accounts ?? {}).length} telegram account(s) — all routing references resolve`,\n })\n return\n }\n for (const f of findings) {\n checks.push({ severity: f.severity, group: \"Routing\", title: f.title, fix: f.fix })\n }\n}\n\nasync function runRuntimeChecks(checks: Check[], cfg: any): Promise<void> {\n const url = cfg.dashboard?.daemonUrl?.replace(/\\/+$/, \"\") || \"http://127.0.0.1:18800\"\n const headers: Record<string, string> = {}\n if (cfg.dashboard?.token) headers[\"Authorization\"] = `Bearer ${cfg.dashboard.token}`\n try {\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), 2000)\n const r = await fetch(url + \"/health\", { headers, signal: ac.signal })\n clearTimeout(timer)\n if (!r.ok) {\n checks.push({ severity: \"warn\", group: \"Runtime\", title: `Daemon responded ${r.status}`, detail: url })\n return\n }\n const body: any = await r.json()\n checks.push({\n severity: \"ok\",\n group: \"Runtime\",\n title: `Daemon healthy — ${body.agents?.length ?? 0} agents live, uptime ${Math.round((body.uptime ?? 0) / 60)}m`,\n detail: url,\n })\n } catch {\n checks.push({\n severity: \"warn\",\n group: \"Runtime\",\n title: \"Daemon not reachable (not running?)\",\n detail: url,\n fix: \"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`.\",\n })\n }\n}\n\nfunction runCodegraphChecks(checks: Check[], cfg: any): void {\n const optedIn = Object.entries(cfg.agents || {})\n .filter(([, a]: [string, any]) =>\n a?.codegraph === true && (a.tier === \"claude-code\" || a.tier === \"codex-cli\"),\n ) as Array<[string, any]>\n\n if (optedIn.length === 0) return // No agent uses codegraph — skip silently.\n\n // Binary on PATH.\n let cgPath: string | null = null\n try {\n cgPath = execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codegraph\"], { encoding: \"utf-8\" })\n .trim().split(\"\\n\")[0] || null\n } catch { cgPath = null }\n\n if (cgPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codegraph\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `codegraph CLI ${ver || \"installed\"}`,\n detail: cgPath,\n })\n } else {\n checks.push({\n severity: \"fail\",\n group: \"CodeGraph\",\n title: \"codegraph CLI not on PATH\",\n detail: `${optedIn.length} agent(s) have codegraph:true but the binary isn't available.`,\n fix: \"Install with `npm i -g @colbymchenry/codegraph`.\",\n })\n }\n\n // Per-workspace index presence.\n for (const [agentId, def] of optedIn) {\n if (!def.workspace || !existsSync(def.workspace)) {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: workspace missing`,\n detail: `Workspace path ${def.workspace} does not exist — codegraph will skip this agent.`,\n })\n continue\n }\n const dbPath = resolve(def.workspace, \".codegraph\", \"codegraph.db\")\n if (existsSync(dbPath)) {\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `${agentId}: index present`,\n detail: dbPath,\n })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: index not built yet`,\n detail: \".codegraph/ missing — daemon will background-index this workspace on next boot.\",\n fix: `Run \\`codegraph init --index ${def.workspace}\\` to build it now.`,\n })\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Output\n// ---------------------------------------------------------------------------\n\nfunction summarize(checks: Check[]): { errors: number; warnings: number; ok: number } {\n return {\n errors: checks.filter((c) => c.severity === \"fail\").length,\n warnings: checks.filter((c) => c.severity === \"warn\").length,\n ok: checks.filter((c) => c.severity === \"ok\").length,\n }\n}\n\nfunction printHumanReport(checks: Check[]): void {\n console.log()\n console.log(chalk.bold(\" agentx doctor\"))\n console.log()\n\n const groups = new Map<string, Check[]>()\n for (const c of checks) {\n if (!groups.has(c.group)) groups.set(c.group, [])\n groups.get(c.group)!.push(c)\n }\n for (const [group, items] of groups) {\n console.log(chalk.bold(\" \" + group))\n for (const c of items) {\n const marker = c.severity === \"ok\" ? chalk.green(\"✓\")\n : c.severity === \"warn\" ? chalk.yellow(\"!\")\n : chalk.red(\"✗\")\n console.log(` ${marker} ${c.title}`)\n if (c.detail) console.log(chalk.dim(\" \" + c.detail.replace(/\\n/g, \"\\n \")))\n if (c.fix) console.log(chalk.dim(\" → \" + c.fix))\n }\n console.log()\n }\n\n const s = summarize(checks)\n if (s.errors > 0) {\n console.log(chalk.red.bold(` ${s.errors} error${s.errors === 1 ? \"\" : \"s\"}`) +\n (s.warnings ? chalk.yellow(`, ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}`) : \"\") +\n `. Fix the error${s.errors === 1 ? \"\" : \"s\"} and rerun.`)\n } else if (s.warnings > 0) {\n console.log(chalk.yellow.bold(` ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}.`) + chalk.dim(\" Review but not blocking.\"))\n } else {\n console.log(chalk.green.bold(` All checks passed (${s.ok}).`))\n }\n console.log()\n}\n","import { execFile } from \"child_process\"\nimport { findHelper } from \"./local\"\n\n// Why a banner shows the Script Editor icon instead of the AgentX logo,\n// in words a person can act on. `agentx notify` falls back to osascript\n// silently — it must never fail to notify — so this is where the reason\n// surfaces: `agentx notifications show` and `agentx doctor` print it.\n//\n// Reading the status never posts a banner and never shows the macOS\n// \"allow notifications\" prompt.\n\nexport type HelperState = \"ready\" | \"unsupported\" | \"missing\" | \"outdated\" | \"not-asked\" | \"not-allowed\" | \"hidden\"\n\nexport interface HelperStatus {\n state: HelperState\n /** One plain sentence on what the person will see. */\n message: string\n /** What to do about it; absent when nothing needs doing. */\n fix?: string\n /** The helper binary that was checked, when there is one. */\n path?: string\n}\n\n/** Runs a command and resolves its stdout, or null when it failed. */\ntype Capture = (file: string, args: string[]) => Promise<string | null>\n\nconst capture: Capture = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: 5_000 }, (err, stdout) => done(err ? null : String(stdout)))\n } catch {\n done(null)\n }\n })\n\nconst SETTINGS = \"Open System Settings › Notifications › AgentX Helper, turn on Allow notifications and choose Banners.\"\n\nexport async function helperStatus(\n deps: { platform?: NodeJS.Platform; helper?: string | null; run?: Capture } = {},\n): Promise<HelperStatus> {\n if ((deps.platform ?? process.platform) !== \"darwin\") {\n return { state: \"unsupported\", message: \"Desktop banners are only shown on a Mac.\" }\n }\n const path = deps.helper === undefined ? findHelper() : deps.helper\n if (!path) {\n return {\n state: \"missing\",\n message: \"AgentX Helper is not installed, so banners come from Script Editor and show its icon.\",\n fix: \"Run agentx desktop install, then run agentx notify \\\"Hello\\\" --title \\\"Test\\\" and click Allow.\",\n }\n }\n const out = await (deps.run ?? capture)(path, [\"notify-status\"])\n let status: { authorization?: string; alertStyle?: string } | null = null\n try { status = out ? JSON.parse(out) : null } catch { status = null }\n if (!status) {\n return {\n state: \"outdated\",\n path,\n message: \"AgentX Helper is too old to report whether it may notify.\",\n fix: \"Run agentx desktop install to update it.\",\n }\n }\n if (status.authorization === \"notDetermined\") {\n return {\n state: \"not-asked\",\n path,\n message: \"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.\",\n fix: \"Run agentx notify \\\"Hello\\\" --title \\\"Test\\\" and click Allow when macOS asks.\",\n }\n }\n if (status.authorization === \"denied\") {\n return { state: \"not-allowed\", path, message: \"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.\", fix: SETTINGS }\n }\n if (status.alertStyle === \"none\") {\n return { state: \"hidden\", path, message: \"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.\", fix: SETTINGS }\n }\n return { state: \"ready\", path, message: \"AgentX Helper posts banners with the AgentX icon.\" }\n}\n"],"mappings":"4GAOAA,IAPA,OAAS,WAAAC,MAAe,YACxB,OAAOC,MAAW,QAClB,OAAS,gBAAAC,MAAoB,gBAC7B,OAAS,cAAAC,EAAY,aAAAC,EAAW,cAAAC,EAAY,gBAAAC,EAAc,eAAAC,EAAa,YAAAC,MAAgB,KACvF,OAAS,QAAAC,EAAM,WAAAC,MAAe,OAC9B,OAAS,WAAAC,MAAe,KACxB,OAAS,iBAAAC,MAAqB,SCN9B,OAAS,YAAAC,MAAgB,gBA0BzB,IAAMC,EAAmB,CAACC,EAAMC,IAC9B,IAAI,QAASC,GAAS,CACpB,GAAI,CACFC,EAASH,EAAMC,EAAM,CAAE,QAAS,GAAM,EAAG,CAACG,EAAKC,IAAWH,EAAKE,EAAM,KAAO,OAAOC,CAAM,CAAC,CAAC,CAC7F,MAAE,CACAH,EAAK,IAAI,CACX,CACF,CAAC,EAEGI,EAAW,kHAEjB,eAAsBC,EACpBC,EAA8E,CAAC,EACxD,CACvB,IAAKA,EAAK,UAAY,QAAQ,YAAc,SAC1C,MAAO,CAAE,MAAO,cAAe,QAAS,0CAA2C,EAErF,IAAMC,EAAOD,EAAK,SAAW,OAAYE,EAAW,EAAIF,EAAK,OAC7D,GAAI,CAACC,EACH,MAAO,CACL,MAAO,UACP,QAAS,wFACT,IAAK,4FACP,EAEF,IAAME,EAAM,MAAOH,EAAK,KAAOT,GAASU,EAAM,CAAC,eAAe,CAAC,EAC3DG,EAAiE,KACrE,GAAI,CAAEA,EAASD,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ACd","names":["init_config","Command","chalk","execFileSync","accessSync","constants","existsSync","readFileSync","readdirSync","statSync","join","resolve","homedir","createRequire","execFile","capture","file","args","done","execFile","err","stdout","SETTINGS","helperStatus","deps","path","findHelper","out","status","runDoctorChecks","opts","checks","runEnvChecks","runDesktopChecks","cfg","runConfigChecks","runReferenceChecks","runWorkspaceChecks","runWorkspaceSettingsChecks","runRoutingChecks","runCodegraphChecks","runNotificationChecks","runReminderChecks","runRuntimeChecks","summarize","doctor","Command","summary","printHumanReport","status","helperStatus","localSettings","helper","platform","isExecutable","file","accessSync","constants","r","command","found","findOnPath","nodeMajor","which","bin","execFileSync","npmPath","claudePath","ver","codexPath","openCodePath","createRequire","e","agents","join","homedir","names","readdirSync","n","name","path","plistPathEnv","readFileSync","ffmpeg","cfgPath","resolve","existsSync","loadDaemonConfig","claudeCodeAgents","id","codexCliAgents","openCodeAgents","refs","collectEnvRefs","envFile","envFromFile","line","m","missing","empty","raw","node","into","item","v","a","abs","statSync","VAR_RE","findings","agentId","wsAbs","fname","p","data","env","k","unexpanded","pathVal","parts","perms","allow","deny","f","webhooks","workflowDir","knownWorkflows","multiEventSources","w","eventType","workflowId","wf","peers","seen","key","prior","agentIds","acctId","acct","KNOWN_KINDS","list","i","creds","url","headers","ac","timer","body","optedIn","cgPath","def","dbPath","c","chalk","groups","group","items","marker","s"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as et,b as tt,c as nt,d as S,e as A,f as N}from"./chunk-72SZI2UW.js";import{a as Te,b as ft}from"./chunk-FX3D7YON.js";import{a as ne,b as He}from"./chunk-FCPTN6NF.js";import{o as we,p as Ke}from"./chunk-SZJMS7K4.js";import{o as We,p as Ze}from"./chunk-
|
|
1
|
+
import{a as et,b as tt,c as nt,d as S,e as A,f as N}from"./chunk-72SZI2UW.js";import{a as Te,b as ft}from"./chunk-FX3D7YON.js";import{a as ne,b as He}from"./chunk-FCPTN6NF.js";import{o as we,p as Ke}from"./chunk-SZJMS7K4.js";import{o as We,p as Ze}from"./chunk-4FFWNPFX.js";import{a as rt,b as ot,c as st,d as it,e as at,f as ct,g as ut,h as lt,i as dt,j as pt,k as mt,l as bt}from"./chunk-RGDKHYY2.js";import{a as E,b as Ye,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function gt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import yt from"better-sqlite3";import{createHash as ht}from"crypto";import{mkdirSync as wt}from"fs";import{dirname as Tt,resolve as Et}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function kt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function xt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&Rt(e),t<2&&At(e),t<3&&St(e)}function St(e){e.exec(`
|
|
2
2
|
ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
|
|
3
3
|
INSERT INTO schema_version (v) VALUES (3);
|
|
4
4
|
`)}function At(e){e.exec(`
|
|
@@ -111,4 +111,4 @@ import{a as et,b as tt,c as nt,d as S,e as A,f as N}from"./chunk-72SZI2UW.js";im
|
|
|
111
111
|
`)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${h}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let x=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=x.answer,x.repaired&&(L=!0)}return{model:a,answers:M,usage:g,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function $t(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:B,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:B}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===B),u=a&&a.type==="tool_use"?a.input:null;return{answers:Pe(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Vt(e,t,r,n,o){let s=[r,ae(t)].join(`
|
|
112
112
|
`),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Pe(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Pe(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function zt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Jt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Bt,Pt,qt,Be,Xt,be=E(()=>{"use strict";Ke();Ue();ft();j();Y();N();z();Bt="claude-code",Pt="claude-haiku-4-5-20251001",qt=24e3,Be=2e3,Xt=3e4});import{readFileSync as Gt}from"fs";import{homedir as Yt}from"os";import{join as Kt}from"path";function v(e={}){let t=(e.baseUrl??Ht).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??Zt,s=e.maxChoiceOptions??en,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),on(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:y,dispose:d}=sn(a.abortSignal,a.timeoutMs??e.timeoutMs??Wt);try{let b={"Content-Type":"application/json"},g=rn(e.apiKeyEnv,e.apiKeyFile);g&&(b.Authorization=`Bearer ${g}`);let w=await p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:nn(a.questions)}),signal:y});if(!w.ok){let k=await w.text().catch(()=>"");throw new Error(`${n} ${w.status}: ${k.slice(0,300)}`)}let f=await w.json(),m=F(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
|
|
113
113
|
${U(m.error)}`);let h=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let x=_(q,h[k]);M[k]=x.answer,x.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function nn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:tn[n.type]};return t}function rn(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Kt(Yt(),t.slice(2)):t;if(!Z.has(n))try{let o=Gt(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function on(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function sn(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Ht,Wt,Zt,en,tn,Z,fe=E(()=>{"use strict";j();N();z();Y();Ht="http://127.0.0.1:8000/v1",Wt=3e4,Zt=6e3,en=50;tn={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var qe={};Ye(qe,{DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>B,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>gt,agreement:()=>rt,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>lt,askSeat:()=>pn,band:()=>Ie,bootstrapInterval:()=>pt,brier:()=>at,buildDesign:()=>Ne,calibrationReport:()=>mt,choice:()=>tt,compareCalibrators:()=>Lt,confidenceFor:()=>re,configureDecisions:()=>cn,coverageCurve:()=>ut,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>v,decisionsRuntime:()=>ln,describeIssues:()=>U,ece:()=>st,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>ve,fitRecalibrator:()=>P,fitTemperature:()=>dt,getDecisionBackend:()=>D,getSeatMode:()=>Ve,labelsOf:()=>S,listDecisionBackends:()=>Ee,logLoss:()=>ct,logit:()=>le,mce:()=>it,measureConsistency:()=>Qt,normalizeDistribution:()=>xe,normalizedNegEntropy:()=>oe,noul:()=>et,pMax:()=>Se,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>F,recordSeatOutcome:()=>dn,registerBuiltinDecisionBackends:()=>an,registerDecisionBackend:()=>R,reliabilityBins:()=>ot,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>un,score:()=>nt,seatEnvVar:()=>$e,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function an(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>v(t)),R("jev",()=>v({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>v({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var Xe=E(()=>{"use strict";ke();N();j();z();C();Y();V();bt();Me();je();ze();pe();be();fe();C();pe();be();fe()});function cn(e){T={...ye,...T,...e},ee=!0}function un(){T={...ye,seats:{}},ee=!1}function mn(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(Ze(),he(We)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=(Xe(),he(qe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}T={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function ln(){return T}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return bn.includes(t)?t:null}function $e(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Ve(e,t=process.env){mn();let r=ge(t[$e(e)]);return r||(T.enabled?ge(T.seats[e]?.mode)??"off":"off")}function dn(e,t,r=!1){if(!(!e||!T.store))try{T.store.recordOutcome(e,t,r)}catch{}}async function pn(e,t,r,n={}){let o=Ve(e);if(o==="off")return null;let s=T.seats[e]??{mode:o},i=n.backend??s.backend??T.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs}),l=fn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return gn(e,o,t,r,i,n,s,a,u),yn(e,i,u),null}}function fn(e,t,r,n,o,s,i){if(!T.store)return null;try{return T.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:Ge(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function gn(e,t,r,n,o,s,i,a,u){if(T.store)try{T.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:Ge(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function Ge(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function yn(e,t,r){let n=Date.now();n-Je<6e4||(Je=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var ye,T,ee,bn,Je,ze=E(()=>{C();V();ye={enabled:!1,defaultBackend:"local",seats:{},store:null},T={...ye},ee=!1;bn=["off","shadow","active"];Je=0});export{D as a,Ee as b,C as c,I as d,V as e,Lt as f,Me as g,Qt as h,je as i,me as j,Un as k,Ue as l,an as m,Xe as n,cn as o,un as p,ln as q,ge as r,$e as s,Ve as t,dn as u,pn as v,ze as w};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-37EABIOJ.js.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import{t as ve,u as Re}from"./chunk-3W2KMI5O.js";import{d as Ie,e as $e}from"./chunk-AQASR6KR.js";import{b as J}from"./chunk-HQMISQ7L.js";import{g as ye,h as ke,i as we,k as xe,l as Se}from"./chunk-QYHABRLM.js";import{q as be}from"./chunk-ZOJUHPD5.js";import{m as he,p as ct}from"./chunk-4FFWNPFX.js";import{existsSync as ut,readdirSync as dt,readFileSync as gt,statSync as ft}from"fs";import{resolve as mt}from"path";function Ae(n,e,t=Date.now(),s=7){let r=s*864e5,i=new Map;for(let a of e){let o=i.get(a.workflowId);o?o.push(a):i.set(a.workflowId,[a])}return n.map(a=>{let o=i.get(a.id)??[],l=o.filter(m=>t-m.at<=r),c=o.filter(m=>t-m.at>r&&t-m.at<=r*2),u=l.filter(m=>m.status==="failed").length,g=o.filter(m=>m.status==="paused").length,d=o.length?Math.max(...o.map(m=>m.at)):null,f=o.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:a.id,name:a.name||a.id,state:f,lastRunAt:d,recent:l.length,prior:c.length,failed:u,paused:g}}).sort((a,o)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[a.state]-l[o.state]||(o.lastRunAt??0)-(a.lastRunAt??0)})}var F=new Map;function Ln(n,e=1e3){if(!ut(n))return[];let t=dt(n).filter(i=>i.endsWith(".jsonl")).map(i=>{let a=mt(n,i);return{path:a,mtime:ft(a).mtimeMs}}).sort((i,a)=>a.mtime-i.mtime).slice(0,e),s=new Set(t.map(i=>i.path));for(let i of F.keys())s.has(i)||F.delete(i);let r=[];for(let{path:i,mtime:a}of t){let o=F.get(i);if(o&&o.mtime===a){o.summary&&r.push(o.summary);continue}let l=pt(i,a);F.set(i,{mtime:a,summary:l}),l&&r.push(l)}return r}function pt(n,e){try{let t=gt(n,"utf-8").split(`
|
|
2
|
+
`).filter(Boolean);if(!t.length)return null;let s=JSON.parse(t[0]),r=s.run?.workflowId;if(!r)return null;let i=s.run?.status??"unknown";for(let a=t.length-1;a>=0;a--){let o=JSON.parse(t[a]),l=o.status??o.run?.status;if(l){i=l;break}}return{workflowId:r,status:i,at:e}}catch{return null}}var ht={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},bt=(n,e,t)=>{try{return be(n,e,t)}catch{return null}},_e=864e5;function Bn(n){let e=n.now??Date.now(),t={...ht,...n.thresholds},s=n.nextFire??bt,r=[];for(let o of n.crons){let l=n.cronRuns.get(o.id)??[],c=o.timezone||"UTC",u=l.map(f=>({at:Date.parse(f.startedAt),status:f.status})),g=l[0],d={id:`cron:${o.id}`,source:"cron",kind:"schedule",name:S(o.id,k.text),trigger:{schedule:S(o.schedule,k.text),timezone:c},agent:o.agent||null,enabled:o.enabled,state:o.enabled?"enabled":"disabled",nextRunAt:o.enabled?G(o.nextRun)??G(s(o.schedule,new Date(e),c)):null,lastRun:g?{at:g.startedAt,status:g.status,summary:It(g.status==="success"?void 0:g.errorSummary,k.summary)}:null,lastSuccessAt:l.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:Ce(u),sampledRuns:l.length,flags:[],attention:null};d.flags=De(d,u,o.schedule,c,null,e,t,s),r.push(je(d))}let i=new Map(Ae(n.workflows.map(o=>({id:o.id,name:o.title})),n.workflowRuns,e).map(o=>[o.id,o])),a=new Map;for(let o of n.workflowRuns){let l=a.get(o.workflowId);l?l.push(o):a.set(o.workflowId,[o])}for(let o of n.workflows){let l=o.nodes.find(v=>v.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},u=o.state||"active",g=u==="active",d=(a.get(o.id)??[]).slice().sort((v,q)=>q.at-v.at),f=d.map(v=>({at:v.at,status:wt(v.status)})),m=f[0],h=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",K=typeof c.timezone=="string"?c.timezone:"UTC",L={id:`workflow:${o.id}`,source:"workflow",kind:h?"schedule":"event",name:S(o.title||o.id,k.text),trigger:h?{schedule:S(b,k.text),timezone:K}:{event:S(typeof c.event=="string"?c.event:"",k.text),filters:St(c.filter,o)},agent:xt(o),enabled:g,state:u,nextRunAt:h&&g&&b?G(s(b,new Date(e),K)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let v=f.find(q=>q.status==="success");return v?new Date(v.at).toISOString():null})(),consecutiveFailures:Ce(f),sampledRuns:d.length,flags:[],attention:null},P=Date.parse(o.updated||o.created||"");L.flags=h?De(L,f,b,K,Number.isFinite(P)?P:null,e,t,s):yt(L,i.get(o.id)?.state==="dormant",Number.isFinite(P)?P:null,e,t),r.push(je(L))}return r.sort(kt).slice(0,k.routines)}function Ce(n){let e=0;for(let t of n)if(!(t.status==="running"||t.status==="paused"||t.status==="unknown"))if(t.status==="failed"||t.status==="timeout")e++;else break;return e}function De(n,e,t,s,r,i,a,o){let l=[],c=e.length?e[0].at:null;if(!n.enabled){let d=Ee(c,r,i,a);return d&&l.push(d),l}if(n.consecutiveFailures>=a.failStreak&&l.push({reason:"failing",detail:`${n.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let u=new Date(c),g=null;for(let d=0;d<a.missedFires&&(g=o(t,u,s),!!g);d++)u=g;return g&&i>g.getTime()+a.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${a.missedFires} scheduled fires missed`}),l}function yt(n,e,t,s,r){let i=[],a=n.lastRun?Date.parse(n.lastRun.at):null;if(!n.enabled){let o=Ee(a,t,s,r);return o&&i.push(o),i}return n.consecutiveFailures>=r.failStreak&&i.push({reason:"failing",detail:`${n.consecutiveFailures} failed runs in a row`}),a===null?i.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&i.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),i}function Ee(n,e,t,s){let r=Math.max(n??0,e??0);return r&&t-r<s.disabledDays*_e?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((t-r)/_e)} days`:"Disabled and never ran"}}function je(n){let e=new Set(n.flags.map(t=>t.reason));return n.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,n}var Te={critical:0,warning:1,info:2};function kt(n,e){let t=n.attention?Te[n.attention]:3,s=e.attention?Te[e.attention]:3;return t-s||Number(e.enabled)-Number(n.enabled)||n.name.localeCompare(e.name)}function wt(n){switch(n){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 xt(n){if(n.ownerAgent)return S(n.ownerAgent,k.text);let e=n.nodes.find(t=>t.type==="agent"&&typeof t.config?.agentId=="string"&&t.config.agentId);return e?S(String(e.config.agentId),k.text):null}function St(n,e){let t=[],s=e?.project;if(s&&t.push(S(`project=${s}`,k.filterValue)),n&&typeof n=="object"&&!Array.isArray(n))for(let[r,i]of Object.entries(n)){let a=Array.isArray(i)?i.map(String):i==null?[]:[String(i)];a.length&&t.push(S(`${r}=${a.join(",")}`,k.filterValue))}return t.slice(0,k.filters)}function G(n){if(!n)return null;let e=n instanceof Date?n:new Date(n);return Number.isFinite(e.getTime())?e.toISOString():null}function S(n,e){return n.length<=e?n:n.slice(0,e-3)+"..."}function It(n,e){return n===void 0?void 0:S(n,e)}import{createHash as $t,randomBytes as Oe}from"crypto";import{existsSync as vt,mkdirSync as Rt,readFileSync as At,writeFileSync as _t}from"fs";import{resolve as Ct,dirname as Dt}from"path";var V="agx_live_",jt=".agentx/tokens.json",Le=class{file;constructor(e=process.cwd(),t=jt){this.file=Ct(e,t)}load(){if(!vt(this.file))return[];try{return JSON.parse(At(this.file,"utf-8"))}catch{return[]}}save(e){Rt(Dt(this.file),{recursive:!0}),_t(this.file,JSON.stringify(e,null,2)+`
|
|
3
|
+
`,"utf-8")}create(e){if(!e.name?.trim())throw new Error("Token name is required.");if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("At least one scope is required.");for(let a of e.scopes)if(!Tt(a))throw new Error(`Invalid scope: ${a}`);let t=Oe(32).toString("hex"),s=V+t,r={id:"tok_"+Oe(4).toString("hex"),name:e.name.trim(),prefix:V+t.slice(0,4),hash:Pe(s),scopes:[...e.scopes],createdAt:new Date().toISOString(),expiresAt:e.expiresInDays?new Date(Date.now()+e.expiresInDays*86400*1e3).toISOString():void 0},i=this.load();return i.push(r),this.save(i),{token:s,record:r}}list(){return this.load()}revoke(e){let t=this.load(),s=t.find(r=>r.id===e);return s?(s.revokedAt=new Date().toISOString(),this.save(t),s):null}isActive(e){let t=this.load().find(s=>s.id===e);return!!t&&!t.revokedAt&&!(t.expiresAt&&Date.parse(t.expiresAt)<Date.now())}verify(e){if(!e||!e.startsWith(V))return null;let t=Pe(e),s=this.load(),r=s.find(o=>o.hash===t);if(!r||r.revokedAt||r.expiresAt&&Date.parse(r.expiresAt)<Date.now())return null;let i=Date.now(),a=r.lastUsedAt?Date.parse(r.lastUsedAt):0;if(i-a>6e4){r.lastUsedAt=new Date(i).toISOString();try{this.save(s)}catch{}}return r}};function Hn(n,e){return!!(n.scopes.includes(e)||e.startsWith("agent:")&&n.scopes.includes("agent:*")||e==="dashboard:read"&&n.scopes.includes("dashboard:write"))}function Tt(n){return n==="dashboard:read"||n==="dashboard:write"||n==="agent:*"||/^agent:[a-z0-9][a-z0-9_-]*$/.test(n)||n==="mesh:peer"||n==="app"}function Pe(n){return"sha256:"+$t("sha256").update(n).digest("hex")}function Kn(n){let e=n.headers.authorization,t=Array.isArray(e)?e[0]:e;if(t&&t.toLowerCase().startsWith("bearer "))return t.slice(7).trim();if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{}return null}import{existsSync as X,readdirSync as Vt,readFileSync as Xt}from"fs";import{resolve as C}from"path";import{existsSync as Et,mkdirSync as Ot,readdirSync as Lt,readFileSync as Pt,renameSync as Ft,writeFileSync as Ut}from"fs";import{resolve as Ue}from"path";var Fe=["discard","keep","pause","approve"],I={title:120,ask:300,recommend:300,source:500,note:500,pendingPerAgent:25},Bt={defaultExpiryDays:3,maxExpiryDays:30};function _(n){return Ue(n,".agentx","approvals")}var Nt=/^[a-z0-9][a-z0-9-]{0,80}$/;function Be(n){return Nt.test(n)}function Ne(n,e){if(!Be(e))throw new Error(`invalid card id: ${e}`);return Ue(_(n),`${e}.json`)}function Mt(n,e){let t=new Date(n).toISOString().slice(0,10),s=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${t}-${s||"card"}-${Math.random().toString(36).slice(2,6)}`}function U(n,e){Ot(_(n),{recursive:!0});let t=Ne(n,e.id),s=`${t}.${process.pid}.tmp`;Ut(s,JSON.stringify(e,null,2)+`
|
|
4
|
+
`),Ft(s,t)}function j(n,e){if(!Be(e))return null;try{return JSON.parse(Pt(Ne(n,e),"utf-8"))}catch{return null}}function T(n,e){let t=_(n);if(!Et(t))return[];let s=[];for(let r of Lt(t).filter(i=>i.endsWith(".json")&&!i.startsWith("_")).sort()){let i=j(n,r.slice(0,-5));i&&(!e||i.status===e)&&s.push(i)}return s}function y(n){return typeof n=="string"?n.replace(/\s+/g," ").trim():""}function Wt(n,e,t){let s=e+t.maxExpiryDays*864e5,r,i=y(n);if(!i)r=e+t.defaultExpiryDays*864e5;else{let a=/^(\d+)\s*([hd])$/i.exec(i);if(a)r=e+Number(a[1])*(a[2].toLowerCase()==="d"?864e5:36e5);else if(r=Date.parse(i),Number.isNaN(r))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${i}")`}}return r<=e?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(r,s)).toISOString()}}function zt(n,e={}){let t=e.now??Date.now(),s=e.settings??Bt,r=y(n.title),i=y(n.ask),a=y(n.recommend),o=y(n.raised_by);if(!r)return{ok:!1,error:"title is required"};if(!i)return{ok:!1,error:"ask is required: the yes/no question"};if(!a)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!o)return{ok:!1,error:"raised_by is required: the agent id"};if(r.length>I.title)return{ok:!1,error:`title is longer than ${I.title} characters`};if(i.length>I.ask)return{ok:!1,error:`ask is longer than ${I.ask} characters`};if(a.length>I.recommend)return{ok:!1,error:`recommend is longer than ${I.recommend} characters`};let l=y(n.if_silent).toLowerCase();if(!Fe.includes(l))return{ok:!1,error:`if_silent must be one of ${Fe.join(", ")}`};let c=Wt(n.expires,t,s);if(!c.ok)return c;let u=y(n.source);if(u.length>I.source)return{ok:!1,error:`source is longer than ${I.source} characters`};if(u&&/^[a-z][a-z0-9+.-]*:/i.test(u)&&!/^https?:\/\//i.test(u))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let g,d=n.reply;return d&&typeof d=="object"&&y(d.channel)&&y(d.chatId)&&(g={channel:y(d.channel),chatId:y(d.chatId),...y(d.accountId)?{accountId:y(d.accountId)}:{}}),{ok:!0,card:{id:Mt(t,r),title:r,ask:i,recommend:a,if_silent:l,expires:c.at,...u?{source:u}:{},raised_by:o,created_at:new Date(t).toISOString(),...g?{reply:g}:{},status:"pending"}}}function Vn(n,e,t={}){let s=zt(e,t);if(!s.ok)return s;let r=T(n,"pending").filter(i=>i.raised_by===s.card.raised_by).length;return r>=I.pendingPerAgent?{ok:!1,error:`${s.card.raised_by} already has ${r} cards waiting; wait for decisions before raising more`}:(U(n,s.card),s)}function Me(n,e,t,s={}){let r=j(n,e);if(!r)return{ok:!1,error:`no card "${e}"`};if(r.status!=="pending")return{ok:!1,error:`card "${e}" is already ${r.status}`};let i=y(s.note).slice(0,I.note),a={...r,status:"decided",verdict:t,decided_by:s.by??"operator",decided_at:new Date(s.now??Date.now()).toISOString(),...i?{note:i}:{}};return U(n,a),{ok:!0,card:a}}function Xn(n,e=Date.now()){let t=[];for(let s of T(n,"pending")){if(Date.parse(s.expires)>e)continue;let r={...s,status:"expired",outcome:s.if_silent,decided_by:"expiry",decided_at:new Date(e).toISOString()};U(n,r),t.push(r)}return t}function Yn(n){return T(n).filter(e=>e.status!=="pending"&&!e.agent_notified_at)}function Qn(n,e,t=Date.now()){let s=j(n,e);!s||s.agent_notified_at||U(n,{...s,agent_notified_at:new Date(t).toISOString()})}function Zn(n){let e=n.status==="decided"?n.verdict==="yes"?"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${n.outcome??n.if_silent}.`,t=[`[Approval result] Your decision card "${n.title}" (${n.id}) is closed.`,`Question: ${n.ask}`,e];return n.note&&t.push(`Operator note: ${n.note}`),n.source&&t.push(`Source: ${n.source}`),n.reply&&t.push(`You raised it from ${n.reply.channel} chat ${n.reply.chatId}; reply there if the requester should know.`),t.push("Act on this result now. Do not raise the same card again."),t.join(`
|
|
5
|
+
`)}import{mkdirSync as Ht,readFileSync as Kt,renameSync as qt,writeFileSync as Jt}from"fs";import{resolve as Gt}from"path";function We(n){return Gt(_(n),"_state.json")}function B(n){try{let e=JSON.parse(Kt(We(n),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{}}}catch{return{snoozed:{}}}}function ze(n,e){Ht(_(n),{recursive:!0});let t=We(n),s=`${t}.${process.pid}.tmp`;Jt(s,JSON.stringify(e,null,2)+`
|
|
6
|
+
`),qt(s,t)}function He(n,e,t,s=Date.now()){let r=B(n),i={};for(let[a,o]of Object.entries(r.snoozed))Date.parse(o)>s&&(i[a]=o);i[e]=t.toISOString(),ze(n,{...r,snoozed:i})}function sr(n,e){ze(n,{...B(n),lastDigest:e})}var Ke=["card","schedule","memory","wiki"],Yt=280;function Y(n,e=Yt){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function qe(n){if(n.configPath)return C(n.configPath);let e=[C(n.root,"agentx.json"),C(n.root,".agentx","config.json")];return e.find(t=>X(t))??e[0]}function Q(n){return n.wikiDir?C(n.wikiDir):C(n.root,".agentx","wiki")}function Qt(n){return T(n.root,"pending").map(Zt)}function Zt(n){return{key:`card:${n.id}`,kind:"card",title:n.title,ask:n.ask,yes:`tell ${n.raised_by} yes`,no:`tell ${n.raised_by} no`,recommend:n.recommend,if_silent:n.if_silent,expires:n.expires,...n.source?{source:n.source}:{},raised_by:n.raised_by,created_at:n.created_at}}function en(n){let e=qe(n);if(!X(e))return[];let t;try{t=JSON.parse(Xt(e,"utf-8"))}catch{return[]}let s=new Date(n.now??Date.now()),r=[];for(let[i,a]of Object.entries(t?.crons??{})){let o=a?.approval;if(!o||o.action!=="create"&&o.action!=="delete")continue;let l=a.timezone||"UTC",c=a.schedule?ye(a.schedule):"",u=a.schedule?`${c.charAt(0).toLowerCase()}${c.slice(1)} (${a.schedule})`:"no schedule",g=String(a.prompt??a.command??""),d=o.action==="create";r.push({key:`schedule:${i}`,kind:"schedule",title:d?`New schedule "${i}" for ${a.agent??"an agent"}`:`Delete schedule "${i}"`,ask:d?`Let ${a.agent??"the agent"} run this ${u}?`:`Remove the schedule "${i}" (${u})?`,yes:d?"enable it":"remove it",no:d?"drop the request":"keep the schedule",raised_by:String(o.requestedBy??"unknown"),created_at:String(o.requestedAt??""),detail:Y(`${g}${d&&a.schedule?` \xB7 first run ${we(ke(a.schedule,l,s),l)}`:""}`),more:"agentx schedule list"})}return r}function Je(n){let e=C(n,".agentx","memory");return X(e)?Vt(e).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}function tn(n){let e=Je(n.root);if(e.length===0)return[];let t=new J(n.root),s=[];for(let r of e)for(let i of t.held(r))s.push({key:`memory:${r}/${i.id}`,kind:"memory",title:`Fact ${r} learned from ${i.source.channel}`,ask:`Let ${r} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:r,created_at:i.createdAt,detail:Y(i.content),more:`agentx memory facts held --agent ${r}`});return s}function nn(n){let e=n.sources.filter(t=>t.failure);return e.length?e.map(t=>`Recurring failure: ${t.agentId}'s ${t.failure.tool} fails with "${t.failure.errorClass}" in ${t.occurrences??1} sessions (${t.failure.runs} runs).`).join(" "):`${n.sources.length} source(s)${n.occurrences>1?`, seen in ${n.occurrences} sessions`:""}.`}function rn(n){return $e(Q(n),"pending").map(e=>{let t=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:t.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:Y(`${nn(t)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var Ge={card:Qt,schedule:en,memory:tn,wiki:rn};function sn(n,e){let t=n.expires?Date.parse(n.expires):1/0,s=e.expires?Date.parse(e.expires):1/0;return t!==s?t-s:(Date.parse(n.created_at)||0)-(Date.parse(e.created_at)||0)}function mr(n,e={}){let t=n.now??Date.now(),{snoozed:s}=B(n.root),r=[],i=[],a=0;for(let o of e.kinds??Ke){let l;try{l=Ge[o](n)}catch(c){i.push({kind:o,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let u=s[c.key];if(u&&Date.parse(u)>t){if(!e.includeSnoozed){a++;continue}c.snoozed_until=u}r.push(c)}}return r.sort(sn),{items:r,snoozed:a,errors:i}}function on(n){let e=n.indexOf(":");if(e<=0)return null;let t=n.slice(0,e),s=n.slice(e+1);return!Ke.includes(t)||!s?null:{kind:t,ref:s}}function an(n,e,t){switch(e){case"card":return j(n.root,t)?.status==="pending";case"wiki":return Ie(Q(n),t)?.status==="pending";default:return Ge[e](n).some(s=>s.key===`${e}:${t}`)}}async function pr(n,e,t,s={}){let r=on(e);if(!r)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:i,ref:a}=r,o=n.now??Date.now(),l=s.by??"operator";if(t==="later"){if(!an(n,i,a))return{ok:!1,error:`nothing waiting for "${e}"`};let u=s.laterHours&&s.laterHours>0?s.laterHours:24,g=new Date(o+u*36e5);return He(n.root,e,g,o),{ok:!0,message:`${e} put off until ${g.toISOString()}`}}let c=t==="yes";switch(i){case"card":{let u=Me(n.root,a,c?"yes":"no",{by:l,note:s.note,now:o});return u.ok?{ok:!0,message:`${e}: ${u.card.raised_by} will be told ${c?"yes":"no"}`}:u}case"schedule":{let u=await(c?xe:Se)(a,{configPath:qe(n),reload:n.reload});return u.success?{ok:!0,message:u.message}:{ok:!1,error:u.message}}case"memory":{let u=a.indexOf("/");if(u<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let g=a.slice(0,u),d=a.slice(u+1);if(!Je(n.root).includes(g))return{ok:!1,error:`no memory for agent "${g}"`};let f=new J(n.root);return f.held(g).some(m=>m.id===d)?(f.review(g,d,c?"approved":"rejected",l),{ok:!0,message:`${e} ${c?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${d}" isn't waiting for review`}}case"wiki":{let u=Q(n),g=c?ve(u,a,{by:l,force:s.force,now:o}):Re(u,a,{by:l,reason:s.note,now:o});return g.ok?{ok:!0,message:c?`${g.proposal.article.path} written to the shared wiki`:`${e} rejected`}:g}}}var Ve=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function br(n){return n==="/api/memory"||n.startsWith("/api/memory/")||n==="/approvals"||n.startsWith("/approvals/")||n==="/events/recent"}function yr(n){return n==="/reload"||n==="/api/processes/kill"||n==="/send"||n==="/send/agent"||n==="/send/contact"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(n)||/^\/crons\/[^/]+\/enabled$/.test(n)}function kr(n){return Ve.has(n)}function wr(n){if(n.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(n.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Ve.has(n.remoteAddress))return{allowed:!0,reason:"loopback"};if(n.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=n.authorizationHeader||"",t=e.startsWith("Bearer ")?e.slice(7).trim():"";return t&&n.acceptedTokens.has(t)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function xr(n,e=process.env){let t=new Set;e.MESH_TOKEN&&t.add(e.MESH_TOKEN);for(let s of n.mesh?.peers||[])s.token&&t.add(s.token);return t}function Sr(n,e,t=process.env){let s=i=>i.replace(/\/+$/,"");return(e===s(n.daemonUrl)?n.token:n.daemons.find(i=>s(i.url)===e)?.token)||t.MESH_TOKEN||void 0}function N(n){return(Array.isArray(n)?n[0]:n)?.trim()??""}function ln(n){try{return new URL(n).host.toLowerCase()}catch{return null}}function cn(n=process.env){return new Set((n.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function $r(n,e=cn()){let t=N(n.origin);if(t){if(e.has(t.replace(/\/+$/,"").toLowerCase()))return"same-origin";let r=ln(t),i=[N(n.host),N(n["x-forwarded-host"])].filter(Boolean).map(a=>a.toLowerCase());return r&&i.includes(r)?"same-origin":"foreign"}let s=N(n["sec-fetch-site"]).toLowerCase();return s==="cross-site"||s==="same-site"?"foreign":"none"}function vr(n){let e=(n||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{readFileSync as ee,writeFileSync as tt,existsSync as te,readdirSync as yn,statSync as kn}from"fs";import{resolve as ne,join as wn}from"path";import{existsSync as Xe,mkdirSync as un,readFileSync as dn,writeFileSync as Ye}from"fs";import{dirname as gn,resolve as Qe}from"path";import{z as p}from"zod";var fn=p.object({type:p.enum(["gitlab","github"]),host:p.string().optional(),project:p.string(),iid:p.number().int().positive(),url:p.string()}),mn=p.object({id:p.string(),title:p.string(),description:p.string().optional(),assignee:p.string().optional(),labels:p.array(p.string()).default([]),milestone:p.string().optional(),status:p.enum(["todo","doing","blocked","done"]).default("todo"),priority:p.number().int().optional(),estimatedSeconds:p.number().int().optional(),source:fn.optional(),importedAt:p.string().optional(),createdAt:p.string(),updatedAt:p.string(),blocker:p.string().optional(),doneNote:p.string().optional()}),pn=p.object({version:p.literal(1),items:p.array(mn).default([])}),M=class{constructor(e){this.path=e}jsonPath(){return Qe(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return Qe(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return Xe(this.jsonPath())}load(){let e=this.jsonPath();if(!Xe(e))return{version:1,items:[]};let t=dn(e,"utf-8");try{return pn.parse(JSON.parse(t))}catch(s){throw new Error(`Backlog file invalid (${e}): ${s.message}`)}}save(e){let t=this.jsonPath();un(gn(t),{recursive:!0}),Ye(t,JSON.stringify(e,null,2)+`
|
|
7
|
+
`),Ye(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(t=>t.id===e)}add(e){let t=this.load();if(t.items.some(i=>i.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let s=new Date().toISOString(),r={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??s,updatedAt:s};return t.items.push(r),this.save(t),r}addMany(e){let t=this.load(),s=new Set(t.items.map(a=>a.id)),r=new Date().toISOString(),i=[];for(let a of e){if(s.has(a.id))continue;let o={...a,labels:a.labels??[],status:a.status??"todo",createdAt:a.createdAt??r,updatedAt:r};t.items.push(o),i.push(o),s.add(o.id)}return i.length&&this.save(t),i}update(e,t){let s=this.load(),r=s.items.findIndex(a=>a.id===e);if(r<0)throw new Error(`backlog item ${e} not found`);let i={...s.items[r],...t,id:s.items[r].id,createdAt:s.items[r].createdAt,updatedAt:new Date().toISOString()};return s.items[r]=i,this.save(s),i}remove(e){let t=this.load(),s=t.items.length;return t.items=t.items.filter(r=>r.id!==e),t.items.length===s?!1:(this.save(t),!0)}toMarkdown(e){let t=["# Backlog","","_Generated from `backlog.json`. Do not edit by hand \u2014 use `agentx backlog` commands._",""],s={doing:[],blocked:[],todo:[],done:[]};for(let i of e.items)s[i.status].push(i);let r=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[i,a]of r)if(s[i].length){t.push(`## ${a}`,"");for(let o of s[i]){let l=i==="done"?"x":" ",c=o.assignee?`@${o.assignee} `:"",u=o.estimatedSeconds?` [time: ${Math.round(o.estimatedSeconds/60)}m]`:"",g=o.source?` (${o.source.type}: ${o.source.project}#${o.source.iid})`:"";t.push(`- [${l}] ${c}${o.title}${u}${g}`),o.source?.url&&t.push(` - <${o.source.url}>`),o.labels.length&&t.push(` - labels: ${o.labels.join(", ")}`),o.milestone&&t.push(` - milestone: ${o.milestone}`),o.blocker&&t.push(` - BLOCKED: ${o.blocker}`)}t.push("")}return t.join(`
|
|
8
|
+
`)}};function Dr(n){return`${n.type}:${n.project}:${n.iid}`}function Ze(n,e,t){let s=[];if(e.type==="gitlab"){let r=t.channels.gitlab?.agentMappings??[];for(let i of n){let a=r.find(o=>o.agentId===i);a?.gitlabUsernames?.length?s.push(a.gitlabUsernames[0]):s.push(i)}}else if(e.type==="github"){let r=t.channels.github?.agentMappings??[];for(let i of n){let a=r.find(o=>o.agentId===i);a?.githubUsernames?.length?s.push(a.githubUsernames[0]):s.push(i)}}return s}async function Z(n,e,t,s=()=>{}){return n.source?n.source.type==="gitlab"?hn(n.source,e,t,s):n.source.type==="github"?bn(n.source,e,t,s):{ok:!1,error:`unknown source.type ${n.source.type}`,attempts:[]}:{ok:!0,attempts:[]}}async function hn(n,e,t,s){let r=t.channels.gitlab,i=r?.token,a=r?.host||(n.host?`https://${n.host}`:void 0);if(!i||!a)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let o=[],l=async(f,m={})=>fetch(`${a}/api/v4${f}`,{...m,headers:{"PRIVATE-TOKEN":i,"Content-Type":"application/json",...m.headers||{}}}),c=encodeURIComponent(n.project),u;e.assigneeUsernames!==void 0&&(u=(await Promise.all(e.assigneeUsernames.map(async m=>{try{let h=await fetch(`${a}/api/v4/users?username=${encodeURIComponent(m)}`,{headers:{"PRIVATE-TOKEN":i}});if(!h.ok)return null;let b=await h.json();return Array.isArray(b)&&b[0]?.id?b[0].id:null}catch{return null}}))).filter(m=>typeof m=="number"));let g;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")g=0;else try{let f=await l(`/projects/${c}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(f.ok){let m=await f.json();Array.isArray(m)&&m[0]?.id&&(g=m[0].id)}}catch(f){s(`[backlog-sync] milestone lookup failed: ${f.message}`)}let d={};if(e.title!==void 0&&(d.title=e.title),e.description!==void 0&&(d.description=e.description),e.labels!==void 0&&(d.labels=e.labels.join(",")),e.addLabels?.length&&(d.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(d.remove_labels=e.removeLabels.join(",")),u!==void 0&&(d.assignee_ids=u),g!==void 0&&(d.milestone_id=g),e.state&&(d.state_event=e.state==="closed"?"close":"reopen"),Object.keys(d).length)try{let f=await l(`/projects/${c}/issues/${n.iid}`,{method:"PUT",body:JSON.stringify(d)});if(o.push({kind:"PUT issue",ok:f.ok,status:f.status}),!f.ok){let m=await f.text().catch(()=>"");return{ok:!1,attempts:o,error:`PUT issue ${f.status}: ${m.slice(0,200)}`,url:n.url}}}catch(f){return o.push({kind:"PUT issue",ok:!1,error:f.message}),{ok:!1,attempts:o,error:f.message,url:n.url}}if(e.note)try{let f=await l(`/projects/${c}/issues/${n.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});o.push({kind:"POST note",ok:f.ok,status:f.status})}catch(f){o.push({kind:"POST note",ok:!1,error:f.message})}return{ok:o.every(f=>f.ok),attempts:o,url:n.url}}async function bn(n,e,t,s){let i=t.channels.github?.token;if(!i)return{ok:!1,error:"github token not configured",attempts:[]};let a=[],o=async(d,f={})=>fetch(`https://api.github.com${d}`,{...f,headers:{Authorization:`Bearer ${i}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...f.headers||{}}}),l=n.project,c;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")c=null;else try{let d=await o(`/repos/${l}/milestones?state=all&per_page=100`);if(d.ok){let f=await d.json(),m=Array.isArray(f)?f.find(h=>h.title===e.milestoneTitle):null;m?.number&&(c=m.number)}}catch(d){s(`[backlog-sync] github milestone lookup failed: ${d.message}`)}let u;if(e.labels!==void 0)u=e.labels;else if(e.addLabels?.length||e.removeLabels?.length)try{let d=await o(`/repos/${l}/issues/${n.iid}`);if(d.ok){let f=await d.json(),m=Array.isArray(f.labels)?f.labels.map(b=>typeof b=="string"?b:b.name):[],h=new Set([...m,...e.addLabels??[]]);for(let b of e.removeLabels??[])h.delete(b);u=[...h]}}catch(d){s(`[backlog-sync] github label fetch failed: ${d.message}`)}let g={};if(e.title!==void 0&&(g.title=e.title),e.description!==void 0&&(g.body=e.description),u!==void 0&&(g.labels=u),e.assigneeUsernames!==void 0&&(g.assignees=e.assigneeUsernames),c!==void 0&&(g.milestone=c),e.state&&(g.state=e.state),Object.keys(g).length)try{let d=await o(`/repos/${l}/issues/${n.iid}`,{method:"PATCH",body:JSON.stringify(g)});if(a.push({kind:"PATCH issue",ok:d.ok,status:d.status}),!d.ok){let f=await d.text().catch(()=>"");return{ok:!1,attempts:a,error:`PATCH issue ${d.status}: ${f.slice(0,200)}`,url:n.url}}}catch(d){return a.push({kind:"PATCH issue",ok:!1,error:d.message}),{ok:!1,attempts:a,error:d.message,url:n.url}}if(e.note)try{let d=await o(`/repos/${l}/issues/${n.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST comment",ok:d.ok,status:d.status})}catch(d){a.push({kind:"POST comment",ok:!1,error:d.message})}return{ok:a.every(d=>d.ok),attempts:a,url:n.url}}var re=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,W=/@([a-z0-9_-]+)/i,et=/\[time:\s*([0-9hm\s]+)\]/i;function xn(n){let e=n.match(/(\d+)\s*h/i),t=n.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(t?parseInt(t[1],10)*60:0)}var se=class{constructor(e,t,s=()=>{}){this.path=e;this.daemon=t;this.log=s;this.store=new M(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=ne(process.cwd(),this.path);return te(e)?ee(e,"utf-8").split(`
|
|
9
|
+
`):[]}writeMd(e){let t=ne(process.cwd(),this.path);tt(t,e.join(`
|
|
10
|
+
`))}async listOpen(e){if(this.store.exists())return this.store.list().filter(i=>i.status!=="done"&&(!i.assignee||i.assignee.toLowerCase()===e.toLowerCase())).map(i=>this.toWorkItem(i));let t=this.readMd(),s=[];for(let r=0;r<t.length;r++){let i=t[r].match(re);if(!i||i[2].toLowerCase()==="x")continue;let o=i[3],l=o.match(W);if(l&&l[1].toLowerCase()!==e.toLowerCase())continue;let c=o.match(et),u=o.replace(W,"").replace(et,"").trim();s.push({id:`backlog:${r}`,title:u||`Task at line ${r+1}`,assignee:l?l[1]:void 0,estimatedSeconds:c?xn(c[1]):void 0,priority:r})}return s}async listAll(e={}){return this.store.exists()?this.store.list().map(t=>this.toWorkItem(t)):[]}async claim(e,t){if(!this.store.exists())return;let s=this.store.findById(t);if(!s)return;let r=this.store.update(t,{assignee:s.assignee||e,status:"doing"});if(r.source&&this.daemon){let i=Ze([r.assignee||e],r.source,this.daemon);Z(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(a=>this.log(`[backlog-sync] claim failed for ${t}: ${a?.message??a}`))}}async report(e,t){if(this.store.exists()&&this.store.findById(e)){let o={};t.status==="done"?o.status="done":t.status==="blocked"?(o.status="blocked",o.blocker=t.blocker||t.note||void 0):t.status==="in-progress"&&(o.status="doing"),t.timeSeconds&&(o.estimatedSeconds=t.timeSeconds);let l=this.store.update(e,o);if(l.source&&this.daemon){let c={};t.status==="done"?(c.addLabels=["Done"],c.removeLabels=["Doing"]):t.status==="blocked"&&(c.addLabels=["Blocked"]),t.note&&(c.note=t.note),Object.keys(c).length&&Z(l,c,this.daemon,this.log).catch(u=>this.log(`[backlog-sync] report failed for ${e}: ${u?.message??u}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let s=parseInt(e.slice(8),10),r=this.readMd(),i=r[s];if(!i)throw new Error(`backlog line ${s} missing`);if(!i.match(re))throw new Error(`backlog line ${s} not a checkbox`);if(t.status==="done"){r[s]=i.replace(/- \[ \]/,"- [x]");let o=t.timeSeconds?` <!-- done by agent, ${Math.round(t.timeSeconds/60)}m -->`:" <!-- done by agent -->";r.splice(s+1,0,o)}else t.status==="blocked"?r.splice(s+1,0,` <!-- BLOCKED: ${t.blocker||t.note||"?"} -->`):t.note&&r.splice(s+1,0,` <!-- ${t.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(r)}toWorkItem(e){let t={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:t,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},ie=class{constructor(e,t){this.root=e;this.glob=t}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,t){if(te(e))for(let s of yn(e)){let r=wn(e,s);kn(r).isDirectory()?this.walk(r,t):s.endsWith(".md")&&t.push(r)}}async listOpen(e){let t=[];this.walk(ne(process.cwd(),this.root),t);let s=[];for(let r of t){let i=ee(r,"utf-8").split(`
|
|
11
|
+
`);for(let a=0;a<i.length;a++){let o=i[a].match(re);if(!o||o[2].toLowerCase()==="x")continue;let l=o[3].match(W);!l||l[1].toLowerCase()!==e.toLowerCase()||s.push({id:`wiki:${r}:${a}`,title:o[3].replace(W,"").trim(),assignee:l[1],priority:a})}}return s}async claim(){}async report(e,t){let s=e.split(":"),r=parseInt(s[s.length-1],10),i=s.slice(1,-1).join(":");if(!te(i))return;let a=ee(i,"utf-8").split(`
|
|
12
|
+
`);t.status==="done"&&a[r]&&(a[r]=a[r].replace(/- \[ \]/,"- [x]"),tt(i,a.join(`
|
|
13
|
+
`)))}},oe=class{constructor(e,t,s,r,i){this.host=e;this.token=t;this.projects=s;this.agentUsernames=r;this.log=i}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[t,s]of Object.entries(this.agentUsernames))if(s.some(r=>r.toLowerCase()===e.toLowerCase()))return t}mapIssue(e,t){let s=e.references?.full?.split("#")[0]||t,r=[],i;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(i=e.labels.map(c=>({name:c.name,color:c.color,text_color:c.text_color})),r=i.map(c=>c.name)):r=e.labels);let o=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(c=>({username:c.username,name:c.name,avatarUrl:c.avatar_url})),l=o[0]?.username;return{id:`gitlab:${s}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:l?this.usernameToAgent(l)||l:void 0,assignees:o,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:r,labelDetails:i,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,t={}){let s=await fetch(`${this.host}/api/v4${e}`,{...t,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...t.headers||{}}});if(!s.ok)throw new Error(`GitLab ${s.status}: ${await s.text().catch(()=>"")}`);return s.json()}async listOpen(e){let t=this.agentUsernames[e]||[];if(!t.length)return[];let s=[],r=this.projects.length?this.projects:["__ALL__"];for(let i of t)for(let a of r)try{let o=`assignee_username=${encodeURIComponent(i)}&state=opened&scope=all&per_page=20`,l=a==="__ALL__"?`/issues?${o}`:`/projects/${encodeURIComponent(a)}/issues?${o}`,c=await this.api(l);for(let u of c){let g=this.mapIssue(u,a);g.assignee=e,s.push(g)}}catch(o){this.log(`[business] GitLab listOpen failed for ${i} on ${a}: ${o.message}`)}return s}async claim(e,t){let{project:s,iid:r,type:i}=this.parseId(t),a=`/projects/${encodeURIComponent(s)}/${i==="issue"?"issues":"merge_requests"}/${r}?add_labels=Doing&remove_labels=To Do`;try{await this.api(a,{method:"PUT"})}catch(o){this.log(`[business] claim label update failed: ${o.message}`)}}async report(e,t){let{project:s,iid:r,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests";if(t.timeSeconds&&t.timeSeconds>0){let o=Math.max(1,Math.round(t.timeSeconds/60)),l=o>=60?`${Math.floor(o/60)}h${o%60?` ${o%60}m`:""}`:`${o}m`;try{await this.api(`/projects/${encodeURIComponent(s)}/${a}/${r}/add_spent_time?duration=${encodeURIComponent(l)}`,{method:"POST"})}catch(c){this.log(`[business] add_spent_time failed: ${c.message}`)}}if(t.status==="done")try{await this.api(`/projects/${encodeURIComponent(s)}/${a}/${r}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(o){this.log(`[business] done label update failed: ${o.message}`)}else if(t.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(s)}/${a}/${r}?add_labels=Blocked`,{method:"PUT"})}catch(o){this.log(`[business] blocked label update failed: ${o.message}`)}if(t.note)try{await this.api(`/projects/${encodeURIComponent(s)}/${a}/${r}/notes`,{method:"POST",body:JSON.stringify({body:t.note})})}catch(o){this.log(`[business] report note failed: ${o.message}`)}}async listAll(e={}){let t=e.sinceDays??30,s=new Date(Date.now()-t*24*36e5).toISOString(),r=new URLSearchParams,i=e.state??"opened";r.set("state",i),r.set("updated_after",s),r.set("scope","all"),r.set("per_page","100"),r.set("with_labels_details","true"),r.set("order_by","updated_at"),r.set("sort","desc"),e.labels?.length&&r.set("labels",e.labels.join(",")),e.milestone&&r.set("milestone",e.milestone),e.search&&r.set("search",e.search);let a=this.projects.length?this.projects:["__ALL__"],o=[];for(let c of a)try{let u=c==="__ALL__"?`/issues?${r.toString()}`:`/projects/${encodeURIComponent(c)}/issues?${r.toString()}`,g=await this.api(u);for(let d of g)o.push(this.mapIssue(d,c))}catch(u){this.log(`[business] GitLab listAll failed on ${c}: ${u.message}`)}let l=o;if(e.notLabels?.length){let c=new Set(e.notLabels);l=l.filter(u=>!(u.labels||[]).some(g=>c.has(g)))}if(e.withoutScopedPrefix){let c=e.withoutScopedPrefix+"::";l=l.filter(u=>!(u.labels||[]).some(g=>g.startsWith(c)))}return l}async setState(e,t){let{project:s,iid:r,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(s)}/${a}/${r}?state_event=${t}`,{method:"PUT"})}async getItem(e){let{project:t,iid:s}=this.parseId(e);try{let r=await this.api(`/projects/${encodeURIComponent(t)}/issues/${s}?with_labels_details=true`);return{...this.mapIssue(r,t),descriptionHtml:r.description_html||void 0,createdAt:r.created_at,author:r.author?{username:r.author.username,name:r.author.name,avatarUrl:r.author.avatar_url}:void 0,allLabels:Array.isArray(r.labels)?typeof r.labels[0]=="object"?r.labels.map(a=>a.name):r.labels:[]}}catch(r){return this.log(`[board] GitLab getItem failed for ${e}: ${r.message}`),null}}async updateItem(e,t){let{project:s,iid:r}=this.parseId(e),i;t.assigneeUsernames&&(i=(await Promise.all(t.assigneeUsernames.map(async u=>{try{let g=await this.api(`/users?username=${encodeURIComponent(u)}`);return Array.isArray(g)&&g[0]?.id?g[0].id:null}catch{return null}}))).filter(u=>typeof u=="number"));let a;if(t.milestoneTitle!==void 0)if(t.milestoneTitle===null||t.milestoneTitle==="")a=0;else try{let c=await this.api(`/projects/${encodeURIComponent(s)}/milestones?title=${encodeURIComponent(t.milestoneTitle)}`);Array.isArray(c)&&c[0]?.id&&(a=c[0].id)}catch(c){this.log(`[board] milestone lookup failed for "${t.milestoneTitle}": ${c.message}`)}let o={};t.title!==void 0&&(o.title=t.title),t.description!==void 0&&(o.description=t.description),t.labels!==void 0&&(o.labels=t.labels.join(",")),t.addLabels?.length&&(o.add_labels=t.addLabels.join(",")),t.removeLabels?.length&&(o.remove_labels=t.removeLabels.join(",")),i!==void 0&&(o.assignee_ids=i),a!==void 0&&(o.milestone_id=a);let l=await this.api(`/projects/${encodeURIComponent(s)}/issues/${r}`,{method:"PUT",body:JSON.stringify(o)});return this.mapIssue(l,s)}async listMembers(){let e=new Map;for(let t of this.projects)try{let s=await this.api(`/projects/${encodeURIComponent(t)}/members/all?per_page=100`);for(let r of s)r.username&&!e.has(r.username)&&e.set(r.username,{username:r.username,name:r.name,avatarUrl:r.avatar_url})}catch(s){this.log(`[board] listMembers failed for ${t}: ${s.message}`)}return[...e.values()].sort((t,s)=>t.username.localeCompare(s.username))}async listMilestones(){let e=new Map;for(let s of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(s)}/milestones?per_page=100`);for(let i of r)i.title&&!e.has(i.title)&&e.set(i.title,{id:i.id,title:i.title,state:i.state,dueDate:i.due_date})}catch(r){this.log(`[board] listMilestones failed for ${s}: ${r.message}`)}let t=[...e.values()];return t.sort((s,r)=>s.state!==r.state?s.state==="active"?-1:1:s.title.localeCompare(r.title)),t}async create(e){let t=e.projectHint||this.projects[0];if(!t)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let s,r=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];r.length&&(s=(await Promise.all(r.map(async c=>{try{let u=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch(u){return this.log(`[board] user lookup failed for ${c}: ${u.message}`),null}}))).filter(c=>typeof c=="number"));let i;if(e.milestoneTitle)try{let l=await this.api(`/projects/${encodeURIComponent(t)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${l.message}`)}let a={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};s?.length&&(a.assignee_ids=s),i!==void 0&&(a.milestone_id=i);let o=await this.api(`/projects/${encodeURIComponent(t)}/issues`,{method:"POST",body:JSON.stringify(a)});return this.mapIssue(o,t)}async transition(e,t,s){await this.transitionMany(e,t?[t]:[],s?[s]:[])}async transitionMany(e,t,s){let{project:r,iid:i,type:a}=this.parseId(e),o=a==="issue"?"issues":"merge_requests",l=new URLSearchParams;t.length&&l.set("add_labels",t.join(",")),s.length&&l.set("remove_labels",s.join(",")),l.toString()&&await this.api(`/projects/${encodeURIComponent(r)}/${o}/${i}?${l.toString()}`,{method:"PUT"})}parseId(e){let s=e.replace(/^gitlab:/,"").split(":"),r=s.pop(),i=s.pop()==="mr"?"mr":"issue";return{project:s.join(":"),type:i,iid:r}}};function Fr(n,e,t){let s=n.workSource;switch(s.type){case"backlog":return new se(s.path,e,t);case"wiki":return new ie(s.path,s.glob);case"gitlab":{let r=e.channels.gitlab;if(!r?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let i={};for(let o of r.agentMappings)o.gitlabUsernames.length&&(i[o.agentId]=o.gitlabUsernames);let a=s.projects.length?s.projects:r.routes.map(o=>o.project);return new oe(r.host,r.token,a,i,t)}}}var ae="unmapped";function le(n,e=[]){if(!n)return ae;let t=e.find(r=>r.id===n);if(t?.client)return t.client;let s=n.indexOf("/");return s>0?n.slice(0,s):n}function Sn(n){let e=new Map,t=n.projects??[],s=n.orgChart??{};for(let i of t)i.pm&&(e.has(i.pm)||e.set(i.pm,le(i.id,t)));let r=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let o=s[i]?.reportsTo;if(!o)return;let l=r(o,a);return l&&e.set(i,l),l};for(let i of Object.keys(s))r(i);return e}function In(n,e,t=[]){if(!t.length)return;let s=t.filter(r=>!r.channel||r.channel===n);return s.find(r=>r.chatId&&e.chatId&&r.chatId===e.chatId)??s.find(r=>r.username&&e.username&&r.username===e.username)??s.find(r=>r.senderId&&e.senderId&&r.senderId===e.senderId)??s.find(r=>r.channel&&!r.chatId&&!r.username&&!r.senderId)}function Br(n,e){let t=In(n.channel,{chatId:n.chatId,username:n.username},e.contactMap);if(t)return t.client;if(n.project)return le(n.project,e.projects);if(n.agentId){let s=Sn(e).get(n.agentId);if(s)return s}return ae}function Nr(n,e){let t=String(n||"").split(":");if(t.length<3)return{agentId:e};let[s,r,...i]=t,a=i.join(":"),o={agentId:e||s,channel:r};return r==="gitlab"||r==="github"?o.project=a.split(":")[0]:r==="cron"||r==="api"||(o.chatId=a.split("@")[0]),o}var $n=n=>n===ae?"internal":"client";function vn(n,e){let t=e.clients?.[n];return{id:n,name:t?.name||n,kind:t?.kind??$n(n),respondWithinMinutes:Rn(t?.respondWithin),standing:t?.standing??[],declared:!!t}}function Mr(n){let e=new Set;for(let t of n.projects??[])e.add(le(t.id,n.projects));for(let t of n.contactMap??[])e.add(t.client);for(let t of Object.keys(n.clients??{}))e.add(t);return[...e].sort().map(t=>vn(t,n))}function Rn(n){let e=/^(\d+)\s*([mhd])$/.exec(String(n??"").trim());if(!e)return;let t=Number(e[1]);return e[2]==="m"?t:e[2]==="h"?t*60:t*1440}import{existsSync as x,readFileSync as ge,writeFileSync as fe,mkdirSync as z,readdirSync as de,rmSync as An,statSync as $}from"fs";import{resolve as nt,relative as _n,dirname as me,join as A,extname as E,basename as pe}from"path";var w=200*1024,rt=new Set([".md",".markdown",".txt"]),D=new Set([".md",".markdown",".txt",".json",".jsonc",".yaml",".yml",".toml",".sh",".bash",".zsh",".py",".js",".mjs",".ts",".tsx",".jsx",".css",".html",".lock",".cfg",".ini",".env",".gitignore"]),Cn=6,Dn=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function R(n,e){if(!n)throw new Error("Agent workspace is not configured.");let t=nt(n);if(x(t)||z(t,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let s=nt(t,e);if(_n(t,s).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return s}function st(n){let e=E(n).toLowerCase();if(!rt.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function ce(n,e){let t=n.split(/\r?\n/).find(s=>s.trim().startsWith("#"));return t&&t.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Kr(n){let e=R(n,"."),t=[],s=new Set,r=[];try{r=de(e)}catch{}for(let o of Dn){let l=A(e,o);if(x(l)&&$(l).isFile()){let c=$(l).size,u=c>0&&c<w?ue(l):"";t.push({path:o,title:ce(u,o),size:c,exists:!0}),s.add(o)}else t.push({path:o,title:o,size:0,exists:!1}),s.add(o)}for(let o of r){if(s.has(o))continue;let l=A(e,o);try{let c=$(l);if(!c.isFile()||!rt.has(E(o).toLowerCase()))continue;let u=c.size>0&&c.size<w?ue(l):"";t.push({path:o,title:ce(u,o),size:c.size,exists:!0})}catch{}}let i=[],a=A(e,".claude","skills");if(x(a))try{for(let o of de(a)){let l=A(a,o),c;try{c=$(l)}catch{continue}if(!c.isDirectory())continue;let u=A(l,"SKILL.md");if(!x(u))continue;let g=$(u),d=g.size<w?ue(u):"";i.push({slug:o,title:ce(d,o),size:g.size,path:`.claude/skills/${o}/SKILL.md`})}}catch{}return i.sort((o,l)=>o.slug.localeCompare(l.slug)),{identity:t,skills:i,workspace:e}}function ue(n){try{return ge(n,"utf-8")}catch{return""}}function qr(n,e){let t=R(n,e);if(st(t),!x(t))return{path:e,content:""};if($(t).size>w)throw new Error(`File is too large to edit in the admin panel (> ${w/1024} KB).`);return{path:e,content:ge(t,"utf-8")}}function Jr(n,e,t){let s=R(n,e);st(s);let r=Buffer.from(t,"utf-8");if(r.length>w)throw new Error(`File too large (${r.length} > ${w} bytes).`);return z(me(s),{recursive:!0}),fe(s,r),{path:e,bytes:r.length}}function Gr(n,e,t={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let s=`.claude/skills/${e}/SKILL.md`,r=R(n,s);if(x(r))throw new Error(`Skill "${e}" already exists.`);z(me(r),{recursive:!0});let i=t.content?.trim()?t.content:jn(e,t.title);return fe(r,i),{slug:e,path:s}}function Vr(n,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let t=R(n,`.claude/skills/${e}`);if(!x(t))throw new Error(`Skill "${e}" not found.`);if(!$(t).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return An(t,{recursive:!0,force:!0}),{slug:e}}function Xr(n,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let t=R(n,`.claude/skills/${e}`);if(!x(t))throw new Error(`Skill "${e}" not found.`);let s=[];return r(t,"",0,s),s.sort((i,a)=>i.kind!==a.kind?i.kind==="dir"?-1:1:i.path.localeCompare(a.path)),s;function r(i,a,o,l){if(o>Cn)return;let c=[];try{c=de(i)}catch{return}for(let u of c){if(u==="node_modules"||u===".git")continue;let g=A(i,u),d=a?`${a}/${u}`:u,f;try{f=$(g)}catch{continue}if(f.isDirectory())l.push({path:`${d}/`,kind:"dir",size:0,editable:!1}),r(g,d,o+1,l);else if(f.isFile()){let m=E(u).toLowerCase(),h=D.has(m)||D.has(u.toLowerCase());l.push({path:d,kind:"file",size:f.size,editable:h&&f.size<w})}}}}function Yr(n,e,t){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!t||t.includes(".."))throw new Error(`Invalid file path: ${t}`);let s=R(n,`.claude/skills/${e}/${t}`);if(!x(s)||!$(s).isFile())throw new Error(`File not found: ${t}`);let r=E(s).toLowerCase(),i=pe(s).toLowerCase();if(!D.has(r)&&!D.has(i))throw new Error(`File type not editable: ${t}`);if($(s).size>w)throw new Error(`File too large to edit (> ${w/1024} KB): ${t}`);return{path:t,content:ge(s,"utf-8")}}function Qr(n,e,t,s){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!t||t.includes(".."))throw new Error(`Invalid file path: ${t}`);let r=R(n,`.claude/skills/${e}/${t}`),i=E(r).toLowerCase(),a=pe(r).toLowerCase();if(!D.has(i)&&!D.has(a))throw new Error(`File type not editable: ${t}`);let o=Buffer.from(s,"utf-8");if(o.length>w)throw new Error(`File too large (${o.length} > ${w} bytes).`);return z(me(r),{recursive:!0}),fe(r,o),{path:t,bytes:o.length}}function Zr(n,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let t=R(n,`.claude/skills/${e}`);if(!x(t))throw new Error(`Skill "${e}" not found.`);let s=r=>x(A(t,r));return s("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:s("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:s("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:s("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:s("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function jn(n,e){return`# ${e?.trim()||n}
|
|
14
|
+
|
|
15
|
+
Describe what this skill does and when the agent should use it. Keep it under ~5 lines \u2014 the agent reads this to decide whether to invoke the skill.
|
|
16
|
+
|
|
17
|
+
## When to use
|
|
18
|
+
- Trigger condition 1
|
|
19
|
+
- Trigger condition 2
|
|
20
|
+
|
|
21
|
+
## How to use
|
|
22
|
+
Document the arguments, commands, or files the skill expects. Example:
|
|
23
|
+
|
|
24
|
+
\`\`\`bash
|
|
25
|
+
# Example invocation
|
|
26
|
+
claude-code ${pe(n)} --arg value
|
|
27
|
+
\`\`\`
|
|
28
|
+
`}ct();var it={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function ot(n){return{...it,...n??{},regions:{...n?.regions??{}},buffer:{...it.buffer,...n?.buffer??{}}}}function ns(n){try{return ot(he(n).screen)}catch{return ot(void 0)}}var Tn=/^[a-z][\w-]*$/,at=["window","screen","menubar","notifications"];function O(n,e,t,s){let r=Number(n);if(n===""||n===null||!Number.isFinite(r)||!t(r))throw new Error(`${e} must be ${s}`);return r}var H=(n,e)=>O(n,e,t=>Number.isInteger(t)&&t>0,"a whole number above 0");function lt(n){let e=typeof n=="string"?n.split(",").map(Number):[n?.x,n?.y,n?.width,n?.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 rs(n,e){let t={...n??{}};if("maxPixels"in e&&(t.maxPixels=H(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(t.timeoutMs=H(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(t.intervalMs=H(e.intervalMs,"intervalMs")),"stableMs"in e&&(t.stableMs=O(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(t.changeThreshold=O(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...t.regions??{}};for(let[i,a]of Object.entries(e.regions)){if(!Tn.test(i))throw new Error(`region name "${i}" must be lowercase letters, digits, - or _`);a===null?delete r[i]:r[i]=lt(a)}t.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,i={...t.buffer??{}};"enabled"in r&&(i.enabled=!!r.enabled),"seconds"in r&&(i.seconds=O(r.seconds,"buffer.seconds",a=>a>0&&a<=120,"above 0 and at most 120")),"fps"in r&&(i.fps=O(r.fps,"buffer.fps",a=>a>0&&a<=10,"above 0 and at most 10")),"maxPixels"in r&&(i.maxPixels=H(r.maxPixels,"buffer.maxPixels")),"region"in r&&(i.region=String(r.region).trim()),t.buffer=i}let s=t.buffer?.region;if(s!==void 0&&!at.includes(s)&&!t.regions?.[s])try{lt(s)}catch{throw new Error(`buffer.region "${s}" is not a region \u2014 use ${[...at,...Object.keys(t.regions??{})].join(", ")}, or x,y,w,h`)}return t}export{Ae as a,Ln as b,le as c,Sn as d,In as e,Br as f,Nr as g,Mr as h,k as i,Bn as j,Le as k,Hn as l,Kn as m,Fe as n,Be as o,j as p,Vn as q,Xn as r,Yn as s,Qn as t,Zn as u,B as v,sr as w,mr as x,pr as y,br as z,yr as A,kr as B,wr as C,xr as D,Sr as E,$r as F,vr as G,M as H,Dr as I,Ze as J,Z as K,oe as L,Fr as M,Kr as N,qr as O,Jr as P,Gr as Q,Vr as R,Xr as S,Yr as T,Qr as U,Zr as V,it as W,ot as X,ns as Y,at as Z,rs as _};
|
|
29
|
+
//# sourceMappingURL=chunk-3RCFUIYR.js.map
|