agentix-cli 0.97.0 → 0.99.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/apps/mac-voice/Sources/AgentXVoice/Character.swift +41 -63
- package/apps/mac-voice/Sources/AgentXVoice/CharacterMath.swift +9 -0
- package/apps/mac-voice/Sources/AgentXVoice/CharacterSim.swift +46 -44
- package/apps/mac-voice/Sources/AgentXVoice/CharacterSimFrame.swift +59 -0
- package/apps/mac-voice/Sources/AgentXVoice/CharacterView.swift +57 -0
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +2 -1
- package/apps/mac-voice/Sources/AgentXVoice/Guide.swift +185 -0
- package/apps/mac-voice/Sources/AgentXVoice/GuideMath.swift +49 -0
- package/apps/mac-voice/Sources/AgentXVoice/Meets.swift +39 -0
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +9 -0
- package/apps/mac-voice/Sources/AgentXVoice/PlayActs.swift +35 -8
- package/apps/mac-voice/Sources/AgentXVoice/PlayMath.swift +17 -9
- package/apps/mac-voice/Sources/AgentXVoice/PlayMotion.swift +110 -0
- package/apps/mac-voice/Sources/AgentXVoice/PlayStage.swift +43 -5
- package/apps/mac-voice/Sources/AgentXVoice/PointerPlay.swift +137 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +7 -0
- package/dist/{App-6R4I6QPE.js → App-XLQDP26J.js} +2 -2
- package/dist/{ChatApp-R3O4BJ24.js → ChatApp-DRDUXZ66.js} +2 -2
- package/dist/{agent-P6GPE7HD.js → agent-QHM3J2XS.js} +2 -2
- package/dist/{board-dashboard-AKQHIY4J.js → board-dashboard-F7ZNW6YA.js} +9 -9
- package/dist/board-dashboard-F7ZNW6YA.js.map +1 -0
- package/dist/{chunk-QPIMPKZ2.js → chunk-4BCAH7XI.js} +2 -2
- package/dist/{chunk-3S4IYAOC.js → chunk-B32A6OOY.js} +2 -2
- package/dist/{chunk-QHAO6U7U.js → chunk-BERHVF3T.js} +2 -2
- package/dist/{chunk-TWC4CYTU.js → chunk-BHKWXFJD.js} +5 -5
- package/dist/{chunk-Q53XKCRL.js → chunk-BTLW2RML.js} +2 -2
- package/dist/{chunk-55HM3SUN.js → chunk-DRUEPGLP.js} +2 -2
- package/dist/{chunk-SZ5TGL25.js → chunk-DXJRMPGH.js} +2 -2
- package/dist/{chunk-ZCQCUA4J.js → chunk-GJ5EJVMZ.js} +2 -2
- package/dist/{chunk-2GFSHO24.js → chunk-IQJ7UZVV.js} +2 -2
- package/dist/{chunk-6W3SCPDK.js → chunk-J4JVKVEK.js} +2 -2
- package/dist/{chunk-MDFUSQ6S.js → chunk-J64VIHL5.js} +2 -2
- package/dist/{chunk-ERPEU2ZR.js → chunk-JREA25GJ.js} +3 -3
- package/dist/chunk-JREA25GJ.js.map +1 -0
- package/dist/{chunk-WLKO6FOL.js → chunk-JZJ7AZJD.js} +2 -2
- package/dist/{chunk-4BG3WJSP.js → chunk-LXJGLNVG.js} +2 -2
- package/dist/{chunk-LXHTVVJV.js → chunk-OFVMUBIP.js} +2 -2
- package/dist/{chunk-TOGRRWBX.js → chunk-QUU5RJ7D.js} +2 -2
- package/dist/{chunk-F3DW5ZJN.js → chunk-S2GPUSBU.js} +2 -2
- package/dist/{chunk-C2POHIWJ.js → chunk-SJMOZY7Y.js} +2 -2
- package/dist/{chunk-3SF7PLHF.js → chunk-WEYMSJGZ.js} +191 -190
- package/dist/chunk-WEYMSJGZ.js.map +1 -0
- package/dist/{chunk-X4S2I233.js → chunk-YYCFI4VP.js} +2 -2
- package/dist/{chunk-DGVTRG5Q.js → chunk-Z4FY64BS.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-UQKCIEHA.js → client-BLUCLNIS.js} +2 -2
- package/dist/{config-OE23UC5C.js → config-ZUMI4IY4.js} +2 -2
- package/dist/config-mutator-S3CD2IWQ.js +2 -0
- package/dist/{doctor-QQ7YLJK4.js → doctor-XGQW5SMD.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{program-O5RQ6NRG.js → program-3FNVZD26.js} +161 -161
- package/dist/program-3FNVZD26.js.map +1 -0
- package/dist/{promote-AW4TJXXT.js → promote-K5LP5Q6Z.js} +2 -2
- package/dist/{query-24BGIJCZ.js → query-LHXSINM2.js} +2 -2
- package/dist/{registry-GZT2OSBK.js → registry-OQUO6NCW.js} +2 -2
- package/dist/{request-planner-U6HHKWLX.js → request-planner-TW5OCKTF.js} +2 -2
- package/dist/{review-candidates-LJUJCVFA.js → review-candidates-EFELFOSY.js} +2 -2
- package/dist/{routing-WCYPBKFH.js → routing-TSRZLD7B.js} +2 -2
- package/dist/schedule-tool-JUHRVU5D.js +2 -0
- package/dist/scheduler-EHJPTULN.js +2 -0
- package/dist/{seat-5PBTFTGS.js → seat-NIPWHLKC.js} +2 -2
- package/dist/{select-JD7MSY25.js → select-UAKDLN76.js} +2 -2
- package/dist/{set-enabled-MUSO2KJL.js → set-enabled-74DLXMSM.js} +2 -2
- package/dist/{tool-Y7SOGJ2S.js → tool-CEBL57UW.js} +2 -2
- package/dist/{tool-FMKGK474.js → tool-TEGHFORD.js} +2 -2
- package/dist/wiki-WOK4SCB7.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-AKQHIY4J.js.map +0 -1
- package/dist/chunk-3SF7PLHF.js.map +0 -1
- package/dist/chunk-ERPEU2ZR.js.map +0 -1
- package/dist/config-mutator-2UK5GX4B.js +0 -2
- package/dist/program-O5RQ6NRG.js.map +0 -1
- package/dist/schedule-tool-E7ER2XOI.js +0 -2
- package/dist/scheduler-FK3LOWU2.js +0 -2
- package/dist/wiki-SJRTAYMT.js +0 -2
- /package/dist/{App-6R4I6QPE.js.map → App-XLQDP26J.js.map} +0 -0
- /package/dist/{ChatApp-R3O4BJ24.js.map → ChatApp-DRDUXZ66.js.map} +0 -0
- /package/dist/{agent-P6GPE7HD.js.map → agent-QHM3J2XS.js.map} +0 -0
- /package/dist/{chunk-QPIMPKZ2.js.map → chunk-4BCAH7XI.js.map} +0 -0
- /package/dist/{chunk-3S4IYAOC.js.map → chunk-B32A6OOY.js.map} +0 -0
- /package/dist/{chunk-QHAO6U7U.js.map → chunk-BERHVF3T.js.map} +0 -0
- /package/dist/{chunk-TWC4CYTU.js.map → chunk-BHKWXFJD.js.map} +0 -0
- /package/dist/{chunk-Q53XKCRL.js.map → chunk-BTLW2RML.js.map} +0 -0
- /package/dist/{chunk-55HM3SUN.js.map → chunk-DRUEPGLP.js.map} +0 -0
- /package/dist/{chunk-SZ5TGL25.js.map → chunk-DXJRMPGH.js.map} +0 -0
- /package/dist/{chunk-ZCQCUA4J.js.map → chunk-GJ5EJVMZ.js.map} +0 -0
- /package/dist/{chunk-2GFSHO24.js.map → chunk-IQJ7UZVV.js.map} +0 -0
- /package/dist/{chunk-6W3SCPDK.js.map → chunk-J4JVKVEK.js.map} +0 -0
- /package/dist/{chunk-MDFUSQ6S.js.map → chunk-J64VIHL5.js.map} +0 -0
- /package/dist/{chunk-WLKO6FOL.js.map → chunk-JZJ7AZJD.js.map} +0 -0
- /package/dist/{chunk-4BG3WJSP.js.map → chunk-LXJGLNVG.js.map} +0 -0
- /package/dist/{chunk-LXHTVVJV.js.map → chunk-OFVMUBIP.js.map} +0 -0
- /package/dist/{chunk-TOGRRWBX.js.map → chunk-QUU5RJ7D.js.map} +0 -0
- /package/dist/{chunk-F3DW5ZJN.js.map → chunk-S2GPUSBU.js.map} +0 -0
- /package/dist/{chunk-C2POHIWJ.js.map → chunk-SJMOZY7Y.js.map} +0 -0
- /package/dist/{chunk-X4S2I233.js.map → chunk-YYCFI4VP.js.map} +0 -0
- /package/dist/{chunk-DGVTRG5Q.js.map → chunk-Z4FY64BS.js.map} +0 -0
- /package/dist/{client-UQKCIEHA.js.map → client-BLUCLNIS.js.map} +0 -0
- /package/dist/{config-OE23UC5C.js.map → config-ZUMI4IY4.js.map} +0 -0
- /package/dist/{config-mutator-2UK5GX4B.js.map → config-mutator-S3CD2IWQ.js.map} +0 -0
- /package/dist/{doctor-QQ7YLJK4.js.map → doctor-XGQW5SMD.js.map} +0 -0
- /package/dist/{promote-AW4TJXXT.js.map → promote-K5LP5Q6Z.js.map} +0 -0
- /package/dist/{query-24BGIJCZ.js.map → query-LHXSINM2.js.map} +0 -0
- /package/dist/{registry-GZT2OSBK.js.map → registry-OQUO6NCW.js.map} +0 -0
- /package/dist/{request-planner-U6HHKWLX.js.map → request-planner-TW5OCKTF.js.map} +0 -0
- /package/dist/{review-candidates-LJUJCVFA.js.map → review-candidates-EFELFOSY.js.map} +0 -0
- /package/dist/{routing-WCYPBKFH.js.map → routing-TSRZLD7B.js.map} +0 -0
- /package/dist/{schedule-tool-E7ER2XOI.js.map → schedule-tool-JUHRVU5D.js.map} +0 -0
- /package/dist/{scheduler-FK3LOWU2.js.map → scheduler-EHJPTULN.js.map} +0 -0
- /package/dist/{seat-5PBTFTGS.js.map → seat-NIPWHLKC.js.map} +0 -0
- /package/dist/{select-JD7MSY25.js.map → select-UAKDLN76.js.map} +0 -0
- /package/dist/{set-enabled-MUSO2KJL.js.map → set-enabled-74DLXMSM.js.map} +0 -0
- /package/dist/{tool-Y7SOGJ2S.js.map → tool-CEBL57UW.js.map} +0 -0
- /package/dist/{tool-FMKGK474.js.map → tool-TEGHFORD.js.map} +0 -0
- /package/dist/{wiki-SJRTAYMT.js.map → wiki-WOK4SCB7.js.map} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as O,b as $,c as U,d as T,e as j}from"./chunk-WPNRDEHW.js";import{t as R,v as E,w as W}from"./chunk-SZ5TGL25.js";import{a as z,b as C,f as V}from"./chunk-72SZI2UW.js";import{a as B,b as re}from"./chunk-FX3D7YON.js";import{o as J,p as te}from"./chunk-5MUJZODV.js";V();var we="wiki-rerank",be=30,se=900;function xe(a){let e=a.excerptChars??se;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ne(t.excerpt,e)}))}}function Se(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:z("Do any of the candidates answer the query?")}}function Ne(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 ne(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)."}},G=[{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 M,appendFileSync as ie,existsSync as S,mkdirSync as F,renameSync as oe,statSync as Q}from"fs";import{resolve as A,dirname as X}from"path";import{createHash as ae}from"crypto";var _=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]"),F(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=O.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{M(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{M(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=O.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);Y(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=T.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=T.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),Y(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 g=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){g=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=g;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,g=p+1;break}}if(!d&&g<r.levels.length&&(d=r.levels[g].id,g++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${g}, 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 u={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(u),o.push(u)}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=$.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 O,b as $,c as U,d as T,e as j}from"./chunk-WPNRDEHW.js";import{t as R,v as E,w as W}from"./chunk-DXJRMPGH.js";import{a as z,b as C,f as V}from"./chunk-72SZI2UW.js";import{a as B,b as re}from"./chunk-FX3D7YON.js";import{o as J,p as te}from"./chunk-5MUJZODV.js";V();var we="wiki-rerank",be=30,se=900;function xe(a){let e=a.excerptChars??se;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ne(t.excerpt,e)}))}}function Se(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:z("Do any of the candidates answer the query?")}}function Ne(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 ne(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)."}},G=[{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 M,appendFileSync as ie,existsSync as S,mkdirSync as F,renameSync as oe,statSync as Q}from"fs";import{resolve as A,dirname as X}from"path";import{createHash as ae}from"crypto";var _=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]"),F(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=O.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{M(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{M(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=O.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);Y(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=T.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=T.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),Y(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 g=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){g=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=g;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,g=p+1;break}}if(!d&&g<r.levels.length&&(d=r.levels[g].id,g++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${g}, 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 u={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(u),o.push(u)}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=$.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)||F(X(n),{recursive:!0}),ie(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=$.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=$.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[ce(e.text),e.channel??""].join("");return ae("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=j.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=j.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=U.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 Y(a,e){F(X(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;M(t,JSON.stringify(e,null,2)),oe(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of G)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of G)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 ce(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)}re();te();W();import{createHash as me}from"crypto";V();W();var P="intent-path",de=.5,le=.3;function pe(a){return{message:fe(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function Z(a,e){let t={};for(let r of a)t[r.id]=he(r);return C(t,e)}function ge(a){return{category:Z(a,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function ue(a){return{verb:Z(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 D(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=pe(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await E(P,n,ge(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>=de,b=[c.choice],g=e.filter(m=>m.parentId===c.choice);if(g.length>=2){let m=t.incumbent?.[0]===c.choice,d=await E(P,{...n,category:c.choice},ue(g),{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;l=Math.min(l,f.pMax),h=h&&f.pMax>=le,b.push(f.choice)}else g.length===1&&b.push(g[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function he(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 fe(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=J(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:q(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)},g=new Set(o.map(u=>u.id)),m=s.map((u,p)=>g.has(u)?-1:p).filter(u=>u>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let u=m.length===0,p=m.length===1&&m[0]===s.length-1;d=u||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(u){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(u?.message||u).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:q(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 D(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&&D(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=B(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=ee(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)??ee(d);if(!v)continue;let u={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(u[p]=y);!u.name&&d!==v&&(u.name=d.trim()),b[v]=u}let g={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(g.input=s.leaf.input),typeof s.leaf.output=="string"&&(g.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:g}}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 ee(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 me("sha1").update(a.join("")).digest("hex").slice(0,16)}function q(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 ve(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{we as a,be as b,xe as c,Se as d,Ne as e,x as f,_ as g,L as h,q as i,ve as j};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-4BCAH7XI.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as $e}from"./chunk-GTJIKXDB.js";import{a as te,b as w}from"./chunk-DG5I6PPM.js";import{q as Ht}from"./chunk-S2GAEH2F.js";import{t as Bt,u as Ut}from"./chunk-
|
|
1
|
+
import{a as $e}from"./chunk-GTJIKXDB.js";import{a as te,b as w}from"./chunk-DG5I6PPM.js";import{q as Ht}from"./chunk-S2GAEH2F.js";import{t as Bt,u as Ut}from"./chunk-YYCFI4VP.js";import{d as Wt,e as Ft}from"./chunk-AQASR6KR.js";import{b as zt,c as ve,e as B,f as U,h as qt}from"./chunk-E5OV6RTG.js";import{A as Se,b as xe,v as Ct,x as ee,y as ke}from"./chunk-BERHVF3T.js";import{a as Nt,b as jt,d as Vt}from"./chunk-Y4CYQV7G.js";import{a as Dt,b as Et}from"./chunk-SHEUCITK.js";import{g as Tt,h as Pt,i as Lt,k as Mt,l as Ot}from"./chunk-LXJGLNVG.js";import{q as _t}from"./chunk-J4JVKVEK.js";import{a as At,b as It}from"./chunk-DRUEPGLP.js";import{Y as we,da as vt,ea as $t,ha as Rt,n as Q,o as bt,p as wt,q as Vr,v as kt,w as St,x as Br}from"./chunk-JREA25GJ.js";import{a as xt,i as Fr}from"./chunk-RJ7DASOU.js";import{a as be,h as Wr}from"./chunk-BRK6M6LA.js";import{existsSync as Ur,readdirSync as Hr,readFileSync as zr,statSync as qr}from"fs";import{resolve as Kr}from"path";function Kt(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],c=a.filter(g=>n-g.at<=r),l=a.filter(g=>n-g.at>r&&n-g.at<=r*2),u=c.filter(g=>g.status==="failed").length,d=a.filter(g=>g.status==="paused").length,p=a.length?Math.max(...a.map(g=>g.at)):null,f=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:f,lastRunAt:p,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var ne=new Map;function pa(t,e=1e3){if(!Ur(t))return[];let n=Hr(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=Kr(t,s);return{path:o,mtime:qr(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of ne.keys())i.has(s)||ne.delete(s);let r=[];for(let{path:s,mtime:o}of n){let a=ne.get(s);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let c=Gr(s,o);ne.set(s,{mtime:o,summary:c}),c&&r.push(c)}return r}function Gr(t,e){try{let n=zr(t,"utf-8").split(`
|
|
2
2
|
`).filter(Boolean);if(!n.length)return null;let i=JSON.parse(n[0]),r=i.run?.workflowId;if(!r)return null;let s=i.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),c=a.status??a.run?.status;if(c){s=c;break}}return{workflowId:r,status:s,at:e}}catch{return null}}var Xr={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},x={routines:200,summary:160,filters:6,filterValue:60,text:120},Jr=(t,e,n)=>{try{return _t(t,e,n)}catch{return null}},Gt=864e5;function ha(t){let e=t.now??Date.now(),n={...Xr,...t.thresholds},i=t.nextFire??Jr,r=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",u=c.map(f=>({at:Date.parse(f.startedAt),status:f.status})),d=c[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,x.text),trigger:{schedule:$(a.schedule,x.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?Re(a.nextRun)??Re(i(a.schedule,new Date(e),l)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:ni(d.status==="success"?void 0:d.errorSummary,x.summary)}:null,lastSuccessAt:c.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:Xt(u),sampledRuns:c.length,flags:[],attention:null};p.flags=Jt(p,u,a.schedule,l,null,e,n,i),r.push(Yt(p))}let s=new Map(Kt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let c=o.get(a.workflowId);c?c.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(I=>I.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},u=a.state||"active",d=u==="active",p=(o.get(a.id)??[]).slice().sort((I,ye)=>ye.at-I.at),f=p.map(I=>({at:I.at,status:Qr(I.status)})),g=f[0],h=c.type==="trigger.cron",y=typeof l.spec=="string"?l.spec:"",D=typeof l.timezone=="string"?l.timezone:"UTC",N={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,x.text),trigger:h?{schedule:$(y,x.text),timezone:D}:{event:$(typeof l.event=="string"?l.event:"",x.text),filters:ti(l.filter,a)},agent:ei(a),enabled:d,state:u,nextRunAt:h&&d&&y?Re(i(y,new Date(e),D)):null,lastRun:g?{at:new Date(g.at).toISOString(),status:g.status}:null,lastSuccessAt:(()=>{let I=f.find(ye=>ye.status==="success");return I?new Date(I.at).toISOString():null})(),consecutiveFailures:Xt(f),sampledRuns:p.length,flags:[],attention:null},Z=Date.parse(a.updated||a.created||"");N.flags=h?Jt(N,f,y,D,Number.isFinite(Z)?Z:null,e,n,i):Yr(N,s.get(a.id)?.state==="dormant",Number.isFinite(Z)?Z:null,e,n),r.push(Yt(N))}return r.sort(Zr).slice(0,x.routines)}function Xt(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function Jt(t,e,n,i,r,s,o,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let p=Qt(l,r,s,o);return p&&c.push(p),c}if(t.consecutiveFailures>=o.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let u=new Date(l),d=null;for(let p=0;p<o.missedFires&&(d=a(n,u,i),!!d);p++)u=d;return d&&s>d.getTime()+o.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${o.missedFires} scheduled fires missed`}),c}function Yr(t,e,n,i,r){let s=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Qt(o,n,i,r);return a&&s.push(a),s}return t.consecutiveFailures>=r.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function Qt(t,e,n,i){let r=Math.max(t??0,e??0);return r&&n-r<i.disabledDays*Gt?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/Gt)} days`:"Disabled and never ran"}}function Yt(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var Zt={critical:0,warning:1,info:2};function Zr(t,e){let n=t.attention?Zt[t.attention]:3,i=e.attention?Zt[e.attention]:3;return n-i||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Qr(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function ei(t){if(t.ownerAgent)return $(t.ownerAgent,x.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),x.text):null}function ti(t,e){let n=[],i=e?.project;if(i&&n.push($(`project=${i}`,x.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,s]of Object.entries(t)){let o=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];o.length&&n.push($(`${r}=${o.join(",")}`,x.filterValue))}return n.slice(0,x.filters)}function Re(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function ni(t,e){return t===void 0?void 0:$(t,e)}import{existsSync as se,readdirSync as xi,readFileSync as ki}from"fs";import{resolve as E}from"path";import{randomBytes as nn}from"crypto";import{existsSync as ii,mkdirSync as si,readdirSync as oi,readFileSync as ai,renameSync as rn,unlinkSync as ci,writeFileSync as li}from"fs";import{resolve as sn}from"path";function en(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var ri=t=>t.trim().split(`
|
|
3
3
|
`).pop()?.slice(0,300)||"no output";async function tn(t,e,n,i=$e){let r=await i(t.bin,[...en(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return r.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${ri(r.stderr||r.stdout)}`}}async function wa(t,e,n,i,r=$e){return(await r(t.bin,[...en(t),"--read-only","media","download","--chat",e,"--id",n,"--output",i],{timeoutMs:12e4})).code===0}var ui=2e3,di=t=>tn(t.wacli,t.to,t.text);function Ae(t){return sn(t,".agentx","whatsapp-triage","drafts")}var pi=t=>/^[a-z0-9-]{8,64}$/.test(t),re=(t,e)=>sn(Ae(t),`${e}.json`);function on(t,e){si(Ae(t),{recursive:!0});let n=re(t,e.id),i=`${n}.${process.pid}.tmp`;li(i,JSON.stringify(e,null,2)+`
|
|
4
4
|
`,{mode:384}),rn(i,n)}function Ra(t,e,n=Date.now()){let i=e.text.trim().slice(0,ui);if(!i)throw new Error("empty draft");let r={...e,text:i,id:`${n.toString(36)}-${nn(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return on(t,r),r}function ie(t,e){if(!pi(e))return null;try{return JSON.parse(ai(re(t,e),"utf-8"))}catch{return null}}function an(t,e){let n=Ae(t);return ii(n)?oi(n).filter(i=>i.endsWith(".json")).map(i=>ie(t,i.slice(0,-5))).filter(i=>!!i&&(!e||i.status===e)).sort((i,r)=>i.created_at.localeCompare(r.created_at)):[]}async function cn(t,e,n,i={}){let r=ie(t,e);if(!r||r.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${re(t,e)}.${process.pid}.${nn(3).toString("hex")}.claim`;try{rn(re(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let o={...r,decided_by:i.by??"operator",decided_at:new Date(i.now??Date.now()).toISOString()};if(n==="no")o.status="rejected";else{let a=await(i.send??di)(r).catch(c=>({ok:!1,error:String(c?.message??c)}));a.ok?o.status="sent":(o.status="failed",o.error=a.error)}on(t,o);try{ci(s)}catch{}return o.status==="failed"?{ok:!1,error:o.error??"send failed"}:{ok:!0,draft:o}}import{mkdirSync as fi,readFileSync as gi,renameSync as mi,writeFileSync as hi}from"fs";import{resolve as yi}from"path";function ln(t){return yi(ve(t),"_state.json")}function R(t){try{let e=JSON.parse(gi(ln(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function H(t,e){fi(ve(t),{recursive:!0});let n=ln(t),i=`${n}.${process.pid}.tmp`;hi(i,JSON.stringify(e,null,2)+`
|
|
@@ -479,4 +479,4 @@ Document the arguments, commands, or files the skill expects. Example:
|
|
|
479
479
|
claude-code ${yt(t)} --arg value
|
|
480
480
|
\`\`\`
|
|
481
481
|
`}Rt();var Mr={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Or(t){return{...Mr,...t??{},regions:{...t?.regions??{}},buffer:{...Mr.buffer,...t?.buffer??{}}}}function Cu(t){try{return Or($t(t).screen)}catch{return Or(void 0)}}var la=/^[a-z][\w-]*$/,Nr=["window","screen","menubar","notifications"];function Y(t,e,n,i){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${i}`);return r}var he=(t,e)=>Y(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function jr(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Du(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=he(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=he(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=he(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=Y(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=Y(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[s,o]of Object.entries(e.regions)){if(!la.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);o===null?delete r[s]:r[s]=jr(o)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,s={...n.buffer??{}};"enabled"in r&&(s.enabled=!!r.enabled),"seconds"in r&&(s.seconds=Y(r.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in r&&(s.fps=Y(r.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in r&&(s.maxPixels=he(r.maxPixels,"buffer.maxPixels")),"region"in r&&(s.region=String(r.region).trim()),n.buffer=s}let i=n.buffer?.region;if(i!==void 0&&!Nr.includes(i)&&!n.regions?.[i])try{jr(i)}catch{throw new Error(`buffer.region "${i}" is not a region \u2014 use ${[...Nr,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Kt as a,pa as b,Ze as c,Os as d,Ns as e,qc as f,Kc as g,Gc as h,Zn as i,Jc as j,Zc as k,T as l,Qn as m,x as n,ha as o,wa as p,di as q,Ra as r,cn as s,R as t,Da as u,Ea as v,fn as w,Na as x,z as y,Ya as z,bn as A,tl as B,fr as C,_l as D,Cl as E,Ml as F,Ao as G,Ol as H,Qa as I,ec as J,tc as K,nc as L,rc as M,ic as N,oc as O,ac as P,hc as Q,Le as R,yc as S,bc as T,q as U,K as V,To as W,zl as X,ql as Y,Kl as Z,Gl as _,st as $,Xl as aa,Ne as ba,je as ca,de as da,ns as ea,is as fa,vc as ga,We as ha,Fe as ia,ss as ja,os as ka,jn as la,Bn as ma,$c as na,ls as oa,Rc as pa,ys as qa,xs as ra,Be as sa,Ss as ta,Un as ua,P as va,$r as wa,Rr as xa,Ar as ya,tu as za,Fo as Aa,_r as Ba,Cr as Ca,pu as Da,fu as Ea,ra as Fa,gu as Ga,Er as Ha,pe as Ia,Nc as Ja,Xn as Ka,Ue as La,Je as Ma,Hc as Na,bu as Oa,wu as Pa,xu as Qa,ku as Ra,Su as Sa,vu as Ta,$u as Ua,Ru as Va,Au as Wa,Mr as Xa,Or as Ya,Cu as Za,Nr as _a,Du as $a};
|
|
482
|
-
//# sourceMappingURL=chunk-
|
|
482
|
+
//# sourceMappingURL=chunk-B32A6OOY.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{c as Ze}from"./chunk-SZDACK6O.js";import{b as ce}from"./chunk-AFRHKA7B.js";import{b as qe,e as Ye,f as Ge,i as Qe,k as Xe,l as et,q as rt}from"./chunk-
|
|
1
|
+
import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{c as Ze}from"./chunk-SZDACK6O.js";import{b as ce}from"./chunk-AFRHKA7B.js";import{b as qe,e as Ye,f as Ge,i as Qe,k as Xe,l as et,q as rt}from"./chunk-J4JVKVEK.js";import{c as Ke,e as ze,f as Je}from"./chunk-KA2UIZXG.js";import{e as He,g as Ue,h as Be,i as de}from"./chunk-GQ76J72O.js";import{a as Ve}from"./chunk-GV7S5BAX.js";import{a as _e,b as oe,c as se,d as Le,e as ae}from"./chunk-QD6IICK7.js";import{v as Ce,w as hn}from"./chunk-DXJRMPGH.js";import{b as Me,f as mn}from"./chunk-72SZI2UW.js";import{c as We,d as je}from"./chunk-QOYAX2FT.js";import{a as ie,i as gn}from"./chunk-RJ7DASOU.js";import{existsSync as yn,mkdirSync as it,readFileSync as wn,writeFileSync as kn,renameSync as bn}from"fs";import{resolve as ot,dirname as vn}from"path";var st=class{filePath;log;constructor(e={}){let t=e.baseDir??ot(process.cwd(),".agentx");this.filePath=ot(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),it(t,{recursive:!0})}key(e,t,n){return`${e}::${t}::${n||"-"}`}load(){if(!yn(this.filePath))return{version:1,overrides:{}};try{let e=wn(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){it(vn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;kn(t,JSON.stringify(e,null,2)),bn(t,this.filePath)}get(e,t,n){let o=this.load().overrides[this.key(e,t,n)];if(o&&!(o.expiresAt&&Date.parse(o.expiresAt)<Date.now()))return o}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),n={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(n.channel,n.chatId,n.accountId)]=n,this.save(t),n}remove(e,t,n){let i=this.load(),o=this.key(e,t,n);return o in i.overrides?(delete i.overrides[o],this.save(i),!0):!1}consumeSummary(e,t,n){let i=this.load(),o=i.overrides[this.key(e,t,n)];if(!o||!o.summary||o.summaryConsumedAt)return;let s=o.summary;return o.summaryConsumedAt=new Date().toISOString(),this.save(i),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(n=>!n.expiresAt||Date.parse(n.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(n=>n.toAgent===e),outgoing:t.filter(n=>n.fromAgent===e)}}};import{readFileSync as ut,writeFileSync as le,appendFileSync as Rn,mkdirSync as $n,existsSync as pt,statSync as xn}from"fs";import{resolve as U}from"path";var at="[Agent Memory \u2014 persistent facts from past conversations]",Sn=2400;function dt(r,e){return r?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function In(r,e=Date.now()){let t=ze(r,e),n=r.undated?"UNVERIFIED (never checked) ":dt(t,He(r.verifiedAt,e));return{line:`- [wiki ${r.id}] ${n}${r.subject} \xB7 ${r.attribute}: ${r.value} (${r.source}, checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy})`,unverified:t}}function An(r,e){let n=!r.source.chatId.startsWith("-")&&/^\d+$/.test(r.source.chatId)?"DM":r.source.chatId,i=Be(r,e);return{line:`- [${r.category}] ${dt(i,Ue(r,e))}${r.content} (${n}, ${r.source.date})`,unverified:i}}function ct(r,e=[],t=Date.now()){let n=[],i=new Set,o=at.length,s=!1;for(let a of r){let d=e.length>0?Je(a.content,e):null,c,u,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(i.has(d.id))continue;i.add(d.id),c=In(d,t),u=d.id}else c=An(a,t),d&&(c.line+=` [differs from wiki ${d.id}]`);let f=c.unverified&&!s?de.length:0;if(o+f+c.line.length>Sn)break;n.push({fact:a,...c,...u?{wikiRef:u}:{}}),o+=f+c.line.length,f&&(s=!0)}return n}function lt(r){if(r.length===0)return"";let e=r.some(t=>t.unverified)?[de]:[];return[at,...e,...r.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var ft=200,Pn=7,gt=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=U(e,".agentx/memory"),this.ledger=new Ke(U(e,".agentx/wiki")),pt(this.memoryDir)||$n(this.memoryDir,{recursive:!0})}filePath(e){return U(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||oe(t.content))return!1;let n=t.source.trust??_e(t.source.channel),i=t.review??Le(n),o={...t,source:{...t.source,trust:n},...i?{review:i}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Rn(this.filePath(e),JSON.stringify(o)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!pt(t))return[];try{let{mtimeMs:n,size:i}=xn(t),o=this.parsedCache.get(t);if(o&&o.mtimeMs===n&&o.size===i)return o.facts.slice();let a=ut(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:n,size:i,facts:a}),a.slice()}catch{return[]}}findRelevant(e,t,n=8){let i=this.getAll(t).filter(ae);if(i.length===0)return[];let o=i.map(g=>`${g.keywords.join(" ")} ${g.content}`),s=U(this.memoryDir,`${t}_bm25_cache.json`),a=je(o,s),d=We(e,a),c=new Map(d.map(g=>[g.docIndex,g.score])),p=i.map((g,h)=>{let m=c.get(h)??0;return g.category==="commitment"&&(m+=1),{memory:g,score:m}}).filter(g=>g.score>0);if(p.length===0)return i.slice(-n);let f=p.sort((g,h)=>h.score-g.score).slice(0,n).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return lt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return ct(e,t)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),i=new Set(t),o=!1;for(let s of n)if(i.has(s.id)){s.accessCount=(s.accessCount||0)+1,s.lastAccessed=new Date().toISOString();let a=s.intervalDays||1;s.intervalDays=Math.min(a*2,30),s.nextReview=new Date(Date.now()+s.intervalDays*864e5).toISOString(),o=!0}o&&le(this.filePath(e),n.map(s=>JSON.stringify(s)).join(`
|
|
@@ -25,4 +25,4 @@ import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{c as Ze}from"./chunk-SZD
|
|
|
25
25
|
`).filter(Boolean),i=[];for(let o=n.length-1;o>=0&&i.length<t;o--)try{let s=JSON.parse(n[o]);(!e||s.person===e)&&i.push(s)}catch{}return i}load(){if(Oe(this.file))try{let e=JSON.parse(Ne(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){Gt(Qt(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${en(4).toString("hex")}.tmp`;Zt(t,JSON.stringify(e,null,2)+`
|
|
26
26
|
`,{encoding:"utf-8",mode:384}),Vt(t,this.file)}};import{extname as ui}from"path";var nn=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,rn=/<agentx-artifact>[\s\S]*$/i;function Ps(r,e=1/0,t=!1){let n=[],i=String(r??"");if(!/<agentx-artifact>/i.test(i))return{text:i,artifacts:n};let o=i.replace(nn,(s,a)=>{try{let d=JSON.parse(a.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&n.length<e){let c=d.mime,u=c.startsWith("image/")?"image":c==="application/pdf"?"pdf":c.startsWith("text/")?"text":"file";n.push({type:u,filename:d.filename,mime:c})}}catch{}return""});return{text:(t?o.replace(rn,""):o).trim(),artifacts:n}}function Ts(r,e=!1){let t=String(r??""),n=t;if(/<agentx-artifact>/i.test(t)){let i=t.replace(nn,(o,s)=>{try{let a=JSON.parse(s.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});n=(e?i.replace(rn,""):i).trim()}return n.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(i,o,s)=>o===void 0||s===void 0?i:`[${o||s}](${s})`)}var pi={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},Os={bytes:20*1024*1024,perMessage:20,pathChars:512};function Ns(r){return pi[ui(r).toLowerCase()]??null}var fi=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
27
27
|
`);function Ds(r,e,t){return r==="app"&&e&&t!==!1?fi:void 0}import{lstatSync as Ee,mkdirSync as gi,readdirSync as mi,realpathSync as De,unlinkSync as hi}from"fs";import{join as ne,resolve as on}from"path";var sn=".agentx/outbox",yi=7*24*60*60*1e3;function wi(r,e){try{let t=De(on(e,r)),n=ne(t,sn);return De(n)===n&&Ee(n).isDirectory()?n:null}catch{return null}}function js(r,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let i=De(on(t,r));Ee(ne(i,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||gi(ne(i,sn),{recursive:!0})}catch{return 0}let n=wi(r,t);return n?an(n,(e.now??Date.now())-(e.maxAgeMs??yi)):0}function an(r,e){let t=0;for(let n of mi(r)){let i=ne(r,n);try{let o=Ee(i);o.isDirectory()?t+=an(i,e):Math.max(o.mtimeMs,o.ctimeMs)<e&&(hi(i),t++)}catch{}}return t}export{st as a,gt as b,mt as c,Fi as d,Nn as e,Wi as f,$ as g,pe as h,v as i,B as j,Bn as k,he as l,we as m,be as n,xe as o,Hr as p,qr as q,Te as r,ar as s,ai as t,tn as u,Ps as v,Ts as w,Os as x,Ns as y,Ds as z,sn as A,js as B};
|
|
28
|
-
//# sourceMappingURL=chunk-
|
|
28
|
+
//# sourceMappingURL=chunk-BERHVF3T.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{B as Ns,a as ys,b as bs,d as xs,f as Fe,l as _s,s as Es,u as Ds,z as Os}from"./chunk-
|
|
1
|
+
import{B as Ns,a as ys,b as bs,d as xs,f as Fe,l as _s,s as Es,u as Ds,z as Os}from"./chunk-BERHVF3T.js";import{a as fs}from"./chunk-GLQLCBJS.js";import{b as ws}from"./chunk-DP7RTNDM.js";import{a as Ps}from"./chunk-W4YR2RO2.js";import{b as ks,c as Bt,d as Ss,e as vs,h as Cs}from"./chunk-J4JVKVEK.js";import{a as hs}from"./chunk-J64VIHL5.js";import{a as jt,b as Ts}from"./chunk-J3SOEFRE.js";import{a as Ut,b as Is}from"./chunk-SIU6STB2.js";import{e as As,i as $s,j as Ms,k as Rs}from"./chunk-X5C5W3E4.js";import{a as ss}from"./chunk-Z4FY64BS.js";import{a as rs,c as os}from"./chunk-MYVHVJWZ.js";import{a as is,b as as,c as cs,d as ds,f as us}from"./chunk-DWADWDMU.js";import{a as ls,b as gs}from"./chunk-23A5K5UW.js";import{g as ps,h as ms}from"./chunk-4BCAH7XI.js";import{a as at,c as Le}from"./chunk-2GIDVZ4H.js";import{q as es,t as ts,v as xe,w as ns}from"./chunk-DXJRMPGH.js";import{a as Ne,b as it,f as Ht}from"./chunk-72SZI2UW.js";import{a as we,b as Dt}from"./chunk-FCPTN6NF.js";import{c as Bn,d as Wn}from"./chunk-QOYAX2FT.js";import{e as me}from"./chunk-DSYKYZMT.js";import{B as Ft,D as oi,F as Qn,J as ii,P as zn,Q as Xn,R as Oe,S as Yn,T as Vn,V as Zn,ha as ai,z as Jn}from"./chunk-JREA25GJ.js";import{a as Lt,i as ri}from"./chunk-RJ7DASOU.js";import{g as Nt,h as si}from"./chunk-BRK6M6LA.js";import{a as qn,b as oe,c as Kn,d as Gn,e as Ot}from"./chunk-2QNT5JDS.js";ns();Ht();var Ls="session-continuity",Fs={continues:Ne("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Ne("Does the new request refer to something stated earlier in the conversation?")};function Hs(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Wt(s.message,1200),previousRequest:s.previousMessage?Wt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Wt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function js(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function Wt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{execa as ht}from"execa";import{spawn as ci}from"node:child_process";import{createHash as di}from"node:crypto";import{createInterface as ui}from"node:readline";var de=class extends Error{},li=s=>ci("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),qt=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),ui({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Kt=class{constructor(e=li,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=di("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([f],[b])=>f.localeCompare(b))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new de("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let f=[...this.entries].find(([,b])=>!b.connection.busy);if(!f)throw new de("Codex warm process capacity reached");f[1].connection.close(),this.entries.delete(f[0])}try{r={fingerprint:n,connection:new qt(e,this.launchProcess)}}catch{throw new de("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,d="",c,l,u,p=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let h=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),k=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let f={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...f,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(k),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let I=new Promise((E,_)=>{i.failTurn=_,i.notify=(C,O)=>{if(O?.threadId!==l)return;let F=O.item,D={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...O,type:C.replace("/","."),...F?{item:{...F,type:D[F.type]||F.type}}:{}}),C==="item/completed"&&F?.type==="agentMessage"&&F.phase==="final_answer"&&(c=F.text),C==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=O.delta,e.onDelta?.(O.delta,d)),C==="thread/tokenUsage/updated"){let L=O.tokenUsage.last,H=L.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-H),outputTokens:(u?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+H,cacheCreateTokens:(u?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}C==="turn/completed"&&(O.turn.status==="completed"?E():_(new Error(O.turn.error?.message||`Codex turn ${O.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:c??d,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(f){if(i.close(),!a&&!e.signal?.aborted)throw new de(f.message);return{content:d,codexSessionId:l,usage:u,error:f.message,duration:Date.now()-t}}finally{clearTimeout(k),clearTimeout(h),e.signal?.removeEventListener("abort",y),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Us=new Kt;import{execFile as Pi}from"child_process";import{StringDecoder as We}from"string_decoder";import{mkdtempSync as or,readFileSync as ir,rmSync as ar}from"fs";import{join as pt}from"path";import{tmpdir as cr}from"os";function ct(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),d=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||d===529||d===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function dt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var Bs=null;function ut(){return Bs}function od(s){Bs=s}function He(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function gi(s,e){if(s.state()==="busy")return null;let n=s.snapshot(),r=s.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?n.claudeSessionId&&n.claudeSessionId!==e.resumeSessionId?`session changed (${n.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:n.claudeSessionId?"session rotated":null}var Te=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Ws=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let n=He(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=gi(r,t);if(!a)return r.claim?.(),r;this.handles.delete(n),this.handleWorkspace.delete(n),this.cfg.log(`[process-registry] respawning ${n}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new Te(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new Te(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=He(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=He(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=He(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=He(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";n.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as pi}from"child_process";import{existsSync as mi,readFileSync as hi}from"fs";import{resolve as fi}from"path";function yi(s){let e=fi(s,"CLAUDE.md");if(!mi(e))return null;try{let t=hi(e,"utf8");return us(t)}catch{return null}}var bi=20*60*1e3,wi=5e3,je=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ue=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function xi(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var qs=class{constructor(e={}){this.opts=e}spawn(e,t){return new Gt(e,t,this.opts)}},Gt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=pi(r,o,{cwd:t.workspace,env:Le(xi({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:yi(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let d=this.waiters.splice(0);for(let c of d)c(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
3
|
`);let a=e.deadlineMs??bi,d=o+a,c=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new je(a));try{for(;;){let l=d-Date.now();if(l<=0)throw c();let u=await this.nextEvent(l);if(u===null&&this.killReason)throw new Ue(this.killReason);if(u===null&&!this.exited)throw c();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},wi);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};Ot();ri();Dt();import{resolve as Ks,join as Gs}from"path";var Ti=4e3;function lt(s){try{let e=Gs(Ks(s.root),".agentx","db.sqlite"),t=Lt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=we(),r=s.input.command?s.input.command.slice(0,Ti):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -27,7 +27,7 @@ ${s}`}function Ei(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
|
|
|
27
27
|
`,u)}};_.stdout?.on("data",v=>{D+=H.write(v);let w=D.split(`
|
|
28
28
|
`);D=w.pop()||"";for(let x of w)K(x)}),_.stderr?.on("data",v=>{L+=j.write(v)});let A=await _;if(i&&i.removeEventListener("abort",F),D+=H.end(),D.trim()&&K(D),L+=j.end(),C)return{content:"",error:O||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:y};if(A.exitCode!==0||h){let v=A,w;return v.timedOut?w=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:h?w=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+L)?w=nr():w=L.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Q(w),duration:Date.now()-d,usage:p,opencodeSessionId:y}}return f=!1,{content:u.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||s.model,opencodeSessionId:y}}catch(I){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let E=/ENOENT|spawn opencode/i.test(I?.message||"")?nr():I?.message;return{content:u,...Q(E||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:y}}finally{b?.(),k?.release(f)}}async function qi(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=le(s,e,n),d="",c=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of c)l.type==="result"&&l.subtype==="success"&&(d=l.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...Q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Ki(s,e,t,n,r,o,i,a,d){let c=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,y=()=>{let f=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(f))}catch{}};a&&(a.aborted?y():a.addEventListener("abort",y,{once:!0}));let h=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);h.unref?.();let k=()=>({content:"",...Q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let f=s.provider||"claude-code",b=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),_=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=ds(s),O=Object.keys(C).length>0,F={task:b,cwd:s.workspace,provider:f,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:_,providerOpts:o,abortSignal:u.signal,mcpServers:O?C:void 0};if(r){let{generateStream:K}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),_=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=ds(s),O=Object.keys(C).length>0,F={task:b,cwd:s.workspace,provider:f,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:_,providerOpts:o,abortSignal:u.signal,mcpServers:O?C:void 0};if(r){let{generateStream:K}=await import("./agent-QHM3J2XS.js"),A="",v,w,x,N;for await(let M of K(F)){if(d)try{d(M)}catch{}if(M.type==="text_delta")A+=M.text,r(M.text,A);else if(M.type==="thinking_delta")M.text&&i&&i(M.text);else if(M.type==="generate_result"){if(M.result.content&&M.result.content!==A){let V=M.result.content.slice(A.length);V?(A=M.result.content,r(V,A)):A=M.result.content}v=M.result.tokensUsed,M.result.inputTokens!=null&&(w=M.result.inputTokens),M.result.outputTokens!=null&&(x=M.result.outputTokens)}else if(M.type==="done"){if(M.result.content&&M.result.content!==A){let V=M.result.content.slice(A.length);V?(A=M.result.content,r(V,A)):A=M.result.content}M.result.tokensUsed!=null&&(v=M.result.tokensUsed)}else M.type==="error"&&(N=M.error)}return N&&!A?p?k():N==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${N}`),duration:Date.now()-c}:((w===void 0||x===void 0)&&v&&(w=Math.round(v*.7),x=v-w),{content:A||"Done.",tokensUsed:v,usage:w!==void 0||x!==void 0?{inputTokens:w||0,outputTokens:x||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:D}=await import("./agent-QHM3J2XS.js"),L=await D(F),H=L.inputTokens,j=L.outputTokens;if((H===void 0||j===void 0)&&L.tokensUsed){let K=L.tokensUsed;H=Math.round(K*.7),j=K-H}return{content:L.content||"Done.",tokensUsed:L.tokensUsed,usage:H!==void 0||j!==void 0?{inputTokens:H||0,outputTokens:j||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(f){return p?k():f?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${f.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",y)}}var Gi=1e3;async function Ji(s,e){let t=Promise.resolve(s).then(i=>({kind:"exit",r:i})),n,r=e.then(()=>new Promise(i=>{n=setTimeout(()=>i({kind:"grace"}),Gi),n.unref?.()})),o=await Promise.race([t,r]);return n&&clearTimeout(n),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Qi(s,e,t,n,r,o,i){let a=ut();if(!a)return null;let d=Date.now(),{channel:c,chatId:l}=yt(e.context),u={agentId:e.agentId,channel:c,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,y=!1;try{let A=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:c,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),y=a.list().length>A}catch(A){return A instanceof Te,null}y&&Vt(e.agentId,s,e.model,n,"persistent");let h=le(s,e,t),k="",f,b,I,E,_,C,O,F="",D="",L=A=>{if(!i||!A)return;let v;if(D&&A.startsWith(D)?v=A.slice(D.length):v=F&&!F.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
33
|
${A}`:A,D=A,!!v){F+=v;try{i(v,F)}catch{}}},H=!1,j=()=>{H=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?j():o.addEventListener("abort",j,{once:!0}));let K=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:A})){if(K=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let w=v.raw.message?.content??[];for(let N of w)N.type==="text"&&typeof N.text=="string"?(k=N.text,L(N.text)):N.type==="tool_use"&&(D="");let x=v.raw.message?.usage;if(x){let N=(x.input_tokens||0)+(x.cache_read_input_tokens||0)+(x.cache_creation_input_tokens||0);N>0&&(E=N)}}if(v.type==="result"){let w=v.raw;if(w.is_error){let x=Q(typeof w.result=="string"?w.result:"claude error");f=x.error,b=x.errorKind}else typeof w.result=="string"&&w.result.length>0&&(k=w.result,F||L(w.result));typeof w.session_id=="string"&&(O=w.session_id),w.usage&&(I={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(_=w.num_turns),typeof w.message?.model=="string"?C=w.message.model:typeof w.model=="string"&&(C=w.model)}}}catch(A){if(H)f="task cancelled by operator",b="cancelled";else if(K)if(A instanceof Ue)f=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,b="interrupted";else if(A instanceof je){let v=Q(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);f=v.error,b=v.errorKind}else{let v=Q(`persistent claude process error: ${A?.message||String(A)}`);f=v.error,b=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",j),null}finally{o&&o.removeEventListener("abort",j)}return H&&!f&&(f="task cancelled by operator",b="cancelled"),{content:H?"":k,error:f,errorKind:b,duration:Date.now()-d,usage:I,contextTokens:E,numTurns:_,billedModel:C,claudeSessionId:O}}function yr(s){let e=oe(s.autonomy);if(!e&&!s.personLimits)return{args:[]};if(!s.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?zs(s.autonomy,s.agentId,s.taskId):{args:[]};return"error"in t||!s.personLimits?t:er(t.args,s.taskId,s.agentId)}function zi(s){return oe(s.autonomy)||!!s.personLimits}async function Xi(s,e,t,n,r,o,i){let a=oe(e.autonomy)?e.autonomy:void 0,d=a&&Xs(a,s.tier)||e.personLimits&&tr(s.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:c,message:a?`${Gn(a)}
|
|
@@ -131,7 +131,7 @@ Agent: ${t.slice(0,1e3)}`}],{model:Ia,maxTokens:512})).content.trim().match(/\[[
|
|
|
131
131
|
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(c){i={content:"",error:c?.message??String(c)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,n,r);if(d){let c=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${c}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let c=i.error?Fe(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";ks().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:c,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(c){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${c?.message??c}`)}return i}async executeInternal(e,t,n,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=oe(e.autonomy),a=Yn(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:Br().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(d){let g=await d;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let c=this.agents.get(e.agentId);if(!c){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(S=>S.id===e.agentId));if(g){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${g.peer}"`);try{let m=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(g.peer,e.message,e.agentId,{timeoutMs:m}),viaMesh:g.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${g.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:l,chatId:u}=yt(e.context),p;if(c.activeTasks>=c.def.maxConcurrent)if(l==="api"||l==="app"||l==="a2a"||l==="mcp"||l==="reminder"||l==="events"||l==="guest"||i){let g=Date.now(),m=25*6e4,S=500;for(;c.activeTasks>=c.def.maxConcurrent;){if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(P=>setTimeout(P,S))}}else if(l==="voice"){let g=Date.now(),m=25*6e4,S=`${e.agentId}\0${u}`;for(;this.messageQueue.isBusy(e.agentId,l,u)||this.voiceClaims.has(S);){if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(m/6e4)}m`};await new Promise(P=>setTimeout(P,500))}p=S,this.voiceClaims.add(S)}else{let g=c.def.queueMode||"collect",m=this.messageQueue.enqueue(e.agentId,l,u,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:l,chatId:u,originalContext:e.context,queuedAt:e.queuedAt});if(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let S=this.messageQueue.pendingCount(e.agentId,l,u);return X().emit("task:queued",{agentId:e.agentId,channel:l,chatId:u,at:new Date().toISOString(),sender:Ft(e.context),humanRoot:Nt(e.context)}),this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${S}) behind=${c.runningTasks.map(P=>P.id).join(",")||"-"} chat=${l}:${u} at=${new Date().toISOString()}`),{content:"",error:xs(m,S)}}}let y=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(g,m)=>{this.log(`[${e.agentId}] ${g} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/1e3))}s`)}});if(p&&this.voiceClaims.delete(p),!y.ok)return this.log(`[${e.agentId}] ${y.reason}`),{content:"",error:y.reason};if(e.queuedAt!==void 0){let g=Er(e.queuedAt);g&&(e.message=`${g}
|
|
132
132
|
${e.message}`),e.queuedAt=void 0}c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let h={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};c.runningTasks.push(h),e.runningTaskId=h.id;let k=zn(this.config.people,e.context);if(e.context&&(k?e.context.person=k.id:delete e.context.person),this.runningContexts.set(h.id,e.context??{}),e.onStart)try{e.onStart(h.id)}catch{}let f=new AbortController;this.taskAborts.set(h.id,{agentId:e.agentId,channel:h.channel,chatId:typeof h.chatId=="string"?h.chatId:"",originalMessage:e.message||"",controller:f});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(h.id,b);let I=g=>{if(g){b.buffer+=g,b.buffer.length>Mo&&(b.buffer=b.buffer.slice(b.buffer.length-Mo));for(let m of b.subscribers)try{m(g)}catch{}}},E=we();e.taskId=E;let _=new Map,C=(g,m,S)=>{try{X().emit("task:step",{taskId:E,agentId:e.agentId,name:"pipeline",action:g,status:S,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},O=0,F=!1,D=()=>{F||(F=!0,O&&C("first-event",O,"ok"))},L;if(t){let g=Xc();L=m=>{D();let S=g(m);if(S&&I(S),_o(E,e.agentId,m),Po(_,m),cn(m,void 0,e.model||c.def.model),r)try{r(m)}catch{}}}else L=g=>{if(D(),_o(E,e.agentId,g),Po(_,g),cn(g,void 0,e.model||c.def.model),r)try{r(g)}catch{}};let H=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,j=H?setTimeout(()=>f.abort(new Error(`timed out after ${Math.round(H/1e3)}s`)),H):void 0;j?.unref?.();let K=(c.def.preSpawnTimeoutSec??Wc)*1e3,A=setTimeout(()=>{f.abort(new Error(`timed out before spawn after ${Math.round(K/1e3)}s in step "${h.step??"start"}"`))},K);A.unref?.();let v=()=>{A&&clearTimeout(A),A=void 0},w=()=>`task=${h.id} chat=${l}:${u} at=${new Date().toISOString()}`,x;f.signal.addEventListener("abort",()=>{let g=ze(f.signal).message;/^timed out/.test(g)&&(x=h.step??"start"),this.log(`[${e.agentId}] task ${h.id} aborted in step "${h.step??"start"}" \u2014 ${g} ${w()}`)},{once:!0});let N=g=>{h.step=g,this.log(`[${e.agentId}] step ${g} ${w()}`)},M=(g,m,S=0)=>{if(f.signal.aborted)return Promise.reject(ze(f.signal));N(g),(g==="agent"||g==="workflow-auto-run")&&(v(),O=Date.now());let P=Date.now(),W=Ao(m(),jc[g]??0,g);return Co(W,f.signal,S).then(B=>(C(g,P,"ok"),B),B=>{throw C(g,P,"error"),B instanceof Re&&this.log(`[${e.agentId}] ${B.message}; continuing without it ${w()}`),B})},V=async(g,m,S,P=0)=>{try{return await M(g,m,P)}catch(W){if(W instanceof Re)return S();throw W}},wn=!1,xn=g=>{if(wn)return;wn=!0,this.runReleases.delete(h.id),j&&clearTimeout(j),v(),c.activeTasks--;let m=c.runningTasks.findIndex(S=>S.id===h.id);m!==-1&&c.runningTasks.splice(m,1),this.runningContexts.delete(h.id),this.taskAborts.delete(h.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
|
|
133
133
|
[task finished]
|
|
134
|
-
`)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),Uc).unref?.();try{let S=b.endedAt,P={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-h.startedAt.getTime(),ok:!g?.error,error:g?.error,...x?{status:"timeout",step:x}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let B=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,l,u).then(S=>{if(S.length===0)return;this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${h.id} chat=${l}:${u} at=${new Date().toISOString()}`);let P=Date.now(),W=()=>X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:P,at:new Date().toISOString()});for(let B of S){let ee=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:ee,queuedAt:B.queuedAt??B.timestamp}).then($=>(Fe($.error)||W(),this.postQueuedResponseToChannel(e.agentId,ee,$)),$=>{throw W(),$}).catch($=>{this.log(`[${e.agentId}] queued message failed: ${$.message}`)})}}).catch(S=>{X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(h.id,xn),this.messageQueue.markRunning(e.agentId,l,u),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${w()}`);let T=e.context?.channel||"api",{evaluateRequest:Oo,selectRequestContext:No}=await import("./request-planner-
|
|
134
|
+
`)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),Uc).unref?.();try{let S=b.endedAt,P={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-h.startedAt.getTime(),ok:!g?.error,error:g?.error,...x?{status:"timeout",step:x}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let B=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,l,u).then(S=>{if(S.length===0)return;this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${h.id} chat=${l}:${u} at=${new Date().toISOString()}`);let P=Date.now(),W=()=>X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:P,at:new Date().toISOString()});for(let B of S){let ee=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:ee,queuedAt:B.queuedAt??B.timestamp}).then($=>(Fe($.error)||W(),this.postQueuedResponseToChannel(e.agentId,ee,$)),$=>{throw W(),$}).catch($=>{this.log(`[${e.agentId}] queued message failed: ${$.message}`)})}}).catch(S=>{X().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(h.id,xn),this.messageQueue.markRunning(e.agentId,l,u),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${w()}`);let T=e.context?.channel||"api",{evaluateRequest:Oo,selectRequestContext:No}=await import("./request-planner-TW5OCKTF.js"),pe=await V("request-gate",()=>Oo(e.message,e.agentId,T),()=>({active:!1,preprocess:!1}));pe.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let R=u,vt=e.context?.sender||"User",ne=c.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,T,R),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${T}:${R}`),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"stale",at:new Date().toISOString()})),e.freshSession||await V("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,T,R,e.seedHistory),()=>{});let Lo=[...this.sessions.getSession(e.agentId,T,R).messages].reverse().find(g=>g.role==="agent")?.content;vo({agent:e.agentId,channel:T,chatId:R,message:e.message,previousReply:Lo,taskId:E}),this.sessions.addUserMessage(e.agentId,T,R,vt,e.message);let Tn=Date.now();X().emit("task:started",{agentId:e.agentId,channel:T,chatId:R,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Tn).toISOString(),taskId:E,resumeOrigin:Pr(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Ft(e.context),...k?{person:k}:{},humanRoot:Nt(e.context),pickup:Jn(e.context),operator:Qn(e.context)});let Y,Ct,kn=this.classifier;if(kn&&T!=="a2a"&&!ne){N("classify");let g=Date.now();Ct=kn.classify({text:e.message,channel:T,sender:e.context?.sender,chatId:R,agentId:e.agentId}).then(m=>{Y=m||void 0,Y?.path?.length&&(h.intentPath=Y.path.slice()),C("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),C("classify",g,"error")})}let In=async g=>{if(!Ct)return;let m;await Promise.race([Ct,new Promise(S=>{m=setTimeout(S,g),m.unref?.()})]),m&&clearTimeout(m)};await In(Oc);let _e=this.config.workflows?.matching,be;if(this.config.workflows?.enabled&&_e?.enabled&&!i)try{let g=new _s({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Es({agentId:e.agentId,channel:T,message:e.message,intentPath:Y?.path},g.list());m&&m.confidence>=_e.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${_e.mode} reasons=${m.reasons.join(",")||"n/a"}`),_e.mode==="auto"&&m.confidence>=_e.autoRunThreshold&&(this.workflowAutoRunner?be={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let Fo=this.wikiHub.getAgentWiki(e.agentId),Sn=this.memoryStore.findRelevant(e.message,e.agentId,ne?3:8),vn=this.memoryStore.buildContext(Sn),Cn=this.memoryStore.contextFacts(Sn),Ho=this.patternStore.findRelevant(e.message,e.agentId,5),jo=this.patternStore.buildContext(Ho),An="";if(!ne)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),S=await M("skills",()=>g(c.def.workspace)),P=e.personLimits?.skills??[],W=P.length?S.filter(B=>!P.some(ee=>Oe(ee,B.frontmatter.name))):S;An=m(W,e.message)}catch{}let U=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,T,R):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,T,R):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,T,R):void 0;if(U&&this.sessions.isSessionStale(e.agentId,T,R)&&(this.log(`[${e.agentId}] session stale for ${T}:${R}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"stale"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"stale",at:new Date().toISOString()}),U=void 0),U&&this.sessions.shouldRotateByTierTwo(e.agentId,T,R)){let g=this.sessions.getLastTurnContextTokens(e.agentId,T,R);this.log(`[${e.agentId}] tier-2 rotation for ${T}:${R} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),U=void 0}if(U&&this.sessions.shouldRotateByTurns(e.agentId,T,R)){let g=this.sessions.getTurnCount(e.agentId,T,R);this.log(`[${e.agentId}] max-turns rotation for ${T}:${R} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,R,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,T,R),X().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:R,reason:"max-turns",at:new Date().toISOString()}),U=void 0}if(U&&c.def.tier==="claude-code"){let g=U;await V("rotate",()=>this.maybeRotateForContinuity(e,c,T,R,g),()=>!1)&&(U=void 0)}try{let g=await M("compact",()=>this.sessions.compactIfNeeded(e.agentId,T,R,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",S=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${T}:${R} (quality: ${m}%, ${S} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let P=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Uo=process.env.AGENTX_CONTEXT_SURGERY==="1",Bo=ne?{maxMessages:8,maxChars:2400}:Uo&&$o(T,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Wo=!U&&!ne?Jc(Fo,e.agentId):void 0,Ve=U?void 0:this.sessions.buildHistoryContext(e.agentId,T,R,Bo),qo=U?void 0:this.sessions.getRotationMemo(e.agentId,T,R)??void 0,$n,Mn=[];if(this.config.procedures?.injection?.enabled&&!U&&!ne)try{let g=new Qe({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=gn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){$n=pn(m),Mn=m.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of m)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(me&&me.cat)try{let m=this.sessions.getSession(e.agentId,T,R).messages,S=m[0],P=m[m.length-1],W=Ve===void 0?`resume=${U?U.slice(0,8):"?"} (no rebuild)`:`fresh history=${Ve.length}c/${Ve.split(`
|
|
135
135
|
`).length}L`,B=`[${e.agentId}] ${T}:${R} ${W} | session.messages=${m.length}`+(m.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${P.timestamp.slice(11,19)}(${P.role}:${(P.content||"").slice(0,40).replace(/\n/g," ")})`:"");me.cat("context",B)}catch(g){me.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Rn;if(c.def.contextReferences&&!U)try{let g=c.def.workspace,m=this.referencesCache.get(g);if(!m){let[P,W]=await M("references",()=>Promise.all([jt(c.def.workspace),Ut(c.def.workspace)]));if(P.byId.size===0&&W.recipes.length===0){let[B,ee]=await M("references",()=>Promise.all([jt(process.cwd()),Ut(process.cwd())]));m={refs:B,recipes:ee}}else m={refs:P,recipes:W};this.referencesCache.set(g,m)}let S=Is({agentId:e.agentId,intentTags:Y?.path,message:e.message},m.recipes,m.refs);S.cards.length>0&&(Rn=Ts(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Pn=this.sessions.getCrossSessionSummary(e.agentId,T,R,e.message),_n,Ze=Tr(e.message);if(Ze)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:T,chatId:R,lookbackDays:Ze.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${Ze.lookbackDays}d on this chat (cue-triggered)]`],S=[...g.turns].sort((P,W)=>P.ts.localeCompare(W.ts));for(let P of S){let W=P.ts.slice(11,16)+" "+P.day,B=P.role==="user"?P.senderName||"User":P.senderName||"Agent";m.push(`${W} ${B}: ${P.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),_n=m.join(`
|
|
136
136
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ze.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Ko=ne?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",En,Dn,On=!1;if(Ko==="planner"&&!pe.active&&T!=="voice"&&T!=="desktop"){try{let{planContext:g}=await import("./context-planner-JU7CNXCB.js"),m=await M("plan-context",()=>g({agentId:e.agentId,channel:T,chatId:R,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(On=!0,En=m.sessionHistory,vn=m.memoryContext,Cn=m.memoryFacts,Pn=m.crossChatContext,Dn=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}On&&U&&(this.sessions.clearClaudeSessionId(e.agentId,T,R),U=void 0)}let At=`${e.agentId}:${T}:${R}`,et=cs(e.message);et&&(et==="default"?(this.activeSouls.delete(At),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(At,et),this.log(`[${e.agentId}] Soul switched to: ${et}`)));let Go=this.activeSouls.get(At),Jo=is(c.def.workspace,Go),Qo=as(Jo),zo=this.agentMemory.indexMarkdown(e.agentId),Xo=c.def.tier==="claude-code"||c.def.tier==="codex-cli"?`[Operating principle]
|
|
137
137
|
Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",Yo=Yc(c.def.richMessages,T),Nn="";if(c.def.workspace){let g=G(c.def.workspace,"CLAUDE.md");if(te(g))try{let m=Xe(g,"utf-8");Nn=`[Project CLAUDE.md]
|
|
@@ -144,9 +144,9 @@ ${$}`),m+=$.length}catch{}}}let Vo=$t.length>0?$t.join(`
|
|
|
144
144
|
|
|
145
145
|
`):"",Mt=[c.def.systemPrompt||"",Xo,Yo,Nn,Vo,Qo||"",zo||""].filter(g=>g.trim().length>0).join(`
|
|
146
146
|
|
|
147
|
-
`)||void 0,Rt={channel:T,chatId:R,channelScope:e.context?.group?"group":T==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,T),systemPrompt:c.def.systemPrompt,sender:vt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ne||$o(T,c.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ne?void 0:jo||void 0,procedureContext:$n,references:Rn,skillInjection:An||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:En??Ve,memoryContext:vn||void 0,crossChatContext:Pn||void 0,longMemoryRecall:_n||void 0,wikiContext:Wo,handoverNote:this.buildHandoverNote(e.agentId,T,R),rotationMemo:qo,eventDigest:U?void 0:Gc(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Os(T,!U,c.def.richMessages);return g?Qc(c.def.workspace,g):void 0})(),intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},nt=pe.active&&pe.preprocess?await V("select-context",()=>No(Rt),()=>({input:Rt,excluded:[]})):{input:Rt,excluded:[]};nt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${nt.excluded.join(", ")}`);let st=Rr(nt.input,ne?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Zo=fs(st,{memory:Cn,procedures:Mn,wikiContext:nt.input.wikiContext}),Pt=(st?.length??0)+(Mt?.length??0)+(e.message?.length??0),rt={history:st?.length??0,sysPrompt:Mt?.length??0,message:e.message?.length??0},Ln=ro(e.agentId,T,R);oo(Ln,Pt,rt);let Fn=io(Ln);Fn&&this.log(`[${e.agentId}] ${Fn}`),Pt>16e3&&this.log(`[${e.agentId}] large context for ${T}:${R}: ${Pt} bytes (history=${rt.history}, sysPrompt=${rt.sysPrompt}, message=${rt.message})`);let _t,Hn=ss(c.def.tier,this.config.decisions.routing);if(!e.model&&Hn&&(!pe.active||pe.preprocess))try{let{routeTaskModel:g}=await import("./routing-
|
|
147
|
+
`)||void 0,Rt={channel:T,chatId:R,channelScope:e.context?.group?"group":T==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,T),systemPrompt:c.def.systemPrompt,sender:vt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ne||$o(T,c.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ne?void 0:jo||void 0,procedureContext:$n,references:Rn,skillInjection:An||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:En??Ve,memoryContext:vn||void 0,crossChatContext:Pn||void 0,longMemoryRecall:_n||void 0,wikiContext:Wo,handoverNote:this.buildHandoverNote(e.agentId,T,R),rotationMemo:qo,eventDigest:U?void 0:Gc(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Os(T,!U,c.def.richMessages);return g?Qc(c.def.workspace,g):void 0})(),intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},nt=pe.active&&pe.preprocess?await V("select-context",()=>No(Rt),()=>({input:Rt,excluded:[]})):{input:Rt,excluded:[]};nt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${nt.excluded.join(", ")}`);let st=Rr(nt.input,ne?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Zo=fs(st,{memory:Cn,procedures:Mn,wikiContext:nt.input.wikiContext}),Pt=(st?.length??0)+(Mt?.length??0)+(e.message?.length??0),rt={history:st?.length??0,sysPrompt:Mt?.length??0,message:e.message?.length??0},Ln=ro(e.agentId,T,R);oo(Ln,Pt,rt);let Fn=io(Ln);Fn&&this.log(`[${e.agentId}] ${Fn}`),Pt>16e3&&this.log(`[${e.agentId}] large context for ${T}:${R}: ${Pt} bytes (history=${rt.history}, sysPrompt=${rt.sysPrompt}, message=${rt.message})`);let _t,Hn=ss(c.def.tier,this.config.decisions.routing);if(!e.model&&Hn&&(!pe.active||pe.preprocess))try{let{routeTaskModel:g}=await import("./routing-TSRZLD7B.js"),m=await M("route-model",()=>g({message:e.message,agent:e.agentId,channel:T,isFollowUp:!!U,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,T,R),cheapModel:Hn}));m.downgraded&&(_t=m.model,this.log(`[${e.agentId}] ${m.reason}`))}catch{}let ei={...e,systemPromptAppend:Mt,..._t?{model:_t}:{}},se,jn=!1,Un=ko({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:c.def.maxExecutionMinutes??20}),ti=L;L=g=>{Un.observe(g),ti?.(g)};try{let g=this.workflowAutoRunner;if(be&&g){let q=be;try{let z=await M("workflow-auto-run",()=>g({workflowId:q.workflowId,agentId:e.agentId,channel:T,chatId:R,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:T,chatId:R,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:q.workflowId,matchConfidence:q.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${be.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:"",duration:0,metadata:{handledByWorkflow:be.workflowId,workflowRunId:z.runId,workflowMatchConfidence:be.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(c.def.tier==="claude-code"){N("dispatch-gate");let q=c.def.persistentProcess?ut():null,z=q!=null&&q.hasLive({agentId:e.agentId,channel:T,chatId:R}),ce=!!U||z,re=[Wr(ce),no(ce,void 0,e.model||c.def.model)].find(De=>De&&De.abort);if(re){c.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${re.reason}`);let De={content:"",error:re.message,duration:0};if(!t){b.buffer=`[error] ${re.message}`;for(let ni of b.subscribers)try{ni(b.buffer)}catch{}}return se=De,De}Qr();let Ee=so();Ee&&this.log(`[${e.agentId}] ${Ee}`)}let m=c.def.tier==="claude-code",S=m?t:(q,z)=>{q&&I(q),t&&t(q,z)},P=!1,W=m?n:q=>{q&&(P?I(q):(I(`\u{1F4AD} ${q}`),P=!0)),n&&n(q)},B=()=>{P&&(I(`
|
|
148
148
|
`),P=!1)},ee=m?S:S?(q,z)=>{B(),S(q,z)}:void 0,$=await M("agent",()=>br(c.def,ei,this.providers,ee,st,U,L,f.signal,W),Bc);if(!$.error){let q=zc(c.def.toolUseRequired,_);if(q){let z=Array.from(_.entries()).map(([ce,ot])=>`${ce}=${ot}`).join(", ")||"none";$.error=`tool_required_not_called: ${q} (invoked: ${z})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${q}, observed ${z}`)}}let Et=this.interruptedRuns.get(h.id);Et&&($.content="",$.error=Et,$.errorKind="interrupted"),se=$;let ae=$.usage?$r($.usage):void 0;if(jn=!0,X().emit("task:completed",{taskId:E,agentId:e.agentId,channel:T,chatId:R,durationMs:Date.now()-Tn,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:Et?!0:void 0,inputTokens:ae?.inputTokens,outputTokens:ae?.outputTokens,cacheReadTokens:ae?.cacheReadTokens,cacheCreateTokens:ae?.cacheCreateTokens,tier2InputTokens:ae?.tier2InputTokens,tier2OutputTokens:ae?.tier2OutputTokens,tier2CacheReadTokens:ae?.tier2CacheReadTokens,tier2CacheCreateTokens:ae?.tier2CacheCreateTokens,resumed:!!U,resumeSessionId:U||void 0,jevArm:pe.arm,numTurns:$.numTurns,injectedContext:Zo,finalResponse:$.content||void 0,billedModel:$.billedModel||c.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let q=$.error?`[error] ${$.error}`:$.content;b.buffer=q;for(let z of b.subscribers)try{z(q)}catch{}}if($.error)c.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,T,R,$.content),So({agent:e.agentId,channel:T,chatId:R,request:e.message,reply:$.content,taskId:E}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,T,R,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,T,R,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,T,R,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,T,R,$.usage,$.contextTokens),$.usage){let re=$.contextTokens,Ee=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(re??Ee)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${T}:${R}: context=${re??"n/a"} tokens (cumulative turn total=${Ee}) \u2014 next turn will rotate`)}if(ls({channel:T,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await In(Nc);try{let re=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:re,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:T,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
149
149
|
|
|
150
150
|
Agent: ${$.content}`,meta:Kc(Y,e.context)})}catch{}gs(e.agentId,e.message,$.content,{channel:T,chatId:R,sender:vt},this.memoryStore).catch(()=>{}),Lr(e.agentId,e.message,$.content,{channel:T,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=$.billedModel||e.model||c.def.model,ce=e.context?.channel,ot=ce&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ce}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,z,ce,ot),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${w()}`)}return $}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=ct(g.message);return se={content:"",error:dt(m),errorKind:m.kind},se}finally{if(Un.stop(),!jn)try{X().emit("task:completed",{taskId:E,agentId:e.agentId,channel:l,chatId:u,durationMs:Date.now()-h.startedAt.getTime(),error:se?.error||(f.signal.aborted?ze(f.signal).message:"run ended before completion"),errorKind:se?.errorKind,interrupted:this.interruptedRuns.has(h.id)?!0:void 0,at:new Date().toISOString()})}catch{}xn(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=G(process.cwd(),Pe,this.safe(e.agentId),t);te(n)||Lc(n,{recursive:!0});let r=G(n,`${this.safe(e.id)}.json`);Hc(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=G(process.cwd(),Pe,this.safe(e));if(!te(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let d=new Date(n).toISOString().slice(0,10),c=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[c,d]){let p=G(a,u);if(te(p))try{for(let y of ie(p)){if(!y.endsWith(".json"))continue;let h=y.split("-")[0],k=parseInt(h,10);if(!Number.isFinite(k)||k<i||k>n)continue;let f=Math.floor((n-k)/36e5),b=t-1-f;b>=0&&b<t&&o[b]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Pe);if(!te(e))return 0;let t=0;for(let n of ie(e)){let r=G(e,n),o;try{o=ie(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),d;try{d=ie(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let l=JSON.parse(Xe(G(a,c),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let p=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:p,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=qc){let t=G(process.cwd(),Pe);if(!te(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ie(t)){let i=G(t,o),a;try{a=ie(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=n))try{Fc(G(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=G(process.cwd(),Pe,this.safe(e));if(!te(n))return[];let r=ie(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(n,i),d;try{d=ie(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let l=JSON.parse(Xe(G(a,c),"utf-8")),{transcript:u,responseText:p,...y}=l;o.push(y)}catch{}}}return o}getTaskRecord(e,t){let n=G(process.cwd(),Pe,this.safe(e));if(!te(n))return null;let r=this.safe(t),o=ie(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(n,i,`${r}.json`);if(te(a))try{return JSON.parse(Xe(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=Ps();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.errorKind==="interrupted"||Fe(n.error))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}findRunningTurn(e,t={}){let n=this.agents.get(e);if(!n)return null;let r;if(t.taskId)r=n.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=n.runningTasks.filter(a=>{let d=yt(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(n=>n.id)}:null}isChatBusy(e,t,n){return this.messageQueue.isBusy(e,t,n)}runningIntentPath(e,t,n){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==n||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}interruptRunning(e){let t=0;for(let[n,r]of this.taskAborts){this.interruptedRuns.set(n,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${n} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:d,originalMessage:c}=o,l=o.controller.signal.aborted,u=!1;l&&c&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,d,c)),this.messageQueue.enqueue(i,a,d,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:n}});let p=this.messageQueue.pendingCount(i,a,d),y=!1;if(r.replace){let h=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(h))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${h}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:y,edited:u,pending:p}}async continueFinishedTask(e,t,n,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,d=i.chatId;return new Promise(c=>{let l=!1,u=p=>{l||(l=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>u({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{Fe(p.error)?u({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>u({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Yc(s,e){return s===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
151
151
|
`)}export{Us as a,od as b,Ws as c,yi as d,qs as e,lt as f,yd as g,Td as h,kd as i,Ad as j,yt as k,Fi as l,hr as m,Wi as n,qi as o,Ki as p,br as q,bt as r,wt as s,ba as t,su as u,ru as v,rn as w,X as x,Fr as y,$a as z,_a as A,Ur as B,Tu as C,Br as D,Gr as E,Vr as F,Ou as G,Zr as H,Qe as I,Tc as J,kc as K,Ic as L,Sc as M,vc as N,gn as O,ag as P,cg as Q,Kc as R,Gc as S,Jc as T,bn as U,Ro as V,Po as W,zc as X,_o as Y,Eo as Z,Yc as _};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-BHKWXFJD.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-
|
|
1
|
+
import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-4BCAH7XI.js";import{b as R}from"./chunk-2GIDVZ4H.js";import{v as C,w as I}from"./chunk-DXJRMPGH.js";import{b as v,c as W}from"./chunk-QOYAX2FT.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function nt(n,a,o,t={}){let u=t.selectorModel??"haiku",g=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,s=t.maxArticles??8,h=t.timeoutMs??6e4,p=t.log??console.error.bind(console,"[wiki-query]"),m=t.messagePath?.length?t.messagePath:void 0,w=t.graphWeight??$,i=x(a.baseDir,"_index.md");if(!B(i))return A("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let e=Y(i,"utf-8"),d=Date.now(),f=[],y="";try{let c=await G(n,a,o,l,m,w);c?(f=c,y=`[wiki-rerank seat] ${c.map(k=>k.title).join(" | ")}`):(y=await Q(q(n,e,l,m),u,h),f=K(y))}catch(c){return p("selector failed:",c?.message),{...A("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-d,synthesisMs:0,selectorOutput:y}}}let S=Date.now()-d;if(f.length===0)return{...A("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let b=F(f,a,o,r,s);if(b.length===0)return{...A("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let M=Date.now(),P="";try{P=await Q(J(n,b),g,h*2)}catch(c){return p("synthesis failed:",c?.message),{...A("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:f,walked:b.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:S,synthesisMs:Date.now()-M,selectorOutput:y}}}let E=Date.now()-M;return{answer:P.trim(),citations:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:f,walked:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:S,synthesisMs:E,selectorOutput:y}}}function A(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,u){let g=new Map;for(let s of a.listArticles(o||""))g.set(s.meta.title.toLowerCase(),s.path);let l=new Map,r=[];for(let s of n)l.has(s.path)||r.push({path:s.path,hop:0});for(;r.length&&l.size<u;){let s=r.shift();if(l.has(s.path)||s.hop>t)continue;let h=o?a.readArticleAs(s.path,o):a.readArticle(s.path);if(h&&(l.set(s.path,{...h,hop:s.hop}),!(s.hop>=t)))for(let p of h.meta.related||[]){let m=g.get(p.toLowerCase());m&&!l.has(m)&&r.push({path:m,hop:s.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,u,g=$){try{let r=(a.rebuildIndex().articles??[]).filter(i=>i.path&&!i.path.includes("/_versions/"));if(r.length<2)return null;let h=H(n,r,u,g).slice(0,O).map(i=>({id:`k${i}`,title:r[i].title||r[i].path,tags:r[i].tags,excerpt:[r[i].type?`type: ${r[i].type}`:"",(r[i].related??[]).length?`related: ${(r[i].related??[]).join(", ")}`:"",(r[i].graphPath??[]).length?`graph: ${(r[i].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),p=await C(j,T({query:n,candidates:h,excerptChars:300}),D(h),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!p||p.mode!=="active")return null;let w=_(p.answers,h).ranked.slice(0,t).map(i=>r[Number(i.slice(1))]).filter(Boolean).map(i=>({title:i.title,path:i.path}));return w.length>0?w:null}catch{return null}}var $=.6;function H(n,a,o,t=$){let u=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),g=W(n,v(u)),l=g.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(g.map(e=>[e.docIndex,l>0?e.score/l:0])),s=!!o?.length,h=e=>s&&e.graphPath?.length?N(o,e.graphPath):0,p=(e,d)=>d.score-e.score||e.i-d.i,m=a.map((e,d)=>({i:d,score:(r.get(d)??0)*(1+t*h(e))})).filter(e=>r.has(e.i)).sort(p),w=a.map((e,d)=>({i:d,score:h(e)})).filter(e=>!r.has(e.i)&&e.score>0).sort(p),i=[...m,...w].map(e=>e.i);for(let e=0;e<a.length;e++)i.includes(e)||i.push(e);return i}function q(n,a,o,t){let u=t?.length?`
|
|
2
2
|
## Intent
|
|
3
3
|
|
|
4
4
|
The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
|
|
@@ -46,4 +46,4 @@ ${o}
|
|
|
46
46
|
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
47
47
|
|
|
48
48
|
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[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 Q(n,a,o){let{writeFileSync:t,mkdirSync:u,rmSync:g}=await import("fs"),{tmpdir:l}=await import("os"),r=x(l(),`agentx-wiki-query-${process.pid}`);u(r,{recursive:!0});let s=x(r,`prompt-${Date.now()}.txt`);t(s,n);try{let h=`cat '${s}' | claude -p - --output-format json --max-turns 1 --model ${a} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,p=L(h,{env:R({...process.env}),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let m=JSON.parse(p);return String(m.result||m.content||"")}catch{return p}}finally{try{g(s,{force:!0})}catch{}}}export{nt as a,$ as b,H as c};
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-BTLW2RML.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{ca as m,da as $,ha as x}from"./chunk-
|
|
1
|
+
import{ca as m,da as $,ha as x}from"./chunk-JREA25GJ.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(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 J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
|
|
2
2
|
`);return{success:!1,path:o,error:`Validation failed:
|
|
3
3
|
${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
|
|
4
4
|
`)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(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 N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(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{w as a,J as b,N as c,j as d,A as e};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-DRUEPGLP.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as gt}from"./chunk-FX3D7YON.js";import{a as ne,b as We}from"./chunk-FCPTN6NF.js";import{o as we,p as He}from"./chunk-5MUJZODV.js";import{ga as Ze,ha as et}from"./chunk-
|
|
1
|
+
import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as gt}from"./chunk-FX3D7YON.js";import{a as ne,b as We}from"./chunk-FCPTN6NF.js";import{o as we,p as He}from"./chunk-5MUJZODV.js";import{ga as Ze,ha as et}from"./chunk-JREA25GJ.js";import{a as ot,b as st,c as it,d as at,e as ct,f as ut,g as lt,h as dt,i as pt,j as mt,k as bt,l as ft}from"./chunk-RGDKHYY2.js";import{a as E,b as Ke,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function yt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import ht from"better-sqlite3";import{createHash as wt}from"crypto";import{mkdirSync as Tt}from"fs";import{dirname as Et,resolve as kt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function xt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function St(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&_t(e),t<2&&Rt(e),t<3&&At(e)}function At(e){e.exec(`
|
|
2
2
|
ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
|
|
3
3
|
INSERT INTO schema_version (v) VALUES (3);
|
|
4
4
|
`)}function Rt(e){e.exec(`
|
|
@@ -111,4 +111,4 @@ import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";im
|
|
|
111
111
|
`)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${h}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let x=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=x.answer,x.repaired&&(L=!0)}return{model:a,answers:M,usage:y,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Vt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:U,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:U}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===U),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function zt(e,t,r,n,o){let s=[r,ae(t)].join(`
|
|
112
112
|
`),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Jt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Gt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Bt,qt,Xt,Ue,$t,be=E(()=>{"use strict";He();Fe();gt();j();Y();v();z();Bt="claude-code",qt="claude-haiku-4-5-20251001",Xt=24e3,Ue=2e3,$t=3e4});import{readFileSync as Yt}from"fs";import{homedir as Kt}from"os";import{join as Ht}from"path";function N(e={}){let t=(e.baseUrl??Wt).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??en,s=e.maxChoiceOptions??tn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),sn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=an(a.abortSignal,a.timeoutMs??e.timeoutMs??Zt);try{let b={"Content-Type":"application/json"},y=on(e.apiKeyEnv,e.apiKeyFile);y&&(b.Authorization=`Bearer ${y}`);let w=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:rn(a.questions)}),signal:g}),g);if(!w.ok){let k=await w.text().catch(()=>"");throw new Error(`${n} ${w.status}: ${k.slice(0,300)}`)}let f=await qe(w.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
|
|
113
113
|
${F(m.error)}`);let h=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let x=_(q,h[k]);M[k]=x.answer,x.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function rn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:nn[n.type]};return t}function on(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Ht(Kt(),t.slice(2)):t;if(!Z.has(n))try{let o=Yt(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function sn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function an(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Wt,Zt,en,tn,nn,Z,fe=E(()=>{"use strict";j();v();z();Y();Wt="http://127.0.0.1:8000/v1",Zt=3e4,en=6e3,tn=50;nn={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};Ke(Xe,{DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>U,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>yt,agreement:()=>ot,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>dt,askSeat:()=>mn,band:()=>Ie,bootstrapInterval:()=>mt,brier:()=>ct,buildDesign:()=>ve,calibrationReport:()=>bt,choice:()=>nt,compareCalibrators:()=>Dt,confidenceFor:()=>re,configureDecisions:()=>un,coverageCurve:()=>lt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>dn,describeIssues:()=>F,ece:()=>it,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>pt,getDecisionBackend:()=>D,getSeatMode:()=>ze,labelsOf:()=>S,listDecisionBackends:()=>Ee,logLoss:()=>ut,logit:()=>le,mce:()=>at,measureConsistency:()=>jt,normalizeDistribution:()=>xe,normalizedNegEntropy:()=>oe,noul:()=>tt,pMax:()=>Se,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>pn,registerBuiltinDecisionBackends:()=>cn,registerDecisionBackend:()=>R,reliabilityBins:()=>st,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>ln,score:()=>rt,seatEnvVar:()=>Ve,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function cn(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();ft();Me();je();Je();pe();be();fe();C();pe();be();fe()});function un(e){T={...ye,...T,...e},ee=!0}function ln(){T={...ye,seats:{}},ee=!1}function bn(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(et(),he(Ze)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}T={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function dn(){return T}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return fn.includes(t)?t:null}function Ve(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function ze(e,t=process.env){bn();let r=ge(t[Ve(e)]);return r||(T.enabled?ge(T.seats[e]?.mode)??"off":"off")}function pn(e,t,r=!1){if(!(!e||!T.store))try{T.store.recordOutcome(e,t,r)}catch{}}async function mn(e,t,r,n={}){let o=ze(e);if(o==="off")return null;let s=T.seats[e]??{mode:o},i=n.backend??s.backend??T.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs}),l=gn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return yn(e,o,t,r,i,n,s,a,u),hn(e,i,u),null}}function gn(e,t,r,n,o,s,i){if(!T.store)return null;try{return T.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:Ye(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function yn(e,t,r,n,o,s,i,a,u){if(T.store)try{T.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:Ye(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function Ye(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function hn(e,t,r){let n=Date.now();n-Ge<6e4||(Ge=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var ye,T,ee,fn,Ge,Je=E(()=>{C();V();ye={enabled:!1,defaultBackend:"local",seats:{},store:null},T={...ye},ee=!1;fn=["off","shadow","active"];Ge=0});export{D as a,Ee as b,C as c,I as d,V as e,Dt as f,Me as g,jt as h,je as i,me as j,Un as k,Fe as l,cn as m,$e as n,un as o,ln as p,dn as q,ge as r,Ve as s,ze as t,pn as u,mn as v,Je as w};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-DXJRMPGH.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{ea as m,ha as b}from"./chunk-
|
|
1
|
+
import{ea as m,ha as b}from"./chunk-JREA25GJ.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
|
|
2
2
|
|
|
3
3
|
`))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
|
|
4
4
|
`))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-GJ5EJVMZ.js.map
|