agentix-cli 0.53.0 → 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-R62ZQVSF.js → App-VRTLAPRF.js} +2 -2
- package/dist/{ChatApp-AS567EFE.js → ChatApp-YENWPZT4.js} +2 -2
- package/dist/{agent-H4NB4BUA.js → agent-HVUGHYBF.js} +2 -2
- package/dist/{board-dashboard-E3MUVNVQ.js → board-dashboard-3XJVYDB3.js} +416 -180
- 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-CCMM5TP4.js → chunk-2TJYZF4E.js} +2 -2
- package/dist/{chunk-FSZXY53Z.js → chunk-33QV5O6P.js} +2 -2
- package/dist/{chunk-NF52Q3TV.js → chunk-37EABIOJ.js} +2 -2
- package/dist/chunk-3RCFUIYR.js +29 -0
- package/dist/chunk-3RCFUIYR.js.map +1 -0
- package/dist/{chunk-6OOK7Y4S.js → chunk-3W2KMI5O.js} +2 -2
- package/dist/{chunk-47EEUZBK.js → chunk-4FFWNPFX.js} +4 -4
- package/dist/chunk-4FFWNPFX.js.map +1 -0
- package/dist/{chunk-FS4WBYY3.js → chunk-4HNHHKJF.js} +2 -2
- package/dist/{chunk-SABOPOYX.js → chunk-6JHA3ZE6.js} +139 -139
- package/dist/chunk-6JHA3ZE6.js.map +1 -0
- package/dist/{chunk-QU6ZUKAD.js → chunk-BKDUCPZ3.js} +2 -2
- package/dist/{chunk-IDYP7G7Z.js → chunk-BMSPRUEJ.js} +33 -33
- package/dist/{chunk-IDYP7G7Z.js.map → chunk-BMSPRUEJ.js.map} +1 -1
- package/dist/{chunk-TH5KNJLA.js → chunk-ENRJ2QEH.js} +2 -2
- package/dist/{chunk-C5JXPMTW.js → chunk-HQMISQ7L.js} +2 -2
- package/dist/{chunk-7DPKPBRJ.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-KB7YIM3W.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-OV35MJKS.js → chunk-QX4R5WY7.js} +2 -2
- package/dist/{chunk-PGJL5V6Y.js → chunk-QYHABRLM.js} +2 -2
- package/dist/{chunk-7OWXFLAM.js → chunk-TLFJVLVQ.js} +166 -160
- package/dist/chunk-TLFJVLVQ.js.map +1 -0
- package/dist/{chunk-OMTRHHZJ.js → chunk-UYMK3XNB.js} +44 -45
- package/dist/chunk-UYMK3XNB.js.map +1 -0
- package/dist/{chunk-VD4TMPJI.js → chunk-WLRHL2P7.js} +2 -2
- package/dist/chunk-WWMFNLKD.js +10 -0
- package/dist/chunk-WWMFNLKD.js.map +1 -0
- package/dist/{chunk-KJWBQZT7.js → chunk-XWU7O3S5.js} +2 -2
- package/dist/{chunk-KFG6WWFS.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-3SW4V44Z.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 +88 -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-DJFMTLRC.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-2H7HCUCZ.js → request-planner-ABD4WIGM.js} +2 -2
- package/dist/{review-candidates-U7R64OCS.js → review-candidates-B6574GOJ.js} +2 -2
- package/dist/{routing-LVQH6WOJ.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-2KGFNCIW.js → seat-VGST5AQB.js} +2 -2
- package/dist/seat-VGST5AQB.js.map +1 -0
- package/dist/{select-XGK27RPP.js → select-Y7SBUCGJ.js} +2 -2
- package/dist/{set-enabled-7YGN2FAZ.js → set-enabled-ARKMDLXN.js} +2 -2
- package/dist/{tool-HKDIZ6I4.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-E3MUVNVQ.js.map +0 -1
- package/dist/chunk-47EEUZBK.js.map +0 -1
- package/dist/chunk-7OWXFLAM.js.map +0 -1
- package/dist/chunk-D4HAR3L3.js +0 -28
- package/dist/chunk-D4HAR3L3.js.map +0 -1
- package/dist/chunk-HRBKSZ34.js +0 -2
- package/dist/chunk-HRBKSZ34.js.map +0 -1
- package/dist/chunk-OMTRHHZJ.js.map +0 -1
- package/dist/chunk-SABOPOYX.js.map +0 -1
- package/dist/client-XTQDYMOX.js +0 -2
- package/dist/config-mutator-H32FXUYJ.js +0 -2
- package/dist/doctor-J6RCHFVE.js +0 -2
- package/dist/memory-extract-MGGXIZTE.js +0 -2
- package/dist/ntfy-ZY2NPGBA.js.map +0 -1
- package/dist/program-SQTOPCQW.js +0 -2
- package/dist/query-UAZUMU4N.js +0 -2
- package/dist/registry-4OUBA2TY.js +0 -2
- package/dist/schedule-tool-2BONJVCJ.js +0 -2
- package/dist/scheduler-7CEXDECA.js +0 -2
- package/dist/wiki-6YT7B5HU.js +0 -2
- /package/dist/{App-R62ZQVSF.js.map → App-VRTLAPRF.js.map} +0 -0
- /package/dist/{ChatApp-AS567EFE.js.map → ChatApp-YENWPZT4.js.map} +0 -0
- /package/dist/{agent-H4NB4BUA.js.map → agent-HVUGHYBF.js.map} +0 -0
- /package/dist/{chunk-CCMM5TP4.js.map → chunk-2TJYZF4E.js.map} +0 -0
- /package/dist/{chunk-FSZXY53Z.js.map → chunk-33QV5O6P.js.map} +0 -0
- /package/dist/{chunk-NF52Q3TV.js.map → chunk-37EABIOJ.js.map} +0 -0
- /package/dist/{chunk-6OOK7Y4S.js.map → chunk-3W2KMI5O.js.map} +0 -0
- /package/dist/{chunk-FS4WBYY3.js.map → chunk-4HNHHKJF.js.map} +0 -0
- /package/dist/{chunk-QU6ZUKAD.js.map → chunk-BKDUCPZ3.js.map} +0 -0
- /package/dist/{chunk-TH5KNJLA.js.map → chunk-ENRJ2QEH.js.map} +0 -0
- /package/dist/{chunk-C5JXPMTW.js.map → chunk-HQMISQ7L.js.map} +0 -0
- /package/dist/{chunk-7DPKPBRJ.js.map → chunk-KLDGJSR5.js.map} +0 -0
- /package/dist/{chunk-KB7YIM3W.js.map → chunk-M67AN4J7.js.map} +0 -0
- /package/dist/{chunk-WKTFP3SK.js.map → chunk-NO2HOK4B.js.map} +0 -0
- /package/dist/{chunk-OV35MJKS.js.map → chunk-QX4R5WY7.js.map} +0 -0
- /package/dist/{chunk-PGJL5V6Y.js.map → chunk-QYHABRLM.js.map} +0 -0
- /package/dist/{chunk-VD4TMPJI.js.map → chunk-WLRHL2P7.js.map} +0 -0
- /package/dist/{chunk-KJWBQZT7.js.map → chunk-XWU7O3S5.js.map} +0 -0
- /package/dist/{chunk-KFG6WWFS.js.map → chunk-ZOJUHPD5.js.map} +0 -0
- /package/dist/{client-XTQDYMOX.js.map → client-N4XQEAVL.js.map} +0 -0
- /package/dist/{compaction-NWPBPWY2.js.map → compaction-H5U32UU6.js.map} +0 -0
- /package/dist/{config-3SW4V44Z.js.map → config-KHKIY6LI.js.map} +0 -0
- /package/dist/{config-mutator-H32FXUYJ.js.map → config-mutator-ZZKFQ7HJ.js.map} +0 -0
- /package/dist/{doctor-J6RCHFVE.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-SQTOPCQW.js.map → ntfy-52EXHVMD.js.map} +0 -0
- /package/dist/{promote-DJFMTLRC.js.map → program-ZWNGK3RB.js.map} +0 -0
- /package/dist/{query-UAZUMU4N.js.map → promote-H6ZHJXTY.js.map} +0 -0
- /package/dist/{registry-4OUBA2TY.js.map → push-keys-2DTD7YNQ.js.map} +0 -0
- /package/dist/{routing-LVQH6WOJ.js.map → push-store-LXTYULUF.js.map} +0 -0
- /package/dist/{schedule-tool-2BONJVCJ.js.map → query-FTE4FLYK.js.map} +0 -0
- /package/dist/{scheduler-7CEXDECA.js.map → registry-HDOFVNRK.js.map} +0 -0
- /package/dist/{request-planner-2H7HCUCZ.js.map → request-planner-ABD4WIGM.js.map} +0 -0
- /package/dist/{review-candidates-U7R64OCS.js.map → review-candidates-B6574GOJ.js.map} +0 -0
- /package/dist/{seat-2KGFNCIW.js.map → routing-BGKZOHOA.js.map} +0 -0
- /package/dist/{wiki-6YT7B5HU.js.map → schedule-tool-UDHXTKWV.js.map} +0 -0
- /package/dist/{select-XGK27RPP.js.map → select-Y7SBUCGJ.js.map} +0 -0
- /package/dist/{set-enabled-7YGN2FAZ.js.map → set-enabled-ARKMDLXN.js.map} +0 -0
- /package/dist/{tool-HKDIZ6I4.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
|
|
@@ -1,7 +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-
|
|
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
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
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
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
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
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-
|
|
7
|
+
//# sourceMappingURL=chunk-33QV5O6P.js.map
|
|
@@ -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
|