agentix-cli 0.160.0 → 0.162.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-ENNAIXFU.js → App-VEMBGGIU.js} +2 -2
- package/dist/{ChatApp-UNYTCNPZ.js → ChatApp-YDIXGL6D.js} +2 -2
- package/dist/{absorb-eval-UVOIKIBZ.js → absorb-eval-Z33YVMFY.js} +2 -2
- package/dist/{agent-JFDIUUCZ.js → agent-2X54W337.js} +2 -2
- package/dist/{board-dashboard-BOQSP6XB.js → board-dashboard-5BIFZPXT.js} +575 -341
- package/dist/board-dashboard-5BIFZPXT.js.map +1 -0
- package/dist/{chunk-NHD6DUBL.js → chunk-6S2S5LFZ.js} +2 -2
- package/dist/{chunk-NHD6DUBL.js.map → chunk-6S2S5LFZ.js.map} +1 -1
- package/dist/{chunk-IMSIYVBM.js → chunk-7PN7VPTC.js} +2 -2
- package/dist/{chunk-4QVGHA4B.js → chunk-CHJNHMPD.js} +2 -2
- package/dist/{chunk-ORAZ3WHL.js → chunk-EZXLWMXC.js} +2 -2
- package/dist/{chunk-LRP2LTLC.js → chunk-F2ECPRGJ.js} +2 -2
- package/dist/{chunk-CI5OJ2JN.js → chunk-FJW4KZO7.js} +2 -2
- package/dist/{chunk-QEJD3KFG.js → chunk-FUGLS3A3.js} +2 -2
- package/dist/{chunk-DEXEPOHH.js → chunk-FW6OJ27C.js} +2 -2
- package/dist/{chunk-QJDYXEEB.js → chunk-GWAITHGZ.js} +2 -2
- package/dist/{chunk-VDXHZAMX.js → chunk-HEGRUOSS.js} +2 -2
- package/dist/{chunk-RW3MTYHG.js → chunk-J3LMELJC.js} +2 -2
- package/dist/{chunk-7NRBMQE6.js → chunk-JABZOVMR.js} +2 -2
- package/dist/{chunk-M4AQRADJ.js → chunk-MCMEJVJC.js} +2 -2
- package/dist/{chunk-TZHVLA3D.js → chunk-MTQMBPYO.js} +2 -2
- package/dist/{chunk-NURZPCUE.js → chunk-OBHWGBDW.js} +2 -2
- package/dist/{chunk-PFNGZ27Y.js → chunk-OO7T7E4O.js} +2 -2
- package/dist/{chunk-ZFMG4GFE.js → chunk-Q6JWDH7G.js} +2 -2
- package/dist/{chunk-N3VQ5NSV.js → chunk-QMPFQ3KR.js} +6 -6
- package/dist/chunk-QMPFQ3KR.js.map +1 -0
- package/dist/{chunk-6LVCXEQE.js → chunk-RE36JAQN.js} +5 -5
- package/dist/{chunk-3MSNOHKU.js → chunk-SZ3CRNX4.js} +2 -2
- package/dist/{chunk-3MSNOHKU.js.map → chunk-SZ3CRNX4.js.map} +1 -1
- package/dist/{chunk-CXBTGXFO.js → chunk-UXUMH5SD.js} +2 -2
- package/dist/{chunk-RJWFVKBK.js → chunk-V2ZJMO63.js} +2 -2
- package/dist/{chunk-Y4KVFLQZ.js → chunk-VCUN55AE.js} +2 -2
- package/dist/{chunk-IMNN5RBR.js → chunk-VYGFBGUM.js} +2 -2
- package/dist/{chunk-XHAPSFAB.js → chunk-XG5FRD7G.js} +9 -9
- package/dist/{chunk-XHAPSFAB.js.map → chunk-XG5FRD7G.js.map} +1 -1
- package/dist/{chunk-H2KVHGAP.js → chunk-XNXKB2VI.js} +2 -2
- package/dist/{chunk-HYNP5WYF.js → chunk-YFNV7LAG.js} +3 -3
- package/dist/{chunk-M5L3SOS2.js → chunk-YG34COEO.js} +3 -3
- package/dist/chunk-YG34COEO.js.map +1 -0
- package/dist/chunk-ZZR7FOZ7.js +90 -0
- package/dist/chunk-ZZR7FOZ7.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{client-LUZU6O45.js → client-2QZHCEB5.js} +2 -2
- package/dist/config-KELRDI3A.js +2 -0
- package/dist/config-mutate-T2WXFS2S.js +2 -0
- package/dist/config-mutator-PLOFE6IA.js +2 -0
- package/dist/{contributions-FCKXPCOL.js → contributions-EH776JXB.js} +2 -2
- package/dist/{doctor-ZGL3U4XJ.js → doctor-IHA2USIQ.js} +2 -2
- package/dist/{follow-up-tool-ARGSSE7Q.js → follow-up-tool-BTV6CBTA.js} +2 -2
- package/dist/hub-NMD7O3DF.js +2 -0
- package/dist/index.d.ts +248 -3
- package/dist/index.js +1 -1
- package/dist/{program-DJJBDNID.js → program-6RAHRSDD.js} +200 -200
- package/dist/program-6RAHRSDD.js.map +1 -0
- package/dist/{promote-BKHGOZB2.js → promote-HX4RGNLX.js} +2 -2
- package/dist/{query-SPGPGSHG.js → query-E5LWOH4B.js} +2 -2
- package/dist/{query-settings-L6FOADK7.js → query-settings-ST5C4FPH.js} +2 -2
- package/dist/{registry-2JIZ3LOU.js → registry-MMZJDIXY.js} +2 -2
- package/dist/{request-planner-JCRREXJX.js → request-planner-RWRMDI3J.js} +2 -2
- package/dist/{review-candidates-OKHRZROS.js → review-candidates-WJ537GUT.js} +2 -2
- package/dist/routing-HQ5R7WP6.js +2 -0
- package/dist/schedule-tool-CVDIKLDN.js +2 -0
- package/dist/scheduler-UELETH3W.js +2 -0
- package/dist/{seat-FQ53NWXV.js → seat-ARUEPPYV.js} +2 -2
- package/dist/{select-YE4C3DZS.js → select-JQLDW6BF.js} +2 -2
- package/dist/{set-enabled-66ZBGZ2O.js → set-enabled-FB5V5DR7.js} +2 -2
- package/dist/{surface-usage-JOOZOGOH.js → surface-usage-W33HGXMP.js} +2 -2
- package/dist/{tool-QNIODAFO.js → tool-7JZ4UIJV.js} +2 -2
- package/dist/{tool-U2HRYX3V.js → tool-ZJCEBWLR.js} +2 -2
- package/dist/wiki-MMSBP2XP.js +2 -0
- package/dist/wiki-enrich-CBXIMFOD.js +2 -0
- package/package.json +2 -2
- package/dist/board-dashboard-BOQSP6XB.js.map +0 -1
- package/dist/chunk-M5L3SOS2.js.map +0 -1
- package/dist/chunk-N3VQ5NSV.js.map +0 -1
- package/dist/chunk-TFN6A3KI.js +0 -90
- package/dist/chunk-TFN6A3KI.js.map +0 -1
- package/dist/config-54LNSYJF.js +0 -2
- package/dist/config-mutate-DPI3LUG5.js +0 -2
- package/dist/config-mutator-W5QTLGCY.js +0 -2
- package/dist/hub-NK7Q4F2X.js +0 -2
- package/dist/program-DJJBDNID.js.map +0 -1
- package/dist/routing-B3B3ANA5.js +0 -2
- package/dist/schedule-tool-GUEADWVH.js +0 -2
- package/dist/scheduler-OKSJXZBX.js +0 -2
- package/dist/wiki-3HUDGN6J.js +0 -2
- package/dist/wiki-enrich-XQ3ZQBWZ.js +0 -2
- /package/dist/{App-ENNAIXFU.js.map → App-VEMBGGIU.js.map} +0 -0
- /package/dist/{ChatApp-UNYTCNPZ.js.map → ChatApp-YDIXGL6D.js.map} +0 -0
- /package/dist/{absorb-eval-UVOIKIBZ.js.map → absorb-eval-Z33YVMFY.js.map} +0 -0
- /package/dist/{agent-JFDIUUCZ.js.map → agent-2X54W337.js.map} +0 -0
- /package/dist/{chunk-IMSIYVBM.js.map → chunk-7PN7VPTC.js.map} +0 -0
- /package/dist/{chunk-4QVGHA4B.js.map → chunk-CHJNHMPD.js.map} +0 -0
- /package/dist/{chunk-ORAZ3WHL.js.map → chunk-EZXLWMXC.js.map} +0 -0
- /package/dist/{chunk-LRP2LTLC.js.map → chunk-F2ECPRGJ.js.map} +0 -0
- /package/dist/{chunk-CI5OJ2JN.js.map → chunk-FJW4KZO7.js.map} +0 -0
- /package/dist/{chunk-QEJD3KFG.js.map → chunk-FUGLS3A3.js.map} +0 -0
- /package/dist/{chunk-DEXEPOHH.js.map → chunk-FW6OJ27C.js.map} +0 -0
- /package/dist/{chunk-QJDYXEEB.js.map → chunk-GWAITHGZ.js.map} +0 -0
- /package/dist/{chunk-VDXHZAMX.js.map → chunk-HEGRUOSS.js.map} +0 -0
- /package/dist/{chunk-RW3MTYHG.js.map → chunk-J3LMELJC.js.map} +0 -0
- /package/dist/{chunk-7NRBMQE6.js.map → chunk-JABZOVMR.js.map} +0 -0
- /package/dist/{chunk-M4AQRADJ.js.map → chunk-MCMEJVJC.js.map} +0 -0
- /package/dist/{chunk-TZHVLA3D.js.map → chunk-MTQMBPYO.js.map} +0 -0
- /package/dist/{chunk-NURZPCUE.js.map → chunk-OBHWGBDW.js.map} +0 -0
- /package/dist/{chunk-PFNGZ27Y.js.map → chunk-OO7T7E4O.js.map} +0 -0
- /package/dist/{chunk-ZFMG4GFE.js.map → chunk-Q6JWDH7G.js.map} +0 -0
- /package/dist/{chunk-6LVCXEQE.js.map → chunk-RE36JAQN.js.map} +0 -0
- /package/dist/{chunk-CXBTGXFO.js.map → chunk-UXUMH5SD.js.map} +0 -0
- /package/dist/{chunk-RJWFVKBK.js.map → chunk-V2ZJMO63.js.map} +0 -0
- /package/dist/{chunk-Y4KVFLQZ.js.map → chunk-VCUN55AE.js.map} +0 -0
- /package/dist/{chunk-IMNN5RBR.js.map → chunk-VYGFBGUM.js.map} +0 -0
- /package/dist/{chunk-H2KVHGAP.js.map → chunk-XNXKB2VI.js.map} +0 -0
- /package/dist/{chunk-HYNP5WYF.js.map → chunk-YFNV7LAG.js.map} +0 -0
- /package/dist/{client-LUZU6O45.js.map → client-2QZHCEB5.js.map} +0 -0
- /package/dist/{config-54LNSYJF.js.map → config-KELRDI3A.js.map} +0 -0
- /package/dist/{config-mutate-DPI3LUG5.js.map → config-mutate-T2WXFS2S.js.map} +0 -0
- /package/dist/{config-mutator-W5QTLGCY.js.map → config-mutator-PLOFE6IA.js.map} +0 -0
- /package/dist/{contributions-FCKXPCOL.js.map → contributions-EH776JXB.js.map} +0 -0
- /package/dist/{doctor-ZGL3U4XJ.js.map → doctor-IHA2USIQ.js.map} +0 -0
- /package/dist/{follow-up-tool-ARGSSE7Q.js.map → follow-up-tool-BTV6CBTA.js.map} +0 -0
- /package/dist/{hub-NK7Q4F2X.js.map → hub-NMD7O3DF.js.map} +0 -0
- /package/dist/{promote-BKHGOZB2.js.map → promote-HX4RGNLX.js.map} +0 -0
- /package/dist/{query-SPGPGSHG.js.map → query-E5LWOH4B.js.map} +0 -0
- /package/dist/{query-settings-L6FOADK7.js.map → query-settings-ST5C4FPH.js.map} +0 -0
- /package/dist/{registry-2JIZ3LOU.js.map → registry-MMZJDIXY.js.map} +0 -0
- /package/dist/{request-planner-JCRREXJX.js.map → request-planner-RWRMDI3J.js.map} +0 -0
- /package/dist/{review-candidates-OKHRZROS.js.map → review-candidates-WJ537GUT.js.map} +0 -0
- /package/dist/{routing-B3B3ANA5.js.map → routing-HQ5R7WP6.js.map} +0 -0
- /package/dist/{schedule-tool-GUEADWVH.js.map → schedule-tool-CVDIKLDN.js.map} +0 -0
- /package/dist/{scheduler-OKSJXZBX.js.map → scheduler-UELETH3W.js.map} +0 -0
- /package/dist/{seat-FQ53NWXV.js.map → seat-ARUEPPYV.js.map} +0 -0
- /package/dist/{select-YE4C3DZS.js.map → select-JQLDW6BF.js.map} +0 -0
- /package/dist/{set-enabled-66ZBGZ2O.js.map → set-enabled-FB5V5DR7.js.map} +0 -0
- /package/dist/{surface-usage-JOOZOGOH.js.map → surface-usage-W33HGXMP.js.map} +0 -0
- /package/dist/{tool-QNIODAFO.js.map → tool-7JZ4UIJV.js.map} +0 -0
- /package/dist/{tool-U2HRYX3V.js.map → tool-ZJCEBWLR.js.map} +0 -0
- /package/dist/{wiki-3HUDGN6J.js.map → wiki-MMSBP2XP.js.map} +0 -0
- /package/dist/{wiki-enrich-XQ3ZQBWZ.js.map → wiki-enrich-CBXIMFOD.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{q as d}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{q as d}from"./chunk-YG34COEO.js";import{b as i,c as u,d as l,e as c}from"./chunk-VYGFBGUM.js";import f from"cronstrue";var p=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||p,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return f.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return d(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{p as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
|
|
2
|
+
//# sourceMappingURL=chunk-UXUMH5SD.js.map
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-MMZJDIXY.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-V2ZJMO63.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{kb as l,tb as m}from"./chunk-ZZR7FOZ7.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
|
|
2
2
|
`,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
|
|
3
3
|
`,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-VCUN55AE.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ib as b,jb as k,lb as x,tb as S}from"./chunk-ZZR7FOZ7.js";S();import{readFileSync as w,writeFileSync as v,existsSync as P}from"fs";import{resolve as d}from"path";function O(r){if(r)return d(r);let e=[d(process.cwd(),"agentx.json"),d(process.cwd(),".agentx/config.json")];for(let n of e)if(P(n))return n;return e[0]}function R(r){return JSON.parse(JSON.stringify(r))}async function C(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function N(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:l,daemonUrl:c}=e,o=O(l);if(!P(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let g;try{g=w(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let p;try{p=JSON.parse(g)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=R(p);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=k(i),u=b.safeParse(a);if(!u.success){let f=u.error.issues.map($=>` ${$.path.join(".")||"<root>"}: ${$.message}`).join(`
|
|
2
2
|
`);return{success:!1,path:o,error:`Validation failed:
|
|
3
3
|
${f}`,after:i}}let m=x(u.data);if(m.length)return{success:!1,path:o,error:`Validation failed:
|
|
4
4
|
${m.map(f=>` ${f}`).join(`
|
|
5
5
|
`)}`,after:i}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{v(o,JSON.stringify(i,null,2)+`
|
|
6
6
|
`)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let h=!1,y;if(s){let a=c||M(i),u=await C(a);u.ok?h=!0:y=u.reason}return{success:!0,path:o,after:i,reloaded:h,reloadSkipped:y}}function M(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function A(r,e,n){let t=e.split("."),s=r;for(let l=0;l<t.length-1;l++){let c=t[l];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function F(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function U(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{O as a,N as b,A as c,F as d,U as e};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-VYGFBGUM.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as _}from"./chunk-QIJLFPWE.js";function
|
|
1
|
+
import{a as _}from"./chunk-QIJLFPWE.js";function c(e){e.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS queued_messages (
|
|
3
3
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4
4
|
agent_id TEXT NOT NULL,
|
|
@@ -13,7 +13,7 @@ import{a as _}from"./chunk-QIJLFPWE.js";function d(e){e.exec(`
|
|
|
13
13
|
`)}function U(e,t){e.prepare(`
|
|
14
14
|
INSERT INTO queued_messages (agent_id, channel, chat_id, person, sender, message_preview, queued_at)
|
|
15
15
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
16
|
-
`).run(t.agentId,t.channel,t.chatId,t.person??null,t.sender?.slice(0,120)??null,t.messagePreview==null?null:String(t.messagePreview).replace(/\s+/g," ").trim().slice(0,200),t.queuedAt)}function
|
|
16
|
+
`).run(t.agentId,t.channel,t.chatId,t.person??null,t.sender?.slice(0,120)??null,t.messagePreview==null?null:String(t.messagePreview).replace(/\s+/g," ").trim().slice(0,200),t.queuedAt)}function v(e,t,a,n,s){return e.prepare("DELETE FROM queued_messages WHERE agent_id = ? AND channel = ? AND chat_id = ? AND queued_at <= ?").run(t,a,n,s).changes??0}function b(e){return e.prepare("DELETE FROM queued_messages").run().changes??0}function M(e){return e.prepare("SELECT id, agent_id, channel, chat_id, person, sender, message_preview, queued_at FROM queued_messages ORDER BY queued_at, id LIMIT 500").all().map(a=>({id:a.id,agentId:a.agent_id,channel:a.channel,chatId:a.chat_id,person:a.person??null,sender:a.sender??null,messagePreview:a.message_preview??null,queuedAt:a.queued_at}))}var N=_(()=>{"use strict"});function l(e){e.exec(`
|
|
17
17
|
CREATE TABLE IF NOT EXISTS forge_comments (
|
|
18
18
|
channel TEXT NOT NULL,
|
|
19
19
|
chat_id TEXT NOT NULL,
|
|
@@ -23,8 +23,8 @@ import{a as _}from"./chunk-QIJLFPWE.js";function d(e){e.exec(`
|
|
|
23
23
|
PRIMARY KEY (channel, chat_id, comment_id)
|
|
24
24
|
);
|
|
25
25
|
CREATE INDEX IF NOT EXISTS idx_forge_comments_chat ON forge_comments(channel, chat_id, at);
|
|
26
|
-
`)}function
|
|
27
|
-
WHERE channel = ? AND chat_id = ? AND at >= ? AND at <= ? ORDER BY at DESC LIMIT ?`).all(t,a,n,s,r)}var
|
|
26
|
+
`)}function S(e,t){e.prepare("INSERT OR IGNORE INTO forge_comments (channel, chat_id, comment_id, agent_id, at) VALUES (?, ?, ?, ?, ?)").run(t.channel,t.chatId,t.commentId.slice(0,64),t.agentId?.slice(0,120)??null,t.at)}function y(e,t,a,n,s,r=5){return e.prepare(`SELECT channel, chat_id AS chatId, comment_id AS commentId, agent_id AS agentId, at FROM forge_comments
|
|
27
|
+
WHERE channel = ? AND chat_id = ? AND at >= ? AND at <= ? ORDER BY at DESC LIMIT ?`).all(t,a,n,s,r)}var m=_(()=>{"use strict"});import{createRequire as R}from"module";import{mkdirSync as p}from"fs";import{dirname as A,resolve as I}from"path";function L(e){let t=String(e?.message??e),a=process.versions.modules,s=`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${a}).`;return/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(t)?`${t} ${s}`:`${t} ${s}`}function O(e=!1){if(o)return o;try{return o=D("better-sqlite3"),o}catch(t){return e||console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${L(t)}`),null}}function Q(e={}){if(e.disabled)return null;if(u)return u;let t=I(process.cwd(),e.path??".agentx/db.sqlite"),a=O(e.quiet);if(!a)return null;try{p(A(t),{recursive:!0});let n=new a(t);return n.pragma("journal_mode = WAL"),n.pragma("synchronous = NORMAL"),n.pragma("foreign_keys = ON"),X(n),u=n,u}catch(n){return e.quiet||console.error(`[storage/sqlite] openDb failed at ${t}: ${L(n)}`),null}}function X(e){e.exec(`
|
|
28
28
|
CREATE TABLE IF NOT EXISTS schema_version (
|
|
29
29
|
v INTEGER PRIMARY KEY
|
|
30
30
|
);
|
|
@@ -195,10 +195,10 @@ import{a as _}from"./chunk-QIJLFPWE.js";function d(e){e.exec(`
|
|
|
195
195
|
`},{v:13,sql:`
|
|
196
196
|
ALTER TABLE task_traces ADD COLUMN jev_arm TEXT;
|
|
197
197
|
CREATE INDEX idx_task_traces_jev_arm ON task_traces(jev_arm, started_at);
|
|
198
|
-
`}],n=e.transaction(s=>{e.exec(s.sql),e.prepare("INSERT INTO schema_version (v) VALUES (?)").run(s.v)});for(let s of a)s.v>t&&n(s);T(e,"task_traces",
|
|
198
|
+
`}],n=e.transaction(s=>{e.exec(s.sql),e.prepare("INSERT INTO schema_version (v) VALUES (?)").run(s.v)});for(let s of a)s.v>t&&n(s);T(e,"task_traces",h),T(e,"task_traces",k),T(e,"task_traces",g),T(e,"task_history",g),T(e,"task_traces",f),e.exec("CREATE INDEX IF NOT EXISTS idx_traces_person_started ON task_traces(person, started_at) WHERE person IS NOT NULL"),c(e),l(e)}function H(e,t,a){let n=Date.now(),r=e.prepare("SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'").get().n<a,i=null;return r||(i=e.prepare("SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'").get().n+1),e.prepare(`
|
|
199
199
|
INSERT INTO task_queue (id, conversation_id, agent_id, summary, status, position, created_at, started_at)
|
|
200
200
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
201
|
-
`).run(t.id,t.conversationId,t.agentId,t.summary,r?"active":"queued",i,n,r?n:null),{id:t.id,status:r?"active":"queued",position:i}}function
|
|
201
|
+
`).run(t.id,t.conversationId,t.agentId,t.summary,r?"active":"queued",i,n,r?n:null),{id:t.id,status:r?"active":"queued",position:i}}function W(e,t,a="done"){let n=Date.now();e.prepare(`
|
|
202
202
|
UPDATE task_queue SET status = ?, finished_at = ?, position = NULL WHERE id = ?
|
|
203
203
|
`).run(a,n,t);let s=e.prepare(`
|
|
204
204
|
SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1
|
|
@@ -206,8 +206,8 @@ import{a as _}from"./chunk-QIJLFPWE.js";function d(e){e.exec(`
|
|
|
206
206
|
UPDATE task_queue SET status = 'active', position = NULL, started_at = ? WHERE id = ?
|
|
207
207
|
`).run(n,s.id);let r=e.prepare(`
|
|
208
208
|
SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC
|
|
209
|
-
`).all(),i=e.prepare("UPDATE task_queue SET position = ? WHERE id = ?");for(let E=0;E<r.length;E++)i.run(E+1,r[E].id)}}function
|
|
209
|
+
`).all(),i=e.prepare("UPDATE task_queue SET position = ? WHERE id = ?");for(let E=0;E<r.length;E++)i.run(E+1,r[E].id)}}function K(e,t){let a=e.prepare("SELECT * FROM task_queue WHERE id = ?").get(t);return a?{id:a.id,conversationId:a.conversation_id,agentId:a.agent_id,summary:a.summary,status:a.status,position:a.position,createdAt:a.created_at,startedAt:a.started_at,finishedAt:a.finished_at}:null}function $(e,t,a=20){return e.prepare(`
|
|
210
210
|
SELECT * FROM task_queue WHERE conversation_id = ?
|
|
211
211
|
ORDER BY created_at DESC LIMIT ?
|
|
212
|
-
`).all(t,a).map(s=>({id:s.id,conversationId:s.conversation_id,agentId:s.agent_id,summary:s.summary,status:s.status,position:s.position,createdAt:s.created_at,startedAt:s.started_at,finishedAt:s.finished_at}))}function
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
212
|
+
`).all(t,a).map(s=>({id:s.id,conversationId:s.conversation_id,agentId:s.agent_id,summary:s.summary,status:s.status,position:s.position,createdAt:s.created_at,startedAt:s.started_at,finishedAt:s.finished_at}))}function V(e,t){let a=Date.now()-t*24*60*60*1e3,n=new Date(a).toISOString(),s=e.prepare("DELETE FROM task_history WHERE started_at < ?").run(n).changes??0,r=e.prepare("DELETE FROM rotations WHERE rotated_at < ?").run(n).changes??0,i=e.prepare("DELETE FROM route_traces WHERE at < ?").run(n).changes??0,E=e.prepare("DELETE FROM task_traces WHERE started_at < ?").run(a).changes??0,d=e.prepare("DELETE FROM forge_comments WHERE at < ?").run(a).changes??0;if(s+r+i+E+d>0)try{e.pragma("incremental_vacuum")}catch{}return{taskHistory:s,rotations:r,routeTraces:i,taskTraces:E,forgeComments:d}}function T(e,t,a){let n=new Set(e.prepare(`PRAGMA table_info(${t})`).all().map(s=>s.name));for(let[s,r]of a)if(!n.has(s))try{e.exec(`ALTER TABLE ${t} ADD COLUMN ${s} ${r}`)}catch(i){if(!/duplicate column name/i.test(String(i?.message)))throw i}}var D,u,o,h,k,g,f,C=_(()=>{"use strict";N();m();D=R(import.meta.url);h=[["resume_origin","TEXT"],["resume_attempt","INTEGER NOT NULL DEFAULT 0"],["resumed_from","TEXT"],["resume_decision","TEXT"],["resume_reason","TEXT"]],k=[["num_turns","INTEGER"],["injected_context","TEXT"]],g=[["person","TEXT"]],f=[["cost_usd","REAL"]]});export{U as a,v as b,b as c,M as d,N as e,S as f,y as g,m as h,Q as i,H as j,W as k,K as l,$ as m,V as n,g as o,T as p,C as q};
|
|
213
|
+
//# sourceMappingURL=chunk-XG5FRD7G.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/storage/queued-messages.ts","../src/storage/forge-comments.ts","../src/storage/sqlite.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\n\n// --- Messages waiting in line behind a busy agent (#443) ---\n//\n// The registry keeps the line itself in memory (agents/message-queue.ts).\n// This table mirrors what is waiting right now, with the person who sent\n// each message, so the member page, which runs in the dashboard and reads\n// the database only, can tell a teammate how many messages are ahead of\n// theirs. A row lives from the moment the message is queued to the moment\n// the line is handed over to a new turn; nothing waits here for long, and\n// the daemon empties the table when it boots, since the line it mirrors\n// did not survive the restart.\n//\n// The preview is the first 200 characters of the message. The member page\n// shows it only to the person who sent it; of anyone else's message it\n// reads the count alone.\n\nexport const QUEUED_PREVIEW_MAX = 200\n\nexport interface QueuedMessageRow {\n id: number\n agentId: string\n channel: string\n chatId: string\n /** The person who sent it (people, #384), when known. */\n person: string | null\n sender: string | null\n messagePreview: string | null\n queuedAt: number\n}\n\nexport function ensureQueuedMessagesTable(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS queued_messages (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n agent_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n person TEXT,\n sender TEXT,\n message_preview TEXT,\n queued_at INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_queued_messages_agent ON queued_messages(agent_id, queued_at);\n `)\n}\n\nexport function insertQueuedMessage(db: Database.Database, m: {\n agentId: string; channel: string; chatId: string\n person?: string | null; sender?: string | null; messagePreview?: string | null; queuedAt: number\n}): void {\n db.prepare(`\n INSERT INTO queued_messages (agent_id, channel, chat_id, person, sender, message_preview, queued_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `).run(\n m.agentId, m.channel, m.chatId, m.person ?? null, m.sender?.slice(0, 120) ?? null,\n m.messagePreview == null ? null : String(m.messagePreview).replace(/\\s+/g, \" \").trim().slice(0, QUEUED_PREVIEW_MAX),\n m.queuedAt,\n )\n}\n\n/** The line of one chat was handed over to a new turn: the messages queued\n * up to `flushedAt` are no longer waiting. One queued again after that\n * moment (the slot was taken meanwhile) has a newer row and stays. */\nexport function flushQueuedMessages(db: Database.Database, agentId: string, channel: string, chatId: string, flushedAt: number): number {\n const r = db.prepare(\n \"DELETE FROM queued_messages WHERE agent_id = ? AND channel = ? AND chat_id = ? AND queued_at <= ?\",\n ).run(agentId, channel, chatId, flushedAt)\n return r.changes ?? 0\n}\n\n/** The daemon starts: the line it kept in memory is gone, so is its mirror. */\nexport function clearQueuedMessages(db: Database.Database): number {\n return db.prepare(\"DELETE FROM queued_messages\").run().changes ?? 0\n}\n\n/** Everything waiting now, oldest first. Small: a line holds a handful of\n * messages, and only while an agent is busy. */\nexport function listQueuedMessages(db: Database.Database): QueuedMessageRow[] {\n const rows = db.prepare(\n \"SELECT id, agent_id, channel, chat_id, person, sender, message_preview, queued_at FROM queued_messages ORDER BY queued_at, id LIMIT 500\",\n ).all() as Array<Record<string, any>>\n return rows.map((r) => ({\n id: r.id, agentId: r.agent_id, channel: r.channel, chatId: r.chat_id,\n person: r.person ?? null, sender: r.sender ?? null, messagePreview: r.message_preview ?? null, queuedAt: r.queued_at,\n }))\n}\n","import type Database from \"better-sqlite3\"\n\n// --- Agent comments on GitHub and GitLab, by id (#1184) ---\n//\n// When the daemon posts an agent's comment on an issue, pull request or\n// merge request, the forge answers with the comment's id. That id is kept\n// here with the chat it went to, so the Wall can link to the exact\n// comment, not only to the issue. Ids and chats only: never the text.\n\nexport const FORGE_COMMENT_CHANNELS = [\"github\", \"gitlab\"] as const\n\nexport interface ForgeCommentRow {\n channel: string\n chatId: string\n commentId: string\n agentId: string | null\n at: number\n}\n\nexport function ensureForgeCommentsTable(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS forge_comments (\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n comment_id TEXT NOT NULL,\n agent_id TEXT,\n at INTEGER NOT NULL,\n PRIMARY KEY (channel, chat_id, comment_id)\n );\n CREATE INDEX IF NOT EXISTS idx_forge_comments_chat ON forge_comments(channel, chat_id, at);\n `)\n}\n\nexport function insertForgeComment(db: Database.Database, c: ForgeCommentRow): void {\n db.prepare(\n \"INSERT OR IGNORE INTO forge_comments (channel, chat_id, comment_id, agent_id, at) VALUES (?, ?, ?, ?, ?)\",\n ).run(c.channel, c.chatId, c.commentId.slice(0, 64), c.agentId?.slice(0, 120) ?? null, c.at)\n}\n\n/** The newest comments on one forge chat in [from, to], newest first. */\nexport function forgeCommentsOn(db: Database.Database, channel: string, chatId: string, from: number, to: number, limit = 5): ForgeCommentRow[] {\n return db.prepare(\n `SELECT channel, chat_id AS chatId, comment_id AS commentId, agent_id AS agentId, at FROM forge_comments\n WHERE channel = ? AND chat_id = ? AND at >= ? AND at <= ? ORDER BY at DESC LIMIT ?`,\n ).all(channel, chatId, from, to, limit) as ForgeCommentRow[]\n}\n","import type Database from \"better-sqlite3\"\nimport { createRequire } from \"module\"\nimport { existsSync, mkdirSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport { ensureQueuedMessagesTable } from \"./queued-messages\"\nimport { ensureForgeCommentsTable } from \"./forge-comments\"\n\n// --- SQLite storage layer ---\n//\n// Move 2 of the architectural review (docs/architecture/hexabot-vs-agentx.md).\n// SQLite for the operational tables — task_history, usage, dedup, sessions —\n// where queryable, indexed access has user-visible value (dashboards,\n// retention, analytics). Workflow definitions, wiki, agent-memory, and\n// references stay as files: they're git-diffable, human-readable, and don't\n// need queries.\n//\n// Approach: subscribe to the event bus (src/events/bus.ts) and write to\n// SQLite from the subscribers. Existing JSON writes are not touched —\n// SQLite runs alongside as a parallel pipeline. Once we have a query API\n// the dashboard depends on, we can deprecate the JSON path. Until then,\n// SQLite is observability-grade only.\n//\n// Synchronous API: better-sqlite3 is sync, no callbacks. The daemon's\n// event loop is the single writer; multiple readers (dashboard) use WAL\n// mode for concurrent read while we write.\n\ntype DatabaseConstructor = typeof Database\n\nconst require = createRequire(import.meta.url)\nlet _db: Database.Database | undefined\nlet _Database: DatabaseConstructor | undefined\n\nfunction betterSqlite3Fix(error: any): string {\n const msg = String(error?.message ?? error)\n const abi = process.versions.modules\n const node = process.version\n const hint = `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${node}, modules ${abi}).`\n if (/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(msg)) {\n return `${msg} ${hint}`\n }\n return `${msg} ${hint}`\n}\n\nfunction loadDatabaseCtor(quiet = false): DatabaseConstructor | null {\n if (_Database) return _Database\n try {\n _Database = require(\"better-sqlite3\") as DatabaseConstructor\n return _Database\n } catch (e: any) {\n if (!quiet) {\n console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\nexport interface OpenOptions {\n /** Resolved relative to cwd. Default: .agentx/db.sqlite */\n path?: string\n /** When true, SQLite writes are skipped (used by tests + opt-out). */\n disabled?: boolean\n /** Suppress the open-failure log. For best-effort callers whose whole\n * contract is \"do nothing if unavailable\" — telemetry, mainly. Without\n * this, a native-binding ABI mismatch prints a paragraph of node-gyp\n * advice on EVERY CLI invocation, which is worse than the thing it\n * is warning about. Load-bearing callers must never pass it. */\n quiet?: boolean\n}\n\n/**\n * Open the per-process SQLite database. Idempotent — repeated calls\n * return the same handle. The file is created on first open; the schema\n * is migrated forward to the latest version.\n *\n * Returns null when disabled — every subscriber should check for null\n * before issuing a write so the daemon stays runnable without SQLite if\n * someone's environment can't compile the native binding.\n */\nexport function openDb(opts: OpenOptions = {}): Database.Database | null {\n if (opts.disabled) return null\n if (_db) return _db\n const path = resolve(process.cwd(), opts.path ?? \".agentx/db.sqlite\")\n const Database = loadDatabaseCtor(opts.quiet)\n if (!Database) return null\n try {\n mkdirSync(dirname(path), { recursive: true })\n const db = new Database(path)\n // WAL keeps readers (dashboard) unblocked while the daemon writes.\n // Synchronous=NORMAL is the SQLite-recommended balance for WAL: the\n // db is durable on power-loss, but a crash within the last few ms can\n // lose the most recent commit. For our use (observability), that's fine.\n db.pragma(\"journal_mode = WAL\")\n db.pragma(\"synchronous = NORMAL\")\n db.pragma(\"foreign_keys = ON\")\n runMigrations(db)\n _db = db\n return _db\n } catch (e: any) {\n // Native binding missing, file unwritable, etc. Surface by default — the\n // alternative was a silent no-op, which makes the \"SQLite not opened\"\n // message in the daemon log impossible to debug. `quiet` callers have\n // explicitly opted out because doing nothing is their correct behavior.\n if (!opts.quiet) {\n console.error(`[storage/sqlite] openDb failed at ${path}: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\n/** Close the global handle. Test-only — production never closes. */\nexport function closeDb(): void {\n if (_db) {\n _db.close()\n _db = undefined\n }\n}\n\n/**\n * Per-version schema steps. New tables / columns go in a new migration —\n * never mutate an old one. Run on every open(); each step is idempotent\n * because it CREATE TABLE IF NOT EXISTS. SQLite has no concurrent\n * migration issue here (single writer process).\n */\nfunction runMigrations(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS schema_version (\n v INTEGER PRIMARY KEY\n );\n `)\n const current = (db\n .prepare(\"SELECT MAX(v) AS v FROM schema_version\")\n .get() as { v: number | null }).v ?? 0\n\n const steps: Array<{ v: number; sql: string }> = [\n {\n v: 1,\n sql: `\n CREATE TABLE task_history (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n status TEXT NOT NULL, -- 'ok' | 'error' | 'timeout'\n message_preview TEXT,\n error TEXT,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n started_at TEXT NOT NULL,\n finished_at TEXT NOT NULL\n );\n CREATE INDEX idx_task_history_agent_started\n ON task_history(agent_id, started_at);\n CREATE INDEX idx_task_history_status\n ON task_history(status, started_at);\n `,\n },\n {\n v: 2,\n sql: `\n CREATE TABLE usage_daily (\n agent_id TEXT NOT NULL,\n model TEXT NOT NULL,\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n input_tokens INTEGER DEFAULT 0,\n output_tokens INTEGER DEFAULT 0,\n cache_read_tokens INTEGER DEFAULT 0,\n cache_create_tokens INTEGER DEFAULT 0,\n tasks INTEGER DEFAULT 0,\n PRIMARY KEY (agent_id, model, day)\n );\n CREATE INDEX idx_usage_day ON usage_daily(day);\n `,\n },\n {\n v: 3,\n sql: `\n CREATE TABLE rotations (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n agent_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n reason TEXT NOT NULL, -- 'stale' | 'tier-2' | 'max-turns'\n last_turn_input_tokens INTEGER,\n rotated_at TEXT NOT NULL\n );\n CREATE INDEX idx_rotations_agent_at\n ON rotations(agent_id, rotated_at);\n `,\n },\n {\n v: 4,\n sql: `\n CREATE TABLE route_traces (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n msg_id TEXT NOT NULL,\n account_id TEXT,\n kind TEXT NOT NULL, -- 'match' | 'drop'\n deciding_stage TEXT,\n agent_id TEXT,\n reason TEXT,\n at TEXT NOT NULL\n );\n CREATE INDEX idx_route_traces_channel_at\n ON route_traces(channel, at);\n `,\n },\n {\n // Move A — tier-2 token buckets on usage_daily. The per-request tier\n // split is decided at record time by TokenTracker (it's a function of\n // the live cumulative input, not the row totals), so we cannot\n // reconstruct it on read. Adding columns is additive and idempotent;\n // existing rows default to 0.\n v: 5,\n sql: `\n ALTER TABLE usage_daily ADD COLUMN tier2_input_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_output_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_read_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_create_tokens INTEGER DEFAULT 0;\n `,\n },\n {\n // task_traces — per-execution observability surface (improvement plan\n // #2). One row per executeTask invocation, keyed by a ULID task_id so\n // it's URL-safe + monotonically sortable. Workflow context columns let\n // pattern queries group runs by workflow (\"agent-managed workflow as\n // the program\" framing); intent_event_id cross-links into the rescue\n // plan's intent ledger so a dispatch decision joins to the execution\n // it produced. Tokens snapshot the final usage at finish time.\n v: 6,\n sql: `\n CREATE TABLE task_traces (\n task_id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n workflow_run_id TEXT,\n workflow_id TEXT,\n workflow_node_id TEXT,\n intent_event_id TEXT,\n intent_decided_by TEXT,\n resume_session_id TEXT,\n final_session_id TEXT,\n model TEXT,\n status TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n finished_at INTEGER,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n error TEXT,\n message_preview TEXT\n );\n CREATE INDEX idx_traces_agent_started ON task_traces(agent_id, started_at);\n CREATE INDEX idx_traces_workflow_run ON task_traces(workflow_run_id);\n CREATE INDEX idx_traces_intent_event ON task_traces(intent_event_id);\n CREATE INDEX idx_traces_status_started ON task_traces(status, started_at);\n `,\n },\n {\n // task_trace_steps — append-only step ledger inside one task. Sequence\n // numbers are 0-based and unique per task_id; ON DELETE CASCADE so\n // pruning task_traces removes children atomically. The (input|output)_\n // summary columns are TEXT — callers cap byte-size at the call site,\n // not in the schema, because the right cap depends on the step kind\n // (a tool_use's args vs a tool_result's stdout have very different\n // typical sizes).\n v: 7,\n sql: `\n CREATE TABLE task_trace_steps (\n task_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n name TEXT NOT NULL,\n action TEXT,\n status TEXT,\n input_summary TEXT,\n output_summary TEXT,\n error TEXT,\n ms INTEGER,\n started_at INTEGER NOT NULL,\n PRIMARY KEY (task_id, seq),\n FOREIGN KEY (task_id) REFERENCES task_traces(task_id) ON DELETE CASCADE\n );\n CREATE INDEX idx_trace_steps_name ON task_trace_steps(name, started_at);\n `,\n },\n {\n // task replay support (handoff item #11). Capture the full original\n // user message AND the agent's final response so 'agentx trace replay\n // <taskId> --diff' can show side-by-side without reconstructing from\n // the step ledger. message_preview stays for cheap listing UX (200\n // chars); original_message holds the untruncated input. final_response\n // mirrors the agent's reply text. Both NULLABLE — old rows have NULL\n // and the replay command falls back to the preview gracefully.\n v: 8,\n sql: `\n ALTER TABLE task_traces ADD COLUMN original_message TEXT;\n ALTER TABLE task_traces ADD COLUMN final_response TEXT;\n `,\n },\n {\n // task_queue — persistent chat-initiated work queue (Phase 2).\n // Each row represents a task an agent queued during a /chat turn.\n // status: 'active' = currently running; 'queued' = waiting;\n // 'done' = completed; 'error' = failed.\n // position is 1-based rank among queued rows (null when active/done/error).\n v: 9,\n sql: `\n CREATE TABLE task_queue (\n id TEXT PRIMARY KEY,\n conversation_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n summary TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'queued',\n position INTEGER,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n finished_at INTEGER\n );\n CREATE INDEX idx_task_queue_status ON task_queue(status, created_at);\n CREATE INDEX idx_task_queue_convo ON task_queue(conversation_id, created_at);\n `,\n },\n {\n // guardrail_decisions — audit trail for the destructive-action guard\n // (PRD R7). One row per PreToolUse guard verdict, written by the\n // short-lived `agentx guard check` hook process. `verdict` is the\n // policy's decision (allow|deny|escalate|warn); `effective_action` is\n // what was actually enforced after the mode downgrade (in warn mode a\n // deny is recorded as verdict=deny, effective_action=allow). task_id is\n // a logical link to task_traces when the guard can resolve it (often\n // null — the hook doesn't always know the AgentX task id). `approver`\n // is reserved for Phase 2 escalation (human who approved/denied).\n v: 10,\n sql: `\n CREATE TABLE guardrail_decisions (\n id TEXT PRIMARY KEY,\n ts INTEGER NOT NULL,\n agent_id TEXT,\n task_id TEXT,\n tool TEXT NOT NULL,\n command TEXT,\n resolved_target TEXT,\n matched_rule TEXT,\n verdict TEXT NOT NULL,\n effective_action TEXT NOT NULL,\n mode TEXT,\n severity TEXT,\n approver TEXT,\n ms INTEGER\n );\n CREATE INDEX idx_guardrail_ts ON guardrail_decisions(ts);\n CREATE INDEX idx_guardrail_verdict ON guardrail_decisions(verdict, ts);\n CREATE INDEX idx_guardrail_agent ON guardrail_decisions(agent_id, ts);\n `,\n },\n {\n // Which operator surfaces actually get used. task_history records agent\n // dispatches and says nothing about which of the ~46 CLI commands or 16\n // dashboard pages anyone opens — the two biggest surfaces by count, and\n // the ones the surface-reduction work needs evidence for.\n //\n // Deliberately NOT folded into usage_daily: that table is keyed by\n // (agent_id, model, day) and is about token cost. Surface counts share\n // none of that shape, and mixing them would corrupt cost reporting.\n //\n // Names only — never arguments, paths, or payloads. This counts which\n // door was opened, not what was carried through it.\n v: 11,\n sql: `\n CREATE TABLE surface_usage (\n kind TEXT NOT NULL, -- 'cli' | 'page'\n name TEXT NOT NULL, -- 'guard log' | '/live'\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n count INTEGER NOT NULL DEFAULT 0,\n last_at TEXT,\n PRIMARY KEY (kind, name, day)\n );\n CREATE INDEX idx_surface_day ON surface_usage(day);\n `,\n },\n {\n // Per-turn token accounting that a with/without comparison can trust.\n // task_traces only carried the tier-1 buckets, and tier-2 turns are\n // where 90%+ of prompt tokens land, so most big turns read as zero.\n // `resumed` is explicit rather than inferred from resume_session_id:\n // NULL means \"not recorded\" (older rows), 0 a fresh session.\n v: 12,\n sql: `\n ALTER TABLE task_traces ADD COLUMN tier2_input_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_output_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_read_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_create_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN resumed INTEGER;\n `,\n },\n {\n // Request-gate experiment arm: 'treatment' (asked Jev), 'holdout'\n // (randomly skipped it), or NULL when the gate was not active. The\n // with/without-Jev comparison groups turns on this column.\n v: 13,\n sql: `\n ALTER TABLE task_traces ADD COLUMN jev_arm TEXT;\n CREATE INDEX idx_task_traces_jev_arm ON task_traces(jev_arm, started_at);\n `,\n },\n ]\n\n const txn = db.transaction((step: { v: number; sql: string }) => {\n db.exec(step.sql)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (?)\").run(step.v)\n })\n\n for (const step of steps) {\n if (step.v > current) txn(step)\n }\n\n // Columns added by name, not by version number. Several branches can each\n // claim the next migration number; a database that already recorded that\n // number from another branch would silently skip ours. Checking the\n // table itself makes these columns appear on every database.\n ensureColumns(db, \"task_traces\", RESUME_COLUMNS)\n ensureColumns(db, \"task_traces\", LESSON_IMPACT_COLUMNS)\n ensureColumns(db, \"task_traces\", PERSON_COLUMNS)\n ensureColumns(db, \"task_history\", PERSON_COLUMNS)\n ensureColumns(db, \"task_traces\", COST_COLUMNS)\n // A person's latest turns, read by the member page every 30 s (#448).\n // Without it that read walks every run on record. Partial: most runs\n // carry no person, and those rows stay out of the index.\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_traces_person_started ON task_traces(person, started_at) WHERE person IS NOT NULL\")\n // Messages waiting behind a busy agent, with who sent them (#443). By\n // name, not by version number, for the same reason as the columns above.\n ensureQueuedMessagesTable(db)\n // Agent comment ids on GitHub and GitLab (#1184), by name too.\n ensureForgeCommentsTable(db)\n}\n\n/** Schema version check for tests. */\nexport function getSchemaVersion(db: Database.Database): number {\n return (db.prepare(\"SELECT MAX(v) AS v FROM schema_version\").get() as { v: number | null }).v ?? 0\n}\n\n// --- task_queue helpers (Phase 2 chat-initiated work queue) ---\n\nexport interface TaskQueueEntry {\n id: string\n conversationId: string\n agentId: string\n summary: string\n status: \"active\" | \"queued\" | \"done\" | \"error\"\n position: number | null\n createdAt: number\n startedAt: number | null\n finishedAt: number | null\n}\n\nexport interface InsertTaskQueueResult {\n id: string\n status: \"active\" | \"queued\"\n position: number | null\n}\n\n/**\n * Insert a new task into the queue. Respects maxConcurrent — if the number\n * of 'active' rows is below the limit the new task is inserted as 'active';\n * otherwise it is 'queued' with a 1-based position.\n */\nexport function insertTaskQueue(\n db: Database.Database,\n entry: { id: string; conversationId: string; agentId: string; summary: string },\n maxConcurrent: number,\n): InsertTaskQueueResult {\n const now = Date.now()\n const activeCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'\")\n .get() as { n: number }).n\n\n const isActive = activeCount < maxConcurrent\n let position: number | null = null\n if (!isActive) {\n const queuedCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'\")\n .get() as { n: number }).n\n position = queuedCount + 1\n }\n\n db.prepare(`\n INSERT INTO task_queue (id, conversation_id, agent_id, summary, status, position, created_at, started_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n entry.id,\n entry.conversationId,\n entry.agentId,\n entry.summary,\n isActive ? \"active\" : \"queued\",\n position,\n now,\n isActive ? now : null,\n )\n\n return { id: entry.id, status: isActive ? \"active\" : \"queued\", position }\n}\n\n/**\n * Mark a task done/error and promote the next queued task (if any) to active.\n */\nexport function completeTaskQueue(\n db: Database.Database,\n id: string,\n status: \"done\" | \"error\" = \"done\",\n): void {\n const now = Date.now()\n db.prepare(`\n UPDATE task_queue SET status = ?, finished_at = ?, position = NULL WHERE id = ?\n `).run(status, now, id)\n\n // Promote oldest queued task to active\n const next = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1\n `).get() as { id: string } | undefined\n if (next) {\n db.prepare(`\n UPDATE task_queue SET status = 'active', position = NULL, started_at = ? WHERE id = ?\n `).run(now, next.id)\n // Resequence remaining queued positions\n const remaining = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC\n `).all() as Array<{ id: string }>\n const upd = db.prepare(\"UPDATE task_queue SET position = ? WHERE id = ?\")\n for (let i = 0; i < remaining.length; i++) {\n upd.run(i + 1, remaining[i].id)\n }\n }\n}\n\n/** Look up a single task_queue row. */\nexport function getTaskQueue(\n db: Database.Database,\n id: string,\n): TaskQueueEntry | null {\n const row = db.prepare(\"SELECT * FROM task_queue WHERE id = ?\").get(id) as Record<string, unknown> | undefined\n if (!row) return null\n return {\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }\n}\n\n/** List task_queue rows for a conversation, newest first. */\nexport function listTaskQueueByConversation(\n db: Database.Database,\n conversationId: string,\n limit = 20,\n): TaskQueueEntry[] {\n const rows = db.prepare(`\n SELECT * FROM task_queue WHERE conversation_id = ?\n ORDER BY created_at DESC LIMIT ?\n `).all(conversationId, limit) as Array<Record<string, unknown>>\n return rows.map((row) => ({\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }))\n}\n\nexport interface PruneResult {\n taskHistory: number\n rotations: number\n routeTraces: number\n taskTraces: number\n}\n\n/**\n * Drop rows older than `retentionDays` from the operational tables that grow\n * unbounded over time. `usage_daily` is bounded by (agent, model, day) and\n * doesn't need pruning; the caller decides whether to keep aggregates beyond\n * the retention window.\n *\n * Mirrors the file-based `pruneTaskHistory` sweep that runs at daemon\n * startup. Cheap — three indexed deletes plus an incremental_vacuum.\n */\nexport function pruneSqliteTables(\n db: Database.Database,\n retentionDays: number,\n): PruneResult {\n const cutoffMs = Date.now() - retentionDays * 24 * 60 * 60 * 1000\n const cutoffIso = new Date(cutoffMs).toISOString()\n\n const taskHistory = (db\n .prepare(`DELETE FROM task_history WHERE started_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const rotations = (db\n .prepare(`DELETE FROM rotations WHERE rotated_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const routeTraces = (db\n .prepare(`DELETE FROM route_traces WHERE at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n // task_traces uses ms-epoch INTEGERs (not ISO strings) on started_at.\n // task_trace_steps cascades automatically via ON DELETE CASCADE.\n const taskTraces = (db\n .prepare(`DELETE FROM task_traces WHERE started_at < ?`)\n .run(cutoffMs).changes ?? 0) as number\n\n // Reclaim the freelist pages so the file shrinks. WAL writes still\n // checkpoint independently.\n if (taskHistory + rotations + routeTraces + taskTraces > 0) {\n try { db.pragma(\"incremental_vacuum\") } catch { /* best-effort */ }\n }\n\n return { taskHistory, rotations, routeTraces, taskTraces }\n}\n\n/** Resume after restart (#103): how to re-enter a run (JSON), its attempt\n * number, the cut-off run it continues, and the boot decision made for it. */\nconst RESUME_COLUMNS: Array<[string, string]> = [\n [\"resume_origin\", \"TEXT\"],\n [\"resume_attempt\", \"INTEGER NOT NULL DEFAULT 0\"],\n [\"resumed_from\", \"TEXT\"],\n [\"resume_decision\", \"TEXT\"],\n [\"resume_reason\", \"TEXT\"],\n]\n\n/** Lesson impact (#98): the memory facts and procedures injected into a turn,\n * as JSON {memory: ids, procedures: ids, wiki: bool}, plus the runtime's turn\n * count. `agentx trace lessons` compares a repeated task before and after\n * each lesson on these columns. */\nconst LESSON_IMPACT_COLUMNS: Array<[string, string]> = [\n [\"num_turns\", \"INTEGER\"],\n [\"injected_context\", \"TEXT\"],\n]\n\n/** People (#384): the id of the known person who started the run. NULL for\n * an unknown sender, for turns software starts, and on older rows. */\nexport const PERSON_COLUMNS: Array<[string, string]> = [[\"person\", \"TEXT\"]]\n\n/** What a run cost in USD, summed per agent per month for the budget (#1162). */\nexport const COST_COLUMNS: Array<[string, string]> = [[\"cost_usd\", \"REAL\"]]\n\n/** Add any of `columns` the table lacks. Idempotent. */\nexport function ensureColumns(db: Database.Database, table: string, columns: Array<[string, string]>): void {\n const have = new Set((db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).map((c) => c.name))\n for (const [name, type] of columns) {\n if (have.has(name)) continue\n try {\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${name} ${type}`)\n } catch (e: any) {\n // Two processes starting on one database: the slower one read the\n // table before the faster one added the column. Already there is fine.\n if (!/duplicate column name/i.test(String(e?.message))) throw e\n }\n }\n}\n"],"mappings":"wCA+BO,SAASA,EAA0BC,EAA6B,CACrEA,EAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAYP,CACH,CAEO,SAASC,EAAoBD,EAAuBE,EAGlD,CACPF,EAAG,QAAQ;AAAA;AAAA;AAAA,GAGV,EAAE,IACDE,EAAE,QAASA,EAAE,QAASA,EAAE,OAAQA,EAAE,QAAU,KAAMA,EAAE,QAAQ,MAAM,EAAG,GAAG,GAAK,KAC7EA,EAAE,gBAAkB,KAAO,KAAO,OAAOA,EAAE,cAAc,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAAE,MAAM,EAAG,GAAkB,EAClHA,EAAE,QACJ,CACF,CAKO,SAASC,EAAoBH,EAAuBI,EAAiBC,EAAiBC,EAAgBC,EAA2B,CAItI,OAHUP,EAAG,QACX,mGACF,EAAE,IAAII,EAASC,EAASC,EAAQC,CAAS,EAChC,SAAW,CACtB,CAGO,SAASC,EAAoBR,EAA+B,CACjE,OAAOA,EAAG,QAAQ,6BAA6B,EAAE,IAAI,EAAE,SAAW,CACpE,CAIO,SAASS,EAAmBT,EAA2C,CAI5E,OAHaA,EAAG,QACd,yIACF,EAAE,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N,EAAuBuC,EAAeC,EAAwC,CAC1G,IAAMC,EAAO,IAAI,IAAKzC,EAAG,QAAQ,qBAAqBuC,IAAQ,EAAE,IAAI,EAA8B,IAAKG,GAAMA,EAAE,IAAI,CAAC,EACpH,OAAW,CAACC,EAAMC,CAAI,IAAKJ,EACzB,GAAI,CAAAC,EAAK,IAAIE,CAAI,EACjB,GAAI,CACF3C,EAAG,KAAK,eAAeuC,gBAAoBI,KAAQC,GAAM,CAC3D,OAASlD,EAAP,CAGA,GAAI,CAAC,yBAAyB,KAAK,OAAOA,GAAG,OAAO,CAAC,EAAG,MAAMA,CAChE,CAEJ,CA9pBA,IA4BMD,EACFI,EACAL,EA2lBEe,EAYAC,EAOOC,EAGAC,EA/oBbmC,EAAAC,EAAA,kBAIAC,IACAC,IAuBMvD,EAAUZ,EAAc,YAAY,GAAG,EA6lBvC0B,EAA0C,CAC9C,CAAC,gBAAiB,MAAM,EACxB,CAAC,iBAAkB,4BAA4B,EAC/C,CAAC,eAAgB,MAAM,EACvB,CAAC,kBAAmB,MAAM,EAC1B,CAAC,gBAAiB,MAAM,CAC1B,EAMMC,EAAiD,CACrD,CAAC,YAAa,SAAS,EACvB,CAAC,mBAAoB,MAAM,CAC7B,EAIaC,EAA0C,CAAC,CAAC,SAAU,MAAM,CAAC,EAG7DC,EAAwC,CAAC,CAAC,WAAY,MAAM,CAAC","names":["ensureQueuedMessagesTable","db","insertQueuedMessage","m","flushQueuedMessages","agentId","channel","chatId","flushedAt","clearQueuedMessages","listQueuedMessages","r","init_queued_messages","__esmMin","ensureForgeCommentsTable","db","insertForgeComment","c","forgeCommentsOn","channel","chatId","from","to","limit","init_forge_comments","__esmMin","createRequire","mkdirSync","dirname","resolve","betterSqlite3Fix","error","msg","abi","hint","loadDatabaseCtor","quiet","_Database","require","e","openDb","opts","_db","path","Database","db","runMigrations","current","steps","txn","step","ensureColumns","RESUME_COLUMNS","LESSON_IMPACT_COLUMNS","PERSON_COLUMNS","COST_COLUMNS","ensureQueuedMessagesTable","ensureForgeCommentsTable","insertTaskQueue","entry","maxConcurrent","now","isActive","position","completeTaskQueue","id","status","next","remaining","upd","i","getTaskQueue","row","listTaskQueueByConversation","conversationId","limit","pruneSqliteTables","retentionDays","cutoffMs","cutoffIso","taskHistory","rotations","routeTraces","taskTraces","table","columns","have","c","name","type","init_sqlite","__esmMin","init_queued_messages","init_forge_comments"]}
|
|
1
|
+
{"version":3,"sources":["../src/storage/queued-messages.ts","../src/storage/forge-comments.ts","../src/storage/sqlite.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\n\n// --- Messages waiting in line behind a busy agent (#443) ---\n//\n// The registry keeps the line itself in memory (agents/message-queue.ts).\n// This table mirrors what is waiting right now, with the person who sent\n// each message, so the member page, which runs in the dashboard and reads\n// the database only, can tell a teammate how many messages are ahead of\n// theirs. A row lives from the moment the message is queued to the moment\n// the line is handed over to a new turn; nothing waits here for long, and\n// the daemon empties the table when it boots, since the line it mirrors\n// did not survive the restart.\n//\n// The preview is the first 200 characters of the message. The member page\n// shows it only to the person who sent it; of anyone else's message it\n// reads the count alone.\n\nexport const QUEUED_PREVIEW_MAX = 200\n\nexport interface QueuedMessageRow {\n id: number\n agentId: string\n channel: string\n chatId: string\n /** The person who sent it (people, #384), when known. */\n person: string | null\n sender: string | null\n messagePreview: string | null\n queuedAt: number\n}\n\nexport function ensureQueuedMessagesTable(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS queued_messages (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n agent_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n person TEXT,\n sender TEXT,\n message_preview TEXT,\n queued_at INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_queued_messages_agent ON queued_messages(agent_id, queued_at);\n `)\n}\n\nexport function insertQueuedMessage(db: Database.Database, m: {\n agentId: string; channel: string; chatId: string\n person?: string | null; sender?: string | null; messagePreview?: string | null; queuedAt: number\n}): void {\n db.prepare(`\n INSERT INTO queued_messages (agent_id, channel, chat_id, person, sender, message_preview, queued_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `).run(\n m.agentId, m.channel, m.chatId, m.person ?? null, m.sender?.slice(0, 120) ?? null,\n m.messagePreview == null ? null : String(m.messagePreview).replace(/\\s+/g, \" \").trim().slice(0, QUEUED_PREVIEW_MAX),\n m.queuedAt,\n )\n}\n\n/** The line of one chat was handed over to a new turn: the messages queued\n * up to `flushedAt` are no longer waiting. One queued again after that\n * moment (the slot was taken meanwhile) has a newer row and stays. */\nexport function flushQueuedMessages(db: Database.Database, agentId: string, channel: string, chatId: string, flushedAt: number): number {\n const r = db.prepare(\n \"DELETE FROM queued_messages WHERE agent_id = ? AND channel = ? AND chat_id = ? AND queued_at <= ?\",\n ).run(agentId, channel, chatId, flushedAt)\n return r.changes ?? 0\n}\n\n/** The daemon starts: the line it kept in memory is gone, so is its mirror. */\nexport function clearQueuedMessages(db: Database.Database): number {\n return db.prepare(\"DELETE FROM queued_messages\").run().changes ?? 0\n}\n\n/** Everything waiting now, oldest first. Small: a line holds a handful of\n * messages, and only while an agent is busy. */\nexport function listQueuedMessages(db: Database.Database): QueuedMessageRow[] {\n const rows = db.prepare(\n \"SELECT id, agent_id, channel, chat_id, person, sender, message_preview, queued_at FROM queued_messages ORDER BY queued_at, id LIMIT 500\",\n ).all() as Array<Record<string, any>>\n return rows.map((r) => ({\n id: r.id, agentId: r.agent_id, channel: r.channel, chatId: r.chat_id,\n person: r.person ?? null, sender: r.sender ?? null, messagePreview: r.message_preview ?? null, queuedAt: r.queued_at,\n }))\n}\n","import type Database from \"better-sqlite3\"\n\n// --- Agent comments on GitHub and GitLab, by id (#1184) ---\n//\n// When the daemon posts an agent's comment on an issue, pull request or\n// merge request, the forge answers with the comment's id. That id is kept\n// here with the chat it went to, so the Wall can link to the exact\n// comment, not only to the issue. Ids and chats only: never the text.\n\nexport const FORGE_COMMENT_CHANNELS = [\"github\", \"gitlab\"] as const\n\nexport interface ForgeCommentRow {\n channel: string\n chatId: string\n commentId: string\n agentId: string | null\n at: number\n}\n\nexport function ensureForgeCommentsTable(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS forge_comments (\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n comment_id TEXT NOT NULL,\n agent_id TEXT,\n at INTEGER NOT NULL,\n PRIMARY KEY (channel, chat_id, comment_id)\n );\n CREATE INDEX IF NOT EXISTS idx_forge_comments_chat ON forge_comments(channel, chat_id, at);\n `)\n}\n\nexport function insertForgeComment(db: Database.Database, c: ForgeCommentRow): void {\n db.prepare(\n \"INSERT OR IGNORE INTO forge_comments (channel, chat_id, comment_id, agent_id, at) VALUES (?, ?, ?, ?, ?)\",\n ).run(c.channel, c.chatId, c.commentId.slice(0, 64), c.agentId?.slice(0, 120) ?? null, c.at)\n}\n\n/** The newest comments on one forge chat in [from, to], newest first. */\nexport function forgeCommentsOn(db: Database.Database, channel: string, chatId: string, from: number, to: number, limit = 5): ForgeCommentRow[] {\n return db.prepare(\n `SELECT channel, chat_id AS chatId, comment_id AS commentId, agent_id AS agentId, at FROM forge_comments\n WHERE channel = ? AND chat_id = ? AND at >= ? AND at <= ? ORDER BY at DESC LIMIT ?`,\n ).all(channel, chatId, from, to, limit) as ForgeCommentRow[]\n}\n","import type Database from \"better-sqlite3\"\nimport { createRequire } from \"module\"\nimport { existsSync, mkdirSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport { ensureQueuedMessagesTable } from \"./queued-messages\"\nimport { ensureForgeCommentsTable } from \"./forge-comments\"\n\n// --- SQLite storage layer ---\n//\n// Move 2 of the architectural review (docs/architecture/hexabot-vs-agentx.md).\n// SQLite for the operational tables — task_history, usage, dedup, sessions —\n// where queryable, indexed access has user-visible value (dashboards,\n// retention, analytics). Workflow definitions, wiki, agent-memory, and\n// references stay as files: they're git-diffable, human-readable, and don't\n// need queries.\n//\n// Approach: subscribe to the event bus (src/events/bus.ts) and write to\n// SQLite from the subscribers. Existing JSON writes are not touched —\n// SQLite runs alongside as a parallel pipeline. Once we have a query API\n// the dashboard depends on, we can deprecate the JSON path. Until then,\n// SQLite is observability-grade only.\n//\n// Synchronous API: better-sqlite3 is sync, no callbacks. The daemon's\n// event loop is the single writer; multiple readers (dashboard) use WAL\n// mode for concurrent read while we write.\n\ntype DatabaseConstructor = typeof Database\n\nconst require = createRequire(import.meta.url)\nlet _db: Database.Database | undefined\nlet _Database: DatabaseConstructor | undefined\n\nfunction betterSqlite3Fix(error: any): string {\n const msg = String(error?.message ?? error)\n const abi = process.versions.modules\n const node = process.version\n const hint = `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${node}, modules ${abi}).`\n if (/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(msg)) {\n return `${msg} ${hint}`\n }\n return `${msg} ${hint}`\n}\n\nfunction loadDatabaseCtor(quiet = false): DatabaseConstructor | null {\n if (_Database) return _Database\n try {\n _Database = require(\"better-sqlite3\") as DatabaseConstructor\n return _Database\n } catch (e: any) {\n if (!quiet) {\n console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\nexport interface OpenOptions {\n /** Resolved relative to cwd. Default: .agentx/db.sqlite */\n path?: string\n /** When true, SQLite writes are skipped (used by tests + opt-out). */\n disabled?: boolean\n /** Suppress the open-failure log. For best-effort callers whose whole\n * contract is \"do nothing if unavailable\" — telemetry, mainly. Without\n * this, a native-binding ABI mismatch prints a paragraph of node-gyp\n * advice on EVERY CLI invocation, which is worse than the thing it\n * is warning about. Load-bearing callers must never pass it. */\n quiet?: boolean\n}\n\n/**\n * Open the per-process SQLite database. Idempotent — repeated calls\n * return the same handle. The file is created on first open; the schema\n * is migrated forward to the latest version.\n *\n * Returns null when disabled — every subscriber should check for null\n * before issuing a write so the daemon stays runnable without SQLite if\n * someone's environment can't compile the native binding.\n */\nexport function openDb(opts: OpenOptions = {}): Database.Database | null {\n if (opts.disabled) return null\n if (_db) return _db\n const path = resolve(process.cwd(), opts.path ?? \".agentx/db.sqlite\")\n const Database = loadDatabaseCtor(opts.quiet)\n if (!Database) return null\n try {\n mkdirSync(dirname(path), { recursive: true })\n const db = new Database(path)\n // WAL keeps readers (dashboard) unblocked while the daemon writes.\n // Synchronous=NORMAL is the SQLite-recommended balance for WAL: the\n // db is durable on power-loss, but a crash within the last few ms can\n // lose the most recent commit. For our use (observability), that's fine.\n db.pragma(\"journal_mode = WAL\")\n db.pragma(\"synchronous = NORMAL\")\n db.pragma(\"foreign_keys = ON\")\n runMigrations(db)\n _db = db\n return _db\n } catch (e: any) {\n // Native binding missing, file unwritable, etc. Surface by default — the\n // alternative was a silent no-op, which makes the \"SQLite not opened\"\n // message in the daemon log impossible to debug. `quiet` callers have\n // explicitly opted out because doing nothing is their correct behavior.\n if (!opts.quiet) {\n console.error(`[storage/sqlite] openDb failed at ${path}: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\n/** Close the global handle. Test-only — production never closes. */\nexport function closeDb(): void {\n if (_db) {\n _db.close()\n _db = undefined\n }\n}\n\n/**\n * Per-version schema steps. New tables / columns go in a new migration —\n * never mutate an old one. Run on every open(); each step is idempotent\n * because it CREATE TABLE IF NOT EXISTS. SQLite has no concurrent\n * migration issue here (single writer process).\n */\nfunction runMigrations(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS schema_version (\n v INTEGER PRIMARY KEY\n );\n `)\n const current = (db\n .prepare(\"SELECT MAX(v) AS v FROM schema_version\")\n .get() as { v: number | null }).v ?? 0\n\n const steps: Array<{ v: number; sql: string }> = [\n {\n v: 1,\n sql: `\n CREATE TABLE task_history (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n status TEXT NOT NULL, -- 'ok' | 'error' | 'timeout'\n message_preview TEXT,\n error TEXT,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n started_at TEXT NOT NULL,\n finished_at TEXT NOT NULL\n );\n CREATE INDEX idx_task_history_agent_started\n ON task_history(agent_id, started_at);\n CREATE INDEX idx_task_history_status\n ON task_history(status, started_at);\n `,\n },\n {\n v: 2,\n sql: `\n CREATE TABLE usage_daily (\n agent_id TEXT NOT NULL,\n model TEXT NOT NULL,\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n input_tokens INTEGER DEFAULT 0,\n output_tokens INTEGER DEFAULT 0,\n cache_read_tokens INTEGER DEFAULT 0,\n cache_create_tokens INTEGER DEFAULT 0,\n tasks INTEGER DEFAULT 0,\n PRIMARY KEY (agent_id, model, day)\n );\n CREATE INDEX idx_usage_day ON usage_daily(day);\n `,\n },\n {\n v: 3,\n sql: `\n CREATE TABLE rotations (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n agent_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n reason TEXT NOT NULL, -- 'stale' | 'tier-2' | 'max-turns'\n last_turn_input_tokens INTEGER,\n rotated_at TEXT NOT NULL\n );\n CREATE INDEX idx_rotations_agent_at\n ON rotations(agent_id, rotated_at);\n `,\n },\n {\n v: 4,\n sql: `\n CREATE TABLE route_traces (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n msg_id TEXT NOT NULL,\n account_id TEXT,\n kind TEXT NOT NULL, -- 'match' | 'drop'\n deciding_stage TEXT,\n agent_id TEXT,\n reason TEXT,\n at TEXT NOT NULL\n );\n CREATE INDEX idx_route_traces_channel_at\n ON route_traces(channel, at);\n `,\n },\n {\n // Move A — tier-2 token buckets on usage_daily. The per-request tier\n // split is decided at record time by TokenTracker (it's a function of\n // the live cumulative input, not the row totals), so we cannot\n // reconstruct it on read. Adding columns is additive and idempotent;\n // existing rows default to 0.\n v: 5,\n sql: `\n ALTER TABLE usage_daily ADD COLUMN tier2_input_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_output_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_read_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_create_tokens INTEGER DEFAULT 0;\n `,\n },\n {\n // task_traces — per-execution observability surface (improvement plan\n // #2). One row per executeTask invocation, keyed by a ULID task_id so\n // it's URL-safe + monotonically sortable. Workflow context columns let\n // pattern queries group runs by workflow (\"agent-managed workflow as\n // the program\" framing); intent_event_id cross-links into the rescue\n // plan's intent ledger so a dispatch decision joins to the execution\n // it produced. Tokens snapshot the final usage at finish time.\n v: 6,\n sql: `\n CREATE TABLE task_traces (\n task_id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n workflow_run_id TEXT,\n workflow_id TEXT,\n workflow_node_id TEXT,\n intent_event_id TEXT,\n intent_decided_by TEXT,\n resume_session_id TEXT,\n final_session_id TEXT,\n model TEXT,\n status TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n finished_at INTEGER,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n error TEXT,\n message_preview TEXT\n );\n CREATE INDEX idx_traces_agent_started ON task_traces(agent_id, started_at);\n CREATE INDEX idx_traces_workflow_run ON task_traces(workflow_run_id);\n CREATE INDEX idx_traces_intent_event ON task_traces(intent_event_id);\n CREATE INDEX idx_traces_status_started ON task_traces(status, started_at);\n `,\n },\n {\n // task_trace_steps — append-only step ledger inside one task. Sequence\n // numbers are 0-based and unique per task_id; ON DELETE CASCADE so\n // pruning task_traces removes children atomically. The (input|output)_\n // summary columns are TEXT — callers cap byte-size at the call site,\n // not in the schema, because the right cap depends on the step kind\n // (a tool_use's args vs a tool_result's stdout have very different\n // typical sizes).\n v: 7,\n sql: `\n CREATE TABLE task_trace_steps (\n task_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n name TEXT NOT NULL,\n action TEXT,\n status TEXT,\n input_summary TEXT,\n output_summary TEXT,\n error TEXT,\n ms INTEGER,\n started_at INTEGER NOT NULL,\n PRIMARY KEY (task_id, seq),\n FOREIGN KEY (task_id) REFERENCES task_traces(task_id) ON DELETE CASCADE\n );\n CREATE INDEX idx_trace_steps_name ON task_trace_steps(name, started_at);\n `,\n },\n {\n // task replay support (handoff item #11). Capture the full original\n // user message AND the agent's final response so 'agentx trace replay\n // <taskId> --diff' can show side-by-side without reconstructing from\n // the step ledger. message_preview stays for cheap listing UX (200\n // chars); original_message holds the untruncated input. final_response\n // mirrors the agent's reply text. Both NULLABLE — old rows have NULL\n // and the replay command falls back to the preview gracefully.\n v: 8,\n sql: `\n ALTER TABLE task_traces ADD COLUMN original_message TEXT;\n ALTER TABLE task_traces ADD COLUMN final_response TEXT;\n `,\n },\n {\n // task_queue — persistent chat-initiated work queue (Phase 2).\n // Each row represents a task an agent queued during a /chat turn.\n // status: 'active' = currently running; 'queued' = waiting;\n // 'done' = completed; 'error' = failed.\n // position is 1-based rank among queued rows (null when active/done/error).\n v: 9,\n sql: `\n CREATE TABLE task_queue (\n id TEXT PRIMARY KEY,\n conversation_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n summary TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'queued',\n position INTEGER,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n finished_at INTEGER\n );\n CREATE INDEX idx_task_queue_status ON task_queue(status, created_at);\n CREATE INDEX idx_task_queue_convo ON task_queue(conversation_id, created_at);\n `,\n },\n {\n // guardrail_decisions — audit trail for the destructive-action guard\n // (PRD R7). One row per PreToolUse guard verdict, written by the\n // short-lived `agentx guard check` hook process. `verdict` is the\n // policy's decision (allow|deny|escalate|warn); `effective_action` is\n // what was actually enforced after the mode downgrade (in warn mode a\n // deny is recorded as verdict=deny, effective_action=allow). task_id is\n // a logical link to task_traces when the guard can resolve it (often\n // null — the hook doesn't always know the AgentX task id). `approver`\n // is reserved for Phase 2 escalation (human who approved/denied).\n v: 10,\n sql: `\n CREATE TABLE guardrail_decisions (\n id TEXT PRIMARY KEY,\n ts INTEGER NOT NULL,\n agent_id TEXT,\n task_id TEXT,\n tool TEXT NOT NULL,\n command TEXT,\n resolved_target TEXT,\n matched_rule TEXT,\n verdict TEXT NOT NULL,\n effective_action TEXT NOT NULL,\n mode TEXT,\n severity TEXT,\n approver TEXT,\n ms INTEGER\n );\n CREATE INDEX idx_guardrail_ts ON guardrail_decisions(ts);\n CREATE INDEX idx_guardrail_verdict ON guardrail_decisions(verdict, ts);\n CREATE INDEX idx_guardrail_agent ON guardrail_decisions(agent_id, ts);\n `,\n },\n {\n // Which operator surfaces actually get used. task_history records agent\n // dispatches and says nothing about which of the ~46 CLI commands or 16\n // dashboard pages anyone opens — the two biggest surfaces by count, and\n // the ones the surface-reduction work needs evidence for.\n //\n // Deliberately NOT folded into usage_daily: that table is keyed by\n // (agent_id, model, day) and is about token cost. Surface counts share\n // none of that shape, and mixing them would corrupt cost reporting.\n //\n // Names only — never arguments, paths, or payloads. This counts which\n // door was opened, not what was carried through it.\n v: 11,\n sql: `\n CREATE TABLE surface_usage (\n kind TEXT NOT NULL, -- 'cli' | 'page'\n name TEXT NOT NULL, -- 'guard log' | '/live'\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n count INTEGER NOT NULL DEFAULT 0,\n last_at TEXT,\n PRIMARY KEY (kind, name, day)\n );\n CREATE INDEX idx_surface_day ON surface_usage(day);\n `,\n },\n {\n // Per-turn token accounting that a with/without comparison can trust.\n // task_traces only carried the tier-1 buckets, and tier-2 turns are\n // where 90%+ of prompt tokens land, so most big turns read as zero.\n // `resumed` is explicit rather than inferred from resume_session_id:\n // NULL means \"not recorded\" (older rows), 0 a fresh session.\n v: 12,\n sql: `\n ALTER TABLE task_traces ADD COLUMN tier2_input_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_output_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_read_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_create_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN resumed INTEGER;\n `,\n },\n {\n // Request-gate experiment arm: 'treatment' (asked Jev), 'holdout'\n // (randomly skipped it), or NULL when the gate was not active. The\n // with/without-Jev comparison groups turns on this column.\n v: 13,\n sql: `\n ALTER TABLE task_traces ADD COLUMN jev_arm TEXT;\n CREATE INDEX idx_task_traces_jev_arm ON task_traces(jev_arm, started_at);\n `,\n },\n ]\n\n const txn = db.transaction((step: { v: number; sql: string }) => {\n db.exec(step.sql)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (?)\").run(step.v)\n })\n\n for (const step of steps) {\n if (step.v > current) txn(step)\n }\n\n // Columns added by name, not by version number. Several branches can each\n // claim the next migration number; a database that already recorded that\n // number from another branch would silently skip ours. Checking the\n // table itself makes these columns appear on every database.\n ensureColumns(db, \"task_traces\", RESUME_COLUMNS)\n ensureColumns(db, \"task_traces\", LESSON_IMPACT_COLUMNS)\n ensureColumns(db, \"task_traces\", PERSON_COLUMNS)\n ensureColumns(db, \"task_history\", PERSON_COLUMNS)\n ensureColumns(db, \"task_traces\", COST_COLUMNS)\n // A person's latest turns, read by the member page every 30 s (#448).\n // Without it that read walks every run on record. Partial: most runs\n // carry no person, and those rows stay out of the index.\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_traces_person_started ON task_traces(person, started_at) WHERE person IS NOT NULL\")\n // Messages waiting behind a busy agent, with who sent them (#443). By\n // name, not by version number, for the same reason as the columns above.\n ensureQueuedMessagesTable(db)\n // Agent comment ids on GitHub and GitLab (#1184), by name too.\n ensureForgeCommentsTable(db)\n}\n\n/** Schema version check for tests. */\nexport function getSchemaVersion(db: Database.Database): number {\n return (db.prepare(\"SELECT MAX(v) AS v FROM schema_version\").get() as { v: number | null }).v ?? 0\n}\n\n// --- task_queue helpers (Phase 2 chat-initiated work queue) ---\n\nexport interface TaskQueueEntry {\n id: string\n conversationId: string\n agentId: string\n summary: string\n status: \"active\" | \"queued\" | \"done\" | \"error\"\n position: number | null\n createdAt: number\n startedAt: number | null\n finishedAt: number | null\n}\n\nexport interface InsertTaskQueueResult {\n id: string\n status: \"active\" | \"queued\"\n position: number | null\n}\n\n/**\n * Insert a new task into the queue. Respects maxConcurrent — if the number\n * of 'active' rows is below the limit the new task is inserted as 'active';\n * otherwise it is 'queued' with a 1-based position.\n */\nexport function insertTaskQueue(\n db: Database.Database,\n entry: { id: string; conversationId: string; agentId: string; summary: string },\n maxConcurrent: number,\n): InsertTaskQueueResult {\n const now = Date.now()\n const activeCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'\")\n .get() as { n: number }).n\n\n const isActive = activeCount < maxConcurrent\n let position: number | null = null\n if (!isActive) {\n const queuedCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'\")\n .get() as { n: number }).n\n position = queuedCount + 1\n }\n\n db.prepare(`\n INSERT INTO task_queue (id, conversation_id, agent_id, summary, status, position, created_at, started_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n entry.id,\n entry.conversationId,\n entry.agentId,\n entry.summary,\n isActive ? \"active\" : \"queued\",\n position,\n now,\n isActive ? now : null,\n )\n\n return { id: entry.id, status: isActive ? \"active\" : \"queued\", position }\n}\n\n/**\n * Mark a task done/error and promote the next queued task (if any) to active.\n */\nexport function completeTaskQueue(\n db: Database.Database,\n id: string,\n status: \"done\" | \"error\" = \"done\",\n): void {\n const now = Date.now()\n db.prepare(`\n UPDATE task_queue SET status = ?, finished_at = ?, position = NULL WHERE id = ?\n `).run(status, now, id)\n\n // Promote oldest queued task to active\n const next = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1\n `).get() as { id: string } | undefined\n if (next) {\n db.prepare(`\n UPDATE task_queue SET status = 'active', position = NULL, started_at = ? WHERE id = ?\n `).run(now, next.id)\n // Resequence remaining queued positions\n const remaining = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC\n `).all() as Array<{ id: string }>\n const upd = db.prepare(\"UPDATE task_queue SET position = ? WHERE id = ?\")\n for (let i = 0; i < remaining.length; i++) {\n upd.run(i + 1, remaining[i].id)\n }\n }\n}\n\n/** Look up a single task_queue row. */\nexport function getTaskQueue(\n db: Database.Database,\n id: string,\n): TaskQueueEntry | null {\n const row = db.prepare(\"SELECT * FROM task_queue WHERE id = ?\").get(id) as Record<string, unknown> | undefined\n if (!row) return null\n return {\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }\n}\n\n/** List task_queue rows for a conversation, newest first. */\nexport function listTaskQueueByConversation(\n db: Database.Database,\n conversationId: string,\n limit = 20,\n): TaskQueueEntry[] {\n const rows = db.prepare(`\n SELECT * FROM task_queue WHERE conversation_id = ?\n ORDER BY created_at DESC LIMIT ?\n `).all(conversationId, limit) as Array<Record<string, unknown>>\n return rows.map((row) => ({\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }))\n}\n\nexport interface PruneResult {\n taskHistory: number\n rotations: number\n routeTraces: number\n taskTraces: number\n forgeComments: number\n}\n\n/**\n * Drop rows older than `retentionDays` from the operational tables that grow\n * unbounded over time. `usage_daily` is bounded by (agent, model, day) and\n * doesn't need pruning; the caller decides whether to keep aggregates beyond\n * the retention window.\n *\n * Mirrors the file-based `pruneTaskHistory` sweep that runs at daemon\n * startup. Cheap — three indexed deletes plus an incremental_vacuum.\n */\nexport function pruneSqliteTables(\n db: Database.Database,\n retentionDays: number,\n): PruneResult {\n const cutoffMs = Date.now() - retentionDays * 24 * 60 * 60 * 1000\n const cutoffIso = new Date(cutoffMs).toISOString()\n\n const taskHistory = (db\n .prepare(`DELETE FROM task_history WHERE started_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const rotations = (db\n .prepare(`DELETE FROM rotations WHERE rotated_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const routeTraces = (db\n .prepare(`DELETE FROM route_traces WHERE at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n // task_traces uses ms-epoch INTEGERs (not ISO strings) on started_at.\n // task_trace_steps cascades automatically via ON DELETE CASCADE.\n const taskTraces = (db\n .prepare(`DELETE FROM task_traces WHERE started_at < ?`)\n .run(cutoffMs).changes ?? 0) as number\n // forge_comments (#1184) also uses ms-epoch INTEGERs on `at`.\n const forgeComments = (db\n .prepare(`DELETE FROM forge_comments WHERE at < ?`)\n .run(cutoffMs).changes ?? 0) as number\n\n // Reclaim the freelist pages so the file shrinks. WAL writes still\n // checkpoint independently.\n if (taskHistory + rotations + routeTraces + taskTraces + forgeComments > 0) {\n try { db.pragma(\"incremental_vacuum\") } catch { /* best-effort */ }\n }\n\n return { taskHistory, rotations, routeTraces, taskTraces, forgeComments }\n}\n\n/** Resume after restart (#103): how to re-enter a run (JSON), its attempt\n * number, the cut-off run it continues, and the boot decision made for it. */\nconst RESUME_COLUMNS: Array<[string, string]> = [\n [\"resume_origin\", \"TEXT\"],\n [\"resume_attempt\", \"INTEGER NOT NULL DEFAULT 0\"],\n [\"resumed_from\", \"TEXT\"],\n [\"resume_decision\", \"TEXT\"],\n [\"resume_reason\", \"TEXT\"],\n]\n\n/** Lesson impact (#98): the memory facts and procedures injected into a turn,\n * as JSON {memory: ids, procedures: ids, wiki: bool}, plus the runtime's turn\n * count. `agentx trace lessons` compares a repeated task before and after\n * each lesson on these columns. */\nconst LESSON_IMPACT_COLUMNS: Array<[string, string]> = [\n [\"num_turns\", \"INTEGER\"],\n [\"injected_context\", \"TEXT\"],\n]\n\n/** People (#384): the id of the known person who started the run. NULL for\n * an unknown sender, for turns software starts, and on older rows. */\nexport const PERSON_COLUMNS: Array<[string, string]> = [[\"person\", \"TEXT\"]]\n\n/** What a run cost in USD, summed per agent per month for the budget (#1162). */\nexport const COST_COLUMNS: Array<[string, string]> = [[\"cost_usd\", \"REAL\"]]\n\n/** Add any of `columns` the table lacks. Idempotent. */\nexport function ensureColumns(db: Database.Database, table: string, columns: Array<[string, string]>): void {\n const have = new Set((db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).map((c) => c.name))\n for (const [name, type] of columns) {\n if (have.has(name)) continue\n try {\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${name} ${type}`)\n } catch (e: any) {\n // Two processes starting on one database: the slower one read the\n // table before the faster one added the column. Already there is fine.\n if (!/duplicate column name/i.test(String(e?.message))) throw e\n }\n }\n}\n"],"mappings":"wCA+BO,SAASA,EAA0BC,EAA6B,CACrEA,EAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAYP,CACH,CAEO,SAASC,EAAoBD,EAAuBE,EAGlD,CACPF,EAAG,QAAQ;AAAA;AAAA;AAAA,GAGV,EAAE,IACDE,EAAE,QAASA,EAAE,QAASA,EAAE,OAAQA,EAAE,QAAU,KAAMA,EAAE,QAAQ,MAAM,EAAG,GAAG,GAAK,KAC7EA,EAAE,gBAAkB,KAAO,KAAO,OAAOA,EAAE,cAAc,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAAE,MAAM,EAAG,GAAkB,EAClHA,EAAE,QACJ,CACF,CAKO,SAASC,EAAoBH,EAAuBI,EAAiBC,EAAiBC,EAAgBC,EAA2B,CAItI,OAHUP,EAAG,QACX,mGACF,EAAE,IAAII,EAASC,EAASC,EAAQC,CAAS,EAChC,SAAW,CACtB,CAGO,SAASC,EAAo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EAAE,SAAW,EAI5B,GAAIE,EAAcC,EAAYC,EAAcC,EAAaC,EAAgB,EACvE,GAAI,CAAEvC,EAAG,OAAO,oBAAoB,CAAE,MAAE,CAA0B,CAGpE,MAAO,CAAE,YAAAmC,EAAa,UAAAC,EAAW,YAAAC,EAAa,WAAAC,EAAY,cAAAC,CAAc,CAC1E,CA6BO,SAASjC,EAAcN,EAAuBwC,EAAeC,EAAwC,CAC1G,IAAMC,EAAO,IAAI,IAAK1C,EAAG,QAAQ,qBAAqBwC,IAAQ,EAAE,IAAI,EAA8B,IAAKG,GAAMA,EAAE,IAAI,CAAC,EACpH,OAAW,CAACC,EAAMC,CAAI,IAAKJ,EACzB,GAAI,CAAAC,EAAK,IAAIE,CAAI,EACjB,GAAI,CACF5C,EAAG,KAAK,eAAewC,gBAAoBI,KAAQC,GAAM,CAC3D,OAASnD,EAAP,CAGA,GAAI,CAAC,yBAAyB,KAAK,OAAOA,GAAG,OAAO,CAAC,EAAG,MAAMA,CAChE,CAEJ,CAnqBA,IA4BMD,EACFI,EACAL,EAgmBEe,EAYAC,EAOOC,EAGAC,EAppBboC,EAAAC,EAAA,kBAIAC,IACAC,IAuBMxD,EAAUZ,EAAc,YAAY,GAAG,EAkmBvC0B,EAA0C,CAC9C,CAAC,gBAAiB,MAAM,EACxB,CAAC,iBAAkB,4BAA4B,EAC/C,CAAC,eAAgB,MAAM,EACvB,CAAC,kBAAmB,MAAM,EAC1B,CAAC,gBAAiB,MAAM,CAC1B,EAMMC,EAAiD,CACrD,CAAC,YAAa,SAAS,EACvB,CAAC,mBAAoB,MAAM,CAC7B,EAIaC,EAA0C,CAAC,CAAC,SAAU,MAAM,CAAC,EAG7DC,EAAwC,CAAC,CAAC,WAAY,MAAM,CAAC","names":["ensureQueuedMessagesTable","db","insertQueuedMessage","m","flushQueuedMessages","agentId","channel","chatId","flushedAt","clearQueuedMessages","listQueuedMessages","r","init_queued_messages","__esmMin","ensureForgeCommentsTable","db","insertForgeComment","c","forgeCommentsOn","channel","chatId","from","to","limit","init_forge_comments","__esmMin","createRequire","mkdirSync","dirname","resolve","betterSqlite3Fix","error","msg","abi","hint","loadDatabaseCtor","quiet","_Database","require","e","openDb","opts","_db","path","Database","db","runMigrations","current","steps","txn","step","ensureColumns","RESUME_COLUMNS","LESSON_IMPACT_COLUMNS","PERSON_COLUMNS","COST_COLUMNS","ensureQueuedMessagesTable","ensureForgeCommentsTable","insertTaskQueue","entry","maxConcurrent","now","isActive","position","completeTaskQueue","id","status","next","remaining","upd","i","getTaskQueue","row","listTaskQueueByConversation","conversationId","limit","pruneSqliteTables","retentionDays","cutoffMs","cutoffIso","taskHistory","rotations","routeTraces","taskTraces","forgeComments","table","columns","have","c","name","type","init_sqlite","__esmMin","init_queued_messages","init_forge_comments"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-TZHVLA3D.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-6QLRRSKU.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
1
|
+
import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-MTQMBPYO.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-6QLRRSKU.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
2
2
|
`,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
|
|
3
3
|
`).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
|
|
4
4
|
`).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
|
|
5
5
|
`),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-XNXKB2VI.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as _,b as F,c as K,d as z,e as J}from"./chunk-6QZKQUAT.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-
|
|
1
|
+
import{a as _,b as F,c as K,d as z,e as J}from"./chunk-6QZKQUAT.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-XNXKB2VI.js";import{a as H}from"./chunk-MWNCS57L.js";import{y as N,z as ot}from"./chunk-MTQMBPYO.js";import{g as Q}from"./chunk-6TURWSMN.js";import{b as E,c as L}from"./chunk-QOYAX2FT.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
|
|
2
2
|
|
|
3
3
|
## Shared wiki (other agents' articles)
|
|
4
4
|
|
|
@@ -51,5 +51,5 @@ ${o}
|
|
|
51
51
|
|
|
52
52
|
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
53
53
|
|
|
54
|
-
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-
|
|
55
|
-
//# sourceMappingURL=chunk-
|
|
54
|
+
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-KELRDI3A.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
|
|
55
|
+
//# sourceMappingURL=chunk-YFNV7LAG.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as S,c as O}from"./chunk-
|
|
1
|
+
import{b as S,c as O}from"./chunk-VYGFBGUM.js";import{h as B,j as J}from"./chunk-3UOTLMXD.js";import{a as I,b as P}from"./chunk-FCPTN6NF.js";import{a as X,b as le}from"./chunk-7I7IEX4S.js";import{d as F}from"./chunk-QIJLFPWE.js";import{execFile as ke}from"child_process";import{writeFileSync as ie,mkdirSync as x,existsSync as b,readFileSync as Ce}from"fs";import{resolve as v}from"path";var ge=["off","shadow","authoritative"],me={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},he="INTENT_LEDGER_MODE";function G(i,e=process.env){let t=U(e[me[i]]);if(t)return t;let n=U(e[he]);return n||"off"}function U(i){if(typeof i!="string")return null;let e=i.trim().toLowerCase();return ge.includes(e)?e:null}P();import fe from"better-sqlite3";import{existsSync as Ge,mkdirSync as pe}from"fs";import{dirname as Ee,resolve as ve}from"path";var T=class{db;path;constructor(e={}){this.path=ve(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),pe(Ee(this.path),{recursive:!0}),this.db=new fe(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Ie(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let n=this.findEventBySourceId(e.source,e.sourceEventId);if(n)return n}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
|
|
2
2
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let n=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
3
3
|
FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return n?Y(n):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
4
4
|
FROM intent_events WHERE id = ?`).get(e);return t?Y(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
|
|
@@ -117,7 +117,7 @@ import{b as S,c as O}from"./chunk-IMNN5RBR.js";import{h as B,j as J}from"./chunk
|
|
|
117
117
|
[Response budget]
|
|
118
118
|
Keep your response under ~${e} tokens (~${t} chars). Be concise \u2014 this is automated batch work, not a conversation.`}function oe(i,e){return i?`${i}
|
|
119
119
|
|
|
120
|
-
${e}`:e}var Me=2*60*60;function ae(i){return Math.max(i??0,Me)}function ce(i,e){let t={};i.runningTaskId&&(t.taskId=i.runningTaskId),i.taskId&&(t.traceId=i.taskId);let n=e.claudeSessionId||e.codexSessionId||e.opencodeSessionId;return n&&(t.sessionId=n),t}function _(i,e,t){let n=[];for(let r of i.split(","))if(r==="*")for(let s=e;s<=t;s++)n.push(s);else if(r.includes("/")){let[s,o]=r.split("/"),a=parseInt(o,10),l=s==="*"?e:parseInt(s,10);for(let c=l;c<=t;c+=a)n.push(c)}else if(r.includes("-")){let[s,o]=r.split("-").map(Number);for(let a=s;a<=o;a++)n.push(a)}else n.push(parseInt(r,10));return[...new Set(n)].sort((r,s)=>r-s)}function de(i,e,t){let n=i.trim().split(/\s+/);if(n.length!==5)throw new Error(`Invalid cron: ${i}`);let r=_(n[0],0,59),s=_(n[1],0,23),o=_(n[2],1,31),a=_(n[3],1,12),l=_(n[4],0,6),c=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),d=new Date(e.getTime()+6e4);d.setSeconds(0,0);let h=new Date(d.getTime()+366*24*60*60*1e3);for(;d<h;){let g=c.formatToParts(d),u=N=>parseInt(g.find(ue=>ue.type===N)?.value||"0",10),m=u("minute"),f=u("hour"),E=u("day"),y=u("month"),p=d.getDay();if(r.includes(m)&&s.includes(f)&&o.includes(E)&&a.includes(y)&&l.includes(p))return d;d.setTime(d.getTime()+6e4)}throw new Error(`No next run found for cron "${i}" within 1 year`)}var A=5,k=[3e4,6e4,3e5,9e5,36e5];function C(i,e){return`${i}/${e.toISOString().replace(/[:.]/g,"-")}`}var D=class{jobs=new Map;fireTokens=new Map;timers=new Map;registry;hooks;runsDir;lastRunFile;running=!1;notifyCallback;deliverCallback;wikiNotes;log;constructor(e,t,n,r=console.error.bind(console,"[cron]")){this.registry=t,this.hooks=n,this.log=r,this.runsDir=v(process.cwd(),".agentx/cron/runs"),this.lastRunFile=v(process.cwd(),".agentx/cron/last-runs.json"),this.wikiNotes=e.wikiNotes;for(let[s,o]of Object.entries(e.crons))this.jobs.set(s,{id:s,enabled:o.enabled&&o.approval?.action!=="create",schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,command:o.command,timeout:o.timeout,model:o.model,maxOutputTokens:o.maxOutputTokens,taskType:o.taskType,autonomy:o.autonomy,onError:o.onError,deliverResult:o.deliverResult!==!1&&!!o.notify,consecutiveErrors:0,totalRuns:0,totalFailures:0}),o.fireToken?.trim()&&this.fireTokens.set(s,o.fireToken.trim())}hasJob(e){return this.jobs.has(e)}getFireToken(e){return this.fireTokens.get(e)}fireNow(e,t={}){let n=this.jobs.get(e);if(!n)return{ok:!1,reason:"unknown"};if(!n.enabled)return{ok:!1,reason:"disabled"};if(!this.running)return{ok:!1,reason:"not-running"};let r=new Date;return L(()=>this.executeJob(e,0,{firedAt:r,payload:t})).catch(s=>{this.log(`Fired job "${e}" threw: ${s?.message??s}`)}),{ok:!0,runId:C(e,r),startedAt:r.toISOString()}}setNotifyCallback(e){this.notifyCallback=e}setDeliverCallback(e){this.deliverCallback=e}async start(){this.running=!0,b(this.runsDir)||x(this.runsDir,{recursive:!0});let e=this.detectMissedRuns();if(e.length>0){this.log(`Detected ${e.length} missed cron run(s) while daemon was down:`);for(let{jobId:t,missedAt:n}of e)this.log(` "${t}" should have run at ${n.toISOString()}`);this.executeMissedRuns(e).catch(t=>{this.log(`Error executing missed runs: ${t.message}`)})}for(let[t,n]of this.jobs){if(!n.enabled){this.log(`Job "${t}" is disabled, skipping`);continue}this.scheduleNext(t)}this.log(`${this.jobs.size} cron job(s) loaded, ${Array.from(this.jobs.values()).filter(t=>t.enabled).length} enabled`)}async stop(){this.running=!1;for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),this.saveLastRuns()}armTimer(e,t,n){let r=t-Date.now();if(r>D.MAX_TIMEOUT_MS){let o=setTimeout(()=>this.armTimer(e,t,n),D.MAX_TIMEOUT_MS);this.timers.set(e,o);return}let s=setTimeout(()=>{if(Date.now()<t){this.armTimer(e,t,n);return}n()},Math.max(0,r));this.timers.set(e,s)}scheduleNext(e){let t=this.jobs.get(e);if(!t||!t.enabled||!this.running)return;let n=this.timers.get(e);n&&clearTimeout(n);try{let r=de(t.schedule,new Date,t.timezone);t.nextRun=r,t.retryPending=!1;let s=r.getTime()-Date.now();this.log(`Job "${e}" next run: ${r.toISOString()} (in ${Math.round(s/1e3)}s)`),this.armTimer(e,r.getTime(),()=>L(()=>this.executeJob(e)))}catch(r){this.log(`Failed to schedule "${e}": ${r.message}`)}}scheduleRetry(e,t){let n=this.jobs.get(e);if(!n||!n.enabled||!this.running)return;if(t>=A){this.log(`Job "${e}" exhausted all ${A} retries, scheduling next regular run`),this.scheduleNext(e);return}let r=k[t]||k[k.length-1];n.retryPending=!0,this.log(`Job "${e}" retry ${t+1}/${A} in ${Math.round(r/1e3)}s`);let s=setTimeout(()=>this.executeJob(e,t+1),r);this.timers.set(e,s)}recordCronDecisionInLedger(e,t,n,r){if(G("cron")!=="off")try{let s=Z(V(),{jobId:e,agentId:t,firedAt:n},JSON.stringify({jobId:e,agentId:t,firedAt:n.toISOString()}),r);return s.outcome==="dispatched"?{eventId:s.eventId,decidedBy:s.decidedBy}:void 0}catch(s){this.log(`[ledger] cron "${e}" record failed: ${s?.message??s}`);return}}async executeCommandJob(e,t,n,r,s){let o=e.command.trim();this.log(`${s?"[fired] ":""}${n?`[retry ${r}] `:""}Running command for "${e.id}"`);let a=!1,l="",c;try{let h=s?{...process.env,[te]:$(s.payload)}:void 0,{stdout:g,stderr:u,code:m}=await Pe(o,e.timeout*1e3,h);l=Xe(`${g}${u?`
|
|
120
|
+
${e}`:e}var Me=2*60*60;function ae(i){return Math.max(i??0,Me)}function ce(i,e){let t={};i.runningTaskId&&(t.taskId=i.runningTaskId),i.taskId&&(t.traceId=i.taskId);let n=e.claudeSessionId||e.codexSessionId||e.opencodeSessionId;return n&&(t.sessionId=n),t}function _(i,e,t){let n=[];for(let r of i.split(","))if(r==="*")for(let s=e;s<=t;s++)n.push(s);else if(r.includes("/")){let[s,o]=r.split("/"),a=parseInt(o,10),l=s==="*"?e:parseInt(s,10);for(let c=l;c<=t;c+=a)n.push(c)}else if(r.includes("-")){let[s,o]=r.split("-").map(Number);for(let a=s;a<=o;a++)n.push(a)}else n.push(parseInt(r,10));return[...new Set(n)].sort((r,s)=>r-s)}function de(i,e,t){let n=i.trim().split(/\s+/);if(n.length!==5)throw new Error(`Invalid cron: ${i}`);let r=_(n[0],0,59),s=_(n[1],0,23),o=_(n[2],1,31),a=_(n[3],1,12),l=_(n[4],0,6),c=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),d=new Date(e.getTime()+6e4);d.setSeconds(0,0);let h=new Date(d.getTime()+366*24*60*60*1e3);for(;d<h;){let g=c.formatToParts(d),u=N=>parseInt(g.find(ue=>ue.type===N)?.value||"0",10),m=u("minute"),f=u("hour"),E=u("day"),y=u("month"),p=d.getDay();if(r.includes(m)&&s.includes(f)&&o.includes(E)&&a.includes(y)&&l.includes(p))return d;d.setTime(d.getTime()+6e4)}throw new Error(`No next run found for cron "${i}" within 1 year`)}var A=5,k=[3e4,6e4,3e5,9e5,36e5];function C(i,e){return`${i}/${e.toISOString().replace(/[:.]/g,"-")}`}var D=class{jobs=new Map;fireTokens=new Map;timers=new Map;registry;hooks;runsDir;lastRunFile;running=!1;notifyCallback;deliverCallback;wikiNotes;log;constructor(e,t,n,r=console.error.bind(console,"[cron]")){this.registry=t,this.hooks=n,this.log=r,this.runsDir=v(process.cwd(),".agentx/cron/runs"),this.lastRunFile=v(process.cwd(),".agentx/cron/last-runs.json"),this.wikiNotes=e.wikiNotes;for(let[s,o]of Object.entries(e.crons))this.jobs.set(s,{id:s,enabled:o.enabled&&o.approval?.action!=="create",schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,command:o.command,timeout:o.timeout,model:o.model,maxOutputTokens:o.maxOutputTokens,taskType:o.taskType,autonomy:o.autonomy,onError:o.onError,value:o.value,deliverResult:o.deliverResult!==!1&&!!o.notify,consecutiveErrors:0,totalRuns:0,totalFailures:0}),o.fireToken?.trim()&&this.fireTokens.set(s,o.fireToken.trim())}hasJob(e){return this.jobs.has(e)}getFireToken(e){return this.fireTokens.get(e)}fireNow(e,t={}){let n=this.jobs.get(e);if(!n)return{ok:!1,reason:"unknown"};if(!n.enabled)return{ok:!1,reason:"disabled"};if(!this.running)return{ok:!1,reason:"not-running"};let r=new Date;return L(()=>this.executeJob(e,0,{firedAt:r,payload:t})).catch(s=>{this.log(`Fired job "${e}" threw: ${s?.message??s}`)}),{ok:!0,runId:C(e,r),startedAt:r.toISOString()}}setNotifyCallback(e){this.notifyCallback=e}setDeliverCallback(e){this.deliverCallback=e}async start(){this.running=!0,b(this.runsDir)||x(this.runsDir,{recursive:!0});let e=this.detectMissedRuns();if(e.length>0){this.log(`Detected ${e.length} missed cron run(s) while daemon was down:`);for(let{jobId:t,missedAt:n}of e)this.log(` "${t}" should have run at ${n.toISOString()}`);this.executeMissedRuns(e).catch(t=>{this.log(`Error executing missed runs: ${t.message}`)})}for(let[t,n]of this.jobs){if(!n.enabled){this.log(`Job "${t}" is disabled, skipping`);continue}this.scheduleNext(t)}this.log(`${this.jobs.size} cron job(s) loaded, ${Array.from(this.jobs.values()).filter(t=>t.enabled).length} enabled`)}async stop(){this.running=!1;for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),this.saveLastRuns()}armTimer(e,t,n){let r=t-Date.now();if(r>D.MAX_TIMEOUT_MS){let o=setTimeout(()=>this.armTimer(e,t,n),D.MAX_TIMEOUT_MS);this.timers.set(e,o);return}let s=setTimeout(()=>{if(Date.now()<t){this.armTimer(e,t,n);return}n()},Math.max(0,r));this.timers.set(e,s)}scheduleNext(e){let t=this.jobs.get(e);if(!t||!t.enabled||!this.running)return;let n=this.timers.get(e);n&&clearTimeout(n);try{let r=de(t.schedule,new Date,t.timezone);t.nextRun=r,t.retryPending=!1;let s=r.getTime()-Date.now();this.log(`Job "${e}" next run: ${r.toISOString()} (in ${Math.round(s/1e3)}s)`),this.armTimer(e,r.getTime(),()=>L(()=>this.executeJob(e)))}catch(r){this.log(`Failed to schedule "${e}": ${r.message}`)}}scheduleRetry(e,t){let n=this.jobs.get(e);if(!n||!n.enabled||!this.running)return;if(t>=A){this.log(`Job "${e}" exhausted all ${A} retries, scheduling next regular run`),this.scheduleNext(e);return}let r=k[t]||k[k.length-1];n.retryPending=!0,this.log(`Job "${e}" retry ${t+1}/${A} in ${Math.round(r/1e3)}s`);let s=setTimeout(()=>this.executeJob(e,t+1),r);this.timers.set(e,s)}recordCronDecisionInLedger(e,t,n,r){if(G("cron")!=="off")try{let s=Z(V(),{jobId:e,agentId:t,firedAt:n},JSON.stringify({jobId:e,agentId:t,firedAt:n.toISOString()}),r);return s.outcome==="dispatched"?{eventId:s.eventId,decidedBy:s.decidedBy}:void 0}catch(s){this.log(`[ledger] cron "${e}" record failed: ${s?.message??s}`);return}}async executeCommandJob(e,t,n,r,s){let o=e.command.trim();this.log(`${s?"[fired] ":""}${n?`[retry ${r}] `:""}Running command for "${e.id}"`);let a=!1,l="",c;try{let h=s?{...process.env,[te]:$(s.payload)}:void 0,{stdout:g,stderr:u,code:m}=await Pe(o,e.timeout*1e3,h);l=Xe(`${g}${u?`
|
|
121
121
|
${u}`:""}`,Fe),a=m===0,a||(c=`exit ${m}${l?`
|
|
122
122
|
${l}`:""}`)}catch(h){c=h?.message??String(h)}let d={jobId:e.id,startedAt:t,completedAt:new Date,success:a,response:l||void 0,error:c,duration:Date.now()-t.getTime(),isRetry:n,retryAttempt:r,...s?{fired:!0}:{}};if(!a){if(e.consecutiveErrors++,e.totalFailures++,e.lastError=c,this.log(`Command job "${e.id}" failed (${e.consecutiveErrors} consecutive): ${c}`),await this.notifyFailure(e,c??"command failed"),e.onError.includes("disable")&&e.consecutiveErrors>=3){e.enabled=!1,this.log(`Job "${e.id}" disabled after ${e.consecutiveErrors} consecutive errors`);try{await S(h=>O(h,`crons.${e.id}.enabled`,!1),{reload:!1})}catch(h){this.log(`Failed to persist disable for "${e.id}": ${h.message}`)}await this.notifyDisabled(e)}this.logRun(d),s||this.scheduleRetry(e.id,r);return}e.consecutiveErrors>0&&this.log(`Job "${e.id}" recovered after ${e.consecutiveErrors} failure(s)`),e.consecutiveErrors=0,e.lastSuccess=new Date,e.lastError=void 0,e.retryPending=!1,this.log(`Command job "${e.id}" completed in ${d.duration}ms`),this.logRun(d),await this.deliverResult(e,l,t),s||this.scheduleNext(e.id)}async executeJob(e,t=0,n){let r=this.jobs.get(e);if(!r||!this.running)return;let s=t>0,o=n?.firedAt??new Date;if(this.hooks?.has("pre:cron-run")){let d=await this.hooks.execute("pre:cron-run",{event:"pre:cron-run",jobId:e,agent:r.agent,prompt:r.prompt});if(d.blocked){this.log(`Job "${e}" blocked by hook: ${d.message}`),this.recordCronDecisionInLedger(e,r.agent,o,{agentId:null,outcome:"halted",reason:`pre-hook blocked: ${d.message??""}`.trim()}),n||this.scheduleNext(e);return}}this.log((n?"[fired] ":"")+(r.command?.trim()?`${s?`[retry ${t}] `:""}Executing job "${e}" -> command`:`${s?`[retry ${t}] `:""}Executing job "${e}" -> agent "${r.agent}"`));let a=o;if(r.lastRun=a,r.totalRuns++,r.command?.trim()){await this.executeCommandJob(r,a,s,t,n);return}let l=this.recordCronDecisionInLedger(e,r.agent,o,{agentId:r.agent,outcome:"dispatched",reason:n?"fired on demand":s?`retry ${t}`:null}),c=ae(r.timeout);try{let d=this.wikiNotesInbox(r,a),h={message:se(oe(d.block,n?ne(r.prompt,n.payload):r.prompt),r.maxOutputTokens),agentId:r.agent,model:r.model,autonomy:r.autonomy,timeoutMinutes:c/60,intentRef:l,context:re(e,r)},g=await this.registry.execute(h),u={jobId:e,startedAt:a,completedAt:new Date,success:!g.error,response:g.content,error:g.error,duration:g.duration||Date.now()-a.getTime(),isRetry:s,retryAttempt:t,timeout:c,...n?{fired:!0}:{},...d.ids.length?{wikiNotes:d.ids}:{},...ce(h,g),...g.autonomy?{autonomy:g.autonomy}:{},...g.autonomyBlocks?.length?{autonomyBlocks:g.autonomyBlocks}:{}};if(u.autonomyBlocks&&this.log(`Job "${e}" (autonomy ${u.autonomy}): ${u.autonomyBlocks.length} action(s) blocked: ${u.autonomyBlocks.map(m=>m.ruleId).join(", ")}`),g.error){if(r.consecutiveErrors++,r.totalFailures++,r.lastError=g.error,this.log(`Job "${e}" failed (${r.consecutiveErrors} consecutive): ${g.error}`),await this.notifyFailure(r,g.error),r.onError.includes("disable")&&r.consecutiveErrors>=3){r.enabled=!1,this.log(`Job "${e}" disabled after ${r.consecutiveErrors} consecutive errors`);try{let m=await S(f=>O(f,`crons.${e}.enabled`,!1),{reload:!1});m.success||this.log(`Failed to persist disable for "${e}": ${m.error}`)}catch(m){this.log(`Failed to persist disable for "${e}": ${m.message}`)}await this.notifyDisabled(r)}this.logRun(u),n||this.scheduleRetry(e,t);return}else r.consecutiveErrors>0&&this.log(`Job "${e}" recovered after ${r.consecutiveErrors} failure(s)`),r.consecutiveErrors=0,r.lastSuccess=new Date,r.lastError=void 0,r.retryPending=!1,this.log(`Job "${e}" completed in ${u.duration}ms`);this.logRun(u),await this.deliverResult(r,g.content,a),this.hooks?.has("post:cron-run")&&await this.hooks.execute("post:cron-run",{event:"post:cron-run",jobId:e,success:u.success,duration:u.duration,error:u.error?new Error(u.error):void 0})}catch(d){r.consecutiveErrors++,r.totalFailures++,r.lastError=d.message,this.log(`Job "${e}" threw: ${d.message}`),await this.notifyFailure(r,d.message),n||this.scheduleRetry(e,t);return}this.saveLastRuns(),n||this.scheduleNext(e)}detectMissedRuns(){let e=[],t=this.loadLastRuns();if(!t)return e;for(let[n,r]of this.jobs){if(!r.enabled)continue;let s=t[n];if(!s)continue;let o=new Date(s);try{let a=de(r.schedule,o,r.timezone);a.getTime()<Date.now()&&e.push({jobId:n,missedAt:a})}catch{}}return e}async executeMissedRuns(e){for(let{jobId:t,missedAt:n}of e){let r=this.jobs.get(t);if(!r||!r.enabled)continue;this.log(`Running missed job "${t}" (was due at ${n.toISOString()})`);let s=ae(r.timeout),o=new Date;try{let a=this.wikiNotesInbox(r,o),l={message:se(`[MISSED RUN \u2014 was scheduled for ${n.toISOString()}]
|
|
123
123
|
|
|
@@ -125,4 +125,4 @@ ${oe(a.block,r.prompt)}`,r.maxOutputTokens),agentId:r.agent,autonomy:r.autonomy,
|
|
|
125
125
|
`);return t.length<=e?t.join(`
|
|
126
126
|
`):t.slice(-e).join(`
|
|
127
127
|
`)}function Pe(i,e,t){return new Promise((n,r)=>{ke("/bin/sh",["-c",i],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(s,o,a)=>{if(s&&s.killed){r(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}n({stdout:String(o??""),stderr:String(a??""),code:s?typeof s.code=="number"?s.code:1:0})})})}export{T as a,V as b,at as c,Le as d,ct as e,dt as f,L as g,ee as h,G as i,ze as j,z as k,Q as l,gt as m,Me as n,ae as o,ce as p,de as q,C as r,M as s};
|
|
128
|
-
//# sourceMappingURL=chunk-
|
|
128
|
+
//# sourceMappingURL=chunk-YG34COEO.js.map
|