agentix-cli 0.45.1 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-YC3VJVPK.js → agent-LI3AZQBC.js} +2 -2
- package/dist/{board-dashboard-U5YP4HWE.js → board-dashboard-IE2P6QFU.js} +2 -2
- package/dist/{board-dashboard-U5YP4HWE.js.map → board-dashboard-IE2P6QFU.js.map} +1 -1
- package/dist/chunk-CTCOWVNL.js +241 -0
- package/dist/chunk-CTCOWVNL.js.map +1 -0
- package/dist/chunk-DP7RTNDM.js +24 -0
- package/dist/chunk-DP7RTNDM.js.map +1 -0
- package/dist/{chunk-SAFAI4AV.js → chunk-E6EW42EA.js} +2 -2
- package/dist/chunk-FRHSQVFN.js +3 -0
- package/dist/chunk-FRHSQVFN.js.map +1 -0
- package/dist/chunk-GAUQOIEE.js +160 -0
- package/dist/chunk-GAUQOIEE.js.map +1 -0
- package/dist/{chunk-3FIS6JD3.js → chunk-NVVXVUQU.js} +2 -2
- package/dist/{chunk-MDAC3PKR.js → chunk-Q6EBTCEZ.js} +160 -399
- package/dist/chunk-Q6EBTCEZ.js.map +1 -0
- package/dist/chunk-RY2EULHS.js +2 -0
- package/dist/chunk-RY2EULHS.js.map +1 -0
- package/dist/chunk-SGFXE5FP.js +109 -0
- package/dist/chunk-SGFXE5FP.js.map +1 -0
- package/dist/{chunk-KZYNQRQQ.js → chunk-Y3SVZ6VS.js} +124 -122
- package/dist/chunk-Y3SVZ6VS.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/program-BIMB44HN.js +2 -0
- package/dist/promote-R6WVBMT7.js +2 -0
- package/dist/proposals-MWMEXRDW.js +2 -0
- package/dist/registry-STML35CV.js +2 -0
- package/dist/registry-STML35CV.js.map +1 -0
- package/dist/review-candidates-ROFQR6XE.js +4 -0
- package/dist/review-candidates-ROFQR6XE.js.map +1 -0
- package/dist/wiki-LGHX3WPI.js +2 -0
- package/dist/wiki-LGHX3WPI.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-3RKIBJG6.js +0 -182
- package/dist/chunk-3RKIBJG6.js.map +0 -1
- package/dist/chunk-KZYNQRQQ.js.map +0 -1
- package/dist/chunk-MDAC3PKR.js.map +0 -1
- package/dist/chunk-MTVRYTLL.js +0 -109
- package/dist/chunk-MTVRYTLL.js.map +0 -1
- package/dist/program-WLPVWTAT.js +0 -2
- package/dist/registry-EESWAPMR.js +0 -2
- package/dist/review-candidates-BFAWNDOR.js +0 -4
- package/dist/review-candidates-BFAWNDOR.js.map +0 -1
- package/dist/wiki-5JORBO4G.js +0 -2
- /package/dist/{agent-YC3VJVPK.js.map → agent-LI3AZQBC.js.map} +0 -0
- /package/dist/{chunk-SAFAI4AV.js.map → chunk-E6EW42EA.js.map} +0 -0
- /package/dist/{chunk-3FIS6JD3.js.map → chunk-NVVXVUQU.js.map} +0 -0
- /package/dist/{program-WLPVWTAT.js.map → program-BIMB44HN.js.map} +0 -0
- /package/dist/{registry-EESWAPMR.js.map → promote-R6WVBMT7.js.map} +0 -0
- /package/dist/{wiki-5JORBO4G.js.map → proposals-MWMEXRDW.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/proposals.ts"],"sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// --- Promotion proposals: lessons wait for a human before the wiki ---\n//\n// `wiki promote` used to write public, org-wide articles straight into the\n// shared wiki from a nightly job. A wrong lesson, or one planted through a\n// poisoned memory, reached every agent the next morning. Now the judge's\n// output becomes a proposal here, with the evidence that produced it, and\n// only an operator's approval writes the article (promote.ts).\n//\n// Storage only: one JSON file per proposal under `<wiki>/_proposals/`.\n// The wiki index skips `_`-prefixed folders, so pending proposals are\n// invisible to agents.\n\nexport type ProposalStatus = \"pending\" | \"approved\" | \"rejected\"\n\n/** The article the judge wants to write. Same shape as PromotedArticle. */\nexport interface ProposedArticle {\n path: string\n title: string\n type?: string\n related?: string[]\n tags: string[]\n content: string\n promotedFrom: string[]\n}\n\n/** One memory or review finding behind the proposal. */\nexport interface ProposalSource {\n stamp: string\n kind: \"memory\" | \"review\"\n agentId: string\n type: string\n name: string\n description: string\n /** Distinct sessions a review finding appeared in. */\n occurrences?: number\n /** Some of those sessions, for a reviewer to open. */\n sessions?: string[]\n /** Who wrote the memory, and in which task (agent-memory provenance). */\n author?: string\n taskId?: string\n updatedAt: string\n /** Start of the memory body. */\n excerpt: string\n}\n\nexport interface ProposalEvidence {\n /** Agents whose memories or reviews back it. */\n agents: string[]\n /** Highest recurrence among its sources (1 for plain memories). */\n occurrences: number\n sources: ProposalSource[]\n}\n\nexport interface PromotionProposal {\n id: string\n createdAt: string\n status: ProposalStatus\n article: ProposedArticle\n evidence: ProposalEvidence\n /** Set when the article already existed: approval refuses if it has\n * changed since, so a proposal can't silently revert someone's edit. */\n replaces?: { lastUpdated: string; contentHash: string }\n decidedBy?: string\n decidedAt?: string\n reason?: string\n}\n\nexport function proposalsDir(wikiDir: string): string {\n return resolve(wikiDir, \"_proposals\")\n}\n\nfunction fileFor(wikiDir: string, id: string): string {\n if (!/^[a-z0-9-]+$/.test(id)) throw new Error(`invalid proposal id: ${id}`)\n return resolve(proposalsDir(wikiDir), `${id}.json`)\n}\n\nexport function newProposalId(now: number, path: string): string {\n const day = new Date(now).toISOString().slice(0, 10)\n const slug = path.replace(/\\.md$/, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 48)\n return `${day}-${slug || \"article\"}-${Math.random().toString(36).slice(2, 6)}`\n}\n\nexport function saveProposal(wikiDir: string, p: PromotionProposal): void {\n mkdirSync(proposalsDir(wikiDir), { recursive: true })\n const path = fileFor(wikiDir, p.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(p, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\nexport function readProposal(wikiDir: string, id: string): PromotionProposal | null {\n try {\n return JSON.parse(readFileSync(fileFor(wikiDir, id), \"utf-8\")) as PromotionProposal\n } catch {\n return null\n }\n}\n\n/** Proposals, oldest first; only `status` ones when given. */\nexport function listProposals(wikiDir: string, status?: ProposalStatus): PromotionProposal[] {\n const dir = proposalsDir(wikiDir)\n if (!existsSync(dir)) return []\n const out: PromotionProposal[] = []\n for (const f of readdirSync(dir).filter((f) => f.endsWith(\".json\")).sort()) {\n const p = readProposal(wikiDir, f.slice(0, -5))\n if (p && (!status || p.status === status)) out.push(p)\n }\n return out\n}\n"],"mappings":"AAAA,OAAS,cAAAA,EAAY,aAAAC,EAAW,eAAAC,EAAa,gBAAAC,EAAc,cAAAC,EAAY,iBAAAC,MAAqB,KAC5F,OAAS,WAAAC,MAAe,OAqEjB,SAASC,EAAaC,EAAyB,CACpD,OAAOF,EAAQE,EAAS,YAAY,CACtC,CAEA,SAASC,EAAQD,EAAiBE,EAAoB,CACpD,GAAI,CAAC,eAAe,KAAKA,CAAE,EAAG,MAAM,IAAI,MAAM,wBAAwBA,GAAI,EAC1E,OAAOJ,EAAQC,EAAaC,CAAO,EAAG,GAAGE,QAAS,CACpD,CAEO,SAASC,EAAcC,EAAaC,EAAsB,CAC/D,IAAMC,EAAM,IAAI,KAAKF,CAAG,EAAE,YAAY,EAAE,MAAM,EAAG,EAAE,EAC7CG,EAAOF,EAAK,QAAQ,QAAS,EAAE,EAAE,YAAY,EAAE,QAAQ,cAAe,GAAG,EAAE,QAAQ,WAAY,EAAE,EAAE,MAAM,EAAG,EAAE,EACpH,MAAO,GAAGC,KAAOC,GAAQ,aAAa,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,EAAG,CAAC,GAC7E,CAEO,SAASC,EAAaR,EAAiBS,EAA4B,CACxEhB,EAAUM,EAAaC,CAAO,EAAG,CAAE,UAAW,EAAK,CAAC,EACpD,IAAMK,EAAOJ,EAAQD,EAASS,EAAE,EAAE,EAC5BC,EAAM,GAAGL,KAAQ,QAAQ,UAC/BR,EAAca,EAAK,KAAK,UAAUD,EAAG,KAAM,CAAC,EAAI;AAAA,CAAI,EACpDb,EAAWc,EAAKL,CAAI,CACtB,CAEO,SAASM,EAAaX,EAAiBE,EAAsC,CAClF,GAAI,CACF,OAAO,KAAK,MAAMP,EAAaM,EAAQD,EAASE,CAAE,EAAG,OAAO,CAAC,CAC/D,MAAE,CACA,OAAO,IACT,CACF,CAGO,SAASU,EAAcZ,EAAiBa,EAA8C,CAC3F,IAAMC,EAAMf,EAAaC,CAAO,EAChC,GAAI,CAACR,EAAWsB,CAAG,EAAG,MAAO,CAAC,EAC9B,IAAMC,EAA2B,CAAC,EAClC,QAAWC,KAAKtB,EAAYoB,CAAG,EAAE,OAAQE,GAAMA,EAAE,SAAS,OAAO,CAAC,EAAE,KAAK,EAAG,CAC1E,IAAMP,EAAIE,EAAaX,EAASgB,EAAE,MAAM,EAAG,EAAE,CAAC,EAC1CP,IAAM,CAACI,GAAUJ,EAAE,SAAWI,IAASE,EAAI,KAAKN,CAAC,EAEvD,OAAOM,CACT","names":["existsSync","mkdirSync","readdirSync","readFileSync","renameSync","writeFileSync","resolve","proposalsDir","wikiDir","fileFor","id","newProposalId","now","path","day","slug","saveProposal","p","tmp","readProposal","listProposals","status","dir","out","f"]}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import{a as En,g as Un,m as Bn}from"./chunk-TCJ3SMOF.js";import{a as wt}from"./chunk-QLTM3F7M.js";import{b as Nn}from"./chunk-DP7RTNDM.js";import{b as Fn}from"./chunk-BIFJSQB5.js";import{a as It,b as Ln}from"./chunk-WPMX3VGI.js";import{a as St,b as Hn}from"./chunk-K33GIBSE.js";import{a as jn}from"./chunk-W4YR2RO2.js";import{a as kn}from"./chunk-ICZPZYYR.js";import{a as In,b as Sn,c as vn,d as Cn,f as An}from"./chunk-DWADWDMU.js";import{a as $n,b as Mn,c as xt,d as Tt,e as Pn,f as kt,g as Rn}from"./chunk-CQR6C5FU.js";import{a as On}from"./chunk-RY2EULHS.js";import{b as _n,c as Dn}from"./chunk-SGFXE5FP.js";import{a as Je,c as Ae}from"./chunk-2GIDVZ4H.js";import{q as wn,t as xn,v as me,w as Tn}from"./chunk-6HMZ5TTM.js";import{a as Ce,b as Ge,f as bt}from"./chunk-F4HZTZHW.js";import{a as he,b as ft}from"./chunk-ZTEU5JVQ.js";import{c as Ke,d as qe}from"./chunk-QOYAX2FT.js";import{e as ue}from"./chunk-DSYKYZMT.js";import{d as fn,e as re,f as yn,g as bn,h as yt}from"./chunk-QJANPP4C.js";Tn();bt();var Wn="session-continuity",Kn={continues:Ce("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:Ce("Does the new request refer to something stated earlier in the conversation?")};function qn(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:vt(s.message,1200),previousRequest:s.previousMessage?vt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>vt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function Gn(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 vt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as Hr,execFile as jr}from"node:child_process";import{createHash as Ur,randomBytes as Br}from"node:crypto";import{createInterface as Wr}from"node:readline";import{promisify as Kr}from"node:util";var qr=Kr(jr),oe=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},Ct=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=qr("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new oe("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=Ur("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([u],[l])=>u.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new oe("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let p=[...this.entries].find(([,h])=>!h.busy);if(!p)throw new oe("Warm server capacity reached",!0);this.close(p[1]),this.entries.delete(p[0])}let u={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:Br(32).toString("hex")},l=Hr("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:u,stdio:["pipe","pipe","pipe"]});o={child:l,env:u,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let d=o;l.stderr.resume(),l.on("exit",()=>this.close(d)),l.on("error",()=>this.close(d));try{await new Promise((p,h)=>{let x=Wr({input:l.stdout}),T=()=>g(new oe("OpenCode server failed before dispatch",!0)),w=()=>g(new Error("task cancelled by operator")),I=setTimeout(T,15e3),g=_=>{clearTimeout(I),l.removeListener("exit",T),l.removeListener("error",T),e.signal?.removeEventListener("abort",w),x.close(),l.stdout.resume(),_?h(_):p()};l.once("exit",T),l.once("error",T),e.signal?.addEventListener("abort",w,{once:!0}),x.on("line",_=>{try{let A=new URL(JSON.parse(_).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;d.url=A.origin,g()}catch{}}),e.signal?.aborted&&w()})}catch(p){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),p}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(u=!1)=>{c||(c=!0,a.busy=!1,u||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},Jn=new Ct;import{execa as Ze}from"execa";import{spawn as Gr}from"node:child_process";import{createHash as Jr}from"node:crypto";import{createInterface as Qr}from"node:readline";var ie=class extends Error{},zr=s=>Gr("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),At=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(),Qr({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
|
+
`)}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()}},$t=class{constructor(e=zr,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=Jr("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[I])=>w.localeCompare(I))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ie("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 w=[...this.entries].find(([,I])=>!I.connection.busy);if(!w)throw new ie("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:n,connection:new At(e,this.launchProcess)}}catch{throw new ie("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,c="",u,l,d,p=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let x=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),T=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 w={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",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(T),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let g=new Promise((_,A)=>{i.failTurn=A,i.notify=(S,y)=>{if(y?.threadId!==l)return;let O=y.item,C={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...y,type:S.replace("/","."),...O?{item:{...O,type:C[O.type]||O.type}}:{}}),S==="item/completed"&&O?.type==="agentMessage"&&O.phase==="final_answer"&&(u=O.text),S==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=y.delta,e.onDelta?.(y.delta,c)),S==="thread/tokenUsage/updated"){let E=y.tokenUsage.last,F=E.cachedInputTokens||0;d={inputTokens:(d?.inputTokens||0)+Math.max(0,(E.inputTokens||0)-F),outputTokens:(d?.outputTokens||0)+(E.outputTokens||0),cacheReadTokens:(d?.cacheReadTokens||0)+F,cacheCreateTokens:(d?.cacheCreateTokens||0)+(E.cacheWriteInputTokens||0)}}S==="turn/completed"&&(y.turn.status==="completed"?_():A(new Error(y.turn.error?.message||`Codex turn ${y.turn.status}`)))}});return g.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await g,{content:u??c,codexSessionId:l,billedModel:e.model,usage:d,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new ie(w.message);return{content:c,codexSessionId:l,usage:d,error:w.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(x),e.signal?.removeEventListener("abort",h),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())}}},Qn=new $t;import{execFile as uo}from"child_process";import{StringDecoder as Pe}from"string_decoder";import{mkdtempSync as cs,readFileSync as ds,rmSync as us}from"fs";import{join as Ye}from"path";import{tmpdir as ls}from"os";function Qe(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 u=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${u?` Resets ${u[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),c=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"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===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"||c===529||c===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"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,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 ze(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var zn=null;function Xe(){return zn}function aa(s){zn=s}function $e(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var fe=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Xn=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=$e(e),r=this.handles.get(n);if(r&&r.state()!=="dead")return r.claim?.(),r;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 fe(`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 fe(`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=$e(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=$e(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=$e(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=$e(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(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",u=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${u})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${u})`)}}}}}};import{spawn as Xr}from"child_process";import{existsSync as Yr,readFileSync as Vr}from"fs";import{resolve as Zr}from"path";function eo(s){let e=Zr(s,"CLAUDE.md");if(!Yr(e))return null;try{let t=Vr(e,"utf8");return An(t)}catch{return null}}var to=20*60*1e3,no=5e3,Me=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Yn=class{constructor(e={}){this.opts=e}spawn(e,t){return new Mt(e,t,this.opts)}},Mt=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=Xr(r,o,{cwd:t.workspace,env:Ae({...process.env},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:eo(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 c=this.waiters.splice(0);for(let u of c)u(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
|
+
`);let a=e.deadlineMs??to,c=o+a,u=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Me(a));try{for(;;){let l=c-Date.now();if(l<=0)throw u();let d=await this.nextEvent(l);if(d===null&&!this.exited)throw u();if(d===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:d.type,raw:d},d.type==="result"){this.onResultEvent(d);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)},no);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
|
+
`))!==-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"}}};yt();import{resolve as Vn,join as Zn}from"path";ft();var so=4e3;function es(s){try{let e=Zn(Vn(s.root),".agentx","db.sqlite"),t=wt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=he(),r=s.input.command?s.input.command.slice(0,so):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
5
|
+
(id, ts, agent_id, task_id, tool, command, resolved_target, matched_rule,
|
|
6
|
+
verdict, effective_action, mode, severity, approver, ms)
|
|
7
|
+
VALUES (@id, @ts, @agent_id, @task_id, @tool, @command, @resolved_target, @matched_rule,
|
|
8
|
+
@verdict, @effective_action, @mode, @severity, @approver, @ms)`).run({id:n,ts:Date.now(),agent_id:s.input.agentId??null,task_id:s.taskId??null,tool:s.input.tool,command:r,resolved_target:s.verdict.resolvedTarget,matched_rule:s.verdict.ruleId,verdict:s.verdict.action,effective_action:s.verdict.effectiveAction,mode:s.mode,severity:s.verdict.severity,approver:s.approver??null,ms:s.ms??null}),n}catch(e){return process.stderr.write(`[agentx-guard] audit write failed: ${e?.message}
|
|
9
|
+
`),null}}function wa(s){let e=Zn(Vn(s.root),".agentx","db.sqlite"),t=wt({path:e});if(!t)return[];let n=[],r={};s.verdict&&(n.push("verdict = @verdict"),r.verdict=s.verdict),s.agentId&&(n.push("agent_id = @agentId"),r.agentId=s.agentId),s.taskId&&(n.push("task_id = @taskId"),r.taskId=s.taskId);let o="SELECT * FROM guardrail_decisions"+(n.length?` WHERE ${n.join(" AND ")}`:"")+" ORDER BY ts DESC LIMIT @limit";return r.limit=s.limit??50,t.prepare(o).all(r)}yt();var ro=50,oo=6*60*60*1e3,Pt=null,ye=new Map;function Ia(s){Pt=s===null?null:String(s)}function io(s,e,t,n){let r=new URLSearchParams({agent:e,autonomy:t,task:n}).toString();return`curl -sf --max-time 10 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${s}/guard/check?${r}`}' || { echo '[agentx-autonomy] guard unreachable: tool call blocked (fail-closed)' >&2; exit 2; }`}function ns(s,e,t){if(!re(s))return{args:[]};if(!Pt)return{error:`autonomy "${s}" cannot be enforced: guard hook endpoint is not configured`};let n={hooks:{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:io(Pt,e,s,t),timeout:15}]}]}},r=[];return s==="report"&&r.push("--disallowedTools","Write,Edit,MultiEdit,NotebookEdit"),r.push("--settings",JSON.stringify(n)),{args:r}}function ss(s,e){return!re(s)||e==="claude-code"?null:`autonomy "${s}" is only enforceable on the claude-code tier (agent tier: ${e??"unknown"}); refusing to run it with full permissions`}function ao(s){for(let[e,t]of ye)s-t.at>oo&&ye.delete(e)}function co(s,e){let t=Date.now();ao(t);let n=ye.get(s)??{at:t,blocks:[]};n.blocks.length<ro&&n.blocks.push(e),n.at=t,ye.set(s,n)}function rs(s){if(!s)return[];let e=ye.get(s);return ye.delete(s),e?.blocks??[]}function ts(s){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:s}})}function Sa(s,e){let t=s.tool_name??"unknown",n=typeof s.tool_input?.command=="string"?s.tool_input.command:void 0,r=typeof s.tool_input?.file_path=="string"?s.tool_input.file_path:typeof s.tool_input?.notebook_path=="string"?s.tool_input.notebook_path:void 0;try{let o=fn.safeParse(e.level),i=o.success?yn(o.data,{tool:t,command:n,filePath:r}):{allowed:!1,ruleId:"autonomy.invalid",reason:`unknown autonomy level "${e.level}"`};if(i.allowed)return{stdout:"",blocked:null};let a=o.success?o.data:"report",c=i.ruleId??"autonomy",u=i.reason??"blocked",l={ts:Date.now(),tool:t,target:(n??r??null)?.slice(0,300)??null,ruleId:c,reason:u},d={matched:!0,action:"deny",effectiveAction:"deny",ruleId:c,severity:"high",message:u,resolvedTarget:null};return es({root:e.root,input:{tool:t,command:n??(r?void 0:t),filePath:r,agentId:e.agentId},verdict:d,mode:"enforce",taskId:e.taskId??null}),e.taskId&&co(e.taskId,l),{stdout:ts(`[agentx-autonomy] Blocked: this routine runs at autonomy "${a}" and ${u} (rule: ${c}). Do not work around it. Finish the task within the limit and list this step in your final answer as a recommendation.`),blocked:l}}catch(o){return{stdout:ts(`[agentx-autonomy] Guard error (fail-closed): ${o?.message??o}`),blocked:null}}}function q(s){let e=Qe(s);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(s||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
|
|
10
|
+
`)}return{error:ze(e),errorKind:e.kind}}function gs(){return`Claude Code CLI not found on PATH. Install it before starting an agent: https://docs.claude.com/en/docs/claude-code . On Linux/macOS: npm i -g @anthropic-ai/claude-code then verify with claude --version. If you don't intend to use the claude-code engine, set the agent's tier to "sdk" or "orchestrator" in agentx.json.`}function Ve(){return`Codex CLI not found on PATH. Install it before starting an agent: npm i -g @openai/codex then verify with codex --version. If you don't intend to use the codex-cli engine, set the agent's tier to "claude-code", "sdk", or "orchestrator" in agentx.json.`}function os(){return`OpenCode CLI not found on PATH. Install it from https://opencode.ai/docs/ and verify with opencode --version. If you don't intend to use the opencode engine, set the agent's tier to "claude-code", "codex-cli", "sdk", or "orchestrator" in agentx.json.`}function ce(s,e,t){let n=[];if(e.context&&!t){let r=e.context,o=["","[Environment]"],i=r.channel==="gitlab"||r.channel?.startsWith("webhook:"),a=r.channel==="telegram";if(r.channel&&o.push(`Channel: ${r.channel}`),r.group&&o.push(`Group: ${r.group}`),r.sender&&o.push(`Message from: ${r.sender}`),r.myHandle&&o.push(`Your handle on this channel: ${r.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&r.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of r.peers){let u=c.handle?` (mention: ${c.handle})`:"",l=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${u}${l}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(o.join(`
|
|
11
|
+
`))}return e.context?.replyToText&&(n.push(""),n.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(n.push(""),n.push(`[Attached file: ${e.context.mediaPath}]`),n.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?n.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?n.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?n.push("A video file is attached. Describe what you can determine about it."):n.push("Please read this file and respond based on its content.")),t&&(n.push(""),n.push(t)),n.push(""),n.push(e.message),n.join(`
|
|
12
|
+
`)}function ps(s,e,t,n,r,o,i=[]){let a=["-p",e,"--output-format",t?"stream-json":"json"];t&&a.push("--verbose"),n&&a.push("--resume",n);let c=r||s.model;return c&&a.push("--model",c),s.permissionMode==="bypassPermissions"&&a.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&a.push("--append-system-prompt",o),a.push(...i),a}function Rt(s,e){return!e||e.trim().length===0?s:`[System]
|
|
13
|
+
${e.trim()}
|
|
14
|
+
|
|
15
|
+
[User]
|
|
16
|
+
${s}`}function lo(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s.model;return i&&o.push("--model",i),r&&o.push("--session",r),s.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(Rt(e,n)),o}function go(s){if(!s||typeof s!="object"||s.type!=="error")return;let e=s.error?.message??s.error??s.message??s.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function is(s){return JSON.stringify(s)}function hs(){let s=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${is(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[s,"serve","--stdio","--cwd",process.cwd()].map(is).join(",")}]`]}function ms(s,e,t,n,r,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...hs()),i||a.push("--color","never");let c=n||s.model;return c&&a.push("--model",c),s.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(Rt(e,r)),a}function et(s,e){let t=Je(s.workspace),n=t.HOME||process.env.HOME,r=[t.PATH||"",n?`${n}/.bun/bin`:"",n?`${n}/.local/bin`:"",n?`${n}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(r.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),_t(t,e)}function _t(s,e){return s.AGENTX_AGENT_ID=e.agentId,e.runningTaskId&&(s.AGENTX_TASK_ID=e.runningTaskId),e.context?.channel&&(s.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(s.AGENTX_CHAT_ID=e.context.chatId),s}function po(s,e){let t=et(s,e),n={};if(t.OPENCODE_CONFIG_CONTENT)try{n=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let r={...n.mcp||{}};for(let[i,a]of Object.entries(s.mcp||{}))r[i]=a.type==="http"?{type:"remote",url:a.url,headers:a.headers}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return r.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...n,mcp:r}),t}function ho(s){if(!s||typeof s!="object")return;if(typeof s.delta=="string")return s.delta;if(typeof s.text_delta=="string")return s.text_delta;if(typeof s.message=="string"&&/message|delta/i.test(String(s.type||"")))return s.message;if(typeof s.text=="string"&&/message|delta|response/i.test(String(s.type||"")))return s.text;let e=s.item||s.msg||s.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(s.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let n=t.map(r=>typeof r?.text=="string"?r.text:"").join("");if(n)return n}}function ae(...s){for(let e of s)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function Dt(s,e=0){if(!s||typeof s!="object"||e>4)return;let t=s.usage||s.token_usage||s.tokenUsage||s.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:ae(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ae(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ae(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ae(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[s.msg,s.message,s.response,s.result,s.item]){let r=Dt(n,e+1);if(r)return r}}function fs(s){if(!(!s||typeof s!="object"))return typeof s.model=="string"&&s.model||typeof s.msg?.model=="string"&&s.msg.model||typeof s.message?.model=="string"&&s.message.model||typeof s.response?.model=="string"&&s.response.model||void 0}function Ot(s,e=0){if(!(!s||typeof s!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let n=s[t];if(typeof n=="string"&&n.trim())return n.trim()}for(let t of[s.msg,s.message,s.response,s.result,s.item]){let n=Ot(t,e+1);if(n)return n}}}function mo(s){let e=typeof s=="string"?s:s?.toString("utf8")||"",t,n,r,o;for(let i of e.split(`
|
|
17
|
+
`))if(i.trim())try{let a=JSON.parse(i);t=Dt(a)||t,n=fs(a)||n,r=Ot(a)||r,o=ys(a)||o}catch{}return{usage:t,billedModel:n,sessionId:r,apiError:o}}function ys(s){if(!(!s||typeof s!="object")){if(s.type==="error"&&typeof s.message=="string")return as(s.message);if(s.type==="turn.failed"){let e=s.error?.message??s.error;if(typeof e=="string")return as(e)}}}function as(s){let e=s.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),n=t?.error?.message??t?.message;if(typeof n=="string"&&n.trim())return n.trim()}catch{}return e}function fo(s){let e=s.permissionMode||"default",t=e==="bypassPermissions",n=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:n}}function Et(s,e,t,n,r){let o=fo(e),i=t||e.model||"<default>",a=n?` resume=${n.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${s} via=${r} model=${i} perm=${o.summary}${a}
|
|
18
|
+
`)}function yo(s){try{let e=JSON.parse(s);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function bo(s){try{let e=JSON.parse(s),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,n=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:n,numTurns:typeof e.num_turns=="number"?e.num_turns:void 0}}catch{return{text:s}}}async function bs(s,e,t,n,r){let o=Date.now(),i=ce(s,e,t),a=xs(e);if("error"in a)return{content:"",error:a.error,duration:Date.now()-o};let c=ps(s,i,!1,n,e.model,e.systemPromptAppend,a.args);if(Et(e.agentId,s,e.model,n,"spawn"),r?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let u;try{let l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),{stdout:d,stderr:p,exitCode:h,killed:x}=await new Promise(I=>{let g=Ae(_t(Je(s.workspace),e),s.billing),_=!1,A=uo("claude",c,{cwd:s.workspace,timeout:l,maxBuffer:10*1024*1024,env:{...g,HOME:g.HOME||"/home/"+(g.USER||"user")}},(S,y,O)=>{I({stdout:y||"",stderr:O||"",exitCode:S?S.code??1:0,killed:_})});if(A.stdin?.end(),r){let S=()=>{_=!0,u=r.reason?.message||(typeof r.reason=="string"?r.reason:"task cancelled by operator");try{A.kill("SIGTERM")}catch{}setTimeout(()=>{try{A.killed||A.kill("SIGKILL")}catch{}},3e3).unref?.()};r.aborted?S():r.addEventListener("abort",S,{once:!0})}});if(x)return{content:"",error:u||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!d&&h!==0){let I;return h===143?I=`Claude Code timed out after ${Math.round(l/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:h==="ENOENT"||/ENOENT|spawn claude/i.test(p||"")?I=gs():I=p?.trim()||`Claude Code exited with code ${h}`,{content:"",...q(I),duration:Date.now()-o}}let T=yo(d);if(T)return{content:"",...q(T),duration:Date.now()-o};let w=bo(d);return{content:w.text,duration:Date.now()-o,claudeSessionId:w.sessionId,usage:w.usage,numTurns:w.numTurns,billedModel:w.billedModel}}catch(l){return console.error(`[runtime] execFile threw: ${l.message}`),{content:"",error:l.message||"Claude Code failed",duration:Date.now()-o}}}async function ws(s,e,t,n,r,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=ce(s,e,n),u=xs(e);if("error"in u)return{content:"",error:u.error,duration:Date.now()-a};let l=ps(s,c,!0,r,e.model,e.systemPromptAppend,u.args);Et(e.agentId,s,e.model,r,"stream");let d="",p,h,x,T,w,I;try{let g=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),_=Ae(_t(Je(s.workspace),e),s.billing),A=Ze("claude",l,{cwd:s.workspace,timeout:g,reject:!1,env:_,extendEnv:!1,buffer:!1,stdin:"ignore"}),S=!1,y;if(i){let D=()=>{S=!0,y=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{A.kill("SIGTERM")}catch{}setTimeout(()=>{try{A.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?D():i.addEventListener("abort",D,{once:!0})}let O="",C=new Pe("utf8");A.stdout&&A.stdout.on("data",D=>{O+=C.write(D);let L=O.split(`
|
|
19
|
+
`);O=L.pop()||"";for(let v of L)if(v.trim())try{let b=JSON.parse(v);if(o)try{o(b)}catch{}if(b.type==="assistant"&&b.message?.usage){let k=b.message.usage,R=(k.input_tokens||0)+(k.cache_read_input_tokens||0)+(k.cache_creation_input_tokens||0);R>0&&(T=R)}if(b.type==="assistant"&&b.message?.content){for(let k of b.message.content)if(k.type==="text"&&k.text){let R=k.text.slice(d.length);R&&(d=k.text,t(R,d))}}if(b.type==="content_block_delta"&&b.delta?.text&&(d+=b.delta.text,t(b.delta.text,d)),b.type==="result"&&b.result){if(b.is_error&&typeof b.result=="string")I=b.result;else{let k=(typeof b.result=="string",b.result);if(typeof k=="string"&&k.length>d.length){let R=k.slice(d.length);d=k,R&&t(R,d)}}b.usage&&(h={inputTokens:b.usage.input_tokens||0,outputTokens:b.usage.output_tokens||0,cacheReadTokens:b.usage.cache_read_input_tokens||0,cacheCreateTokens:b.usage.cache_creation_input_tokens||0}),typeof b.model=="string"&&(p=b.model),typeof b.session_id=="string"&&(x=b.session_id),typeof b.num_turns=="number"&&(w=b.num_turns)}b.type==="system"&&b.subtype==="init"&&(typeof b.model=="string"&&(p=b.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${b.apiKeySource} version=${b.claude_code_version} model=${b.model} permMode=${b.permissionMode}
|
|
20
|
+
`))}catch{v.trim()&&!v.startsWith("{")&&(d+=v+`
|
|
21
|
+
`,t(v+`
|
|
22
|
+
`,d))}});let E=await A,F=C.end();if(F&&(O+=F),S)return{content:"",error:y||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!d&&E.stdout&&(d=typeof E.stdout=="string"?E.stdout:""),E.exitCode!==0&&!d){let D=typeof E.stderr=="string"?E.stderr:"",L=E,v;return L.timedOut?v=`Claude Code timed out after ${Math.round(g/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:L.signal?v=D.trim()||`Claude Code killed by signal ${L.signal}`:L.code==="ENOENT"||/ENOENT|spawn claude/i.test((L.shortMessage||"")+" "+D)?v=gs():v=D.trim()||`Claude Code exited with code ${L.exitCode??"unknown"}`,{content:"",...q(v),duration:Date.now()-a}}return I?{content:"",...q(I),duration:Date.now()-a,usage:h,contextTokens:T,numTurns:w,billedModel:p,claudeSessionId:x}:{content:d,duration:Date.now()-a,usage:h,contextTokens:T,numTurns:w,billedModel:p,claudeSessionId:x}}catch(g){return{content:d||"",...q(g.message),duration:Date.now()-a,usage:h,contextTokens:T,numTurns:w,billedModel:p,claudeSessionId:x}}}async function wo(s,e,t,n){let r=Date.now(),o=ce(s,e,t),i=cs(Ye(ls(),"agentx-codex-")),a=Ye(i,"last-message.txt"),c=ms(s,o,!1,e.model,e.systemPromptAppend,a,n);try{let u=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),l=await Ze("codex",c,{cwd:s.workspace,timeout:u,reject:!1,env:et(s,e),extendEnv:!1,stdin:"ignore"}),d=mo(l.stdout);if(l.exitCode!==0||d.apiError){let h=l,x;return h.timedOut?x=`Codex CLI timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:d.apiError?x=d.apiError:h.signal?x=l.stderr.trim()||`Codex CLI killed by signal ${h.signal}`:h.code==="ENOENT"||/ENOENT|spawn codex/i.test((h.shortMessage||"")+" "+l.stderr)?x=Ve():x=l.stderr.trim()||l.stdout.trim()||`Codex CLI exited with code ${h.exitCode??"unknown"}`,{content:"",...q(x),duration:Date.now()-r,usage:d.usage,billedModel:d.billedModel,codexSessionId:d.sessionId||n}}let p="";try{p=ds(a,"utf8").trim()}catch{}return p||(p=l.stdout.trim()),{content:p,duration:Date.now()-r,usage:d.usage,billedModel:d.billedModel,codexSessionId:d.sessionId||n}}catch(u){let l=/ENOENT|spawn codex/i.test(u?.message||"")?Ve():u?.message;return{content:"",...q(l||"Codex CLI failed"),duration:Date.now()-r}}finally{us(i,{recursive:!0,force:!0})}}async function xo(s,e,t,n,r,o){let i=Date.now(),a=ce(s,e,n),c=cs(Ye(ls(),"agentx-codex-")),u=Ye(c,"last-message.txt"),l=ms(s,a,!0,e.model,e.systemPromptAppend,u,r),d="",p,h,x,T;try{let w=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),I=Ze("codex",l,{cwd:s.workspace,timeout:w,reject:!1,env:et(s,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let g="",_="",A=!1,S=new Pe("utf8"),y=new Pe("utf8"),O=Math.min(w,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),C,E=()=>{C&&clearTimeout(C),C=setTimeout(()=>{A=!0,I.kill("SIGTERM",{forceKillAfterTimeout:5e3})},O)};E(),I.stderr?.on("data",b=>{E(),_+=y.write(b),_.length>16e3&&(_=_.slice(-16e3))}),I.stdout?.on("data",b=>{E(),g+=S.write(b);let k=g.split(`
|
|
23
|
+
`);g=k.pop()||"";for(let R of k)if(R.trim())try{let U=JSON.parse(R);if(o)try{o(U)}catch{}p=Dt(U)||p,h=fs(U)||h,x=Ot(U)||x,T=ys(U)||T;let P=ho(U);if(P&&P!==d){let z=P.startsWith(d)?P.slice(d.length):P;d=P.startsWith(d)?P:d+P,z&&t(z,d)}}catch{d+=R+`
|
|
24
|
+
`,t(R+`
|
|
25
|
+
`,d)}});let F=await I;C&&clearTimeout(C);let D=S.end();D&&(g+=D);let L=y.end();if(L&&(_+=L),F.exitCode!==0&&!d||T){let b=_||(typeof F.stderr=="string"?F.stderr:""),k=F,R;return A?R=`Codex CLI produced no output for ${Math.round(O/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:k.timedOut?R=`Codex CLI timed out after ${Math.round(w/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:T?R=T:k.signal?R=b.trim()||`Codex CLI killed by signal ${k.signal}`:k.code==="ENOENT"||/ENOENT|spawn codex/i.test((k.shortMessage||"")+" "+b)?R=Ve():R=b.trim()||`Codex CLI exited with code ${k.exitCode??"unknown"}`,{content:"",...q(R),duration:Date.now()-i,usage:p,billedModel:h,codexSessionId:x||r}}let v="";try{v=ds(u,"utf8").trim()}catch{}if(v&&v!==d){let b=v.startsWith(d)?v.slice(d.length):v;d=v,b&&t(b,d)}return{content:d,duration:Date.now()-i,usage:p,billedModel:h,codexSessionId:x||r}}catch(w){let I=/ENOENT|spawn codex/i.test(w?.message||"")?Ve():w?.message;return{content:d,...q(I||"Codex CLI failed"),duration:Date.now()-i,usage:p,billedModel:h,codexSessionId:x||r}}finally{us(c,{recursive:!0,force:!0})}}async function To(s,e,t,n,r,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let u=ce(s,e,n),l=lo(s,u,e.model,e.systemPromptAppend,e.freshSession?void 0:r),d="",p,h=e.freshSession?void 0:r,x,T,w=!0,I;try{let g=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),_=po(s,e);if(s.persistentProcess)try{T=await Jn.acquire({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:_,model:e.model||s.model,permission:s.permissionMode,fresh:e.freshSession,signal:i}),l.splice(1,0,"--server",T.url),_=T.env,o?.({type:"opencode.ready",reused:T.reused,startupMs:Date.now()-c})}catch(b){if(!(b instanceof oe))throw b;b.standalone&&l.splice(1,0,"--standalone"),o?.({type:"opencode.fallback",reason:b.message})}if(i?.aborted)throw new Error("task cancelled by operator");let A=Ze("opencode",l,{cwd:s.workspace,timeout:g,reject:!1,env:_,extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||s.model,resumeSessionId:r})}catch{}let S=!1,y,O=()=>{T?.invalidate(),S=!0,y=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{A.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",O,{once:!0}),I=()=>i?.removeEventListener("abort",O),i?.aborted&&O();let C="",E="",F=new Pe("utf8"),D=new Pe("utf8"),L=b=>{if(b.trim())try{let k=JSON.parse(b);try{o?.(k)}catch{}typeof k.sessionID=="string"&&(h=k.sessionID);let R=k.type==="text"&&typeof k.part?.text=="string"?k.part.text:void 0;R&&(d||o?.({type:"opencode.first_output",elapsedMs:Date.now()-c,reused:T?.reused??!1}),d+=R,t?.(R,d));let U=k.type==="reasoning"&&typeof k.part?.text=="string"?k.part.text:void 0;U&&a?.(U);let P=k.type==="step_finish"?k.part?.tokens:void 0;P&&(p={inputTokens:ae(P.input),outputTokens:ae(P.output),cacheReadTokens:ae(P.cache?.read),cacheCreateTokens:ae(P.cache?.write)}),x=go(k)||x}catch{d+=b+`
|
|
26
|
+
`,t?.(b+`
|
|
27
|
+
`,d)}};A.stdout?.on("data",b=>{C+=F.write(b);let k=C.split(`
|
|
28
|
+
`);C=k.pop()||"";for(let R of k)L(R)}),A.stderr?.on("data",b=>{E+=D.write(b)});let v=await A;if(i&&i.removeEventListener("abort",O),C+=F.end(),C.trim()&&L(C),E+=D.end(),S)return{content:"",error:y||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if(v.exitCode!==0||x){let b=v,k;return b.timedOut?k=`OpenCode timed out after ${Math.round(g/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:x?k=x:b.code==="ENOENT"||/ENOENT|spawn opencode/i.test((b.shortMessage||"")+" "+E)?k=os():k=E.trim()||`OpenCode exited with code ${b.exitCode??"unknown"}`,{content:"",...q(k),duration:Date.now()-c,usage:p,opencodeSessionId:h}}return w=!1,{content:d.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||s.model,opencodeSessionId:h}}catch(g){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(g?.message||"")?os():g?.message;return{content:d,...q(_||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:h}}finally{I?.(),T?.release(w)}}async function ko(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ce(s,e,n),c="",u=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of u)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Io(s,e,t,n,r,o,i,a,c){let u=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),d=new AbortController,p=!1,h=()=>{let w=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{d.abort(new Error(w))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let x=setTimeout(()=>{p=!0;try{d.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);x.unref?.();let T=()=>({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()-u});try{let w=s.provider||"claude-code",I=n?`${n}
|
|
29
|
+
|
|
30
|
+
${e.message}`:e.message,g=e.context?.sender,_=typeof g=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(g),A=e.context?.channel==="web-chat"&&_?{userId:g,agentId:e.agentId||"acme-public"}:void 0,S=Cn(s),y=Object.keys(S).length>0,O={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:d.signal,mcpServers:y?S:void 0};if(r){let{generateStream:L}=await import("./agent-LI3AZQBC.js"),v="",b,k,R,U;for await(let P of L(O)){if(c)try{c(P)}catch{}if(P.type==="text_delta")v+=P.text,r(P.text,v);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==v){let z=P.result.content.slice(v.length);z?(v=P.result.content,r(z,v)):v=P.result.content}b=P.result.tokensUsed,P.result.inputTokens!=null&&(k=P.result.inputTokens),P.result.outputTokens!=null&&(R=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==v){let z=P.result.content.slice(v.length);z?(v=P.result.content,r(z,v)):v=P.result.content}P.result.tokensUsed!=null&&(b=P.result.tokensUsed)}else P.type==="error"&&(U=P.error)}return U&&!v?p?T():U==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...q(`Orchestrator error: ${U}`),duration:Date.now()-u}:((k===void 0||R===void 0)&&b&&(k=Math.round(b*.7),R=b-k),{content:v||"Done.",tokensUsed:b,usage:k!==void 0||R!==void 0?{inputTokens:k||0,outputTokens:R||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u})}let{generate:C}=await import("./agent-LI3AZQBC.js"),E=await C(O),F=E.inputTokens,D=E.outputTokens;if((F===void 0||D===void 0)&&E.tokensUsed){let L=E.tokensUsed;F=Math.round(L*.7),D=L-F}return{content:E.content||"Done.",tokensUsed:E.tokensUsed,usage:F!==void 0||D!==void 0?{inputTokens:F||0,outputTokens:D||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u}}catch(w){return p?T():w?.message==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...q(`Orchestrator error: ${w.message}`),duration:Date.now()-u}}finally{clearTimeout(x),a&&a.removeEventListener("abort",h)}}async function So(s,e,t,n,r,o,i){let a=Xe();if(!a)return null;let c=Date.now(),u=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",d={agentId:e.agentId,channel:u,chatId:l};if(e.freshSession)try{await a.kill(d,"freshSession=true")}catch{}let p,h=!1;try{let v=a.list().length;p=a.acquire(d,{agentId:e.agentId,channel:u,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),h=a.list().length>v}catch(v){return v instanceof fe,null}h&&Et(e.agentId,s,e.model,n,"persistent");let x=ce(s,e,t),T="",w,I,g,_,A,S,y,O="",C="",E=v=>{if(!i||!v)return;let b;if(C&&v.startsWith(C)?b=v.slice(C.length):b=O&&!O.endsWith(`
|
|
31
|
+
`)?`
|
|
32
|
+
|
|
33
|
+
${v}`:v,C=v,!!b){O+=b;try{i(b,O)}catch{}}},F=!1,D=()=>{F=!0,a.kill(d,"operator-cancel").catch(()=>{})};o&&(o.aborted?D():o.addEventListener("abort",D,{once:!0}));let L=!1;try{let v=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let b of p.runTurn({message:x,taskId:e.taskId??"unknown",deadlineMs:v})){if(L=!0,r)try{r(b.raw)}catch{}if(b.type==="assistant"){let k=b.raw.message?.content??[];for(let U of k)U.type==="text"&&typeof U.text=="string"?(T=U.text,E(U.text)):U.type==="tool_use"&&(C="");let R=b.raw.message?.usage;if(R){let U=(R.input_tokens||0)+(R.cache_read_input_tokens||0)+(R.cache_creation_input_tokens||0);U>0&&(_=U)}}if(b.type==="result"){let k=b.raw;if(k.is_error){let R=q(typeof k.result=="string"?k.result:"claude error");w=R.error,I=R.errorKind}else typeof k.result=="string"&&k.result.length>0&&(T=k.result,O||E(k.result));typeof k.session_id=="string"&&(y=k.session_id),k.usage&&(g={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.num_turns=="number"&&(A=k.num_turns),typeof k.message?.model=="string"?S=k.message.model:typeof k.model=="string"&&(S=k.model)}}}catch(v){if(F)w="task cancelled by operator",I="cancelled";else if(L)if(v instanceof Me){let b=q(`Claude Code timed out after ${Math.round(v.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);w=b.error,I=b.errorKind}else{let b=q(`persistent claude process error: ${v?.message||String(v)}`);w=b.error,I=b.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${v?.message||v}); falling back to spawn-per-task`),a.release(d,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",D),null}finally{o&&o.removeEventListener("abort",D)}return F&&!w&&(w="task cancelled by operator",I="cancelled"),{content:F?"":T,error:w,errorKind:I,duration:Date.now()-c,usage:g,contextTokens:_,numTurns:A,billedModel:S,claudeSessionId:y}}function xs(s){return re(s.autonomy)?s.taskId?ns(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function vo(s,e,t,n,r,o,i){let a=e.autonomy,c=ss(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let u=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:u,message:`${bn(a)}
|
|
34
|
+
|
|
35
|
+
${e.message}`};process.stderr.write(`[claude-autonomy] agent=${e.agentId} level=${a} task=${u} via=spawn (persistent process bypassed)
|
|
36
|
+
`);let d=t?await ws(s,l,t,n,r,o,i):await bs(s,l,n,r,i),p=rs(u);return{...d,autonomy:a,...p.length?{autonomyBlocks:p}:{}}}async function Ts(s,e,t,n,r,o,i,a,c){if(re(e.autonomy))return vo(s,e,n,r,o,i,a);switch(s.tier){case"claude-code":if(s.persistentProcess){let u=await So(s,e,r,o,i,a,n);if(u!==null)return u}return n?ws(s,e,n,r,o,i,a):bs(s,e,r,o,a);case"codex-cli":if(s.persistentProcess)try{let u=await Qn.run({key:JSON.stringify([e.agentId,e.context?.channel,e.context?.chatId]),cwd:s.workspace,env:et(s,e),args:hs(),model:e.model||s.model,bypass:s.permissionMode==="bypassPermissions",prompt:Rt(ce(s,e,r),e.systemPromptAppend),resume:o,fresh:e.freshSession,timeoutMs:Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),signal:a,onEvent:i,onDelta:n});return{...u,...u.error?q(u.error):{}}}catch(u){if(!(u instanceof ie))throw u;if(i?.({type:"codex.fallback",reason:u.message}),a?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled"}}return n?xo(s,e,n,r,o,i):wo(s,e,r,o);case"opencode":return To(s,e,n,r,o,i,a,c);case"sdk":{let u=s.provider||"claude",l=t[u]?.apiKey;return l?ko(s,e,l,r):{content:"",error:`No API key for provider "${u}". Configure providers.${u}.apiKey`}}case"orchestrator":{let u=s.provider||"claude-code",l=t[u],d=l?.apiKey;return Io(s,e,d,r,n,{thinking:l?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${s.tier}`}}}import{readFileSync as be,writeFileSync as ks,mkdirSync as Co,existsSync as Nt,readdirSync as Lt}from"fs";import{resolve as we}from"path";var Ft=12e3,Re=30,Ao=720,$o=40,Mo=18e4,Po="[Compacted conversation summary",Ro=7*864e5,_o=[/\bearlier\b/i,/\bbefore\b/i,/\bjust said\b/i,/\btold (?:me|you|us|him|her|them)\b/i,/\bmention(?:ed|ing)?\b/i,/\bask(?:ed)? (?:me|you|him|her|them|about)\b/i,/\bping(?:ed)?\b/i,/\bdm\b/i,/\bdirect message\b/i,/\bother (?:chat|group|conversation|thread)\b/i,/\bthat (?:chat|group|conversation|thread)\b/i,/\bsame (?:issue|thread|conversation)\b/i,/\bcontinuing\b/i,/@\w{2,}_?(?:bot|agent)\b/i,/قلت/,/قال(?:لك|لي|له|لها|لنا)?/,/قبل/,/الحين/,/الثاني/,/المجموعة/];function Do(s){return s?_o.some(e=>e.test(s)):!1}var Oo=[{re:/\byesterday\b/i,days:2},{re:/\bأمس\b/,days:2},{re:/\bcouple (?:of )?days\b/i,days:4},{re:/\bfew days\b/i,days:4},{re:/\blast week\b/i,days:8},{re:/\bالأسبوع الماضي\b/,days:8},{re:/\bweek ago\b/i,days:8},{re:/\bremember\b/i,days:3},{re:/\bpreviously\b/i,days:3},{re:/\bwe (?:discussed|talked|agreed|decided)\b/i,days:3},{re:/\bas (?:i|we) (?:said|told|mentioned)\b/i,days:3},{re:/\bcontinue from\b/i,days:3},{re:/\bتذكر\b/,days:3}];function Ss(s){if(!s)return null;let e=0;for(let t of Oo)t.re.test(s)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function Is(s,e,t,n){if(s.length===0)return!1;let r=s[s.length-1];return r.role===e&&(r.name??"")===t&&r.content===n}function vs(s,e){let t=(s??[]).filter(o=>o.role==="user"),n=t[t.length-1];return n?(n.content===e?t[t.length-2]:n)?.content??null:null}function Cs(s,e,t){if(t<=0)return[];let n=(s??[]).filter(i=>i.role==="user"),r=n[n.length-1],o=(r&&r.content===e?n.length-1:n.length)-1;return o<=0?[]:n.slice(Math.max(0,o-t),o).map(i=>i.content)}function Eo(s){let e=s.slice(11,16),t=e.slice(0,2),n=parseInt(e.slice(3,5),10);if(Number.isNaN(n))return e;let r=Math.floor(n/15)*15;return`${t}:${r.toString().padStart(2,"0")}`}var tt=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=we(e,".agentx/sessions"),Nt(this.sessionsDir)||Co(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Ao),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??$o),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Mo)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n,r){if(r?.length){let l=this.getSession(e,t,n);l.messages.length===0&&this.appendSeededMessages(l,r);return}if(!this.adapterResolver)return;let o=this.sessionKey(e,t,n),i=this.seedingPromises.get(o);if(i)return i;let a=this.getSession(e,t,n);if(a.messages.length>0)return;let c=this.adapterResolver(t);if(!c?.seedHistory)return;let u=(async()=>{try{let l=await c.seedHistory(n,{maxMessages:Re,maxChars:Ft});l.length>0&&this.appendSeededMessages(a,l)}catch{}})();this.seedingPromises.set(o,u);try{await u}finally{this.seedingPromises.delete(o)}}appendSeededMessages(e,t){if(t.length===0)return;let n=new Set;for(let o of e.messages)o.externalId&&n.add(o.externalId);let r=0;for(let o of t)o.externalId&&n.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),r++);r!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,n){let r=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${r}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return we(this.sessionsDir,`${t}.json`)}getSession(e,t,n){let r=this.sessionKey(e,t,n);if(this.cache.has(r))return this.cache.get(r);let o=this.sessionFile(r);if(Nt(o))try{let u=JSON.parse(be(o,"utf-8"));return this.cache.set(r,u),u}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),c={id:r,agentId:e,channel:t,chatId:n,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(r,c),this.save(c),c}loadPreviousDaySession(e,t,n){let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${n}:${r}`,i=this.sessionFile(o);if(!Nt(i))return null;try{return JSON.parse(be(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,r,o){let i=this.getSession(e,t,n);Is(i.messages,"user",r,o)||(i.messages.push({role:"user",name:r,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,n,r){let o=this.getSession(e,t,n),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(r||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,n,r){let o=this.getSession(e,t,n);Is(o.messages,"agent",e,r)||(o.messages.push({role:"agent",name:e,content:r,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.claudeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getCodexSessionId(e,t,n){return this.getSession(e,t,n).codexSessionId}setCodexSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.codexSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,n){return this.getSession(e,t,n).opencodeSessionId}setOpenCodeSessionId(e,t,n,r){let o=this.getSession(e,t,n);o.opencodeSessionId=r,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,n,r={}){let o=this.getSession(e,t,n);if(o.messages.length===0)return"";let i=Math.max(1,r.maxMessages??Re),a=Math.max(200,r.maxChars??Ft),c=[],u=0;for(let p=o.messages.length-1;p>=0&&c.length<i;p--){let h=o.messages[p];if(u+=h.content.length,c.push(h),u>=a)break}c.reverse();let l=[`[Conversation history for today (${o.day})]`],d="";for(let p of c){let h=Eo(p.timestamp);h!==d&&(l.push(`\u2014 ${h} \u2014`),d=h);let x=p.name||(p.role==="user"?"User":"Agent");l.push(`${x}: ${p.content}`)}return l.push("[End of history \u2014 respond to the latest message above]"),l.push(""),l.join(`
|
|
37
|
+
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),n=new Date;n.setUTCHours(0,0,0,0);let r=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():n.toISOString(),o=e.after??r,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=Lt(this.sessionsDir).filter(A=>A.startsWith(`${a}:`)&&A.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let u=o.slice(0,10),l=i.slice(0,10),d=/:(\d{4}-\d{2}-\d{2})\.json$/,p=c.filter(A=>{let S=A.match(d);if(!S)return!1;let y=S[1];return y>=u&&y<=l}),h=[],x=0,T=e.query?.toLowerCase(),w=e.participants?.length?new Set(e.participants):void 0;for(let A of p){let S;try{S=JSON.parse(be(we(this.sessionsDir,A),"utf-8"))}catch{continue}if(S.agentId===e.agentId&&!(e.channel&&S.channel!==e.channel)&&!(e.chatId&&S.chatId!==e.chatId))for(let y of S.messages)x++,!(!y.timestamp||y.timestamp<o||y.timestamp>=i)&&(w&&y.role==="user"&&!w.has(y.name??"")||T&&!y.content.toLowerCase().includes(T)||h.push({ts:y.timestamp,role:y.role,senderName:y.name??"",content:y.content,channel:S.channel,chatId:S.chatId,day:S.day,sessionFile:A}))}h.sort((A,S)=>S.ts.localeCompare(A.ts));let I=h.slice(0,t),g=I.length>0?I[I.length-1].ts:null,_=h.length>t;return{turns:I,oldestTs:g,hasMore:_,totalScanned:x}}recentByChatId(e){let t=Math.min(Math.max(e.limit??Re,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),r=n.slice(0,10),o;try{o=Lt(this.sessionsDir).filter(d=>d.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`,a=o.filter(d=>{if(!d.includes(i))return!1;let p=d.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return p?p[1]>=r:!1}),c=[];for(let d of a){let p;try{p=JSON.parse(be(we(this.sessionsDir,d),"utf-8"))}catch{continue}if(!(p.channel!==e.channel||p.chatId!==e.chatId))for(let h of p.messages)!h.timestamp||h.timestamp<n||c.push({ts:h.timestamp,role:h.role,senderName:h.name??"",content:h.content,agentId:p.agentId,sessionFile:d})}let u=new Set,l=[];for(let d of c){let p=`${d.ts}|${d.role}|${d.senderName}|${d.content}`;u.has(p)||(u.add(p),l.push(d))}return l.sort((d,p)=>d.ts.localeCompare(p.ts)),l.slice(-t)}sessionIdleMs(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?null:Date.now()-new Date(r.updatedAt).getTime()}isSessionStale(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:Date.now()-new Date(r.updatedAt).getTime()>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,n,r){if(r!==void 0&&r!==""&&!Do(r))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=Lt(this.sessionsDir).filter(u=>u.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&u.includes(o)&&u.endsWith(".json")),c=[];for(let u of a)try{let l=JSON.parse(be(we(this.sessionsDir,u),"utf-8"));if(l.id===i||l.messages.length===0)continue;let d=l.messages.slice(-4),h=!l.chatId.startsWith("-")&&/^\d+$/.test(l.chatId)?"DM":l.chatId,x=d.map(T=>` [${T.timestamp.slice(11,16)}] ${T.name||T.role}: ${T.content.slice(0,200)}`);c.push(`From ${h} (${l.channel}):
|
|
38
|
+
${x.join(`
|
|
39
|
+
`)}`)}catch{}return c.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...c,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
|
|
40
|
+
`)}catch{return""}}async compactIfNeeded(e,t,n,r){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-QXU3A4LQ.js");if(!i(o.messages))return{compacted:!1};let u=await a(o.messages,e,r,{channel:t,chatId:n});return u.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,u),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:u.qualityScore,lostEntities:u.lostEntities,drift:u.drift})}hasCompaction(e,t,n){let r=this.getSession(e,t,n);return r.messages.length>0&&r.messages[0].content.startsWith(Po)}clearClaudeSessionId(e,t,n){let r=this.getSession(e,t,n);delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}clearSession(e,t,n){let r=this.getSession(e,t,n);r.messages=[],delete r.claudeSessionId,delete r.codexSessionId,delete r.opencodeSessionId,delete r.turnCount,delete r.lastTurnInputTokens,delete r.lastTurnContextTokens,r.updatedAt=new Date().toISOString(),this.save(r)}shouldRotateByTurns(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let r=this.getSession(e,t,n);return!r.claudeSessionId&&!r.codexSessionId&&!r.opencodeSessionId?!1:(r.lastTurnContextTokens??r.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,r,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(r.inputTokens||0)+(r.cacheReadTokens||0)+(r.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return we(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(be(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,r,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:r,reason:o,capturedAt:new Date().toISOString()},ks(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let r=this.readRotationMemos()[`${e}:${t}:${n}`];if(!r?.memo)return null;let o=Date.now()-Date.parse(r.capturedAt);return!Number.isFinite(o)||o>Ro?null:r}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,n){let r=this.getSession(e,t,n);return r.lastTurnContextTokens??r.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>Re&&(e.messages=e.messages.slice(-Re));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>Ft&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let r=t-e.messages.length;r>0&&ue.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${r} message(s): ${t} -> ${e.messages.length} (${n}c)`)}save(e){try{let t=this.sessionFile(e.id);ks(t,JSON.stringify(e,null,2))}catch{}}};var nt=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],r=t-36e5,o=n.filter(c=>c>r),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],u=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:u}}if(o.length>=this.maxPerHour){let c=o[0],u=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:u}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,r=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=r)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=r-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(u=>setTimeout(u,c))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(r=>r>t-6e4).length,lastHour:n.filter(r=>r>t-36e5).length}}};import{readFileSync as _e,writeFileSync as As,appendFileSync as No,existsSync as xe,mkdirSync as Lo}from"fs";import{resolve as Te}from"path";var Ms={"claude-fable":{input:10,output:50,cacheRead:1,cacheCreate:12.5},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-8":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-7":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-6":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus":{input:15,output:75,cacheRead:1.5,cacheCreate:18.75},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheCreate:2.5},"claude-sonnet":{input:3,output:15,cacheRead:.3,cacheCreate:3.75},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheCreate:1.25}},Ps=2e5,Fo=1.5;function Ho(s){let e=s.toLowerCase(),t=(...n)=>n.some(r=>e.includes(r));return t("fable","mythos")?"claude-fable":e.includes("opus")?t("opus-5","opus5","opus-5-")?"claude-opus-5":t("4-8","4.8")?"claude-opus-4-8":t("4-7","4.7")?"claude-opus-4-7":t("4-6","4.6")?"claude-opus-4-6":t("4-5","4.5")?"claude-opus-4-5":t("4-1","4.1","opus-3","opus3","-3-")?"claude-opus":"claude-opus-5":e.includes("haiku")?"claude-haiku":t("sonnet-5","sonnet5")?"claude-sonnet-5":"claude-sonnet"}function Rs(s){return s.inputTokens+s.cacheReadTokens+s.cacheCreateTokens>Ps?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:s.inputTokens,tier2OutputTokens:s.outputTokens,tier2CacheReadTokens:s.cacheReadTokens,tier2CacheCreateTokens:s.cacheCreateTokens}:{inputTokens:s.inputTokens,outputTokens:s.outputTokens,cacheReadTokens:s.cacheReadTokens,cacheCreateTokens:s.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var $s=500,jo=".agentx/pricing/custom.json",ke=class{dir;cache=null;pricing;constructor(e=Te(process.cwd(),".agentx/usage")){this.dir=e,Lo(this.dir,{recursive:!0}),this.pricing=Uo()}getPricing(){return this.pricing}static calculateCost(e,t,n=Ms){let r=Ho(t||e.model||"claude-sonnet"),o=n[r]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,u=e.tier2CacheCreateTokens||0,l=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,d=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+u/1e6*o.cacheCreate;return l+d*Fo}cost(e,t){return ke.calculateCost(e,t,this.pricing)}record(e,t,n,r,o,i,a,c,u){let l=this.today(),d=l.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};d.tasks++,d.totalDuration+=t,a&&(d.model=a);let p=0,h=0,x=0,T=0,w=0,I=0,g=0,_=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>Ps?(w=n.inputTokens,I=n.outputTokens,g=n.cacheReadTokens,_=n.cacheCreateTokens):(p=n.inputTokens,h=n.outputTokens,x=n.cacheReadTokens,T=n.cacheCreateTokens):r!==void 0&&o!==void 0&&(p=Math.ceil(r/4),h=Math.ceil(o/4)),d.inputTokens+=p,d.outputTokens+=h,d.cacheReadTokens+=x,d.cacheCreateTokens+=T,d.tier2InputTokens=(d.tier2InputTokens||0)+w,d.tier2OutputTokens=(d.tier2OutputTokens||0)+I,d.tier2CacheReadTokens=(d.tier2CacheReadTokens||0)+g,d.tier2CacheCreateTokens=(d.tier2CacheCreateTokens||0)+_,i&&d.errors++,d.byChannel||(d.byChannel={});let A=(c||"other").toLowerCase(),S=d.byChannel[A]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};S.tasks++,S.totalDuration+=t,S.inputTokens+=p,S.outputTokens+=h,S.cacheReadTokens+=x,S.cacheCreateTokens+=T,S.tier2InputTokens+=w,S.tier2OutputTokens+=I,S.tier2CacheReadTokens+=g,S.tier2CacheCreateTokens+=_,i&&S.errors++,d.byChannel[A]=S,u&&(d.sessionKeys||(d.sessionKeys=[]),d.sessionKeys.includes(u)||(d.sessionKeys.push(u),d.sessionKeys.length>$s&&d.sessionKeys.splice(0,d.sessionKeys.length-$s))),l.agents[e]=d,this.save(l)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(xe(t))try{return this.cache=JSON.parse(_e(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!xe(t))return null;try{return JSON.parse(_e(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let r=0,o=0,i=0,a=0,c=0,u=0,l="",d=0,p={},h={},x={};for(let[T,w]of Object.entries(n.agents)){let I=this.cost(w);p[T]=I,r+=w.tasks,o+=(w.inputTokens||0)+(w.tier2InputTokens||0),i+=(w.outputTokens||0)+(w.tier2OutputTokens||0),a+=(w.cacheReadTokens||0)+(w.tier2CacheReadTokens||0),c+=(w.cacheCreateTokens||0)+(w.tier2CacheCreateTokens||0),u+=I,I>d&&(d=I,l=T);let g=w.sessionKeys?.length||0;h[T]={sessions:g,avgTasksPerSession:g>0?w.tasks/g:w.tasks};for(let[_,A]of Object.entries(w.byChannel||{})){let S=this.cost(A,w.model);x[_]=(x[_]||0)+S}}return{date:t,totalTasks:r,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:u,topAgent:l,topCost:d,agentCosts:p,agentSessionStats:h,byChannel:x}}appendToTokenCosts(e,t){let n=t||Te(process.cwd(),".agentx/TOKEN_COSTS.md"),r=u=>u<.01?u.toFixed(4):u.toFixed(2),o=u=>u>=1e6?`${(u/1e6).toFixed(1)}M`:u>=1e3?`${(u/1e3).toFixed(0)}K`:String(u),i=Object.entries(e.agentCosts).sort(([,u],[,l])=>l-u).map(([u,l])=>{let d=e.agentSessionStats[u],p=d&&d.sessions>0?` (${d.sessions}s, ${d.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${u}: $${r(l)}${p}`}).join(", "),a=Object.entries(e.byChannel).sort(([,u],[,l])=>l-u).map(([u,l])=>`${u}: $${r(l)}`).join(", "),c=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${r(e.totalCost)} | ${i} | ${a} |`;xe(n)?No(n,c+`
|
|
41
|
+
`):As(n,`# Token Costs
|
|
42
|
+
|
|
43
|
+
Daily token cost tracking. Auto-appended at midnight, host time.
|
|
44
|
+
Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
45
|
+
|
|
46
|
+
| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
|
|
47
|
+
|------|-------|-------|--------|---------|---------|------|-----------|-------------|
|
|
48
|
+
`+c+`
|
|
49
|
+
`)}hasTokenCostsEntry(e,t){let n=t||Te(process.cwd(),".agentx/TOKEN_COSTS.md");if(!xe(n))return!1;try{let r=_e(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(r)}catch{return!1}}lastTokenCostsDate(e){let t=e||Te(process.cwd(),".agentx/TOKEN_COSTS.md");if(!xe(t))return null;try{let r=_e(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(r.length===0)return null;let o=r.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return o.sort(),o[o.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,r=[],o=this.lastTokenCostsDate(t.filePath),i=[],a=new Date(`${e}T00:00:00Z`);for(let c=0;c<n;c++){let u=a.toISOString().slice(0,10);if(o&&u<=o)break;i.push(u),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let c of i){if(this.hasTokenCostsEntry(c,t.filePath))continue;let u=this.generateDailyReport(c);!u||u.totalTasks===0||(this.appendToTokenCosts(u,t.filePath),r.push(c))}return r}summary(e=7){let t=0,n=0,r=0,o=0,i=0,a=0,c=0,u={},l={};for(let x=0;x<e;x++){let T=new Date(Date.now()-x*864e5).toISOString().slice(0,10),w=this.getDate(T);if(w)for(let[I,g]of Object.entries(w.agents)){let _=this.cost(g);t+=g.tasks;let A=(g.inputTokens||0)+(g.tier2InputTokens||0),S=(g.outputTokens||0)+(g.tier2OutputTokens||0),y=(g.cacheReadTokens||0)+(g.tier2CacheReadTokens||0),O=(g.cacheCreateTokens||0)+(g.tier2CacheCreateTokens||0);n+=A,r+=S,o+=y,i+=O,a+=g.errors,c+=_;let C=u[I]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};C.tasks+=g.tasks,C.input+=A,C.output+=S,C.cacheRead+=y,C.cacheCreate+=O,C.total=C.input+C.output+C.cacheRead+C.cacheCreate,C.totalDuration+=g.totalDuration,C.avgDuration=C.totalDuration/C.tasks,C.cost+=_,C.sessions+=g.sessionKeys?.length||0,g.model&&(C.model=g.model),u[I]=C;for(let[E,F]of Object.entries(g.byChannel||{})){let D=this.cost(F,g.model),L=l[E]||{tasks:0,cost:0};L.tasks+=F.tasks,L.cost+=D,l[E]=L}}}let d=n+r+o+i,p=o+i>0?o/(o+i):0,h={};for(let[x,T]of Object.entries(u))h[x]={sessions:T.sessions,avgTasksPerSession:T.sessions>0?T.tasks/T.sessions:T.tasks};return{totalTasks:t,totalTokens:d,totalInput:n,totalOutput:r,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:p,totalErrors:a,totalCost:c,byAgent:u,byChannel:l,sessionStats:h}}filePath(e){return Te(this.dir,`${e}.json`)}save(e){try{As(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function Uo(){let s=JSON.parse(JSON.stringify(Ms));try{let e=Te(process.cwd(),jo);if(!xe(e))return s;let t=JSON.parse(_e(e,"utf-8"));for(let[n,r]of Object.entries(t))s[n]||(s[n]={input:0,output:0,cacheRead:0,cacheCreate:0}),Object.assign(s[n],r)}catch{}return s}var Bo={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:400,memory:400,history:1200,"cross-chat":800,wiki:2500}},_s=4;function Ds(s,e=Bo){let t=Wo(s,e);t.sort((i,a)=>i.priority-a.priority);let n=[],r=0,o=e.totalBudget*_s;for(let i of t){if(!i.content)continue;let a=i.maxTokens*_s,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(r+c.length>o){let u=o-r;u>100&&n.push(c.slice(0,u)+"...");break}n.push(c),r+=c.length}return n.join(`
|
|
50
|
+
|
|
51
|
+
`)}function Wo(s,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(Ko(s,t("channel",200))),n.push(qo(s,t("scope",200))),s.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:s.landscape,tags:["landscape","world-model"]}),s.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:s.systemPrompt.split(`
|
|
52
|
+
`)[0],tags:["identity",s.agentId]}),s.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:s.bootstrapContext,tags:["bootstrap","identity","personality"]}),s.references&&n.push({name:"references",priority:4.7,maxTokens:t("references",500),content:s.references,tags:["references","verified","deterministic"]}),s.intent&&s.intent.path.length>0){let i=[`[Intent path: ${s.intent.pathLabel}${s.intent.status==="pending"?" (pending approval)":""}]`],a=s.intent.path[s.intent.path.length-1],c=s.intent.axes?.[a];if(c&&Object.keys(c).length){let u=Object.entries(c).map(([l,d])=>` ${l}: ${d}`).join(`
|
|
53
|
+
`);i.push(u)}s.intent.leaf?.input&&i.push(` input: ${s.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
|
|
54
|
+
`),tags:["intent",...s.intent.path]})}else{let i=Go(s.message);i.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let r=[];s.replyToText&&r.push(`[Replying to]: ${s.replyToText.slice(0,300)}`),s.mediaPath&&(r.push(`[Attached file: ${s.mediaPath}]`),r.push(`[File type: ${s.mediaType||"unknown"}]`),s.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):s.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),s.issueMR&&r.push(`[${s.issueMR.type} #${s.issueMR.iid}: ${s.issueMR.title}]`),r.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
|
|
55
|
+
`),tags:["artifacts",...s.mediaType?["media"]:[]]}),s.skillInjection&&n.push({name:"skills",priority:6.4,maxTokens:t("skills",800),content:s.skillInjection,tags:["skills","auto-inject"]}),s.patternContext&&n.push({name:"patterns",priority:6.5,maxTokens:t("patterns",300),content:s.patternContext,tags:["patterns","behavioral","self-improving"]}),s.procedureContext&&n.push({name:"procedures",priority:6.6,maxTokens:t("procedures",400),content:s.procedureContext,tags:["procedures","sop"]}),s.memoryContext&&n.push({name:"memory",priority:6.7,maxTokens:t("memory",400),content:s.memoryContext,tags:["memory","persistent"]});let o=s.groupHistory||s.sessionHistory;if(o&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"]}),s.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:s.crossChatContext,tags:["history","cross-chat"]}),s.longMemoryRecall&&n.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:s.longMemoryRecall,tags:["history","long-memory"]}),s.handoverNote){let i=[`[Handover] You are taking over this conversation from ${s.handoverNote.fromAgent}.`];s.handoverNote.summary&&i.push(`Operator summary: ${s.handoverNote.summary}`),i.push(`Handover time: ${s.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
|
|
56
|
+
`),tags:["handover",s.handoverNote.fromAgent]})}return s.rotationMemo&&n.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${s.rotationMemo.reason}, ${s.rotationMemo.capturedAt}). Carry on from these facts; do not claim you lack prior context:]`,s.rotationMemo.memo].join(`
|
|
57
|
+
`),tags:["continuity","rotation-memo"]}),s.wikiContext&&n.push({name:"wiki",priority:6.1,maxTokens:t("wiki",2500),content:s.wikiContext,tags:["wiki","knowledge"]}),n}function Ko(s,e){let t=[`Channel: ${s.channel}`];s.chatId&&t.push(`Chat ID: ${s.chatId} (use this verbatim in /recall, /send)`);let n=[],r=[s.channel];switch(s.channel){case"telegram":s.agentHandle&&t.push(`Your handle: ${s.agentHandle}`),t.push(`From: ${s.sender}`),s.senderId&&t.push(`Telegram user ID: ${s.senderId}`),s.senderUsername&&t.push(`Username: @${s.senderUsername}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),n.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${s.sender}`),n.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only"),n.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${s.sender}`),n.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),n.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),n.push("Never narrate what you are about to do \u2014 just do it and report the result"),r.push("code-review");break;case"discord":t.push(`From: ${s.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:s.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),r.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
58
|
+
`),tags:r,rules:n}}function qo(s,e){let t=[],n=[];if(s.channelScope==="group"&&s.groupName?(t.push(`Group: ${s.groupName}`),n.push("group",s.groupName)):s.channelScope==="project"&&s.projectPath?(t.push(`Project: ${s.projectPath}`),n.push("project",s.projectPath)):s.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),s.channelMeta){let r=s.channelMeta;if(r.agents?.length&&(t.push(`[Verified bots in this chat: ${r.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),r.project&&t.push(`Project: ${r.project}`),r.issue&&t.push(`${r.issue.type} #${r.issue.iid}${r.issue.title?`: ${r.issue.title}`:""}`),r.facts?.length)for(let o of r.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
59
|
+
`),tags:n}}function Go(s){let e=[],t=s.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}import{readFileSync as Jo,writeFileSync as Ht,appendFileSync as Qo,mkdirSync as zo,existsSync as Os}from"fs";import{resolve as jt}from"path";var Es=200,Xo=7,st=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=jt(e,".agentx/memory"),Os(this.memoryDir)||zo(this.memoryDir,{recursive:!0})}filePath(e){return jt(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||xt(t.content))return!1;let n=t.source.trust??Mn(t.source.channel),r=t.review??Pn(n),o={...t,source:{...t.source,trust:n},...r?{review:r}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Qo(this.filePath(e),JSON.stringify(o)+`
|
|
60
|
+
`),!0}getAll(e){let t=this.filePath(e);if(!Os(t))return[];try{return Jo(t,"utf-8").split(`
|
|
61
|
+
`).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return[]}}findRelevant(e,t,n=8){let r=this.getAll(t).filter(kt);if(r.length===0)return[];let o=r.map(h=>`${h.keywords.join(" ")} ${h.content}`),i=jt(this.memoryDir,`${t}_bm25_cache.json`),a=qe(o,i),c=Ke(e,a),u=new Map(c.map(h=>[h.docIndex,h.score])),d=r.map((h,x)=>{let T=u.get(x)??0;return h.category==="commitment"&&(T+=1),{memory:h,score:T}}).filter(h=>h.score>0);if(d.length===0)return r.slice(-n);let p=d.sort((h,x)=>x.score-h.score).slice(0,n).map(h=>h.memory);if(p.length>0)try{this.recordAccess(t,p.map(h=>h.id))}catch{}return p}buildContext(e){if(e.length===0)return"";let t=["[Agent Memory \u2014 persistent facts from past conversations]"],n=t[0].length;for(let r of e){let i=!r.source.chatId.startsWith("-")&&/^\d+$/.test(r.source.chatId)?"DM":r.source.chatId,a=`- [${r.category}] ${r.content} (${i}, ${r.source.date})`;if(n+a.length>2400)break;t.push(a),n+=a.length}return t.push("[End Memory]"),t.join(`
|
|
62
|
+
`)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),r=new Set(t),o=!1;for(let i of n)if(r.has(i.id)){i.accessCount=(i.accessCount||0)+1,i.lastAccessed=new Date().toISOString();let a=i.intervalDays||1;i.intervalDays=Math.min(a*2,30),i.nextReview=new Date(Date.now()+i.intervalDays*864e5).toISOString(),o=!0}o&&Ht(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
63
|
+
`)+`
|
|
64
|
+
`)}getDueForReview(e,t=5){let n=this.getAll(e).filter(kt),r=Date.now();return n.filter(o=>o.category==="task-state"?!1:o.nextReview?new Date(o.nextReview).getTime()<=r:!0).sort((o,i)=>!o.nextReview&&i.nextReview?-1:o.nextReview&&!i.nextReview?1:o.nextReview&&i.nextReview?new Date(o.nextReview).getTime()-new Date(i.nextReview).getTime():(o.accessCount||0)-(i.accessCount||0)).slice(0,t)}buildRecallContext(e){let t=this.getDueForReview(e,5);if(t.length===0)return"";let n=["[Memory Recall \u2014 facts due for review, verify they are still accurate]"];for(let r of t){let o=Math.round((Date.now()-new Date(r.createdAt).getTime())/864e5);n.push(`- [${r.category}] ${r.content} (${o}d old, accessed ${r.accessCount||0}x)`)}return n.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),n.join(`
|
|
65
|
+
`)}held(e){return this.getAll(e).filter(t=>t.review==="held"||t.review===void 0&&Tt(t)==="external")}review(e,t,n,r="operator"){let o=this.getAll(e),i=o.find(a=>a.id===t);return i?(i.review=n,i.reviewedBy=r,i.reviewedAt=new Date().toISOString(),this.rewrite(e,o),!0):!1}scrubSecrets(e,t=!1){let n=this.getAll(e),r=n.filter(i=>i.category!=="secret"&&!xt(i.content)),o=n.length-r.length;return t&&o>0&&this.rewrite(e,r),o}trustSummary(e){let t={};for(let n of this.getAll(e)){let r=`${Tt(n)}${n.review?`/${n.review}`:""}`;t[r]=(t[r]??0)+1}return t}rewrite(e,t){Ht(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
66
|
+
`)+(t.length?`
|
|
67
|
+
`:""))}hasSimilar(e,t){let n=this.getAll(e),o=t.toLowerCase().split(/\s+/).filter(i=>i.length>3);return n.some(i=>{let a=i.content.toLowerCase();return o.filter(u=>a.includes(u)).length>=o.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let n=Date.now(),r=Xo*24*60*60*1e3;t=t.filter(i=>i.category==="task-state"&&i.expiresAt?new Date(i.expiresAt).getTime()>n:i.category==="task-state"&&!i.expiresAt?n-new Date(i.createdAt).getTime()<r:!0),t.length>Es&&(t=t.slice(-Es));let o=this.filePath(e);Ht(o,t.map(i=>JSON.stringify(i)).join(`
|
|
68
|
+
`)+`
|
|
69
|
+
`)}};var rt=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,n){return`${e}:${t}:${n}`}getOrCreate(e,t,n){let r=this.key(e,t,n);return this.queues.has(r)||this.queues.set(r,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(r)}setMode(e,t,n,r){this.getOrCreate(e,t,n).mode=r}onFlush(e,t,n,r){this.getOrCreate(e,t,n).onFlush=r}isBusy(e,t,n){return this.getOrCreate(e,t,n).running}markRunning(e,t,n){let r=this.getOrCreate(e,t,n);return r.running?!1:(r.running=!0,!0)}enqueue(e,t,n,r){let o=this.getOrCreate(e,t,n);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(r),o.mode}}async markDone(e,t,n){let r=this.getOrCreate(e,t,n);if(r.running=!1,r.pending.length===0)return[];let o=[...r.pending];switch(r.pending=[],r.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
|
|
70
|
+
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext};return r.onFlush&&await r.onFlush([a]),[a]}case"followup":return r.onFlush&&await r.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let r=this.key(e,t,n);this.queues.delete(r)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as Yo,writeFileSync as Ns,appendFileSync as Vo,mkdirSync as Zo,existsSync as Ls}from"fs";import{resolve as Ut}from"path";var Fs=50,ei="claude-haiku-4-20250514",ti=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
|
|
71
|
+
|
|
72
|
+
Extract patterns like:
|
|
73
|
+
- "When asked about X, the approach that works is Y"
|
|
74
|
+
- "User prefers Z style of communication"
|
|
75
|
+
- "For deployment tasks, always check A before doing B"
|
|
76
|
+
- "This codebase uses pattern X, so generate code following X"
|
|
77
|
+
|
|
78
|
+
SKIP:
|
|
79
|
+
- Factual information (names, dates, URLs)
|
|
80
|
+
- Routine task completions
|
|
81
|
+
- Greetings or small talk
|
|
82
|
+
|
|
83
|
+
Output a JSON array:
|
|
84
|
+
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
85
|
+
|
|
86
|
+
If nothing worth extracting, output: []`,ot=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Ut(e,".agentx/patterns"),Ls(this.patternsDir)||Zo(this.patternsDir,{recursive:!0})}filePath(e){return Ut(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!Ls(t))return[];try{return Yo(t,"utf-8").split(`
|
|
87
|
+
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};Vo(this.filePath(e),JSON.stringify(n)+`
|
|
88
|
+
`)}findRelevant(e,t,n=5){let r=this.getAll(t);if(r.length===0)return[];let o=r.map(l=>`${l.context} ${l.pattern}`),i=Ut(this.patternsDir,`${t}_bm25_cache.json`),a=qe(o,i),u=Ke(e,a).slice(0,n).map(l=>r[l.docIndex]).filter(l=>l.confidence>=.3);return u.length>0&&this.recordAccess(t,u.map(l=>l.id)),u}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let n of e)t.push(`- ${n.pattern} (context: ${n.context}, confidence: ${Math.round(n.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
|
|
89
|
+
`)}hasSimilar(e,t){let n=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return r.filter(c=>i.includes(c)).length>=r.length*.6})}recordAccess(e,t){let n=this.getAll(e),r=new Set(t),o=!1;for(let i of n)r.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&Ns(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
90
|
+
`)+`
|
|
91
|
+
`)}prune(e){let t=this.getAll(e);t.length<=Fs||(t.sort((n,r)=>r.confidence*r.accessCount-n.confidence*n.accessCount),t=t.slice(0,Fs),Ns(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
92
|
+
`)+`
|
|
93
|
+
`))}};async function Hs(s,e,t,n,r){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-KO2DODIO.js"),c=(await o("claude").generate([{role:"system",content:ti},{role:"user",content:`User: ${e.slice(0,500)}
|
|
94
|
+
|
|
95
|
+
Agent: ${t.slice(0,1e3)}`}],{model:ei,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let u=JSON.parse(c[0]);if(!(!Array.isArray(u)||u.length===0)){for(let l of u)r.hasSimilar(s,l.pattern)||r.addPattern(s,{agentId:s,pattern:l.pattern,context:l.context,confidence:l.confidence||.5,source:n});Math.random()<.05&&r.prune(s)}}import{EventEmitter as ni}from"events";var Wt=class{inner=new ni;constructor(){this.inner.setMaxListeners(50)}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){return this.inner.emit(e,t)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this}},Bt;function te(){return Bt||(Bt=new Wt),Bt}ft();ft();var js=["manual","notify","auto"];function si(s){return typeof s=="string"&&js.includes(s)}var Kt={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var De=class{sessions=new Map;items=new Map;waiters=new Map;opts;constructor(e={}){this.opts={...Kt,...e}}options(){return this.opts}register(e,t={}){let n=t.now??Date.now(),r=this.sessions.get(e);if(r)return r.lastSeenAt=n,t.cwd&&(r.cwd=t.cwd),t.model&&(r.model=t.model),r;let o={sessionId:e,cwd:t.cwd??"",agentIds:[],mode:"notify",lastSeenAt:n,registeredAt:n,model:t.model,drainedThisTurn:0};return this.sessions.set(e,o),o}touch(e,t=Date.now()){let n=this.sessions.get(e);return n&&(n.lastSeenAt=t),n}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,n){let r=this.sessions.get(e);if(r){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));return r.agentIds.includes(t)||r.agentIds.push(t),n&&(r.mode=n),r}}unbind(e,t){let n=this.sessions.get(e);if(n)return n.agentIds=t?n.agentIds.filter(r=>r!==t):[],n}setMode(e,t){let n=this.sessions.get(e);if(n)return n.mode=t,n}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now()){this.sessions.delete(e);for(let n of this.items.values())n.sessionId===e&&(n.state==="pending"||n.state==="claimed")&&this.settle(n,"expired",t,"session ended")}offer(e,t=Date.now()){let n=this.sessionFor(e.agentId);if(!n)return null;if(t-n.lastSeenAt>this.opts.staleSessionMs)return this.deregister(n.sessionId,t),null;let r={id:he(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:ri(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(r.id,r),new Promise(o=>{this.waiters.set(r.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,n)=>t.createdAt-n.createdAt)}pendingCount(e){let t=0;for(let n of this.items.values())n.sessionId===e&&n.state==="pending"&&t++;return t}claim(e,t=Date.now()){let n=this.sessions.get(e);if(!n||n.awaitingAnswer)return;let r=this.pending(e)[0];if(!(!r||r.state!=="pending"))return r.state="claimed",r.claimedAt=t,n.awaitingAnswer=r.id,n.lastSeenAt=t,n.drainedThisTurn++,r}answer(e,t,n=Date.now()){let r=this.sessions.get(e);if(!r?.awaitingAnswer)return;let o=this.items.get(r.awaitingAnswer);if(r.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",n),o}release(e,t=Date.now()){let n=this.sessions.get(e);if(!n?.awaitingAnswer)return;let r=this.items.get(n.awaitingAnswer);if(n.awaitingAnswer=void 0,!(!r||r.state!=="claimed"))return r.state="pending",r.claimedAt=void 0,n.lastSeenAt=t,r}expire(e,t,n=Date.now()){let r=this.items.get(e);if(!r||r.state!=="pending"&&r.state!=="claimed")return!1;let o=this.sessions.get(r.sessionId);return o?.awaitingAnswer===r.id&&(o.awaitingAnswer=void 0),this.settle(r,"expired",n,t),!0}sweep(e=Date.now()){let t=0;for(let n of this.items.values())n.state==="pending"&&e-n.createdAt>=this.opts.claimTimeoutMs?this.expire(n.id,"not claimed in time",e)&&t++:n.state==="claimed"&&e-(n.claimedAt??n.createdAt)>=this.opts.claimTimeoutMs&&this.expire(n.id,"claimed but never answered",e)&&t++;for(let n of this.sessions.values())e-n.lastSeenAt>this.opts.staleSessionMs&&this.deregister(n.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let n=0;for(let[r,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(r),n++);return n}settle(e,t,n,r){e.state=t,e.settledAt=n;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:r??"expired"}))}};function ri(s,e){return s.length<=e?s:`${s.slice(0,e)}
|
|
96
|
+
\u2026[truncated ${s.length-e} chars]`}var qt;function Us(){return qt||(qt=new De),qt}yt();import{readFileSync as oi}from"fs";import{homedir as ii}from"os";import{join as ai}from"path";var Oe=null,ci=6e4;function di(){try{let s=ai(ii(),".claude.json"),e=oi(s,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function ui(s,e=Date.now()){if(!s)return{available:!0,checkedAt:e,unknown:!0};let t=typeof s.cachedExtraUsageDisabledReason=="string"?s.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function li(s=!1){let e=Date.now();return!s&&Oe&&e-Oe.checkedAt<ci||(Oe=ui(di(),e)),Oe}function Bs(s){let e=li();return e.available||s?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var Ws={warnRatio:.8},G={...Ws},gi=5*60*60*1e3,pi=60*60*1e3,le=[];function Ks(s){G={...Ws,...s||{}}}function qs(s){let e=s-gi,t=0;for(;t<le.length&&le[t]<e;)t++;t>0&&le.splice(0,t)}function Gs(s=Date.now()){qs(s),le.push(s)}function Js(s=Date.now()){qs(s);let e=s-pi,t=0;for(let o=le.length-1;o>=0&&le[o]>=e;o--)t++;let n=le.length,r={lastHour:t,last5h:n,maxPerHour:G.maxPerHour,maxPer5h:G.maxPer5h};return G.maxPerHour&&G.maxPerHour>0&&(r.hourlyRatio=t/G.maxPerHour),G.maxPer5h&&G.maxPer5h>0&&(r.fiveHourRatio=n/G.maxPer5h),r}function Qs(s,e=Date.now()){let t=Js(e);return s?null:G.maxPerHour&&t.lastHour>=G.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${G.maxPerHour} in the last hour. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPerHour in DaemonConfig if this is a false positive.`,usage:t}:G.maxPer5h&&t.last5h>=G.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${G.maxPer5h} in the last 5h. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPer5h in DaemonConfig if this is a false positive.`,usage:t}:null}function zs(s=Date.now()){let e=Js(s),t=G.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=t&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=t&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of cap)`:null}var Gt=new Map;function Xs(s,e,t){return t?`${s}:${e}:${t}`:`${s}:${e}`}function Ys(s,e,t,n=Date.now()){let r=Gt.get(s);r||(r={key:s,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},Gt.set(s,r)),r.samples+=1,r.baseline=.2*e+(1-.2)*r.baseline,r.current=e,r.peak=Math.max(r.peak,e),r.lastAt=n,r.ring.push({key:s,timestamp:n,total:e,parts:t}),r.ring.length>100&&r.ring.shift()}function Vs(s){let e=Gt.get(s);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let n=e.current/e.baseline;return`prompt-size drift for ${s}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as Y,mkdirSync as ji,readdirSync as ne,readFileSync as Ne,rmSync as Ui,writeFileSync as Bi}from"fs";import{resolve as B}from"path";import{existsSync as pe,mkdirSync as Jt,readFileSync as hi,readdirSync as mi,renameSync as fi,unlinkSync as yi,writeFileSync as it}from"fs";import{resolve as de,relative as at}from"path";import{z as K}from"zod";var ge=K.object({id:K.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:K.string().min(1),trigger:K.string().min(1,"procedures must describe when they apply"),inputs:K.array(K.string()).default([]),expected:K.string().optional(),kpis:K.array(K.string()).default([]),owner:K.string().optional(),tags:K.array(K.string()).default([]),status:K.enum(["draft","active","deprecated"]).default("active"),source:K.string().optional(),evidence:K.array(K.string()).default([]),created:K.string().optional(),updated:K.string().optional(),related:K.array(K.string()).default([])});function bi(s){let e=s.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:s};let t={};for(let n of e[1].split(`
|
|
97
|
+
`)){let r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!r)continue;let o=r[1],i=r[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function ct(s){let e=["---"];return e.push(`id: ${s.id}`),e.push(`title: "${s.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${s.trigger.replace(/"/g,'\\"')}"`),s.inputs?.length&&e.push(`inputs: ${JSON.stringify(s.inputs)}`),s.expected&&e.push(`expected: "${s.expected.replace(/"/g,'\\"')}"`),s.kpis?.length&&e.push(`kpis: ${JSON.stringify(s.kpis)}`),s.owner&&e.push(`owner: ${s.owner}`),s.tags?.length&&e.push(`tags: ${JSON.stringify(s.tags)}`),e.push(`status: ${s.status}`),s.source&&e.push(`source: "${s.source.replace(/"/g,'\\"')}"`),s.evidence?.length&&e.push(`evidence: ${JSON.stringify(s.evidence)}`),s.related?.length&&e.push(`related: ${JSON.stringify(s.related)}`),s.created&&e.push(`created: ${s.created}`),s.updated&&e.push(`updated: ${s.updated}`),e.push("---"),e.join(`
|
|
98
|
+
`)}var Ee=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??de(process.cwd(),".agentx/procedures"),Jt(this.baseDir,{recursive:!0})}pathFor(e){return de(this.baseDir,`${e}.md`)}get draftsDir(){return de(this.baseDir,"_drafts")}draftPathFor(e){return de(this.draftsDir,`${e}.md`)}parseFile(e){let t=hi(e,"utf-8"),{meta:n,body:r}=bi(t),o=ge.safeParse({...n,inputs:n.inputs||[],kpis:n.kpis||[],tags:n.tags||[],related:n.related||[],evidence:n.evidence||[]});return o.success?{meta:o.data,body:r.trim(),path:at(this.baseDir,e)}:null}listDir(e){if(!pe(e))return[];let t=[];for(let n of mi(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let r=this.parseFile(de(e,n.name));r&&t.push(r)}return t.sort((n,r)=>n.meta.id.localeCompare(r.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return pe(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return pe(t)?this.parseFile(t):null}add(e,t){let n=ge.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),r=this.pathFor(n.id);if(pe(r))throw new Error(`Procedure already exists: ${n.id}`);return it(r,ct(n)+`
|
|
99
|
+
|
|
100
|
+
`+t.trim()+`
|
|
101
|
+
`),{meta:n,body:t.trim(),path:at(this.baseDir,r)}}update(e,t,n){let r=this.get(e);if(!r)throw new Error(`Procedure not found: ${e}`);let o=ge.parse({...r.meta,...t,id:r.meta.id,updated:new Date().toISOString().slice(0,10)}),i=n!==void 0?n:r.body;return it(this.pathFor(e),ct(o)+`
|
|
102
|
+
|
|
103
|
+
`+i.trim()+`
|
|
104
|
+
`),{meta:o,body:i.trim(),path:r.path}}addDraft(e,t){let n=ge.parse({...e,status:"draft",created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)});if(this.get(n.id))throw new Error(`Procedure already exists: ${n.id}`);let r=this.draftPathFor(n.id);if(pe(r))throw new Error(`Draft already exists: ${n.id}`);return Jt(this.draftsDir,{recursive:!0}),it(r,ct(n)+`
|
|
105
|
+
|
|
106
|
+
`+t.trim()+`
|
|
107
|
+
`),{meta:n,body:t.trim(),path:at(this.baseDir,r)}}promoteDraft(e){let t=this.getDraft(e);if(!t)throw new Error(`Draft not found: ${e}`);if(this.get(e))throw new Error(`Procedure already exists: ${e}`);let n=ge.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return it(this.pathFor(e),ct(n)+`
|
|
108
|
+
|
|
109
|
+
`+t.body+`
|
|
110
|
+
`),yi(this.draftPathFor(e)),{meta:n,body:t.body,path:at(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!pe(t))throw new Error(`Draft not found: ${e}`);let n=de(this.draftsDir,"_rejected");Jt(n,{recursive:!0}),fi(t,de(n,`${e}.md`))}isRejected(e){return pe(de(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as wi,mkdirSync as xi,readFileSync as Ti,writeFileSync as ki}from"fs";import{dirname as Ii,resolve as Si}from"path";import{z as J}from"zod";var vi=J.object({key:J.string(),count:J.number().int().min(0).default(0),firstSeen:J.string(),lastSeen:J.string(),taskIds:J.array(J.string()).default([]),sampleMessage:J.string().default(""),status:J.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:J.string().optional()}),Ci=J.object({minedThrough:J.string().optional(),candidates:J.array(vi).default([])});function Zs(s){return Si(s,"_candidates.json")}function Ai(s){let e=Zs(s);if(!wi(e))return{candidates:[]};try{let t=Ci.safeParse(JSON.parse(Ti(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function $i(s,e){let t=Zs(s);xi(Ii(t),{recursive:!0}),ki(t,JSON.stringify(e,null,2)+`
|
|
111
|
+
`)}function Mi(s,e,t,n,r){let o=s.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:n,lastSeen:n,taskIds:[],sampleMessage:r,status:"counting"},s.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,n<o.firstSeen&&(o.firstSeen=n),n>o.lastSeen&&(o.lastSeen=n),o.sampleMessage||(o.sampleMessage=r)),o}function Pi(s,e){return s.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function Ri(s,e,t,n){let r=s.candidates.find(o=>o.key===e);r&&(r.status=t,n&&(r.procedureId=n))}function Qt(s){return new Set(s.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function er(s,e){if(s.size===0||e.size===0)return 0;let t=0;for(let n of s)e.has(n)&&t++;return t/Math.max(s.size,e.size)}function zt(s,e,t={}){let n=Math.max(1,t.limit??3),r=t.minScore??.2,o=Qt(s),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],u=er(o,Qt(a.meta.trigger));u>0&&c.push("trigger");let l=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),d=er(o,Qt(l));d>0&&c.push("title/tags");let p=Math.min(1,u*.7+d*.5);p>=r&&i.push({procedure:a,score:p,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,n)}function Xt(s){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...s.map(t=>{let n=t.procedure,r=[`[Known procedure: ${n.meta.title}]`,n.meta.trigger];return n.meta.inputs.length&&r.push(`Inputs: ${n.meta.inputs.join(", ")}`),r.push(n.body),n.meta.expected&&r.push(`Done when: ${n.meta.expected}`),r.push(`(details: agentx procedure show ${n.meta.id})`),r.join(`
|
|
112
|
+
`)})].join(`
|
|
113
|
+
|
|
114
|
+
`)}Tn();bt();var Vt="turn-progress",tr={progress:Ge({progressing:"Recent steps move the task forward: new files, commands or checks, results that differ from earlier ones, or a long step whose output shows it advancing.",looping:"The agent repeats the same or near-identical step (same command, same check, same edit retried with small tweaks) and gets the same failure or result each time.",blocked:"Progress depends on something the agent cannot change from here: missing access or credentials, a service that is down, or a decision only the user can make."},"How the agent's current turn is going, judged from its most recent steps.")},Yt=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s;function nr(s){return{agent:s.agent,request:Yt(s.request,1500),elapsedMinutes:Math.round(s.elapsedMinutes),budgetMinutes:s.budgetMinutes,trigger:s.trigger,recentSteps:s.steps.map(e=>({tool:e.tool,input:Yt(e.input,300),...e.result!==void 0?{result:Yt(e.result,300)}:{},...e.error?{failed:!0}:{}})),...s.repeated?{mostRepeatedCall:s.repeated}:{}}}bt();var sr="turn-handoff",rr="approval-binding",or={nextStep:Ge({proceed:"The question asks permission for a local, reversible next step that is already inside what the user asked for, such as writing or testing code in the working copy, reading, or running checks.",ask_outward:"The next step changes something outside the working copy or is hard to undo: pushing, publishing, merging, deploying, deleting, spending money, or messaging someone other than the user.",ask_ambiguous:"The agent cannot tell what the user wants: several different goals are plausible, or the user must choose between options with different results."},"What the agent should do with the question it ended its turn on.")},ir={approves:Ce("The user's message approves the plan or step the agent proposed at the end of its previous reply.",{true:'The message accepts the proposal, including terse replies such as "yes", "go ahead" or "ok do it", possibly with small additions that do not change the plan.',false:"The message declines, changes the plan, asks something new, or answers a different question than the one the agent asked."})},_i=(s,e)=>s.length>e?`${s.slice(0,e)}\u2026`:s,ar=(s,e)=>s.length>e?`\u2026${s.slice(-e)}`:s,Di=/(should i|want me to|shall i|do you want|which (one|option|task)|let me know)[^\n]*$/i;function Zt(s){let e=s.trim();return e?/\?\s*(\*\*)?\s*$/.test(e)?!0:Di.test(e.split(`
|
|
115
|
+
`).slice(-3).join(" ")):!1}var Oi=/^\s*(yes|yep|yeah|ok(ay)?|sure|go( ahead)?|proceed|do it|please do|confirmed?|approved?|go-ahead|let'?s go|oui|نعم)\b/i;function cr(s){return s.trim().length<=160&&Oi.test(s)}function dr(s){return s.trim().length<=160}function ur(s){return{agent:s.agent,channel:s.channel,request:_i(s.request,1500),agentReplyEnding:ar(s.reply,1200)}}function lr(s){return{agent:s.agent,channel:s.channel,userMessage:s.message,agentPreviousReplyEnding:ar(s.previousReply,1200)}}var Ei=5*6e4,Ni=3,Li=12,Fi=24*60*6e4,gr=new Set(["cron","heartbeat","bench","a2a","business"]),Hi={observe(){},stop(){}};function pr(s){if(xn(Vt)==="off")return Hi;let e=s.now??Date.now,t=e(),n=[],r=new Map,o=new Map,i=new Set,a=0,c=!1,u=()=>{let p;for(let[h,x]of o)x>1&&(!p||x>p.times)&&(p={call:h,times:x});return p},l=p=>{if(c)return;c=!0,a=n.length;let h=nr({agent:s.agent,request:s.request,elapsedMinutes:(e()-t)/6e4,budgetMinutes:s.budgetMinutes,steps:n.slice(-Li),repeated:u(),trigger:p});me(Vt,h,tr,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,trigger:p}}).finally(()=>{c=!1})},d=setInterval(()=>{n.length>a&&l("checkpoint")},s.checkpointMs??Ei);return d.unref?.(),{observe(p){let h=Array.isArray(p?.message?.content)?p.message.content:[];if(p?.type==="assistant")for(let x of h){if(x?.type!=="tool_use")continue;let T=x.input?JSON.stringify(x.input):"",w={tool:x.name||"tool",input:T};n.push(w),typeof x.id=="string"&&r.set(x.id,w);let I=`${w.tool}(${T})`,g=(o.get(I)??0)+1;o.set(I,g),g>=Ni&&!i.has(I)&&(i.add(I),l("repetition"))}else if(p?.type==="user")for(let x of h){if(x?.type!=="tool_result")continue;let T=r.get(x.tool_use_id);T&&(T.result=Array.isArray(x.content)?x.content.map(w=>typeof w?.text=="string"?w.text:"").join(""):typeof x.content=="string"?x.content:"",x.is_error&&(T.error=!0))}},stop(){clearInterval(d)}}}var en=new Map,hr=(s,e,t)=>`${s}\0${e}\0${t}`;function mr(s){if(gr.has(s.channel)||!Zt(s.reply))return;let e=hr(s.agent,s.channel,s.chatId);me(sr,ur(s),or,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}}).then(t=>{t?.callId&&en.set(e,{callId:t.callId,at:Date.now()})})}function fr(s){if(gr.has(s.channel))return;let e=hr(s.agent,s.channel,s.chatId),t=en.get(e);if(t){en.delete(e);let n=wn().store;if(n&&Date.now()-t.at<Fi)try{n.label(t.callId,"userReply",cr(s.message)?"approved":"redirected",{kind:"outcome",labeledBy:"next-user-message"})}catch{}}!s.previousReply||!dr(s.message)||!Zt(s.previousReply)||me(rr,lr({agent:s.agent,channel:s.channel,message:s.message,previousReply:s.previousReply}),ir,{links:[{kind:"task",id:s.taskId}],features:{agent:s.agent,channel:s.channel}})}function yr(s,e){return e!=="claude-code"&&e!=="codex-cli"?!1:s==="github"||s==="gitlab"}var Ir;function Od(s){Ir=s}function Ed(){return Ir}var br=64*1024,Wi=5*60*1e3,Ie=".agentx/task-history",Ki=30;function Le(s,e=800){return s.length<=e?s:s.slice(0,e)+` \u2026[+${s.length-e} chars]`}function qi(s,e){let t={};return s?.path?.length&&(t.intentPath=s.path,t.intentPathLabel=s.pathLabel),e?.sender&&(t.sender=e.sender),e?.senderId&&(t.senderId=e.senderId),e?.senderUsername&&(t.senderUsername=e.senderUsername),e?.group&&e?.sender&&(t.group=e.group),Object.keys(t).length>0?t:void 0}function Gi(s,e,t={}){let n;try{n=s.listArticles(e)}catch{return""}if(n.length===0)return"";let r=new Map;for(let l of n){let d=l.meta.type||"untyped",p=r.get(d)||[];p.push(l.meta.title),r.set(d,p)}let o=t.maxArticles??400,i=n.length<=o,a=Array.from(r.entries()).sort().map(([l,d])=>i?`**${l}** (${d.length}) \u2014 ${d.sort().join(" \xB7 ")}`:`**${l}** \u2014 ${d.length} article${d.length===1?"":"s"}`).join(`
|
|
116
|
+
`),c=process.argv[1]||"dist/cli.js",u=s.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 the single source of truth]",`${n.length} article${n.length===1?"":"s"}. This is long-term memory for the whole fleet: who people are, what systems exist, what happened, what was decided, how we do things.`,"","It outranks every other context you are given. Your workspace memory, injected skills, mined procedures and behavioural patterns are all either staged into the wiki or derived from it \u2014 where any of them disagrees with the wiki, the wiki is right and the other is stale.","","Catalog:",a,"",`For the contents of an article, or any question spanning several, run:
|
|
117
|
+
node ${c} wiki query "the question" --dir ${u} --agent ${e}`,"","It walks the catalog and the wikilink graph and returns a cited answer. Ask it before you grep the workspace or answer from your own recollection.","[End Institutional Wiki]"].join(`
|
|
118
|
+
`)}var tn=8*1024;function wr(s){if(s.length<=tn)return s;let e=s.length-tn;return s.slice(0,tn)+`\u2026[+${e}]`}function xr(s,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let n of t){if(n?.type!=="tool_use")continue;let r=typeof n.name=="string"?n.name:"";r&&s.set(r,(s.get(r)??0)+1)}}function Ji(s,e){if(!s||s.length===0)return null;for(let t of s)if((e.get(t)??0)===0)return t;return null}function Tr(s,e,t){if(!t||typeof t!="object")return;let n=t.type,r=new Date().toISOString(),o=te();if(n==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:s,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?wr(a):null,at:r})}return}if(n==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:s,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?wr(a):null,at:r})}return}}function Qi(){let s="",e="";return t=>{if(!t||typeof t!="object")return"";let n=t.type;if(n==="opencode.ready")return`. opencode ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
119
|
+
`;if(n==="opencode.first_output")return`. opencode first output=${t.elapsedMs}ms
|
|
120
|
+
`;if(n==="opencode.fallback")return`. opencode using CLI fallback: ${t.reason}
|
|
121
|
+
`;if(n==="codex.ready")return`. codex ${t.reused?"reused":"started"} ready=${t.startupMs}ms
|
|
122
|
+
`;if(n==="codex.first_output")return`. codex first output=${t.elapsedMs}ms
|
|
123
|
+
`;if(n==="codex.fallback")return`. codex using CLI fallback: ${t.reason}
|
|
124
|
+
`;if(n==="codex.spawned"){let r=t.model?` model=${t.model}`:"",o=t.resumeSessionId?` resume=${String(t.resumeSessionId).slice(0,8)}`:"";return`. codex started${r}${o}
|
|
125
|
+
`}if(n==="thread.started")return`. codex thread started${t.thread_id?` thread=${String(t.thread_id).slice(0,8)}`:""}
|
|
126
|
+
`;if(n==="turn.started")return`. codex turn started
|
|
127
|
+
`;if(n==="turn.completed"){let r=t.usage||{},o=r.input_tokens??r.inputTokens,i=r.output_tokens??r.outputTokens;return`. codex turn completed${o||i?` input=${o||0} output=${i||0}`:""}
|
|
128
|
+
`}if(n==="item.started"||n==="item.completed"){let r=t.item||{};if(r.type==="agent_message"&&typeof r.text=="string"){let c=r.text,u=c.startsWith(e)?c.slice(e.length):c;return e=c.startsWith(e)?c:e+c,u}let o=r.type||"item",i=r.name||r.command||r.tool_name||r.id||"";if(n==="item.started")return`
|
|
129
|
+
> codex ${o}${i?` ${i}`:""}
|
|
130
|
+
`;let a=r.output||r.result||r.text||r.error||"";return`< codex ${o}${i?` ${i}`:""}${a?`: ${Le(String(a),800)}`:""}
|
|
131
|
+
`}if(n==="error"||n==="turn.failed"){let r=t.message||t.error||t.reason||JSON.stringify(t);return`[error] ${Le(String(r),800)}
|
|
132
|
+
`}if(n==="system"&&t.subtype==="init"){let r=t.model?` model=${t.model}`:"",o=t.session_id?` session=${t.session_id.slice(0,8)}`:"";return`\xB7 init${r}${o}
|
|
133
|
+
`}if(n==="assistant"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="text"&&typeof o.text=="string")o.text.length>s.length&&(r+=o.text.slice(s.length),s=o.text);else if(o.type==="thinking"&&typeof o.thinking=="string")r+=`
|
|
134
|
+
\u{1F4AD} ${Le(o.thinking,600)}
|
|
135
|
+
`;else if(o.type==="tool_use"){let i=o.name||"tool",a=o.input?Le(JSON.stringify(o.input),400):"";r+=`
|
|
136
|
+
\u2192 ${i}(${a})
|
|
137
|
+
`}return r}if(n==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Le(i,800)}
|
|
138
|
+
`}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
139
|
+
`:""}}var kr=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Nn;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;classifier;graphStore;handoverStore=new En;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new tt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new On(void 0,void 0,"unified"),this.memoryStore=new st,this.patternStore=new ot,this.rateLimiter=new nt,this.tokenTracker=new ke,this.messageQueue=new rt,Ks({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new _n({baseDir:B(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Dn({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let u=c.toLowerCase();n.includes(u)&&u.length>o&&(r=i,o=u.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,o){let i=null,a=null,c=[];try{let p=this.sessions.getSession(e.agentId,n,r);i=vs(p.messages,e.message??""),c=Cs(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let u={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await me(Wn,qn(u),Kn,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!Gn(l.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,r),te().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-QEO3COFH.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let u=o.split(/[:@.]/).filter(Boolean).slice(0,4);this.memoryStore.addMemory(e,{agentId:e,category:"fact",content:`[Rotation memo \xB7 ${i}] ${c.memo}`,keywords:["rotation-memo",r,...u],source:{channel:r,chatId:o,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}}),this.sessions.setRotationMemo(e,r,o,c.memo,i),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let n=[];for(let[r,o]of this.agents)r!==e&&n.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
|
|
140
|
+
`)[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(a){i={content:"",error:a?.message??String(a)}}if(e.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Fn().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,r){let o=re(e.autonomy),i=o?null:Us().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(i){let m=await i;if(m.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${m.sessionId}`),{content:m.text,viaAttachedSession:m.sessionId};this.log(`[${e.agentId}] attached session did not take it (${m.reason}) \u2014 spawning`)}let a=this.agents.get(e.agentId);if(!a){if(o)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(this.meshFallback){let m=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(M=>M.id===e.agentId));if(m){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${m.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(m.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:m.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${m.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let c=e.context?.channel||"api",u=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||o){let m=Date.now(),f=25*6e4,M=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-m>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(N=>setTimeout(N,M))}}else{let m=a.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,c,u,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:u,originalContext:e.context});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let M=this.messageQueue.pendingCount(e.agentId,c,u);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${M})`),{content:"",error:`__queued__:${f}:${M}`}}}let l=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(m,f)=>{this.log(`[${e.agentId}] ${m} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(!l.ok)return this.log(`[${e.agentId}] ${l.reason}`),{content:"",error:l.reason};a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let d={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};if(a.runningTasks.push(d),e.runningTaskId=d.id,e.onStart)try{e.onStart(d.id)}catch{}let p=new AbortController;this.taskAborts.set(d.id,{agentId:e.agentId,channel:d.channel,chatId:typeof d.chatId=="string"?d.chatId:"",originalMessage:e.message||"",controller:p});let h={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(d.id,h);let x=m=>{if(m){h.buffer+=m,h.buffer.length>br&&(h.buffer=h.buffer.slice(h.buffer.length-br));for(let f of h.subscribers)try{f(m)}catch{}}},T=he();e.taskId=T;let w=new Map,I;if(t){let m=Qi();I=f=>{let M=m(f);if(M&&x(M),Tr(T,e.agentId,f),xr(w,f),r)try{r(f)}catch{}}}else I=m=>{if(Tr(T,e.agentId,m),xr(w,m),r)try{r(m)}catch{}};this.messageQueue.markRunning(e.agentId,c,u),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent})`);let g=e.context?.channel||"api",{evaluateRequest:_,selectRequestContext:A}=await import("./request-planner-KYQCJDAW.js"),S=await _(e.message,e.agentId,g);S.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let y=e.context?.chatId||e.context?.group||e.context?.sender||"default",O=e.context?.sender||"User",C=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,g,y),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${g}:${y}`),te().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:y,reason:"stale",at:new Date().toISOString()})),e.freshSession||await this.sessions.seedIfEmpty(e.agentId,g,y,e.seedHistory);let E=[...this.sessions.getSession(e.agentId,g,y).messages].reverse().find(m=>m.role==="agent")?.content;fr({agent:e.agentId,channel:g,chatId:y,message:e.message,previousReply:E,taskId:T}),this.sessions.addUserMessage(e.agentId,g,y,O,e.message);let F=Date.now();te().emit("task:started",{agentId:e.agentId,channel:g,chatId:y,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(F).toISOString(),taskId:T});let D;if(this.classifier&&g!=="a2a"&&!C)try{D=await this.classifier.classify({text:e.message,channel:g,sender:e.context?.sender,agentId:e.agentId})||void 0}catch(m){this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`)}let L=this.config.workflows?.matching,v;if(this.config.workflows?.enabled&&L?.enabled&&!o)try{let m=new Un({baseDir:B(process.cwd(),this.config.workflows.dir)}),f=Bn({agentId:e.agentId,channel:g,message:e.message,intentPath:D?.path},m.list());f&&f.confidence>=L.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${L.mode} reasons=${f.reasons.join(",")||"n/a"}`),L.mode==="auto"&&f.confidence>=L.autoRunThreshold&&(this.workflowAutoRunner?v={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(m){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${m?.message||m}`)}let b=this.wikiHub.getAgentWiki(e.agentId),k=this.memoryStore.findRelevant(e.message,e.agentId,C?3:8),R=this.memoryStore.buildContext(k),U=this.patternStore.findRelevant(e.message,e.agentId,5),P=this.patternStore.buildContext(U),z="";if(!C)try{let{loadLocalSkills:m,getAutoInjectSkills:f}=await import("./loader-BOKE5M5S.js"),M=await m(a.def.workspace);z=f(M,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,g,y):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,g,y):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,g,y):void 0;if(j&&this.sessions.isSessionStale(e.agentId,g,y)&&(this.log(`[${e.agentId}] session stale for ${g}:${y}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,y,"stale"),this.sessions.clearClaudeSessionId(e.agentId,g,y),te().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:y,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,g,y)){let m=this.sessions.getLastTurnContextTokens(e.agentId,g,y);this.log(`[${e.agentId}] tier-2 rotation for ${g}:${y} (last turn context: ${m} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,y,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,g,y),te().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:y,reason:"tier-2",lastTurnInputTokens:m,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,g,y)){let m=this.sessions.getTurnCount(e.agentId,g,y);this.log(`[${e.agentId}] max-turns rotation for ${g}:${y} (${m} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,g,y,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,g,y),te().emit("session:rotated",{agentId:e.agentId,channel:g,chatId:y,reason:"max-turns",at:new Date().toISOString()}),j=void 0}j&&a.def.tier==="claude-code"&&await this.maybeRotateForContinuity(e,a,g,y,j)&&(j=void 0);try{let m=await this.sessions.compactIfNeeded(e.agentId,g,y,this.memoryStore);if(m.compacted){let f=m.qualityScore??"?",M=m.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${g}:${y} (quality: ${f}%, ${M} entities lost)`),m.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${m.lostEntities.slice(0,5).join(", ")}`),m.drift){let N=m.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${N.overallScore} (lexicon=${N.lexiconDecay}, tools=${N.toolShift}, semantic=${N.semanticDrift})`),N.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${N.lostWords.slice(0,5).join(", ")}`)}}}catch(m){this.log(`[${e.agentId}] compaction failed (non-fatal): ${m.message}`)}let Sr=process.env.AGENTX_CONTEXT_SURGERY==="1",vr=C?{maxMessages:8,maxChars:2400}:Sr&&yr(g,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Cr=!j&&!C?Gi(b,e.agentId):void 0,Fe=j?void 0:this.sessions.buildHistoryContext(e.agentId,g,y,vr),Ar=j?void 0:this.sessions.getRotationMemo(e.agentId,g,y)??void 0,nn;if(this.config.procedures?.injection?.enabled&&!j&&!C)try{let m=new Ee({baseDir:B(process.cwd(),this.config.procedures.dir)}),f=zt(e.message,m.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){nn=Xt(f);for(let M of f)this.log(`[${e.agentId}] procedure match ${M.procedure.meta.id} score=${M.score.toFixed(2)} (${M.reasons.join(",")})`)}}catch(m){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${m?.message||m}`)}if(ue&&ue.cat)try{let f=this.sessions.getSession(e.agentId,g,y).messages,M=f[0],N=f[f.length-1],W=Fe===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${Fe.length}c/${Fe.split(`
|
|
141
|
+
`).length}L`,V=`[${e.agentId}] ${g}:${y} ${W} | session.messages=${f.length}`+(f.length>0?` first=${M.timestamp.slice(11,19)}(${M.role}:${(M.content||"").slice(0,40).replace(/\n/g," ")}) last=${N.timestamp.slice(11,19)}(${N.role}:${(N.content||"").slice(0,40).replace(/\n/g," ")})`:"");ue.cat("context",V)}catch(m){ue.cat("context",`[${e.agentId}] context-diag error: ${m?.message??m}`)}let sn;if(a.def.contextReferences&&!j)try{let m=a.def.workspace,f=this.referencesCache.get(m);if(!f){let[N,W]=await Promise.all([It(a.def.workspace),St(a.def.workspace)]);if(N.byId.size===0&&W.recipes.length===0){let[V,$]=await Promise.all([It(process.cwd()),St(process.cwd())]);f={refs:V,recipes:$}}else f={refs:N,recipes:W};this.referencesCache.set(m,f)}let M=Hn({agentId:e.agentId,intentTags:D?.path,message:e.message},f.recipes,f.refs);M.cards.length>0&&(sn=Ln(M.cards,500*4)),M.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${M.unresolvedIds.join(", ")}`)}catch(m){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${m?.message||m}`)}let rn=this.sessions.getCrossSessionSummary(e.agentId,g,y,e.message),on,He=Ss(e.message);if(He)try{let m=this.sessions.recallTurns({agentId:e.agentId,channel:g,chatId:y,lookbackDays:He.lookbackDays,limit:12});if(m.turns.length>0){let f=[`[Long-memory recall \u2014 last ${He.lookbackDays}d on this chat (cue-triggered)]`],M=[...m.turns].sort((N,W)=>N.ts.localeCompare(W.ts));for(let N of M){let W=N.ts.slice(11,16)+" "+N.day,V=N.role==="user"?N.senderName||"User":N.senderName||"Agent";f.push(`${W} ${V}: ${N.content}`)}m.hasMore&&f.push(`[\u2026${m.totalScanned-m.turns.length}+ older turns available \u2014 call /recall with before=${m.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),on=f.join(`
|
|
142
|
+
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${He.lookbackDays}d, turns=${m.turns.length}, scanned=${m.totalScanned}`)}}catch(m){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${m.message}`)}let $r=C?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",an,cn,dn=!1;if($r==="planner"&&!S.active&&g!=="voice"&&g!=="desktop"){try{let{planContext:m}=await import("./context-planner-AQHJMVY2.js"),f=await m({agentId:e.agentId,channel:g,chatId:y,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore});f?(dn=!0,an=f.sessionHistory,R=f.memoryContext,rn=f.crossChatContext,cn=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(m){this.log(`[${e.agentId}] planner failed (non-fatal): ${m.message} \u2014 falling back to layered (keeping --resume for continuity)`)}dn&&j&&(this.sessions.clearClaudeSessionId(e.agentId,g,y),j=void 0)}let dt=`${e.agentId}:${g}:${y}`,je=vn(e.message);je&&(je==="default"?(this.activeSouls.delete(dt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(dt,je),this.log(`[${e.agentId}] Soul switched to: ${je}`)));let Mr=this.activeSouls.get(dt),Pr=In(a.def.workspace,Mr),Rr=Sn(Pr),_r=this.agentMemory.indexMarkdown(e.agentId),Dr=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
|
|
143
|
+
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.`:"",Or=a.def.richMessages!==!1&&(g==="telegram"||g==="whatsapp")?["[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."].join(`
|
|
144
|
+
`):"",un="";if(a.def.workspace){let m=B(a.def.workspace,"CLAUDE.md");if(Y(m))try{let f=Ne(m,"utf-8");un=`[Project CLAUDE.md]
|
|
145
|
+
${f.length>4e3?f.slice(0,4e3)+`
|
|
146
|
+
|
|
147
|
+
[CLAUDE.md truncated to 4KB]`:f}`}catch{}}let Ue=e.context?.runbookPath,ut=[];if(Ue&&Y(Ue)){let m=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],f=0,M=4e3,N=16e3;for(let W of m){if(f>=N)break;let V=B(Ue,W);if(Y(V))try{let $=Ne(V,"utf-8"),X=$.length>M?$.slice(0,M)+`
|
|
148
|
+
|
|
149
|
+
[${W} truncated to ${M} bytes]`:$;ut.push(`[Project Runbook \u2014 ${W} from ${Ue}]
|
|
150
|
+
${X}`),f+=X.length}catch{}}}let Er=ut.length>0?ut.join(`
|
|
151
|
+
|
|
152
|
+
`):"",lt=[a.def.systemPrompt||"",Dr,Or,un,Er,Rr||"",_r||""].filter(m=>m.trim().length>0).join(`
|
|
153
|
+
|
|
154
|
+
`)||void 0,ln={channel:g,chatId:y,channelScope:e.context?.group?"group":g==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,g),systemPrompt:a.def.systemPrompt,sender:O,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:C||yr(g,a.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:C?void 0:P||void 0,procedureContext:nn,references:sn,skillInjection:z||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:an??Fe,memoryContext:R||void 0,crossChatContext:rn||void 0,longMemoryRecall:on||void 0,wikiContext:Cr,handoverNote:this.buildHandoverNote(e.agentId,g,y),rotationMemo:Ar,intent:D?{path:D.path,pathLabel:D.pathLabel,pathId:D.pathId,axes:D.axes,leaf:D.leaf,status:D.status}:void 0,message:e.message},gt=S.active&&S.preprocess?await A(ln):{input:ln,excluded:[]};gt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${gt.excluded.join(", ")}`);let pt=Ds(gt.input,C?{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),ht=(pt?.length??0)+(lt?.length??0)+(e.message?.length??0),Be={history:pt?.length??0,sysPrompt:lt?.length??0,message:e.message?.length??0},gn=Xs(e.agentId,g,y);Ys(gn,ht,Be);let pn=Vs(gn);pn&&this.log(`[${e.agentId}] ${pn}`),ht>16e3&&this.log(`[${e.agentId}] large context for ${g}:${y}: ${ht} bytes (history=${Be.history}, sysPrompt=${Be.sysPrompt}, message=${Be.message})`);let mt,hn=kn(a.def.tier,this.config.decisions.routing);if(!e.model&&hn&&(!S.active||S.preprocess))try{let{routeTaskModel:m}=await import("./routing-OC3QJI3W.js"),f=await m({message:e.message,agent:e.agentId,channel:g,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,g,y),cheapModel:hn});f.downgraded&&(mt=f.model,this.log(`[${e.agentId}] ${f.reason}`))}catch{}let Nr={...e,systemPromptAppend:lt,...mt?{model:mt}:{}},Z,mn=pr({agent:e.agentId,request:e.message,taskId:T,budgetMinutes:a.def.maxExecutionMinutes??20}),Lr=I;I=m=>{mn.observe(m),Lr?.(m)};try{if(v&&this.workflowAutoRunner)try{let H=await this.workflowAutoRunner({workflowId:v.workflowId,agentId:e.agentId,channel:g,chatId:y,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:g,chatId:y,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:D?.path,matchedWorkflowId:v.workflowId,matchConfidence:v.confidence}});return this.log(`[${e.agentId}] workflow auto-run started ${v.workflowId} run=${H.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),Z={content:"",duration:0,metadata:{handledByWorkflow:v.workflowId,workflowRunId:H.runId,workflowMatchConfidence:v.confidence}},Z}catch(H){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${H?.message||H}`)}if(a.def.tier==="claude-code"){let H=a.def.persistentProcess?Xe():null,Q=H!=null&&H.hasLive({agentId:e.agentId,channel:g,chatId:y}),se=!!j||Q,ee=[Bs(se),Qs(se)].find(ve=>ve&&ve.abort);if(ee){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ee.reason}`);let ve={content:"",error:ee.message,duration:0};if(!t){h.buffer=`[error] ${ee.message}`;for(let Fr of h.subscribers)try{Fr(h.buffer)}catch{}}return Z=ve,ve}Gs();let Se=zs();Se&&this.log(`[${e.agentId}] ${Se}`)}let m=a.def.tier==="claude-code",f=m?t:(H,Q)=>{H&&x(H),t&&t(H,Q)},M=!1,N=m?n:H=>{H&&(M?x(H):(x(`\u{1F4AD} ${H}`),M=!0)),n&&n(H)},W=()=>{M&&(x(`
|
|
155
|
+
`),M=!1)},V=m?f:f?(H,Q)=>{W(),f(H,Q)}:void 0,$=await Ts(a.def,Nr,this.providers,V,pt,j,I,p.signal,N);if(!$.error){let H=Ji(a.def.toolUseRequired,w);if(H){let Q=Array.from(w.entries()).map(([se,We])=>`${se}=${We}`).join(", ")||"none";$.error=`tool_required_not_called: ${H} (invoked: ${Q})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${H}, observed ${Q}`)}}Z=$;let X=$.usage?Rs($.usage):void 0;if(te().emit("task:completed",{taskId:T,agentId:e.agentId,channel:g,chatId:y,durationMs:Date.now()-F,error:$.error||void 0,inputTokens:X?.inputTokens,outputTokens:X?.outputTokens,cacheReadTokens:X?.cacheReadTokens,cacheCreateTokens:X?.cacheCreateTokens,tier2InputTokens:X?.tier2InputTokens,tier2OutputTokens:X?.tier2OutputTokens,tier2CacheReadTokens:X?.tier2CacheReadTokens,tier2CacheCreateTokens:X?.tier2CacheCreateTokens,resumed:!!j,resumeSessionId:j||void 0,jevArm:S.arm,finalResponse:$.content||void 0,billedModel:$.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let H=$.error?`[error] ${$.error}`:$.content;h.buffer=H;for(let Q of h.subscribers)try{Q(H)}catch{}}if($.error)a.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,g,y,$.content),mr({agent:e.agentId,channel:g,chatId:y,request:e.message,reply:$.content,taskId:T}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,g,y,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,g,y,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,g,y,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,g,y,$.usage,$.contextTokens),$.usage){let ee=$.contextTokens,Se=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ee??Se)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${g}:${y}: context=${ee??"n/a"} tokens (cumulative turn total=${Se}) \u2014 next turn will rotate`)}if($n({channel:g,content:`User: ${e.message}`,responseLength:$.content.length}).capture){try{let ee=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ee,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:g,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
156
|
+
|
|
157
|
+
Agent: ${$.content}`,meta:qi(D,e.context)})}catch{}Rn(e.agentId,e.message,$.content,{channel:g,chatId:y,sender:O},this.memoryStore).catch(()=>{}),Hs(e.agentId,e.message,$.content,{channel:g,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let Q=$.billedModel||e.model||a.def.model,se=e.context?.channel,We=se&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${se}:${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,Q,se,We),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:""))}return $}catch(m){a.errors++,this.log(`[${e.agentId}] unexpected error: ${m.message}`);let f=Qe(m.message);return Z={content:"",error:ze(f),errorKind:f.kind},Z}finally{mn.stop(),a.activeTasks--;let m=a.runningTasks.findIndex(f=>f.id===d.id);m!==-1&&a.runningTasks.splice(m,1),this.taskAborts.delete(d.id),h.done=!0,h.endedAt=new Date;for(let f of h.subscribers)try{f(`
|
|
158
|
+
[task finished]
|
|
159
|
+
`)}catch{}h.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(d.id),Wi).unref?.();try{let f=h.endedAt,M={id:d.id,agentId:e.agentId,channel:d.channel,chatId:d.chatId,sender:d.sender,message:e.message||"",startedAt:d.startedAt.toISOString(),endedAt:f.toISOString(),durationMs:f.getTime()-d.startedAt.getTime(),ok:!Z?.error,error:Z?.error,responseText:Z?.content||"",transcript:h.buffer};this.persistTaskRecord(M);let N=(M.responseText||M.error||"").trim();if(N){let W=N.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:W,at:f,ok:M.ok})}}catch(f){this.log(`[${e.agentId}] task history persist failed: ${f?.message}`)}this.messageQueue.markDone(e.agentId,c,u).then(f=>{if(f.length!==0){this.log(`[${e.agentId}] flushing ${f.length} queued message(s)`);for(let M of f){let N=M.originalContext||{channel:M.channel,sender:M.sender,chatId:M.chatId};this.execute({message:M.text,agentId:e.agentId,context:N}).then(W=>this.postQueuedResponseToChannel(e.agentId,N,W)).catch(W=>{this.log(`[${e.agentId}] queued message failed: ${W.message}`)})}}}).catch(f=>{this.log(`[${e.agentId}] queue flush failed: ${f.message}`)})}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;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=B(process.cwd(),Ie,this.safe(e.agentId),t);Y(n)||ji(n,{recursive:!0});let r=B(n,`${this.safe(e.id)}.json`);Bi(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=B(process.cwd(),Ie,this.safe(e));if(!Y(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),u=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let d of[u,c]){let p=B(a,d);if(Y(p))try{for(let h of ne(p)){if(!h.endsWith(".json"))continue;let x=h.split("-")[0],T=parseInt(x,10);if(!Number.isFinite(T)||T<i||T>n)continue;let w=Math.floor((n-T)/36e5),I=t-1-w;I>=0&&I<t&&o[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=B(process.cwd(),Ie);if(!Y(e))return 0;let t=0;for(let n of ne(e)){let r=B(e,n),o;try{o=ne(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=B(r,i),c;try{c=ne(a).filter(u=>u.endsWith(".json")).sort().reverse()}catch{continue}for(let u of c)try{let l=JSON.parse(Ne(B(a,u),"utf-8")),d=(l.responseText||l.error||"").trim();if(!d)continue;let p=d.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=Ki){let t=B(process.cwd(),Ie);if(!Y(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ne(t)){let i=B(t,o),a;try{a=ne(i)}catch{continue}for(let c of a){let u=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(u)||u>=n))try{Ui(B(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=B(process.cwd(),Ie,this.safe(e));if(!Y(n))return[];let r=ne(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=B(n,i),c;try{c=ne(a).filter(u=>u.endsWith(".json"))}catch{continue}c.sort().reverse();for(let u of c){if(o.length>=t)break;try{let l=JSON.parse(Ne(B(a,u),"utf-8")),{transcript:d,responseText:p,...h}=l;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let n=B(process.cwd(),Ie,this.safe(e));if(!Y(n))return null;let r=this.safe(t),o=ne(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=B(n,i,`${r}.json`);if(Y(a))try{return JSON.parse(Ne(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=jn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.error?.startsWith("__queued__"))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}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}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}}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:u}=o,l=o.controller.signal.aborted,d=!1;l&&u&&(d=this.sessions.removeLastUserMessageIfMatches(i,a,c,u)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let p=this.messageQueue.pendingCount(i,a,c),h=!1;if(r.replace){let x=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(x))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${x}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${d?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:d,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,c=i.chatId;return new Promise(u=>{let l=!1,d=p=>{l||(l=!0,u(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>d({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{p.error?.startsWith("__queued__")?d({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?d({ok:!1,status:500,error:p.error||"run did not start"}):d({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>d({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}};export{Jn as a,Qn as b,aa as c,Xn as d,eo as e,Yn as f,es as g,wa as h,Ia as i,Sa as j,fo as k,bs as l,To as m,ko as n,Io as o,Ts as p,tt as q,nt as r,st as s,te as t,js as u,si as v,Us as w,Ee as x,Ai as y,$i as z,Mi as A,Pi as B,Ri as C,zt as D,Od as E,Ed as F,qi as G,Gi as H,tn as I,wr as J,xr as K,Ji as L,Tr as M,kr as N};
|
|
160
|
+
//# sourceMappingURL=chunk-GAUQOIEE.js.map
|