agentix-cli 0.182.0 → 0.183.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-XWSSUYKF.js → App-777XBP22.js} +2 -2
- package/dist/{ChatApp-UT2BRHYE.js → ChatApp-ZYMF5HSR.js} +2 -2
- package/dist/{absorb-eval-SFGUURBD.js → absorb-eval-HYGBAPXS.js} +2 -2
- package/dist/{adapter-UHR7FVM7.js → adapter-VV626IYN.js} +2 -2
- package/dist/{agent-5NTFSCEO.js → agent-BS5VSO5T.js} +2 -2
- package/dist/{board-dashboard-7HIME2W4.js → board-dashboard-3CMB3NPI.js} +543 -2158
- package/dist/board-dashboard-3CMB3NPI.js.map +1 -0
- package/dist/{chunk-IFHVAHQM.js → chunk-3ENH7HAS.js} +2 -2
- package/dist/chunk-5ELIX7BQ.js +3 -0
- package/dist/chunk-5ELIX7BQ.js.map +1 -0
- package/dist/{chunk-YX4R2VGD.js → chunk-6D4RGQCU.js} +2 -2
- package/dist/{chunk-FYFJ7IQJ.js → chunk-6KWHQAXS.js} +2 -2
- package/dist/{chunk-FDX4IGLK.js → chunk-6MY7VXQV.js} +2 -2
- package/dist/chunk-CZMVJP7O.js +2 -0
- package/dist/chunk-CZMVJP7O.js.map +1 -0
- package/dist/{chunk-4KNHLHE3.js → chunk-DOCAWXV5.js} +2 -2
- package/dist/{chunk-5NGQQOVK.js → chunk-DYNXOYFN.js} +2 -2
- package/dist/{chunk-RDWDDPBI.js → chunk-GXOKZSCS.js} +2 -2
- package/dist/{chunk-Y4TVCWWF.js → chunk-JJ2WRGKI.js} +2 -2
- package/dist/{chunk-XI2HH5NR.js → chunk-KLWCVTBM.js} +2 -2
- package/dist/{chunk-MD2HCGSC.js → chunk-M7V7NCX6.js} +2 -2
- package/dist/chunk-M7V7NCX6.js.map +1 -0
- package/dist/chunk-MLNA54RW.js +888 -0
- package/dist/chunk-MLNA54RW.js.map +1 -0
- package/dist/{chunk-7WGJZLVJ.js → chunk-OIECBQ45.js} +2 -2
- package/dist/{chunk-XHJ5SVO5.js → chunk-OTITQCEQ.js} +271 -271
- package/dist/chunk-OTITQCEQ.js.map +1 -0
- package/dist/{chunk-QGNV2HA4.js → chunk-PIVIOIEC.js} +2 -2
- package/dist/{chunk-QB6UPODO.js → chunk-QSJA6S66.js} +2 -2
- package/dist/{chunk-IGBW4VVM.js → chunk-R2QFKEX5.js} +2 -2
- package/dist/{chunk-NIPMVM3G.js → chunk-RG6MO7G5.js} +2 -2
- package/dist/{chunk-5YG2ZQQW.js → chunk-RQOMUGUM.js} +2 -2
- package/dist/{chunk-Z4XVPGPZ.js → chunk-SBJHIBWX.js} +3 -3
- package/dist/{chunk-GEFZMDDX.js → chunk-TD2D4TGI.js} +2 -2
- package/dist/{chunk-H2KOXGDX.js → chunk-UNZVDS3P.js} +2 -2
- package/dist/{chunk-YSPBVLTZ.js → chunk-VDUMYEJH.js} +2 -2
- package/dist/{chunk-BY3AUZYM.js → chunk-XBQISUBE.js} +2 -2
- package/dist/chunk-XPE2WKPF.js +2903 -0
- package/dist/chunk-XPE2WKPF.js.map +1 -0
- package/dist/{chunk-JNWXHOJE.js → chunk-YH7NALJ4.js} +2 -2
- package/dist/{chunk-Y5TBOMHY.js → chunk-YZCQDZCA.js} +5 -5
- package/dist/{chunk-343MPMLD.js → chunk-ZOCRNNNG.js} +2 -2
- package/dist/{chunk-4WSJKKSA.js → chunk-ZSS3GL5A.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-SQMU25PS.js → client-CMQZO22V.js} +2 -2
- package/dist/{config-56NBA4SF.js → config-BMYFEAO5.js} +2 -2
- package/dist/{config-mutate-PD4O3HZ7.js → config-mutate-N6W52YXB.js} +2 -2
- package/dist/config-mutator-S5SGBNOG.js +2 -0
- package/dist/{contributions-DKTJ623L.js → contributions-KRES5F2V.js} +2 -2
- package/dist/{doctor-OI6GJZR5.js → doctor-2KACCIZU.js} +2 -2
- package/dist/{follow-up-tool-DYSLS6ZI.js → follow-up-tool-M57XXTPX.js} +2 -2
- package/dist/{hub-4HDMTSR7.js → hub-FVAPTKTF.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{program-4GDIWCDM.js → program-BHDAV67G.js} +260 -259
- package/dist/program-BHDAV67G.js.map +1 -0
- package/dist/{promote-3272TZNI.js → promote-LXKF6A24.js} +2 -2
- package/dist/push-bridge-NR7SLHGX.js +1 -1
- package/dist/{query-7XM6V4QG.js → query-W7OBMMVM.js} +2 -2
- package/dist/{query-settings-HHVBIIVQ.js → query-settings-PTA2SA63.js} +2 -2
- package/dist/{registry-QL3AM3UH.js → registry-OHUOHAD2.js} +2 -2
- package/dist/{request-planner-WNEDEA7X.js → request-planner-T44RMVNO.js} +2 -2
- package/dist/{review-candidates-TGPDJMWJ.js → review-candidates-LKFIKTY6.js} +2 -2
- package/dist/{routing-ALXY25NE.js → routing-7HEUMP4R.js} +2 -2
- package/dist/schedule-tool-W6KPENHW.js +2 -0
- package/dist/{scheduler-5PHNW243.js → scheduler-I3UNKBBJ.js} +2 -2
- package/dist/{seat-ZYVVEILY.js → seat-DAMUB3CU.js} +2 -2
- package/dist/{select-6QLEV6AC.js → select-PMNHXNKI.js} +2 -2
- package/dist/self-SO6GCVYD.js +2 -0
- package/dist/{set-enabled-SYYTKJPC.js → set-enabled-36JN5ZRJ.js} +2 -2
- package/dist/signal-exit-C5EUGHKI.js +3 -0
- package/dist/signal-exit-C5EUGHKI.js.map +1 -0
- package/dist/{sprint-tool-PYVHPHR2.js → sprint-tool-Z4RRPK6I.js} +2 -2
- package/dist/{tool-TDOUM3BJ.js → tool-B6I22BG2.js} +2 -2
- package/dist/{tool-ZKZ4KYJT.js → tool-KTL4TLZP.js} +2 -2
- package/dist/{tool-GIYOYXXM.js → tool-SK3AAQYW.js} +2 -2
- package/dist/{wiki-ZRGLGMII.js → wiki-H2CBE4SM.js} +2 -2
- package/dist/wiki-enrich-GTUSSLCD.js +2 -0
- package/package.json +4 -1
- package/dist/board-dashboard-7HIME2W4.js.map +0 -1
- package/dist/chunk-7PQQZC6B.js +0 -310
- package/dist/chunk-7PQQZC6B.js.map +0 -1
- package/dist/chunk-MD2HCGSC.js.map +0 -1
- package/dist/chunk-NRUUT5TL.js +0 -256
- package/dist/chunk-NRUUT5TL.js.map +0 -1
- package/dist/chunk-OKADR5QO.js +0 -869
- package/dist/chunk-OKADR5QO.js.map +0 -1
- package/dist/chunk-R3CDFSNF.js +0 -580
- package/dist/chunk-R3CDFSNF.js.map +0 -1
- package/dist/chunk-XHJ5SVO5.js.map +0 -1
- package/dist/chunk-ZRALOFEG.js +0 -2035
- package/dist/chunk-ZRALOFEG.js.map +0 -1
- package/dist/config-mutator-ITL64FBW.js +0 -2
- package/dist/processes-M7YPWX7H.js +0 -2
- package/dist/program-4GDIWCDM.js.map +0 -1
- package/dist/schedule-tool-22UBZXCG.js +0 -2
- package/dist/signal-exit-WL7G3EEZ.js +0 -2
- package/dist/signal-exit-WL7G3EEZ.js.map +0 -1
- package/dist/wiki-enrich-CTID7JQW.js +0 -2
- /package/dist/{App-XWSSUYKF.js.map → App-777XBP22.js.map} +0 -0
- /package/dist/{ChatApp-UT2BRHYE.js.map → ChatApp-ZYMF5HSR.js.map} +0 -0
- /package/dist/{absorb-eval-SFGUURBD.js.map → absorb-eval-HYGBAPXS.js.map} +0 -0
- /package/dist/{adapter-UHR7FVM7.js.map → adapter-VV626IYN.js.map} +0 -0
- /package/dist/{agent-5NTFSCEO.js.map → agent-BS5VSO5T.js.map} +0 -0
- /package/dist/{chunk-IFHVAHQM.js.map → chunk-3ENH7HAS.js.map} +0 -0
- /package/dist/{chunk-YX4R2VGD.js.map → chunk-6D4RGQCU.js.map} +0 -0
- /package/dist/{chunk-FYFJ7IQJ.js.map → chunk-6KWHQAXS.js.map} +0 -0
- /package/dist/{chunk-FDX4IGLK.js.map → chunk-6MY7VXQV.js.map} +0 -0
- /package/dist/{chunk-4KNHLHE3.js.map → chunk-DOCAWXV5.js.map} +0 -0
- /package/dist/{chunk-5NGQQOVK.js.map → chunk-DYNXOYFN.js.map} +0 -0
- /package/dist/{chunk-RDWDDPBI.js.map → chunk-GXOKZSCS.js.map} +0 -0
- /package/dist/{chunk-Y4TVCWWF.js.map → chunk-JJ2WRGKI.js.map} +0 -0
- /package/dist/{chunk-XI2HH5NR.js.map → chunk-KLWCVTBM.js.map} +0 -0
- /package/dist/{chunk-7WGJZLVJ.js.map → chunk-OIECBQ45.js.map} +0 -0
- /package/dist/{chunk-QGNV2HA4.js.map → chunk-PIVIOIEC.js.map} +0 -0
- /package/dist/{chunk-QB6UPODO.js.map → chunk-QSJA6S66.js.map} +0 -0
- /package/dist/{chunk-IGBW4VVM.js.map → chunk-R2QFKEX5.js.map} +0 -0
- /package/dist/{chunk-NIPMVM3G.js.map → chunk-RG6MO7G5.js.map} +0 -0
- /package/dist/{chunk-5YG2ZQQW.js.map → chunk-RQOMUGUM.js.map} +0 -0
- /package/dist/{chunk-Z4XVPGPZ.js.map → chunk-SBJHIBWX.js.map} +0 -0
- /package/dist/{chunk-GEFZMDDX.js.map → chunk-TD2D4TGI.js.map} +0 -0
- /package/dist/{chunk-H2KOXGDX.js.map → chunk-UNZVDS3P.js.map} +0 -0
- /package/dist/{chunk-YSPBVLTZ.js.map → chunk-VDUMYEJH.js.map} +0 -0
- /package/dist/{chunk-BY3AUZYM.js.map → chunk-XBQISUBE.js.map} +0 -0
- /package/dist/{chunk-JNWXHOJE.js.map → chunk-YH7NALJ4.js.map} +0 -0
- /package/dist/{chunk-Y5TBOMHY.js.map → chunk-YZCQDZCA.js.map} +0 -0
- /package/dist/{chunk-343MPMLD.js.map → chunk-ZOCRNNNG.js.map} +0 -0
- /package/dist/{chunk-4WSJKKSA.js.map → chunk-ZSS3GL5A.js.map} +0 -0
- /package/dist/{client-SQMU25PS.js.map → client-CMQZO22V.js.map} +0 -0
- /package/dist/{config-56NBA4SF.js.map → config-BMYFEAO5.js.map} +0 -0
- /package/dist/{config-mutate-PD4O3HZ7.js.map → config-mutate-N6W52YXB.js.map} +0 -0
- /package/dist/{config-mutator-ITL64FBW.js.map → config-mutator-S5SGBNOG.js.map} +0 -0
- /package/dist/{contributions-DKTJ623L.js.map → contributions-KRES5F2V.js.map} +0 -0
- /package/dist/{doctor-OI6GJZR5.js.map → doctor-2KACCIZU.js.map} +0 -0
- /package/dist/{follow-up-tool-DYSLS6ZI.js.map → follow-up-tool-M57XXTPX.js.map} +0 -0
- /package/dist/{hub-4HDMTSR7.js.map → hub-FVAPTKTF.js.map} +0 -0
- /package/dist/{processes-M7YPWX7H.js.map → promote-LXKF6A24.js.map} +0 -0
- /package/dist/{promote-3272TZNI.js.map → query-W7OBMMVM.js.map} +0 -0
- /package/dist/{query-settings-HHVBIIVQ.js.map → query-settings-PTA2SA63.js.map} +0 -0
- /package/dist/{query-7XM6V4QG.js.map → registry-OHUOHAD2.js.map} +0 -0
- /package/dist/{request-planner-WNEDEA7X.js.map → request-planner-T44RMVNO.js.map} +0 -0
- /package/dist/{review-candidates-TGPDJMWJ.js.map → review-candidates-LKFIKTY6.js.map} +0 -0
- /package/dist/{registry-QL3AM3UH.js.map → routing-7HEUMP4R.js.map} +0 -0
- /package/dist/{routing-ALXY25NE.js.map → schedule-tool-W6KPENHW.js.map} +0 -0
- /package/dist/{schedule-tool-22UBZXCG.js.map → scheduler-I3UNKBBJ.js.map} +0 -0
- /package/dist/{scheduler-5PHNW243.js.map → seat-DAMUB3CU.js.map} +0 -0
- /package/dist/{select-6QLEV6AC.js.map → select-PMNHXNKI.js.map} +0 -0
- /package/dist/{seat-ZYVVEILY.js.map → self-SO6GCVYD.js.map} +0 -0
- /package/dist/{set-enabled-SYYTKJPC.js.map → set-enabled-36JN5ZRJ.js.map} +0 -0
- /package/dist/{sprint-tool-PYVHPHR2.js.map → sprint-tool-Z4RRPK6I.js.map} +0 -0
- /package/dist/{tool-TDOUM3BJ.js.map → tool-B6I22BG2.js.map} +0 -0
- /package/dist/{tool-ZKZ4KYJT.js.map → tool-KTL4TLZP.js.map} +0 -0
- /package/dist/{tool-GIYOYXXM.js.map → tool-SK3AAQYW.js.map} +0 -0
- /package/dist/{wiki-ZRGLGMII.js.map → wiki-H2CBE4SM.js.map} +0 -0
- /package/dist/{wiki-enrich-CTID7JQW.js.map → wiki-enrich-GTUSSLCD.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-UOK5MMKD.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-
|
|
1
|
+
import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-UOK5MMKD.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-FVAPTKTF.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-Q3HCFXDT.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-MZMIQ3SV.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-MZMIQ3SV.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
|
|
2
2
|
`).slice(0,12).map(n=>` | ${n}`).join(`
|
|
3
3
|
`)))}u.outcomes.length===0&&console.log(t.dim(" nothing to do: no entity of these types changed since the last run (--force redoes them)")),console.log(t.dim(` spent $${u.costUsd.toFixed(3)} of $${w}${u.capped?" \xB7 stopped at the cap":""}`))})}export{N as a,I as b};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-YH7NALJ4.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ba as ao,Da as co,G as Jr,N as Ot,O as zr,V as Dt,X as Qr,a as Rr,b as _r,d as $n,f as Ye,ha as Xr,i as Br,ia as Yr,j as Wr,ja as Zr,k as Pt,la as Vr,ma as eo,n as Et,na as to,oa as no,q as qr,r as Gr,ra as so,sa as ro,v as Kr,va as oo,wa as io}from"./chunk-
|
|
1
|
+
import{Ba as ao,Da as co,G as Jr,N as Ot,O as zr,V as Dt,X as Qr,a as Rr,b as _r,d as $n,f as Ye,ha as Xr,i as Br,ia as Yr,j as Wr,ja as Zr,k as Pt,la as Vr,ma as eo,n as Et,na as to,oa as no,q as qr,r as Gr,ra as so,sa as ro,v as Kr,va as oo,wa as io}from"./chunk-PIVIOIEC.js";import{b as Pr}from"./chunk-MEFPXHQJ.js";import{a as Rn}from"./chunk-W4YR2RO2.js";import{a as Mr}from"./chunk-VJVXEVZ7.js";import{b as Or,c as Mn,d as Lr,e as _t,h as Nr}from"./chunk-6KWHQAXS.js";import{h as Ar,i as Cr}from"./chunk-BE64IJWM.js";import{a as An,b as Er}from"./chunk-J3SOEFRE.js";import{a as Cn,b as Dr}from"./chunk-SIU6STB2.js";import{e as Ur,i as Fr,j as Hr,k as jr}from"./chunk-X5C5W3E4.js";import{a as $r}from"./chunk-TD2D4TGI.js";import{g as kr,h as vr}from"./chunk-QSJA6S66.js";import{c as lr,f as gr}from"./chunk-JJ2WRGKI.js";import{s as dr,v as Rt,w as ur,y as be,z as vn}from"./chunk-6D4RGQCU.js";import{a as Xe,b as Oe,f as Mt}from"./chunk-72SZI2UW.js";import{a as Ee,b as xn}from"./chunk-FCPTN6NF.js";import{a as pr,c as fr}from"./chunk-MYVHVJWZ.js";import{e as De,h as mr,i as Ce}from"./chunk-QUFIUXMQ.js";import{a as hr,b as yr,c as wr,d as br,l as xr}from"./chunk-AV7T3SYT.js";import{a as Sr,b as Tr}from"./chunk-LE3BXIUF.js";import{c as Ir}from"./chunk-BERWTVG2.js";import{c as Ys,d as Zs}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Ca as nr,Fa as Tn,Gb as Jc,Ha as Gc,Ka as sr,Pa as Kc,Va as rr,Wa as kn,Xa as or,Ya as Qe,Za as ir,_a as ar,eb as cr}from"./chunk-M7V7NCX6.js";import{g as ze,h as Wc}from"./chunk-VJ5HC63R.js";import{j as In,r as qc}from"./chunk-UEEB3UTU.js";import{a as Vs,b as pe,c as er,d as tr,e as Sn}from"./chunk-VQRY4IDI.js";vn();Mt();var Lt="tool-set",uo=["answer","code","full"],lo={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},zc=.1;function po(n){return{task:go(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:go(n.agentPrompt,600)}:{}}}var fo={bundle:Oe({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function mo(n,e=zc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=_n(s.answer),o=_n(s.code),i=_n(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function ho(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>lo.answer.includes(t))?"answer":e.every(t=>lo.code.includes(t))?"code":"full"}function yo(n,e){return uo.indexOf(n)<uo.indexOf(e)}function _n(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function go(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var wo=!1;function bo(n,e){let t=Rt(Lt);if(t!=="off")return t==="active"&&!wo&&(wo=!0,e(`[decisions] seat "${Lt}" is set to active, but only shadow is built: it records and changes nothing`)),be(Lt,po(n),fo,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=mo(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function xo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=ho(r);ur(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(yo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Qc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function So(n,e){let t=Qc(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function Pn(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}vn();Mt();var Io="session-continuity",To={continues:Xe("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Xe("Does the new request refer to something stated earlier in the conversation?")};function ko(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:En(n.message,1200),previousRequest:n.previousMessage?En(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>En(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function vo(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function En(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Gt}from"execa";import{spawn as Xc}from"node:child_process";import{createHash as Yc}from"node:crypto";import{createInterface as Zc}from"node:readline";var xe=class extends Error{},Vc=n=>Xc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),On=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Zc({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Dn=class{constructor(e=Vc,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=Yc("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([h],[P])=>h.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new xe("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let h=[...this.entries].find(([,P])=>!P.connection.busy);if(!h)throw new xe("Codex warm process capacity reached");h[1].connection.close(),this.entries.delete(h[0])}try{r={fingerprint:s,connection:new On(e,this.launchProcess)}}catch{throw new xe("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,d="",c,u,l,p,m=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),C=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let h={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...h,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(C),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let O=new Promise((A,_)=>{i.failTurn=_,i.notify=(M,N)=>{if(N?.threadId!==u)return;let L=N.item,W={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...N,type:M.replace("/","."),...L?{item:{...L,type:W[L.type]||L.type}}:{}}),M==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(c=L.text),M==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=N.delta,e.onDelta?.(N.delta,d)),M==="thread/tokenUsage/updated"){let F=N.tokenUsage.last;p=F.inputTokens;let q=F.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(F.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(F.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(F.cacheWriteInputTokens||0)}}M==="turn/completed"&&(N.turn.status==="completed"?A():_(new Error(N.turn.error?.message||`Codex turn ${N.turn.status}`)))}});return O.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await O,{content:c??d,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(h){if(i.close(),!a&&!e.signal?.aborted)throw new xe(h.message);return{content:d,codexSessionId:u,usage:l,contextTokens:p,error:h.message,duration:Date.now()-t}}finally{clearTimeout(C),clearTimeout(b),e.signal?.removeEventListener("abort",y),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},$o=new Dn;import{execFile as Sd}from"child_process";import{StringDecoder as nt}from"string_decoder";import{mkdtempSync as qo,readFileSync as Go,rmSync as Ko}from"fs";import{join as Wt}from"path";import{tmpdir as Jo}from"os";function Nt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),d=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||d===529||d===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Ut(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Ft(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,d=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&d>s)&&(e=r,t=a,s=d)}return e}var Ao=null;function Ht(){return Ao}function qp(n){Ao=n}function Ze(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function ed(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var Le=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},Co=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=Ze(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=ed(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new Le(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new Le(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Ze(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Ze(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Ze(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<s&&(s=i,t=o)}if(!t)return!1;let r=Ze(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(s.key,i)}catch(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";s.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as td}from"child_process";import{randomUUID as nd}from"crypto";import{existsSync as sd,readFileSync as rd}from"fs";import{resolve as od}from"path";function id(n){let e=od(n,"CLAUDE.md");if(!sd(e))return null;try{let t=rd(e,"utf8");return xr(t)}catch{return null}}var ad=20*60*1e3,cd=5e3,Ve=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},et=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function dd(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var Mo=class{constructor(e={}){this.opts=e}spawn(e,t){return new Ln(e,t,this.opts)}},Ln=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=td(r,o,{cwd:t.workspace,env:Ce(dd({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:id(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let d=this.waiters.splice(0);for(let c of d)c(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(m=>{t=m}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=nd(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
3
|
`);let d=e.deadlineMs??ad,c=o+d,u=()=>(this.kill(`turn deadline (${Math.round(d/6e4)}m)`),new Ve(d)),l=!1,p=null;try{for(;;){let m=c-Date.now();if(m<=0)throw u();let y=await this.nextEvent(m);if(y===null&&this.killReason)throw new et(this.killReason);if(y===null&&!this.exited)throw u();if(y===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(y.type==="user"&&y.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(y.type==="system"&&y.subtype==="init")p=y;else if(y.type==="result"){p=null;let b=typeof y.result=="string"?y.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${b.length} chars): ${b.slice(0,120)}`)}continue}if(yield{type:y.type,raw:y},y.type==="result"){this.onResultEvent(y);return}}}finally{let m=this.snap.state==="busy";this.snap={...this.snap,...m?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},cd);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};Sn();qc();xn();import{resolve as Ro,join as _o}from"path";var ud=4e3;function jt(n){try{let e=_o(Ro(n.root),".agentx","db.sqlite"),t=In({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ee(),r=n.input.command?n.input.command.slice(0,ud):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -31,7 +31,7 @@ ${n}`}function Td(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
|
|
|
31
31
|
`,l)}};A.stdout?.on("data",T=>{L+=F.write(T);let x=L.split(`
|
|
32
32
|
`);L=x.pop()||"";for(let U of x)X(U)}),A.stderr?.on("data",T=>{W+=q.write(T)});let v=await A;if(i&&i.removeEventListener("abort",N),L+=F.end(),L.trim()&&X(L),W+=q.end(),_)return{content:"",error:M||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:m};if(v.exitCode!==0||y){let T=v,x;return T.timedOut?x=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:y?x=y:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+W)?x=jo():x=W.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...Z(x),duration:Date.now()-d,usage:p,opencodeSessionId:m}}return C=!1,{content:l.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||n.model,opencodeSessionId:m}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let O=/ENOENT|spawn opencode/i.test(P?.message||"")?jo():P?.message;return{content:l,...Z(O||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:m}}finally{h?.(),b?.release(C)}}async function Od(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Se(n,e,s),d="",c=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of c)u.type==="result"&&u.subtype==="success"&&(d=u.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Dd(n,e,t,s,r,o,i,a,d){let c=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,m=()=>{let C=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(C))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let y=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);y.unref?.();let b=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let C=n.provider||"claude-code",h=s?`${s}
|
|
33
33
|
|
|
34
|
-
${e.message}`:e.message,P=e.context?.sender,O=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),A=e.context?.channel==="web-chat"&&O?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=br(n),M=Object.keys(_).length>0,N={task:h,cwd:e.cwd??n.workspace,provider:C,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:l.signal,mcpServers:M?_:void 0};if(r){let{generateStream:X}=await import("./agent-
|
|
34
|
+
${e.message}`:e.message,P=e.context?.sender,O=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),A=e.context?.channel==="web-chat"&&O?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=br(n),M=Object.keys(_).length>0,N={task:h,cwd:e.cwd??n.workspace,provider:C,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:l.signal,mcpServers:M?_:void 0};if(r){let{generateStream:X}=await import("./agent-BS5VSO5T.js"),v="",T,x,U,j;for await(let E of X(N)){if(d)try{d(E)}catch{}if(E.type==="text_delta")v+=E.text,r(E.text,v);else if(E.type==="thinking_delta")E.text&&i&&i(E.text);else if(E.type==="generate_result"){if(E.result.content&&E.result.content!==v){let J=E.result.content.slice(v.length);J?(v=E.result.content,r(J,v)):v=E.result.content}T=E.result.tokensUsed,E.result.inputTokens!=null&&(x=E.result.inputTokens),E.result.outputTokens!=null&&(U=E.result.outputTokens)}else if(E.type==="done"){if(E.result.content&&E.result.content!==v){let J=E.result.content.slice(v.length);J?(v=E.result.content,r(J,v)):v=E.result.content}E.result.tokensUsed!=null&&(T=E.result.tokensUsed)}else E.type==="error"&&(j=E.error)}return j&&!v?p?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Z(`Orchestrator error: ${j}`),duration:Date.now()-c}:((x===void 0||U===void 0)&&T&&(x=Math.round(T*.7),U=T-x),{content:v||"Done.",tokensUsed:T,usage:x!==void 0||U!==void 0?{inputTokens:x||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:L}=await import("./agent-BS5VSO5T.js"),W=await L(N),F=W.inputTokens,q=W.outputTokens;if((F===void 0||q===void 0)&&W.tokensUsed){let X=W.tokensUsed;F=Math.round(X*.7),q=X-F}return{content:W.content||"Done.",tokensUsed:W.tokensUsed,usage:F!==void 0||q!==void 0?{inputTokens:F||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(C){return p?b():C?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Z(`Orchestrator error: ${C.message}`),duration:Date.now()-c}}finally{clearTimeout(y),a&&a.removeEventListener("abort",m)}}var Un=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},Ld=1e3;async function Nd(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),Ld),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Ud(n,e,t,s,r,o,i){let a=Ht();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=Jt(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,m=!1;try{let v=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:c,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),m=a.list().length>v}catch(v){return v instanceof Le,null}m&&Bn(e.agentId,n,e.model,s,"persistent");let y=Se(n,e,t),b="",C,h,P,O,A,_,M,N="",L="",W=v=>{if(!i||!v)return;let T;if(L&&v.startsWith(L)?T=v.slice(L.length):T=N&&!N.endsWith(`
|
|
35
35
|
`)?`
|
|
36
36
|
|
|
37
37
|
${v}`:v,L=v,!!T){N+=T;try{i(T,N)}catch{}}},F=!1,q=()=>{F=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let X=!1;try{let v=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of p.runTurn({message:y,taskId:e.taskId??"unknown",deadlineMs:v})){if(X=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let x=T.raw.message?.content??[];for(let j of x)j.type==="text"&&typeof j.text=="string"?(b=j.text,W(j.text)):j.type==="tool_use"&&(L="");let U=T.raw.message?.usage;if(U){let j=(U.input_tokens||0)+(U.cache_read_input_tokens||0)+(U.cache_creation_input_tokens||0);j>0&&(O=j)}}if(T.type==="result"){let x=T.raw;if(x.is_error){let U=Z(typeof x.result=="string"?x.result:"claude error");C=U.error,h=U.errorKind}else typeof x.result=="string"&&x.result.length>0&&(b=x.result,N||W(x.result));typeof x.session_id=="string"&&(M=x.session_id),x.usage&&(P={inputTokens:x.usage.input_tokens||0,outputTokens:x.usage.output_tokens||0,cacheReadTokens:x.usage.cache_read_input_tokens||0,cacheCreateTokens:x.usage.cache_creation_input_tokens||0}),typeof x.num_turns=="number"&&(A=x.num_turns),typeof x.message?.model=="string"?_=x.message.model:typeof x.model=="string"?_=x.model:_=Ft(x.modelUsage)||_}}}catch(v){if(F)C="task cancelled by operator",h="cancelled";else if(X)if(v instanceof et)C=`Claude Code was stopped mid-turn (${v.reason}), before its time limit`,h="interrupted";else if(v instanceof Ve){let T=Z(`Claude Code timed out after ${Math.round(v.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);C=T.error,h=T.errorKind}else{let T=Z(`persistent claude process error: ${v?.message||String(v)}`);C=T.error,h=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${v?.message||v}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return F&&!C&&(C="task cancelled by operator",h="cancelled"),{content:F?"":b,error:C,errorKind:h,duration:Date.now()-d,usage:P,contextTokens:O,numTurns:A,billedModel:_,claudeSessionId:M}}function si(n){let e=pe(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?Oo(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Fo(t.args,n.taskId,n.agentId)}function Fd(n){return pe(n.autonomy)||!!n.personLimits}async function Hd(n,e,t,s,r,o,i){let a=pe(e.autonomy)?e.autonomy:void 0,d=a&&Do(a,n.tier)||e.personLimits&&Ho(n.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:c,message:a?`${tr(a)}
|
|
@@ -164,7 +164,7 @@ ${b}`,timeLimitRequest:b,timeLimitContinuation:u.continuation,timeLimitStartedAt
|
|
|
164
164
|
${e.message}`),e.queuedAt=void 0}let b=ki({message:e.message,home:e.context?.home}),C=Ti(c.runningTasks,b,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});C&&(this.log(`[${e.agentId}] ${C.slice(0,160)}`),e.message=`${C}
|
|
165
165
|
${e.message}`),c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let h={...b.length?{homes:b}:{},id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};c.runningTasks.push(h),e.runningTaskId=h.id;let P=kn(this.config.people,e.context);if(e.context&&(P?e.context.person=P.id:delete e.context.person),this.runningContexts.set(h.id,e.context??{}),e.onStart)try{e.onStart(h.id)}catch{}let O=new AbortController;this.taskAborts.set(h.id,{agentId:e.agentId,channel:h.channel,chatId:typeof h.chatId=="string"?h.chatId:"",originalMessage:e.message||"",controller:O,sender:e.context?.sender,rootId:_t()?.rootId,workflowRunId:e.workflowRunId??(typeof h.chatId=="string"&&h.chatId.startsWith("workflow:")&&h.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let A={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(h.id,A);let _=g=>{if(g){A.buffer+=g,A.buffer.length>lc&&(A.buffer=A.buffer.slice(A.buffer.length-lc));for(let f of A.subscribers)try{f(g)}catch{}}},M=Ee();e.taskId=M,h.traceId=M;let N=this.taskAborts.get(h.id);N&&(N.traceId=M);let L=new Map,W=(g,f,k)=>{try{V().emit("task:step",{taskId:M,agentId:e.agentId,name:"pipeline",action:g,status:k,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},F=0,q=!1,X=()=>{q||(q=!0,F&&W("first-event",F,"ok"))},v;if(t){let g=Cp();v=f=>{X();let k=g(f);if(k&&_(k),fc(M,e.agentId,f),pc(L,f),Zn(f,void 0,e.model||c.def.model),r)try{r(f)}catch{}}}else v=g=>{if(X(),fc(M,e.agentId,g),pc(L,g),Zn(g,void 0,e.model||c.def.model),r)try{r(g)}catch{}};let T=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,x=T?setTimeout(()=>O.abort(new Error(`timed out after ${Math.round(T/1e3)}s`)),T):void 0;x?.unref?.();let U=(c.def.preSpawnTimeoutSec??bp)*1e3,j=setTimeout(()=>{O.abort(new Error(`timed out before spawn after ${Math.round(U/1e3)}s in step "${h.step??"start"}"`))},U);j.unref?.();let E=()=>{j&&clearTimeout(j),j=void 0},J=()=>`task=${h.id} chat=${u}:${l} at=${new Date().toISOString()}`,re;O.signal.addEventListener("abort",()=>{let g=Pe(O.signal).message;/^timed out/.test(g)&&(re=h.step??"start"),this.log(`[${e.agentId}] task ${h.id} aborted in step "${h.step??"start"}" \u2014 ${g} ${J()}`)},{once:!0});let ee=g=>{h.step=g,this.log(`[${e.agentId}] step ${g} ${J()}`)},R=(g,f,k=0)=>{if(O.signal.aborted)return Promise.reject(Pe(O.signal));ee(g),(g==="agent"||g==="workflow-auto-run")&&(E(),F=Date.now());let I=Date.now(),B=Ea(f(),gp[g]??0,g);return Pa(B,O.signal,k).then(G=>(W(g,I,"ok"),G),G=>{throw W(g,I,"error"),G instanceof Be&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${J()}`),G})},te=async(g,f,k,I=0)=>{try{return await R(g,f,I)}catch(B){if(B instanceof Be)return k();throw B}},ie=!1,un=!1,ws=g=>{if(!(!ie||un)){un=!0;try{V().emit("task:completed",{taskId:M,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-h.startedAt.getTime(),error:g?.error||(O.signal.aborted?Pe(O.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(h.id)?!0:void 0,stopped:!this.interruptedRuns.has(h.id)&&(this.stoppedRuns.has(h.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},bs=!1,xs=g=>{if(bs)return;bs=!0,ws(g),this.runReleases.delete(h.id),x&&clearTimeout(x),E(),c.activeTasks--;let f=c.runningTasks.findIndex(I=>I.id===h.id);f!==-1&&c.runningTasks.splice(f,1),this.runningContexts.delete(h.id),this.taskAborts.delete(h.id);let k=this.runEndWaiters.get(h.id);this.runEndWaiters.delete(h.id);for(let I of k??[])try{I()}catch{}A.done=!0,A.endedAt=new Date;for(let I of A.subscribers)try{I(`
|
|
166
166
|
[task finished]
|
|
167
|
-
`)}catch{}A.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),yp).unref?.();try{let I=A.endedAt,B={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:I.toISOString(),durationMs:I.getTime()-h.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(h.id)||g?.errorKind==="stopped"?{status:"stopped"}:re?{status:"timeout",step:re}:{},responseText:g?.content||"",transcript:A.buffer};this.persistTaskRecord(B);let G=(B.responseText||B.error||"").trim();if(G){let Q=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:I,ok:B.ok})}}catch(I){this.log(`[${e.agentId}] task history persist failed: ${I?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(I=>{if(I.length===0)return;this.log(`[${e.agentId}] flushing ${I.length} queued message(s) after task=${h.id} chat=${u}:${l} at=${new Date().toISOString()}`);let B=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,count:I.length,at:new Date().toISOString()});let G=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,at:new Date().toISOString()});for(let Q of I){let $e=Q.originalContext||{channel:Q.channel,sender:Q.sender,chatId:Q.chatId};this.execute({message:Q.text,agentId:e.agentId,context:$e,queuedAt:Q.queuedAt??Q.timestamp}).then(ye=>(Ye(ye.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,ye)),ye=>{throw G(),ye}).catch(ye=>{this.log(`[${e.agentId}] queued message failed: ${ye.message}`)})}}).catch(I=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${I.message}`)})};this.runReleases.set(h.id,xs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${J()}`);let w=e.context?.channel||"api",{evaluateRequest:yc,selectRequestContext:wc}=await import("./request-planner-WNEDEA7X.js"),Ss=te("request-gate",()=>yc(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),ln=!1;Ss.then(()=>{ln=!0},()=>{ln=!0});let S=l,gn=e.context?.sender||"User",ue=c.def.tier==="codex-cli",Ge=sa(this.config.session,w,c.def.tier),ft=ra(this.config.session),le=e.isolated===!0,Ke=!le&&Ge==="lean"&&ft.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,S),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${S}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}));let mt=this.sessions.sessionIdleMs(e.agentId,w,S);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,S,e.seedHistory),()=>{});let bc=[...this.sessions.getSession(e.agentId,w,S).messages].reverse().find(g=>g.role==="agent")?.content;Ra({agent:e.agentId,channel:w,chatId:S,message:e.message,previousReply:bc,taskId:M}),this.sessions.addUserMessage(e.agentId,w,S,gn,e.message);let Is=Date.now(),Ts={agentId:e.agentId,channel:w,chatId:S,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Is).toISOString(),taskId:M,resumeOrigin:mi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Tn(e.context),...P?{person:P}:{},humanRoot:ze(e.context),pickup:nr(e.context),operator:sr(e.context),dueAt:_a(e.context),taskType:on(e.context)};V().emit("task:started",Ts),ie=!0;let ne,pn,ks=this.classifier;if(ks&&w!=="a2a"&&!ue){ee("classify");let g=Date.now();pn=ks.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:S,agentId:e.agentId}).then(f=>{ne=f||void 0,ne?.path?.length&&(h.intentPath=ne.path.slice()),W("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),W("classify",g,"error")})}let vs=async g=>{if(!pn)return;let f;await Promise.race([pn,new Promise(k=>{f=setTimeout(k,g),f.unref?.()})]),f&&clearTimeout(f)};await vs(ip);let Te=this.config.workflows?.matching,he,$s,As=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&As?.enabled&&(As.agents[e.agentId]??!0)&&!i&&ze(e.context))try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&($s=Qr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?he={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Xr(this.config.workflows,e.agentId)&&Yr(e)?this.workflowRuns:void 0;if(ke&&!he&&!i&&this.workflowAutoRunner&&ze(e.context))try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list()),k=Te?.autoRunThreshold??.85;f&&f.confidence>=k&&(he={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?lp():void 0,xc=ae?Zr(ae):void 0,Sc=this.wikiHub.getAgentWiki(e.agentId),Cs=this.memoryStore.findRelevant(e.message,e.agentId,ue?3:8),Ms=this.memoryStore.buildContext(Cs),Rs=this.memoryStore.contextFacts(Cs),Ic=this.patternStore.findRelevant(e.message,e.agentId,5),Tc=this.patternStore.buildContext(Ic),_s="";if(!ue)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),k=await R("skills",()=>g(c.def.workspace)),I=e.personLimits?.skills??[],B=I.length?k.filter(G=>!I.some(Q=>Qe(Q,G.frontmatter.name))):k;_s=f(B,e.message)}catch{}let H=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,S):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,S):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,S):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,S,mt)&&(this.log(`[${e.agentId}] session stale for ${w}:${S}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,S)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,S);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${S} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,S)){let g=this.sessions.getTurnCount(e.agentId,w,S);this.log(`[${e.agentId}] max-turns rotation for ${w}:${S} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&c.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=So({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,S),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,S),idleMs:mt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${S}: ${Pn(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"cost");let k=this.sessions.getLastTurnInputTokens(e.agentId,w,S);this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"cost",lastTurnInputTokens:k,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${S}: would ${Pn(f)}`)}}if(H&&c.def.tier==="claude-code"){let g=H;await te("rotate",()=>this.maybeRotateForContinuity(e,c,w,S,g),()=>!1)&&(H=void 0)}try{let g=await R("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,S,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",k=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${S} (quality: ${f}%, ${k} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let I=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${I.overallScore} (lexicon=${I.lexiconDecay}, tools=${I.toolShift}, semantic=${I.semanticDrift})`),I.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${I.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let kc=process.env.AGENTX_CONTEXT_SURGERY==="1",vc=ue?{maxMessages:8,maxChars:2400}:kc&&uc(w,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,$c=!H&&!ue?vp(Sc,e.agentId,{notesInbox:kp(this.config)}):void 0,ht=!H&&!Ke?this.sessions.buildHistoryContext(e.agentId,w,S,vc):void 0,Ac=H?void 0:this.sessions.getRotationMemo(e.agentId,w,S)??void 0,Ps,Es=[];if(this.config.procedures?.injection?.enabled&&!H&&!ue)try{let g=new at({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=ss(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){Ps=rs(f),Es=f.map(k=>({id:k.procedure.meta.id,title:k.procedure.meta.title}));for(let k of f)this.log(`[${e.agentId}] procedure match ${k.procedure.meta.id} score=${k.score.toFixed(2)} (${k.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,S).messages,k=f[0],I=f[f.length-1],B=ht===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${ht.length}c/${ht.split(`
|
|
167
|
+
`)}catch{}A.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),yp).unref?.();try{let I=A.endedAt,B={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:I.toISOString(),durationMs:I.getTime()-h.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(h.id)||g?.errorKind==="stopped"?{status:"stopped"}:re?{status:"timeout",step:re}:{},responseText:g?.content||"",transcript:A.buffer};this.persistTaskRecord(B);let G=(B.responseText||B.error||"").trim();if(G){let Q=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:I,ok:B.ok})}}catch(I){this.log(`[${e.agentId}] task history persist failed: ${I?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(I=>{if(I.length===0)return;this.log(`[${e.agentId}] flushing ${I.length} queued message(s) after task=${h.id} chat=${u}:${l} at=${new Date().toISOString()}`);let B=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,count:I.length,at:new Date().toISOString()});let G=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,at:new Date().toISOString()});for(let Q of I){let $e=Q.originalContext||{channel:Q.channel,sender:Q.sender,chatId:Q.chatId};this.execute({message:Q.text,agentId:e.agentId,context:$e,queuedAt:Q.queuedAt??Q.timestamp}).then(ye=>(Ye(ye.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,ye)),ye=>{throw G(),ye}).catch(ye=>{this.log(`[${e.agentId}] queued message failed: ${ye.message}`)})}}).catch(I=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${I.message}`)})};this.runReleases.set(h.id,xs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${J()}`);let w=e.context?.channel||"api",{evaluateRequest:yc,selectRequestContext:wc}=await import("./request-planner-T44RMVNO.js"),Ss=te("request-gate",()=>yc(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),ln=!1;Ss.then(()=>{ln=!0},()=>{ln=!0});let S=l,gn=e.context?.sender||"User",ue=c.def.tier==="codex-cli",Ge=sa(this.config.session,w,c.def.tier),ft=ra(this.config.session),le=e.isolated===!0,Ke=!le&&Ge==="lean"&&ft.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,S),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${S}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}));let mt=this.sessions.sessionIdleMs(e.agentId,w,S);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,S,e.seedHistory),()=>{});let bc=[...this.sessions.getSession(e.agentId,w,S).messages].reverse().find(g=>g.role==="agent")?.content;Ra({agent:e.agentId,channel:w,chatId:S,message:e.message,previousReply:bc,taskId:M}),this.sessions.addUserMessage(e.agentId,w,S,gn,e.message);let Is=Date.now(),Ts={agentId:e.agentId,channel:w,chatId:S,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Is).toISOString(),taskId:M,resumeOrigin:mi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Tn(e.context),...P?{person:P}:{},humanRoot:ze(e.context),pickup:nr(e.context),operator:sr(e.context),dueAt:_a(e.context),taskType:on(e.context)};V().emit("task:started",Ts),ie=!0;let ne,pn,ks=this.classifier;if(ks&&w!=="a2a"&&!ue){ee("classify");let g=Date.now();pn=ks.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:S,agentId:e.agentId}).then(f=>{ne=f||void 0,ne?.path?.length&&(h.intentPath=ne.path.slice()),W("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),W("classify",g,"error")})}let vs=async g=>{if(!pn)return;let f;await Promise.race([pn,new Promise(k=>{f=setTimeout(k,g),f.unref?.()})]),f&&clearTimeout(f)};await vs(ip);let Te=this.config.workflows?.matching,he,$s,As=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&As?.enabled&&(As.agents[e.agentId]??!0)&&!i&&ze(e.context))try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&($s=Qr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?he={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Xr(this.config.workflows,e.agentId)&&Yr(e)?this.workflowRuns:void 0;if(ke&&!he&&!i&&this.workflowAutoRunner&&ze(e.context))try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list()),k=Te?.autoRunThreshold??.85;f&&f.confidence>=k&&(he={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?lp():void 0,xc=ae?Zr(ae):void 0,Sc=this.wikiHub.getAgentWiki(e.agentId),Cs=this.memoryStore.findRelevant(e.message,e.agentId,ue?3:8),Ms=this.memoryStore.buildContext(Cs),Rs=this.memoryStore.contextFacts(Cs),Ic=this.patternStore.findRelevant(e.message,e.agentId,5),Tc=this.patternStore.buildContext(Ic),_s="";if(!ue)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),k=await R("skills",()=>g(c.def.workspace)),I=e.personLimits?.skills??[],B=I.length?k.filter(G=>!I.some(Q=>Qe(Q,G.frontmatter.name))):k;_s=f(B,e.message)}catch{}let H=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,S):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,S):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,S):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,S,mt)&&(this.log(`[${e.agentId}] session stale for ${w}:${S}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,S)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,S);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${S} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,S)){let g=this.sessions.getTurnCount(e.agentId,w,S);this.log(`[${e.agentId}] max-turns rotation for ${w}:${S} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&c.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=So({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,S),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,S),idleMs:mt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${S}: ${Pn(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"cost");let k=this.sessions.getLastTurnInputTokens(e.agentId,w,S);this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"cost",lastTurnInputTokens:k,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${S}: would ${Pn(f)}`)}}if(H&&c.def.tier==="claude-code"){let g=H;await te("rotate",()=>this.maybeRotateForContinuity(e,c,w,S,g),()=>!1)&&(H=void 0)}try{let g=await R("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,S,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",k=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${S} (quality: ${f}%, ${k} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let I=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${I.overallScore} (lexicon=${I.lexiconDecay}, tools=${I.toolShift}, semantic=${I.semanticDrift})`),I.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${I.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let kc=process.env.AGENTX_CONTEXT_SURGERY==="1",vc=ue?{maxMessages:8,maxChars:2400}:kc&&uc(w,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,$c=!H&&!ue?vp(Sc,e.agentId,{notesInbox:kp(this.config)}):void 0,ht=!H&&!Ke?this.sessions.buildHistoryContext(e.agentId,w,S,vc):void 0,Ac=H?void 0:this.sessions.getRotationMemo(e.agentId,w,S)??void 0,Ps,Es=[];if(this.config.procedures?.injection?.enabled&&!H&&!ue)try{let g=new at({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=ss(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){Ps=rs(f),Es=f.map(k=>({id:k.procedure.meta.id,title:k.procedure.meta.title}));for(let k of f)this.log(`[${e.agentId}] procedure match ${k.procedure.meta.id} score=${k.score.toFixed(2)} (${k.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,S).messages,k=f[0],I=f[f.length-1],B=ht===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${ht.length}c/${ht.split(`
|
|
168
168
|
`).length}L`,G=`[${e.agentId}] ${w}:${S} ${B} | session.messages=${f.length}`+(f.length>0?` first=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")}) last=${I.timestamp.slice(11,19)}(${I.role}:${(I.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ae.cat("context",G)}catch(g){Ae.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Os;if(c.def.contextReferences&&!H)try{let g=c.def.workspace,f=this.referencesCache.get(g);if(!f){let[I,B]=await R("references",()=>Promise.all([An(c.def.workspace),Cn(c.def.workspace)]));if(I.byId.size===0&&B.recipes.length===0){let[G,Q]=await R("references",()=>Promise.all([An(process.cwd()),Cn(process.cwd())]));f={refs:G,recipes:Q}}else f={refs:I,recipes:B};this.referencesCache.set(g,f)}let k=Dr({agentId:e.agentId,intentTags:ne?.path,message:e.message},f.recipes,f.refs);k.cards.length>0&&(Os=Er(k.cards,500*4)),k.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${k.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Ds=le||Ke?"":this.sessions.getCrossSessionSummary(e.agentId,w,S,e.message),Ls,yt=le?null:ai(e.message);if(yt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:S,lookbackDays:yt.lookbackDays,limit:12});if(g.turns.length>0){let f=[`[Long-memory recall \u2014 last ${yt.lookbackDays}d on this chat (cue-triggered)]`],k=[...g.turns].sort((I,B)=>I.ts.localeCompare(B.ts));for(let I of k){let B=I.ts.slice(11,16)+" "+I.day,G=I.role==="user"?I.senderName||"User":I.senderName||"Agent";f.push(`${B} ${G}: ${I.content}`)}g.hasMore&&f.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),Ls=f.join(`
|
|
169
169
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${yt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Cc=ue?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",Ns,Us,Fs=!1;ln||ee("request-gate");let ve=await Ss;if(ve.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Cc==="planner"&&!le&&!ve.active&&!Ke&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-CVCRW5TV.js"),f=await R("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:S,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(Fs=!0,Ns=f.sessionHistory,Ms=f.memoryContext,Rs=f.memoryFacts,Ds=f.crossChatContext,Us=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Fs&&H&&(this.sessions.clearClaudeSessionId(e.agentId,w,S),H=void 0)}let fn=`${e.agentId}:${w}:${S}`,wt=wr(e.message);wt&&(wt==="default"?(this.activeSouls.delete(fn),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(fn,wt),this.log(`[${e.agentId}] Soul switched to: ${wt}`)));let Mc=this.activeSouls.get(fn),Rc=hr(c.def.workspace,Mc),_c=yr(Rc),Pc=le?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Ec=mp(c.def.tier),Oc=Mp(c.def.richMessages,w),Dc=c.def.tier==="claude-code"&&(le||Ge!=="lean"||oa(ft)),Hs="";if(c.def.workspace&&!Dc){let g=K(c.def.workspace,"CLAUDE.md");if(de(g))try{let f=gt(g,"utf-8");Hs=`[Project CLAUDE.md]
|
|
170
170
|
${f.length>4e3?f.slice(0,4e3)+`
|
|
@@ -178,9 +178,9 @@ ${$e}`),f+=$e.length}catch{}}}let Lc=mn.length>0?mn.join(`
|
|
|
178
178
|
|
|
179
179
|
`)||void 0,xt={channel:w,chatId:S,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:c.def.systemPrompt,sender:gn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ue||Ke||uc(w,c.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ue?void 0:Tc||void 0,procedureContext:[Ps,$s].filter(Boolean).join(`
|
|
180
180
|
|
|
181
|
-
`)||void 0,workflowRunContext:xc,references:Os,skillInjection:_s||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ns??ht,memoryContext:Ms||void 0,crossChatContext:Ds||void 0,longMemoryRecall:Ls||void 0,contextOnDemand:Ke&&!H?la(w,S):void 0,wikiContext:$c,handoverNote:this.buildHandoverNote(e.agentId,w,S),watcherNote:(()=>{try{return this.runNote?.(Ts)}catch{return}})(),rotationMemo:Ac,eventDigest:H?void 0:Tp(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=ao(w,!H,c.def.richMessages);return g?$p(c.def.workspace,g):void 0})(),intent:ne?{path:ne.path,pathLabel:ne.pathLabel,pathId:ne.pathId,axes:ne.axes,leaf:ne.leaf,status:ne.status}:void 0,message:e.message};le&&Object.assign(xt,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let St=e.model?void 0:gr({tier:c.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?mt:null});St?.downgraded&&this.log(`[${e.agentId}] ${St.reason}`);let js=lr(c.def.tier,this.config.decisions.routing),Bs=St?.downgraded?Promise.resolve(St.model):!e.model&&js&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-
|
|
181
|
+
`)||void 0,workflowRunContext:xc,references:Os,skillInjection:_s||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ns??ht,memoryContext:Ms||void 0,crossChatContext:Ds||void 0,longMemoryRecall:Ls||void 0,contextOnDemand:Ke&&!H?la(w,S):void 0,wikiContext:$c,handoverNote:this.buildHandoverNote(e.agentId,w,S),watcherNote:(()=>{try{return this.runNote?.(Ts)}catch{return}})(),rotationMemo:Ac,eventDigest:H?void 0:Tp(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=ao(w,!H,c.def.richMessages);return g?$p(c.def.workspace,g):void 0})(),intent:ne?{path:ne.path,pathLabel:ne.pathLabel,pathId:ne.pathId,axes:ne.axes,leaf:ne.leaf,status:ne.status}:void 0,message:e.message};le&&Object.assign(xt,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let St=e.model?void 0:gr({tier:c.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?mt:null});St?.downgraded&&this.log(`[${e.agentId}] ${St.reason}`);let js=lr(c.def.tier,this.config.decisions.routing),Bs=St?.downgraded?Promise.resolve(St.model):!e.model&&js&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-7HEUMP4R.js"),f=await R("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?mt:null,cheapModel:js}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),Ws=!1;Bs.then(()=>{Ws=!0});let It=ve.active&&ve.preprocess?await te("select-context",()=>wc(xt),()=>({input:xt,excluded:[]})):{input:xt,excluded:[]};It.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${It.excluded.join(", ")}`);let Tt=fi(It.input,ue?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Nc=Mr(Tt,{memory:Rs,procedures:Es,wikiContext:It.input.wikiContext}),yn=(Tt?.length??0)+(hn?.length??0)+(e.message?.length??0),kt={history:Tt?.length??0,sysPrompt:hn?.length??0,message:e.message?.length??0},qs=Qi(e.agentId,w,S);Xi(qs,yn,kt);let Gs=Yi(qs);Gs&&this.log(`[${e.agentId}] ${Gs}`),yn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${S}: ${yn} bytes (history=${kt.history}, sysPrompt=${kt.sysPrompt}, message=${kt.message})`),Ws||ee("route-model");let Ks=await Bs,Js=c.def.tier!=="claude-code"?void 0:le?ca():Ge==="lean"?aa(c.def.workspace,ft,void 0,w):ua(c.def.workspace);Ge==="lean"&&!le&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${ga(Ge,ft,w)}`);let zs=c.def.tier==="claude-code"&&!H?bo({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:c.def.systemPrompt??null,taskId:M},g=>this.log(g)):void 0,Uc={...e,systemPromptAppend:hn,...Js?{claudeArgs:Js}:{},...Ks?{model:Ks}:{}},se,Qs=Aa({agent:e.agentId,request:e.message,taskId:M,budgetMinutes:c.def.maxExecutionMinutes??20}),Fc=v,Xs=!1,wn=!0;v=g=>{if(Qs.observe(g),ae&&wn)for(let f of eo(g))Vr(f.name,f.input)||(wn=!1);Fc?.(g)};try{let g=this.workflowAutoRunner;if(he&&g){let D=he;try{let z=await R("workflow-auto-run",()=>g({workflowId:D.workflowId,agentId:e.agentId,channel:w,chatId:S,message:e.message,...D.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:S,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ne?.path,matchedWorkflowId:D.workflowId,matchConfidence:D.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${he.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:D.follow?`Started the workflow "${z.title??D.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:he.workflowId,workflowRunId:z.runId,workflowMatchConfidence:he.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ae&&ke)try{let D=no(ke,e.resumedFrom);to(ke,{runId:ae,agentId:e.agentId,channel:w,chatId:S,message:e.message,taskId:M,...D?{continues:D}:{}}),Xs=!0,h.workflow={runId:ae,workflowId:zr}}catch(D){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${D?.message||D}`)}let f=()=>{if(c.def.tier!=="claude-code")return null;ee("dispatch-gate");let D=c.def.persistentProcess?Ht():null,z=D!=null&&D.hasLive({agentId:e.agentId,channel:w,chatId:S}),ce=!!H||z,ge=[Oi(ce),Ji(ce,void 0,e.model||c.def.model)].find(Ct=>Ct&&Ct.abort);if(ge){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ge.reason}`);let Ct={content:"",error:ge.message,errorKind:"dispatch_hold",duration:0};if(!t){A.buffer=`[error] ${ge.message}`;for(let Bc of A.subscribers)try{Bc(A.buffer)}catch{}}return Ct}Fi();let Je=zi();return Je&&this.log(`[${e.agentId}] ${Je}`),null},k=Et(e.agentId,void 0,Pt(e.agentId,e.context?.chatId));if(k){if(ee("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${k.reason}`),!t){A.buffer=`[error] ${k.message}`;for(let D of A.subscribers)try{D(A.buffer)}catch{}}return c.errors++,se={content:"",error:k.message,errorKind:"budget_cap",duration:0},se}let I=this.planCloudSession(c.def,e);if(I.route==="local"){let D=f();if(D)return c.errors++,se=D,D}let B=c.def.tier==="claude-code",G=B?t:(D,z)=>{D&&_(D),t&&t(D,z)},Q=!1,$e=B?s:D=>{D&&(Q?_(D):(_(`\u{1F4AD} ${D}`),Q=!0)),s&&s(D)},ye=()=>{Q&&(_(`
|
|
182
182
|
`),Q=!1)},Hc=B?G:G?(D,z)=>{ye(),G(D,z)}:void 0,$=await R("agent",async()=>{if(I.route!=="local"){let z=await this.runCloudSession(c.def,e,I,M);if(z)return z;let ce=f();if(ce)return ce}let D=await this.inTaskWorktree(c.def,Uc);return ri(D.def,D.task,this.providers,Hc,Tt,D.fresh?void 0:H,v,O.signal,$e)},wp);if(!$.error){let D=Ap(c.def.toolUseRequired,L);if(D){let z=Array.from(L.entries()).map(([ce,At])=>`${ce}=${At}`).join(", ")||"none";$.error=`tool_required_not_called: ${D} (invoked: ${z})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${D}, observed ${z}`)}}zs&&xo(zs,{toolUses:L,eventsSeen:q,error:$.error,agentId:e.agentId},D=>this.log(D));let vt=this.interruptedRuns.get(h.id);vt&&($.content="",$.error=vt,$.errorKind="interrupted");let bn=vt?void 0:this.stoppedRuns.get(h.id);bn&&($.content="",$.error=bn,$.errorKind="stopped"),se=$;let we=$.usage?Ar($.usage):void 0,jc=$.billedModel||e.model||c.def.model||void 0,$t=$.costUsd??($.usage?this.tokenTracker.runCost($.usage,jc,c.def.tier):void 0);if(un=!0,V().emit("task:completed",{taskId:M,agentId:e.agentId,channel:w,chatId:S,durationMs:Date.now()-Is,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:vt?!0:void 0,stopped:bn?!0:void 0,inputTokens:we?.inputTokens,outputTokens:we?.outputTokens,cacheReadTokens:we?.cacheReadTokens,cacheCreateTokens:we?.cacheCreateTokens,tier2InputTokens:we?.tier2InputTokens,tier2OutputTokens:we?.tier2OutputTokens,tier2CacheReadTokens:we?.tier2CacheReadTokens,tier2CacheCreateTokens:we?.tier2CacheCreateTokens,resumed:!!H,resumeSessionId:H||void 0,jevArm:ve.arm,numTurns:$.numTurns,costUsd:$t!==void 0&&Number.isFinite($t)&&$t>0?$t:void 0,injectedContext:Nc,finalResponse:$.content||void 0,billedModel:$.billedModel||e.model||c.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let D=$.error?`[error] ${$.error}`:$.content;A.buffer=D;for(let z of A.subscribers)try{z(D)}catch{}}if($.error)c.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,S,$.content),Ma({agent:e.agentId,channel:w,chatId:S,request:e.message,reply:$.content,taskId:M}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,S,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,S,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,S,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,w,S,$.usage,$.contextTokens),$.usage){let ge=$.contextTokens,Je=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ge??Je)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${S}: context=${ge??"n/a"} tokens (cumulative turn total=${Je}) \u2014 next turn will rotate`)}if(Sr({channel:w,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await vs(ap);try{let ge=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ge,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
183
183
|
|
|
184
184
|
Agent: ${$.content}`,meta:Ip(ne,e.context)})}catch{}Tr(e.agentId,e.message,$.content,{channel:w,chatId:S,sender:gn},this.memoryStore).catch(()=>{}),Ci(e.agentId,e.message,$.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=$.billedModel||e.model||c.def.model,ce=e.context?.channel,At=ce&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ce}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,z,ce,At),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${J()}`)}return $}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let f=Nt(g.message);return se={content:"",error:Ut(f),errorKind:f.kind},se}finally{if(Qs.stop(),Xs&&ae&&ke)try{let g=se?.usage,f=so(ke,ae,{error:se?se.error||void 0:O.signal.aborted?Pe(O.signal).message:"run ended before completion",canceled:ro(se?.errorKind)||this.stoppedRuns.has(h.id)||this.interruptedRuns.has(h.id)||!se&&O.signal.aborted,durationMs:Date.now()-h.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:wn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${g?.message||g}`)}ws(se),xs(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?hp(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:oo(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),qe,this.safe(e.agentId),t);de(s)||cp(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);up(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=K(process.cwd(),qe,this.safe(e));if(!de(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let d=new Date(s).toISOString().slice(0,10),c=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[c,d]){let p=K(a,l);if(de(p))try{for(let m of me(p)){if(!m.endsWith(".json"))continue;let y=m.split("-")[0],b=parseInt(y,10);if(!Number.isFinite(b)||b<i||b>s)continue;let C=Math.floor((s-b)/36e5),h=t-1-C;h>=0&&h<t&&o[h]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),qe);if(!de(e))return 0;let t=0;for(let s of me(e)){let r=K(e,s),o;try{o=me(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),d;try{d=me(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let u=JSON.parse(gt(K(a,c),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Sp){let t=K(process.cwd(),qe);if(!de(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of me(t)){let i=K(t,o),a;try{a=me(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=s))try{dp(K(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),qe,this.safe(e));if(!de(s))return[];let r=me(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=K(s,i),d;try{d=me(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let u=JSON.parse(gt(K(a,c),"utf-8")),{transcript:l,responseText:p,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),qe,this.safe(e));if(!de(s))return null;let r=this.safe(t),o=me(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(s,i,`${r}.json`);if(de(a))try{return JSON.parse(gt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Et(t,void 0,Pt(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=Rn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||Ye(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){pp.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let d=Jt(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:d,originalMessage:c}=o,u=o.controller.signal.aborted,l=!1;u&&c&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,d,c));let p=Date.now();this.messageQueue.enqueue(i,a,d,{text:t,sender:s,timestamp:p,channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:s}});let m=this.messageQueue.pendingCount(i,a,d);V().emit("task:queued",{agentId:i,channel:a,chatId:d,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:rr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let y=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:y,edited:l,pending:m}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,d=i.chatId;return new Promise(c=>{let u=!1,l=p=>{u||(u=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{Ye(p.error)?l({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Mp(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
185
185
|
`)}export{$o as a,qp as b,Co as c,id as d,Mo as e,jt as f,sf as g,cf as h,df as i,ff as j,Jt as k,Cd as l,ti as m,Ed as n,Od as o,Dd as p,ri as q,Qt as r,Xt as s,su as t,Bf as u,Wf as v,Gf as w,Zt as x,zf as y,Qn as z,V as A,Mi as B,Su as C,vu as D,Pi as E,um as F,Ei as G,Ni as H,Wi as I,km as J,qi as K,tn as L,Pm as M,Em as N,at as O,Ll as P,Nl as Q,Ul as R,Fl as S,Hl as T,ss as U,on as V,dh as W,cn as X,an as Y,Ua as Z,dt as _,Fa as $,hh as aa,yh as ba,wh as ca,bh as da,xh as ea,Sh as fa,Ih as ga,wg as ha,Ya as ia,We as ja,fp as ka,mp as la,Zy as ma,Vy as na,hp as oa,xp as pa,Ip as qa,Tp as ra,vp as sa,ys as ta,gc as ua,pc as va,Ap as wa,fc as xa,mc as ya,Mp as za};
|
|
186
|
-
//# sourceMappingURL=chunk-
|
|
186
|
+
//# sourceMappingURL=chunk-YZCQDZCA.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-
|
|
1
|
+
import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-OIECBQ45.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
|
|
2
2
|
## Worldview
|
|
3
3
|
|
|
4
4
|
${r}
|
|
@@ -249,4 +249,4 @@ ${u}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
|
|
|
249
249
|
Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let m=[{role:"user",content:n}];s&&(m.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),m.push({role:"user",content:`Your previous response failed validation: ${s}
|
|
250
250
|
Re-emit the FULL corrected JSON object.`}));let u=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:m}),signal:i.signal});if(!u.ok){let a=await u.text().catch(()=>"");throw new Error(`anthropic API ${u.status}: ${a.slice(0,500)}`)}let d=await u.json(),e=(Array.isArray(d.content)?d.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
|
|
251
251
|
`).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...l)=>t(l.map(String).join(" "))),p=c.rebuildIndex(),m=z(r),u=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(u,p,m,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let d=p.articles.map(l=>({title:l.title,path:l.path,type:l.type})),g=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,d,g);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,d,g);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(l=>l.candidates),w=new Set(y.map(l=>l.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(l=>[l.stamp,l]));for(let l of f.articles){let A=c.readArticle(l.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${l.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(l.promotedFrom,T),S={id:Y(o,l.path),createdAt:v,status:"pending",article:l,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:l.path,title:l.title,type:l.type,stamps:l.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of l.promotedFrom)k.push({stamp:X,decision:"proposed",article:l.path,proposal:S.id,at:v})}for(let l of f.skipped)k.push({stamp:l.stamp,decision:"skipped",reason:l.reason,at:v}),i.skipped.push(l);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let m=s.now??Date.now(),u=new Date(m).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??u,lastUpdated:u,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let g=new Date(m).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:g}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:g};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
|
|
252
|
-
//# sourceMappingURL=chunk-
|
|
252
|
+
//# sourceMappingURL=chunk-ZOCRNNNG.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Gb as $,fb as y}from"./chunk-
|
|
1
|
+
import{Gb as $,fb as y}from"./chunk-M7V7NCX6.js";import{randomBytes as x}from"crypto";import{existsSync as b,mkdirSync as k,readdirSync as M,readFileSync as j,renameSync as E,unlinkSync as S,writeFileSync as C}from"fs";import{resolve as u}from"path";function f(t){return u(t,".agentx","email")}function d(t,e){k(u(t,".."),{recursive:!0});let r=`${t}.${process.pid}.tmp`;C(r,JSON.stringify(e,null,2)+`
|
|
2
2
|
`,{mode:384}),E(r,t)}function g(t){try{return JSON.parse(j(t,"utf-8"))}catch{return null}}var D=t=>u(f(t),"threads.json");function w(t){return g(D(t))??{}}function F(t,e){return w(t)[e.toLowerCase()]}function I(t,e){let r=w(t);r[e.to.toLowerCase()]=e,d(D(t),r)}var h=(t,e)=>u(f(t),"cursors",`${e}.json`);function L(t,e){return g(h(t,e))}function z(t,e,r){d(h(t,e),r)}var T=2e4,_=t=>u(f(t),"drafts"),N=t=>/^[a-z0-9-]{8,64}$/.test(t),c=(t,e)=>u(_(t),`${e}.json`);function B(t,e,r=Date.now()){let n=e.text.trim().slice(0,T);if(!n)throw new Error("empty reply");let s={...e,text:n,id:`${r.toString(36)}-${x(4).toString("hex")}`,status:"pending",created_at:new Date(r).toISOString()};return d(c(t,s.id),s),s}function v(t,e){return N(e)?g(c(t,e)):null}function U(t,e){let r=_(t);return b(r)?M(r).filter(n=>n.endsWith(".json")).map(n=>v(t,n.slice(0,-5))).filter(n=>!!n&&(!e||n.status===e)).sort((n,s)=>n.created_at.localeCompare(s.created_at)):[]}async function V(t,e,r,n){let s=v(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no email reply "${e}" is waiting`};let i=`${c(t,e)}.${process.pid}.${x(3).toString("hex")}.claim`;try{E(c(t,e),i)}catch{return{ok:!1,error:`email reply "${e}" is already being decided`}}let a=n.text!==void 0&&n.text.trim()!==""&&n.text.trim()!==s.text,o={...s,...a?{text:n.text.trim().slice(0,T),edited:!0}:{},decided_by:n.by??"operator",decided_at:new Date(n.now??Date.now()).toISOString()};if(r==="no")o.status="rejected";else{let m=await n.send(o).catch(p=>({ok:!1,error:String(p?.message??p)}));if(!m.ok){d(c(t,e),{...s,error:m.error});try{S(i)}catch{}return{ok:!1,error:`not sent: ${m.error}`}}o.status="sent",delete o.error}d(c(t,e),o);try{S(i)}catch{}return{ok:!0,draft:o}}$();function l(t,e){return(t??"").replace(/\$\{(\w+)\}/g,(r,n)=>e[n]??"")}function P(t,e=process.env){let r={host:t.imap.host,port:t.imap.port,secure:t.imap.secure,user:l(t.imap.user,e)||t.address,password:l(t.imap.password,e)},n={host:t.smtp.host,port:t.smtp.port,secure:t.smtp.secure,user:l(t.smtp.user,e)||r.user,password:l(t.smtp.password,e)||r.password};return{imap:r,smtp:n}}async function J(t,e,r,n=process.env){let{smtp:s}=P(t,n);if(!s.password)throw new Error(`no SMTP password for ${t.address}: set it in .env`);let{default:i}=await import("nodemailer"),a=i.createTransport({host:s.host,port:s.port,secure:s.secure,auth:{user:s.user,pass:s.password},connectionTimeout:2e4,greetingTimeout:2e4,socketTimeout:6e4});try{return(await a.sendMail({from:{name:e,address:t.address},to:r.toName?{name:r.toName,address:r.to}:r.to,subject:r.subject,text:r.text,...r.inReplyTo?{inReplyTo:r.inReplyTo}:{},...r.references?{references:r.references}:{},headers:{"Auto-Submitted":"auto-replied"}})).messageId}finally{a.close()}}function q(t,e){return async r=>{let n=t?.channels?.email?.accounts?.[r.account];if(!n)return{ok:!1,error:`no email account "${r.account}" in agentx.json`};let s=y.safeParse(n);if(!s.success)return{ok:!1,error:`email account "${r.account}": ${s.error.issues[0]?.message}`};let i=s.data,a=i.name||t?.agents?.[r.agent]?.name||r.agent;return await J(i,a,{to:r.to,toName:r.to_name,subject:r.subject,inReplyTo:r.in_reply_to,references:r.references,text:r.text},e),{ok:!0}}}export{F as a,I as b,L as c,z as d,B as e,v as f,U as g,V as h,P as i,J as j,q as k};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-ZSS3GL5A.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-BHDAV67G.js"),{installCliSignalExit:r}=await import("./signal-exit-C5EUGHKI.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=client-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-R2QFKEX5.js";import"./chunk-M7V7NCX6.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
|
|
2
|
+
//# sourceMappingURL=client-CMQZO22V.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Ab as x,Bb as y,Cb as z,Db as A,Eb as B,Gb as C,db as a,eb as b,fb as c,gb as d,hb as e,ib as f,jb as g,kb as h,lb as i,mb as j,nb as k,ob as l,pb as m,qb as n,rb as o,sb as p,tb as q,ub as r,vb as s,wb as t,xb as u,yb as v,zb as w}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=config-
|
|
1
|
+
import{Ab as x,Bb as y,Cb as z,Db as A,Eb as B,Gb as C,db as a,eb as b,fb as c,gb as d,hb as e,ib as f,jb as g,kb as h,lb as i,mb as j,nb as k,ob as l,pb as m,qb as n,rb as o,sb as p,tb as q,ub as r,vb as s,wb as t,xb as u,yb as v,zb as w}from"./chunk-M7V7NCX6.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-QIJLFPWE.js";C();export{a as INTEGRATION_KINDS,x as WIKI_CONTRIBUTE_JOB,y as WIKI_CONTRIBUTE_MERGE_JOB,A as WIKI_SUMMARIZE_JOB,q as approvalsConfigSchema,f as callsSchema,d as cameraBotSchema,v as crossFieldProblems,s as daemonConfigSchema,c as emailAccountSchema,b as eventSubscriptionSchema,t as expandEnvVars,e as isCronExpression,u as loadDaemonConfig,n as membersConfigSchema,i as mergePolicyConfigSchema,m as peopleConfigSchema,l as personSchema,p as qualityReportConfigSchema,o as requestStatusConfigSchema,k as requestsConfigSchema,g as reviewGateConfigSchema,h as trackersConfigSchema,w as validateWorkspaces,r as wallConfigSchema,j as watchersConfigSchema,z as withContributionJobs,B as withSummariesJob};
|
|
2
|
+
//# sourceMappingURL=config-BMYFEAO5.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=config-mutate-
|
|
1
|
+
import{a,b}from"./chunk-3ENH7HAS.js";import"./chunk-M7V7NCX6.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-QIJLFPWE.js";export{a as mutateAgentxConfig,b as writeAgentxConfig};
|
|
2
|
+
//# sourceMappingURL=config-mutate-N6W52YXB.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-6MY7VXQV.js";import"./chunk-M7V7NCX6.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
|
|
2
|
+
//# sourceMappingURL=config-mutator-S5SGBNOG.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ee}from"./chunk-
|
|
1
|
+
import{a as ee}from"./chunk-RG6MO7G5.js";import"./chunk-VDUMYEJH.js";import{f as Q,k as V}from"./chunk-VJVXEVZ7.js";import{b as O}from"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-OWNQ2FD4.js";import{b as X}from"./chunk-KEXBEUSU.js";import"./chunk-SBJHIBWX.js";import"./chunk-JTFCU5LH.js";import"./chunk-QSJA6S66.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-6D4RGQCU.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QUFIUXMQ.js";import"./chunk-BERWTVG2.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import"./chunk-DCIYOPJF.js";import"./chunk-7I7IEX4S.js";import"./chunk-M7V7NCX6.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
|
|
2
2
|
`),se(t,n)}function ie(n){return{agents:E(w(S(n),"state.json"),{agents:{}}).agents??{}}}function ye(n){let r=w(S(n),"pending");return z(r)?re(r).filter(t=>t.endsWith(".json")).sort().map(t=>E(w(r,t),null)).filter(t=>!!t):[]}function G(n){return w(S(n),"held.json")}function K(n,r={}){let t=E(G(n),[]);return r.all?t:t.filter(a=>a.status==="held")}function _e(n){let r=w(S(n),"reports");if(!z(r))return null;let t=re(r).filter(a=>a.endsWith(".json")).sort().pop();return t?E(w(r,t),null):null}function ke(n,r,t,a={}){let o=ie(r).agents[t],c=a.now??Date.now(),e=a.since??o?.lastRunAt??new Date(c-864e5).toISOString(),d=e.slice(0,10),u=new Set(o?.processed??[]),s=[];for(let g of n.getAgentEntries(t))g.date<d||u.has(g.id)||s.push({id:g.id,at:g.date,kind:"chat",title:[g.source,g.sourceContext].filter(Boolean).join(" \xB7 "),text:g.content});if(a.db){let g=Date.parse(e);for(let l of V(a.db,{agentId:t,since:Number.isFinite(g)?g:void 0,limit:500})){if(l.status==="in-flight"||u.has(l.taskId))continue;let k=(Q(a.db,l.taskId)?.steps??[]).filter(b=>b.name==="tool_use"||b.action).slice(0,be).map(b=>`- ${b.action??b.name}${b.inputSummary?` ${x(b.inputSummary,160)}`:""}${b.outputSummary?` \u2192 ${x(b.outputSummary,240)}`:""}${b.error?` \u2717 ${x(b.error,120)}`:""}`),y=[`Request: ${x(l.originalMessage??l.messagePreview??"",600)}`,k.length?`Tool calls:
|
|
3
3
|
${k.join(`
|
|
4
4
|
`)}`:"",l.finalResponse?`Reply: ${x(l.finalResponse,800)}`:""].filter(Boolean).join(`
|
|
@@ -54,4 +54,4 @@ _Sources: ${t.sources.join("; ")}._`,a);return n.writeArticle(r,{title:t.title,.
|
|
|
54
54
|
`).replace(/\n{3,}/g,`
|
|
55
55
|
|
|
56
56
|
`).trim(),superseded:d}}function Ce(n){let r=n.previous?` (previously: ${n.previous})`:"";return`- **${n.attribute}:** ${n.value} \u2014 ${n.source}; checked ${n.checkedAt.slice(0,10)} by ${n.by}${r}`}function Re(n){let r=n.match(/^- \*\*.+?:\*\* (.*?) — .*?; checked (\S+) by \S+(?: \(previously: (.*)\))?$/);return r?{value:r[1],checkedAt:r[2],...r[3]?{previous:r[3]}:{}}:void 0}function J(n,r){return`contribution:${n}@${r.slice(0,10)}`}var Te={person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"};function de(n,r,t){let a=r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"page",o=t?Te[t]:"contributions",c=`${o}/${a}.md`;for(let e=2;n.readArticle(c);e++)c=`${o}/${a}-${e}.md`;return c}export{_ as DEFAULT_CONTRIBUTION_LIMITS,B as FACTS_HEADING,ue as applyFactLines,De as approveHeld,xe as buildContributionPrompt,S as contributionsDir,_e as latestReport,K as listHeld,ye as listPendingBatches,Be as mergeContributions,W as pageKey,Ae as parseContributionPatches,ke as pendingWork,Se as possibleDuplicate,Fe as rejectHeld,ce as replaceOnce,Me as runContribution};
|
|
57
|
-
//# sourceMappingURL=contributions-
|
|
57
|
+
//# sourceMappingURL=contributions-KRES5F2V.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=doctor-
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i}from"./chunk-DYNXOYFN.js";import"./chunk-KLWCVTBM.js";import"./chunk-IMLAPB7G.js";import"./chunk-CTNZVRPA.js";import"./chunk-MNG2AMKZ.js";import"./chunk-QPABR72X.js";import"./chunk-KP7KDLZ2.js";import"./chunk-OSH2PEBH.js";import"./chunk-M7V7NCX6.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-QIJLFPWE.js";export{i as daemonVoiceCheck,b as doctor,g as meshPeerTokenChecks,h as meshTokenChecksFromConfig,a as runDoctorChecks,e as runMirrorChecks,d as runNativeChecks,c as runNotificationChecks,f as runReminderChecks};
|
|
2
|
+
//# sourceMappingURL=doctor-2KACCIZU.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{b as h}from"./chunk-
|
|
1
|
+
import{b as h}from"./chunk-DOCAWXV5.js";import"./chunk-RKPAVWXF.js";import"./chunk-UNZVDS3P.js";import{b as I}from"./chunk-AJ5HMDRW.js";import"./chunk-KP7KDLZ2.js";import"./chunk-6KWHQAXS.js";import"./chunk-6MY7VXQV.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-M7V7NCX6.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-QIJLFPWE.js";var p=t=>typeof t=="string"?t.trim():"";function $(t){return[`Run ${t.runId} "${t.title}" [${t.status}] on step ${t.step}: waiting on ${t.waitingOn}.`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",...(t.steps??[]).slice(-8).map(s=>`- ${String(s.at).slice(0,16).replace("T"," ")} ${s.step} ${s.status}${s.note?`: ${s.note}`:""}`)].filter(Boolean).join(`
|
|
2
2
|
`)}async function T(t,c){let s=c.fetch??fetch,m=c.daemonUrl.replace(/\/$/,""),r=(p(t.action)||"list").toLowerCase(),f=c.env??process.env,w=async i=>{let l=await s(`${m}${i}`,{signal:AbortSignal.timeout(1e4)}),n=await l.json().catch(()=>({}));return{ok:l.ok,status:l.status,data:n}};try{if(r==="list"){let e=await w("/follow-up");if(!e.ok)return`Error: ${e.data?.error||`HTTP ${e.status}`}`;let o=e.data.groups??[];return o.length?o.map(d=>[`${d.tag}:`,...d.rows.map(a=>`- ${a.runId} "${a.title}" on ${a.step}: waiting on ${a.waitingOn} (since ${String(a.since).slice(0,16).replace("T"," ")} UTC)`)].join(`
|
|
3
3
|
`)).join(`
|
|
4
4
|
`):"No follow-up workflows are running."}if(r==="match"){let e=p(t.request)||p(t.title);if(!e)return"Error: match needs `request`: the owner's request in their words.";let o=h(t,f),d=await w(`/follow-up/match?q=${encodeURIComponent(e)}${o?`&agentId=${encodeURIComponent(o.agentId)}`:""}`);if(!d.ok)return`Error: ${d.data?.error||`HTTP ${d.status}`}`;let a=d.data.matches??[];return a.length?["Saved workflows, best fit first (confidence 0-1):",...a.map(u=>`- ${u.workflowId} "${u.title}" (${u.confidence}${u.autoStart?", starts without asking":""}): ${u.steps.map(k=>k.id).join(" \u2192 ")}`),'Start one with {action:"start", workflowId:"<id>", title:"\u2026", tags:["client:<name>"]}. Run its steps through the workflow, not by hand.'].join(`
|
|
5
5
|
`):"No saved workflow fits. If the request has several steps, build one: start with title and steps."}if(r==="status"){let e=p(t.runId);if(!e)return"Error: status needs runId.";let o=await w(`/follow-up/${encodeURIComponent(e)}`);return o.ok?$(o.data.run):`Error: ${o.data?.error||`HTTP ${o.status}`}`}let i=h(t,f);if(!i)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let l=await s(`${m}/follow-up`,{method:"POST",headers:{"Content-Type":"application/json",...I(f)},body:JSON.stringify({action:r,agentId:i.agentId,workflowId:t.workflowId,title:t.title,description:t.description,tags:t.tags,inputs:t.inputs,steps:t.steps,edges:t.edges,approval:t.approval,autoStart:t.autoStart,requestId:t.requestId,runId:t.runId,step:t.step,evidence:t.evidence,note:t.note,reason:t.reason,fromRun:t.fromRun,status:t.status}),signal:AbortSignal.timeout(2e4)}),n=await l.json().catch(()=>({}));if(!l.ok)return`Error: ${n?.error||`HTTP ${l.status}`}`;if(r==="start"){let e=n.run;return[`Started run ${e.runId} "${e.title}"${n.built?" (built from the steps you gave; propose it with fromRun to keep it)":""}.`,n.awaitingApproval?"It waits for the owner's approval before the first step.":`It is on step ${e.step}: ${e.waitingOn}.`,"AgentX follows it from here: it starts each step, reminds whoever is slow, and tells the owner when it ends. Do not run its steps by hand.",...n.warning?[`Note: ${n.warning}`]:[]].join(" ")}return r==="plan"?[`Plan recorded on run ${n.run?.runId??t.runId}:`,...(n.plan??[]).map(e=>`- ${e.id} ${e.title}`),'Report each step with {action:"step", runId, step:"<id>", status:"started"|"done"|"failed"}.'].join(`
|
|
6
6
|
`):r==="step"?`Step recorded. ${n.run?$(n.run):""}`.trim():r==="done"?`Step recorded as done. ${n.run?$(n.run):""}`.trim():r==="blocked"?"The step is marked blocked and the owner is told. Nothing more happens on it until it is sorted.":`Saved ${n.workflowId} switched off, and asked the owner (card ${n.cardId}) whether to keep it as a reusable workflow.`}catch(i){return`Error: couldn't reach the daemon (${i?.message??i}).`}}export{T as runWorkflowTool};
|
|
7
|
-
//# sourceMappingURL=follow-up-tool-
|
|
7
|
+
//# sourceMappingURL=follow-up-tool-M57XXTPX.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=hub-
|
|
1
|
+
import{a}from"./chunk-TD2D4TGI.js";import"./chunk-OIECBQ45.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QSJA6S66.js";import"./chunk-WPNRDEHW.js";import"./chunk-6D4RGQCU.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-DCIYOPJF.js";import"./chunk-7I7IEX4S.js";import"./chunk-M7V7NCX6.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as WikiHub};
|
|
2
|
+
//# sourceMappingURL=hub-FVAPTKTF.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ia as Tt,Ja as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-
|
|
1
|
+
import{Ia as Tt,Ja as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-OTITQCEQ.js";import"./chunk-MLNA54RW.js";import"./chunk-GTJIKXDB.js";import"./chunk-GXOKZSCS.js";import"./chunk-ZVP6GB4G.js";import"./chunk-KLWCVTBM.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-ZSS3GL5A.js";import"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-UMHN33JQ.js";import"./chunk-CTNZVRPA.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import"./chunk-ZOCRNNNG.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-MNG2AMKZ.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-QPABR72X.js";import"./chunk-UNZVDS3P.js";import"./chunk-AJ5HMDRW.js";import"./chunk-KP7KDLZ2.js";import{m as lt,n as ct,o as dt,p as mt,q as pt,ya as yt}from"./chunk-YZCQDZCA.js";import"./chunk-PIVIOIEC.js";import"./chunk-MEFPXHQJ.js";import{a as L}from"./chunk-BAXGL6TY.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-RQOMUGUM.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-SZDACK6O.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-VJVXEVZ7.js";import{t as ut}from"./chunk-6KWHQAXS.js";import"./chunk-6MY7VXQV.js";import"./chunk-3UOTLMXD.js";import"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-TD2D4TGI.js";import{a as ht}from"./chunk-OIECBQ45.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-SBJHIBWX.js";import"./chunk-JTFCU5LH.js";import{f as gt,g as ft}from"./chunk-QSJA6S66.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-JJ2WRGKI.js";import{j as it,k as rt,l as at}from"./chunk-6D4RGQCU.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-QUFIUXMQ.js";import"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-DCIYOPJF.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{Gb as nt,vb as tt,xb as st,zb as ot}from"./chunk-M7V7NCX6.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
4
|
${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
|