agentix-cli 0.70.1 → 0.71.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/mac-voice/Sources/AgentXVoice/CallModel.swift +55 -0
- package/apps/mac-voice/Sources/AgentXVoice/Calls.swift +172 -0
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +28 -3
- package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +2 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +108 -4
- package/dist/{App-LFQTOADB.js → App-PRD5JNO4.js} +2 -2
- package/dist/{ChatApp-RNMG2HWX.js → ChatApp-BKS6OJ3L.js} +2 -2
- package/dist/{agent-7IW6472I.js → agent-QF2JQ72Z.js} +2 -2
- package/dist/{board-dashboard-MYWXVYU3.js → board-dashboard-AROMOAKS.js} +4 -4
- package/dist/{chunk-MTPCD4NV.js → chunk-3C2SQDIH.js} +211 -201
- package/dist/chunk-3C2SQDIH.js.map +1 -0
- package/dist/{chunk-7PWXCN22.js → chunk-4XBYHKYG.js} +2 -2
- package/dist/{chunk-YFROK44Z.js → chunk-5Y7QRFSL.js} +2 -2
- package/dist/{chunk-RKZGENSE.js → chunk-6LTD7XL5.js} +2 -2
- package/dist/{chunk-RN7G3D53.js → chunk-AAA6NGY5.js} +2 -2
- package/dist/chunk-AHOGFVHA.js +15 -0
- package/dist/{chunk-XXBW7CFN.js.map → chunk-AHOGFVHA.js.map} +1 -1
- package/dist/{chunk-D3RJMC37.js → chunk-BO4WLXXC.js} +2 -2
- package/dist/{chunk-KTGPH77J.js → chunk-D233M73Q.js} +2 -2
- package/dist/{chunk-O2QVQVOV.js → chunk-DJMUP6TK.js} +2 -2
- package/dist/{chunk-4J4YVJFH.js → chunk-EMRQ6W5J.js} +2 -2
- package/dist/{chunk-N4EIYNN4.js → chunk-HXW4NAWF.js} +2 -2
- package/dist/{chunk-KTNOY4LW.js → chunk-IK2XG65P.js} +2 -2
- package/dist/{chunk-MOUSATFW.js → chunk-JBVABB26.js} +2 -2
- package/dist/{chunk-E6CYC4HQ.js → chunk-JU67IZLC.js} +3 -3
- package/dist/chunk-JU67IZLC.js.map +1 -0
- package/dist/{chunk-3ZRFES25.js → chunk-K6CHA6JJ.js} +2 -2
- package/dist/{chunk-4HCQEGXO.js → chunk-MT3BD6WG.js} +164 -162
- package/dist/chunk-MT3BD6WG.js.map +1 -0
- package/dist/{chunk-2DWDXT7G.js → chunk-OTMDMGHE.js} +5 -5
- package/dist/{chunk-LKA5UUGT.js → chunk-RCKICCTT.js} +2 -2
- package/dist/{chunk-5FD7HE2J.js → chunk-SELIVR6U.js} +2 -2
- package/dist/{chunk-7334DGUO.js → chunk-SFWA67GQ.js} +2 -2
- package/dist/{chunk-FEQ4W4XA.js → chunk-WLX4766Y.js} +2 -2
- package/dist/{chunk-DXAWW7ZQ.js → chunk-XJQNIFZ4.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/client-UPBQVXYM.js +2 -0
- package/dist/config-UY5K6SCL.js +2 -0
- package/dist/config-mutator-7KOSRAQF.js +2 -0
- package/dist/doctor-GFPSIJGB.js +2 -0
- package/dist/index.d.ts +55 -0
- package/dist/index.js +1 -1
- package/dist/program-XMGZOYX3.js +2 -0
- package/dist/{promote-USGFU5NN.js → promote-YLKNYYIU.js} +2 -2
- package/dist/{query-NLSKOIWJ.js → query-CVRXEG43.js} +2 -2
- package/dist/registry-HZL363TA.js +2 -0
- package/dist/{request-planner-VOWMXWRI.js → request-planner-76NCBYBW.js} +2 -2
- package/dist/{review-candidates-F6RLNHS2.js → review-candidates-ZUXMX6BJ.js} +2 -2
- package/dist/{routing-2LAWEIUG.js → routing-EIGWDKH7.js} +2 -2
- package/dist/schedule-tool-PSZMP7C4.js +2 -0
- package/dist/scheduler-S24PXNB6.js +2 -0
- package/dist/{seat-4LLK2XBM.js → seat-QOY6FA4N.js} +2 -2
- package/dist/{select-NJHTHKEQ.js → select-JHKHO5BO.js} +2 -2
- package/dist/{set-enabled-HPR6VJCG.js → set-enabled-DVJIUOKX.js} +2 -2
- package/dist/{tool-XQMGKZP5.js → tool-WKSLNQ6H.js} +2 -2
- package/dist/wiki-PTXUMSIR.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-4HCQEGXO.js.map +0 -1
- package/dist/chunk-E6CYC4HQ.js.map +0 -1
- package/dist/chunk-MTPCD4NV.js.map +0 -1
- package/dist/chunk-XXBW7CFN.js +0 -15
- package/dist/client-IQIBHXVS.js +0 -2
- package/dist/config-7AK5TI2D.js +0 -2
- package/dist/config-mutator-EI5JNMY4.js +0 -2
- package/dist/doctor-CTWQODQG.js +0 -2
- package/dist/program-ZKGWGTPV.js +0 -2
- package/dist/registry-T7SCVP55.js +0 -2
- package/dist/schedule-tool-GOQFT2XQ.js +0 -2
- package/dist/scheduler-GJVRJQ7K.js +0 -2
- package/dist/wiki-RQ5P4WWJ.js +0 -2
- /package/dist/{App-LFQTOADB.js.map → App-PRD5JNO4.js.map} +0 -0
- /package/dist/{ChatApp-RNMG2HWX.js.map → ChatApp-BKS6OJ3L.js.map} +0 -0
- /package/dist/{agent-7IW6472I.js.map → agent-QF2JQ72Z.js.map} +0 -0
- /package/dist/{board-dashboard-MYWXVYU3.js.map → board-dashboard-AROMOAKS.js.map} +0 -0
- /package/dist/{chunk-7PWXCN22.js.map → chunk-4XBYHKYG.js.map} +0 -0
- /package/dist/{chunk-YFROK44Z.js.map → chunk-5Y7QRFSL.js.map} +0 -0
- /package/dist/{chunk-RKZGENSE.js.map → chunk-6LTD7XL5.js.map} +0 -0
- /package/dist/{chunk-RN7G3D53.js.map → chunk-AAA6NGY5.js.map} +0 -0
- /package/dist/{chunk-D3RJMC37.js.map → chunk-BO4WLXXC.js.map} +0 -0
- /package/dist/{chunk-KTGPH77J.js.map → chunk-D233M73Q.js.map} +0 -0
- /package/dist/{chunk-O2QVQVOV.js.map → chunk-DJMUP6TK.js.map} +0 -0
- /package/dist/{chunk-4J4YVJFH.js.map → chunk-EMRQ6W5J.js.map} +0 -0
- /package/dist/{chunk-N4EIYNN4.js.map → chunk-HXW4NAWF.js.map} +0 -0
- /package/dist/{chunk-KTNOY4LW.js.map → chunk-IK2XG65P.js.map} +0 -0
- /package/dist/{chunk-MOUSATFW.js.map → chunk-JBVABB26.js.map} +0 -0
- /package/dist/{chunk-3ZRFES25.js.map → chunk-K6CHA6JJ.js.map} +0 -0
- /package/dist/{chunk-2DWDXT7G.js.map → chunk-OTMDMGHE.js.map} +0 -0
- /package/dist/{chunk-LKA5UUGT.js.map → chunk-RCKICCTT.js.map} +0 -0
- /package/dist/{chunk-5FD7HE2J.js.map → chunk-SELIVR6U.js.map} +0 -0
- /package/dist/{chunk-7334DGUO.js.map → chunk-SFWA67GQ.js.map} +0 -0
- /package/dist/{chunk-FEQ4W4XA.js.map → chunk-WLX4766Y.js.map} +0 -0
- /package/dist/{chunk-DXAWW7ZQ.js.map → chunk-XJQNIFZ4.js.map} +0 -0
- /package/dist/{client-IQIBHXVS.js.map → client-UPBQVXYM.js.map} +0 -0
- /package/dist/{config-7AK5TI2D.js.map → config-UY5K6SCL.js.map} +0 -0
- /package/dist/{config-mutator-EI5JNMY4.js.map → config-mutator-7KOSRAQF.js.map} +0 -0
- /package/dist/{doctor-CTWQODQG.js.map → doctor-GFPSIJGB.js.map} +0 -0
- /package/dist/{program-ZKGWGTPV.js.map → program-XMGZOYX3.js.map} +0 -0
- /package/dist/{promote-USGFU5NN.js.map → promote-YLKNYYIU.js.map} +0 -0
- /package/dist/{query-NLSKOIWJ.js.map → query-CVRXEG43.js.map} +0 -0
- /package/dist/{registry-T7SCVP55.js.map → registry-HZL363TA.js.map} +0 -0
- /package/dist/{request-planner-VOWMXWRI.js.map → request-planner-76NCBYBW.js.map} +0 -0
- /package/dist/{review-candidates-F6RLNHS2.js.map → review-candidates-ZUXMX6BJ.js.map} +0 -0
- /package/dist/{routing-2LAWEIUG.js.map → routing-EIGWDKH7.js.map} +0 -0
- /package/dist/{schedule-tool-GOQFT2XQ.js.map → schedule-tool-PSZMP7C4.js.map} +0 -0
- /package/dist/{scheduler-GJVRJQ7K.js.map → scheduler-S24PXNB6.js.map} +0 -0
- /package/dist/{seat-4LLK2XBM.js.map → seat-QOY6FA4N.js.map} +0 -0
- /package/dist/{select-NJHTHKEQ.js.map → select-JHKHO5BO.js.map} +0 -0
- /package/dist/{set-enabled-HPR6VJCG.js.map → set-enabled-DVJIUOKX.js.map} +0 -0
- /package/dist/{tool-XQMGKZP5.js.map → tool-WKSLNQ6H.js.map} +0 -0
- /package/dist/{wiki-RQ5P4WWJ.js.map → wiki-PTXUMSIR.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Yn,b as Vn,d as es,f as nt,l as gs,r as ps,x as hs,z as ms}from"./chunk-
|
|
1
|
+
import{a as Yn,b as Vn,d as es,f as nt,l as gs,r as ps,x as hs,z as ms}from"./chunk-6LTD7XL5.js";import{a as Mt}from"./chunk-N6EWZGIX.js";import{a as Xn}from"./chunk-WP6KLXTP.js";import{b as Zn}from"./chunk-DP7RTNDM.js";import{a as ls}from"./chunk-W4YR2RO2.js";import{b as ns,c as _t,d as rs,e as os,h as is}from"./chunk-5Y7QRFSL.js";import{a as Rt,b as ts}from"./chunk-J3SOEFRE.js";import{a as Pt,b as ss}from"./chunk-SIU6STB2.js";import{e as as,i as cs,j as ds,k as us}from"./chunk-X5C5W3E4.js";import{a as Hn}from"./chunk-K6CHA6JJ.js";import{a as jn,b as Un,c as Bn,d as Wn,f as qn}from"./chunk-DWADWDMU.js";import{a as Kn,b as Gn}from"./chunk-23A5K5UW.js";import{a as zn}from"./chunk-RCKICCTT.js";import{g as Jn,h as Qn}from"./chunk-AAA6NGY5.js";import{a as tt,c as De}from"./chunk-2GIDVZ4H.js";import{q as Nn,t as Ln,v as Te,w as Fn}from"./chunk-DJMUP6TK.js";import{a as Ee,b as et,f as $t}from"./chunk-72SZI2UW.js";import{a as xe,b as Ct}from"./chunk-FCPTN6NF.js";import{c as Rn,d as Pn}from"./chunk-QOYAX2FT.js";import{e as me}from"./chunk-DSYKYZMT.js";import{A as So,d as _n,e as ie,f as En,g as Dn,h as At,s as On}from"./chunk-AHOGFVHA.js";Fn();$t();var fs="session-continuity",ys={continues:Ee("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:Ee("Does the new request refer to something stated earlier in the conversation?")};function bs(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Et(s.message,1200),previousRequest:s.previousMessage?Et(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Et(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function ws(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 Et(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as vo,execFile as Co}from"node:child_process";import{createHash as Ao,randomBytes as $o}from"node:crypto";import{createInterface as Mo}from"node:readline";import{promisify as Ro}from"node:util";var Po=Ro(Co),ae=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},Dt=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=Po("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 ae("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=Ao("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([d],[l])=>d.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new ae("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 g=[...this.entries].find(([,f])=>!f.busy);if(!g)throw new ae("Warm server capacity reached",!0);this.close(g[1]),this.entries.delete(g[0])}let d={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:$o(32).toString("hex")},l=vo("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:d,stdio:["pipe","pipe","pipe"]});o={child:l,env:d,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let u=o;l.stderr.resume(),l.on("exit",()=>this.close(u)),l.on("error",()=>this.close(u));try{await new Promise((g,f)=>{let y=Mo({input:l.stdout}),x=()=>T(new ae("OpenCode server failed before dispatch",!0)),b=()=>T(new Error("task cancelled by operator")),S=setTimeout(x,15e3),T=D=>{clearTimeout(S),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",b),y.close(),l.stdout.resume(),D?f(D):g()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",b,{once:!0}),y.on("line",D=>{try{let M=new URL(JSON.parse(D).url);if(M.protocol!=="http:"||M.hostname!=="127.0.0.1"||!M.port||M.username||M.password)return;u.url=M.origin,T()}catch{}}),e.signal?.aborted&&b()})}catch(g){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),g}}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:(d=!1)=>{c||(c=!0,a.busy=!1,d||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()))}}}},xs=new Dt;import{execa as ct}from"execa";import{spawn as _o}from"node:child_process";import{createHash as Eo}from"node:crypto";import{createInterface as Do}from"node:readline";var ce=class extends Error{},Oo=s=>_o("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Ot=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(),Do({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Nt=class{constructor(e=Oo,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=Eo("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[S])=>b.localeCompare(S))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ce("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 b=[...this.entries].find(([,S])=>!S.connection.busy);if(!b)throw new ce("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:n,connection:new Ot(e,this.launchProcess)}}catch{throw new ce("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="",d,l,u,g=!1,f=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",f,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),x=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 b={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",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(x),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let T=new Promise((D,M)=>{i.failTurn=M,i.notify=(C,_)=>{if(_?.threadId!==l)return;let N=_.item,E={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:C.replace("/","."),...N?{item:{...N,type:E[N.type]||N.type}}:{}}),C==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),C==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=_.delta,e.onDelta?.(_.delta,c)),C==="thread/tokenUsage/updated"){let L=_.tokenUsage.last,F=L.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-F),outputTokens:(u?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+F,cacheCreateTokens:(u?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}C==="turn/completed"&&(_.turn.status==="completed"?D():M(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return T.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await T,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new ce(b.message);return{content:c,codexSessionId:l,usage:u,error:b.message,duration:Date.now()-t}}finally{clearTimeout(x),clearTimeout(y),e.signal?.removeEventListener("abort",f),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())}}},Ts=new Nt;import{execFile as Yo}from"child_process";import{StringDecoder as Fe}from"string_decoder";import{mkdtempSync as Os,readFileSync as Ns,rmSync as Ls}from"fs";import{join as it}from"path";import{tmpdir as Fs}from"os";function st(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 d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[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 rt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var ks=null;function ot(){return ks}function Tc(s){ks=s}function Oe(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function No(s,e){if(s.state()==="busy")return null;let n=s.snapshot(),r=s.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?n.claudeSessionId&&n.claudeSessionId!==e.resumeSessionId?`session changed (${n.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:n.claudeSessionId?"session rotated":null}var ke=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Is=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=Oe(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=No(r,t);if(!a)return r.claim?.(),r;this.handles.delete(n),this.handleWorkspace.delete(n),this.cfg.log(`[process-registry] respawning ${n}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new ke(`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 ke(`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=Oe(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=Oe(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Oe(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=Oe(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",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Lo}from"child_process";import{existsSync as Fo,readFileSync as Ho}from"fs";import{resolve as jo}from"path";function Uo(s){let e=jo(s,"CLAUDE.md");if(!Fo(e))return null;try{let t=Ho(e,"utf8");return qn(t)}catch{return null}}var Bo=20*60*1e3,Wo=5e3,Ne=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Le=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function qo(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var Ss=class{constructor(e={}){this.opts=e}spawn(e,t){return new Lt(e,t,this.opts)}},Lt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=Lo(r,o,{cwd:t.workspace,env:De(qo({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:Uo(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 d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
3
|
`);let a=e.deadlineMs??Bo,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Ne(a));try{for(;;){let l=c-Date.now();if(l<=0)throw d();let u=await this.nextEvent(l);if(u===null&&this.killReason)throw new Le(this.killReason);if(u===null&&!this.exited)throw d();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Wo);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};At();import{resolve as vs,join as Cs}from"path";Ct();var Ko=4e3;function As(s){try{let e=Cs(vs(s.root),".agentx","db.sqlite"),t=Mt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=xe(),r=s.input.command?s.input.command.slice(0,Ko):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -27,7 +27,7 @@ ${s}`}function Zo(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
|
|
|
27
27
|
`,u)}};M.stdout?.on("data",I=>{E+=F.write(I);let w=E.split(`
|
|
28
28
|
`);E=w.pop()||"";for(let k of w)U(k)}),M.stderr?.on("data",I=>{L+=H.write(I)});let A=await M;if(i&&i.removeEventListener("abort",N),E+=F.end(),E.trim()&&U(E),L+=H.end(),C)return{content:"",error:_||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if(A.exitCode!==0||y){let I=A,w;return I.timedOut?w=`OpenCode timed out after ${Math.round(T/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:y?w=y:I.code==="ENOENT"||/ENOENT|spawn opencode/i.test((I.shortMessage||"")+" "+L)?w=_s():w=L.trim()||`OpenCode exited with code ${I.exitCode??"unknown"}`,{content:"",...G(w),duration:Date.now()-c,usage:g,opencodeSessionId:f}}return b=!1,{content:u.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||s.model,opencodeSessionId:f}}catch(T){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let D=/ENOENT|spawn opencode/i.test(T?.message||"")?_s():T?.message;return{content:u,...G(D||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:f}}finally{S?.(),x?.release(b)}}async function ui(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ue(s,e,n),c="",d=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of d)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...G(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function li(s,e,t,n,r,o,i,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,g=!1,f=()=>{let b=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(b))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let y=setTimeout(()=>{g=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);y.unref?.();let x=()=>({content:"",...G(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let b=s.provider||"claude-code",S=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,T=e.context?.sender,D=typeof T=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(T),M=e.context?.channel==="web-chat"&&D?{userId:T,agentId:e.agentId||"acme-public"}:void 0,C=Wn(s),_=Object.keys(C).length>0,N={task:S,cwd:s.workspace,provider:b,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:M,providerOpts:o,abortSignal:u.signal,mcpServers:_?C:void 0};if(r){let{generateStream:U}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,T=e.context?.sender,D=typeof T=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(T),M=e.context?.channel==="web-chat"&&D?{userId:T,agentId:e.agentId||"acme-public"}:void 0,C=Wn(s),_=Object.keys(C).length>0,N={task:S,cwd:s.workspace,provider:b,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:M,providerOpts:o,abortSignal:u.signal,mcpServers:_?C:void 0};if(r){let{generateStream:U}=await import("./agent-QF2JQ72Z.js"),A="",I,w,k,O;for await(let h of U(N)){if(c)try{c(h)}catch{}if(h.type==="text_delta")A+=h.text,r(h.text,A);else if(h.type==="thinking_delta")h.text&&i&&i(h.text);else if(h.type==="generate_result"){if(h.result.content&&h.result.content!==A){let ee=h.result.content.slice(A.length);ee?(A=h.result.content,r(ee,A)):A=h.result.content}I=h.result.tokensUsed,h.result.inputTokens!=null&&(w=h.result.inputTokens),h.result.outputTokens!=null&&(k=h.result.outputTokens)}else if(h.type==="done"){if(h.result.content&&h.result.content!==A){let ee=h.result.content.slice(A.length);ee?(A=h.result.content,r(ee,A)):A=h.result.content}h.result.tokensUsed!=null&&(I=h.result.tokensUsed)}else h.type==="error"&&(O=h.error)}return O&&!A?g?x():O==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...G(`Orchestrator error: ${O}`),duration:Date.now()-d}:((w===void 0||k===void 0)&&I&&(w=Math.round(I*.7),k=I-w),{content:A||"Done.",tokensUsed:I,usage:w!==void 0||k!==void 0?{inputTokens:w||0,outputTokens:k||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:E}=await import("./agent-QF2JQ72Z.js"),L=await E(N),F=L.inputTokens,H=L.outputTokens;if((F===void 0||H===void 0)&&L.tokensUsed){let U=L.tokensUsed;F=Math.round(U*.7),H=U-F}return{content:L.content||"Done.",tokensUsed:L.tokensUsed,usage:F!==void 0||H!==void 0?{inputTokens:F||0,outputTokens:H||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(b){return g?x():b?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...G(`Orchestrator error: ${b.message}`),duration:Date.now()-d}}finally{clearTimeout(y),a&&a.removeEventListener("abort",f)}}var gi=1e3;async function pi(s,e){let t=Promise.resolve(s).then(i=>({kind:"exit",r:i})),n,r=e.then(()=>new Promise(i=>{n=setTimeout(()=>i({kind:"grace"}),gi),n.unref?.()})),o=await Promise.race([t,r]);return n&&clearTimeout(n),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function hi(s,e,t,n,r,o,i){let a=ot();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:d,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let g,f=!1;try{let A=a.list().length;g=a.acquire(u,{agentId:e.agentId,channel:d,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),f=a.list().length>A}catch(A){return A instanceof ke,null}f&&Wt(e.agentId,s,e.model,n,"persistent");let y=ue(s,e,t),x="",b,S,T,D,M,C,_,N="",E="",L=A=>{if(!i||!A)return;let I;if(E&&A.startsWith(E)?I=A.slice(E.length):I=N&&!N.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
33
|
${A}`:A,E=A,!!I){N+=I;try{i(I,N)}catch{}}},F=!1,H=()=>{F=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?H():o.addEventListener("abort",H,{once:!0}));let U=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let I of g.runTurn({message:y,taskId:e.taskId??"unknown",deadlineMs:A})){if(U=!0,r)try{r(I.raw)}catch{}if(I.type==="assistant"){let w=I.raw.message?.content??[];for(let O of w)O.type==="text"&&typeof O.text=="string"?(x=O.text,L(O.text)):O.type==="tool_use"&&(E="");let k=I.raw.message?.usage;if(k){let O=(k.input_tokens||0)+(k.cache_read_input_tokens||0)+(k.cache_creation_input_tokens||0);O>0&&(D=O)}}if(I.type==="result"){let w=I.raw;if(w.is_error){let k=G(typeof w.result=="string"?w.result:"claude error");b=k.error,S=k.errorKind}else typeof w.result=="string"&&w.result.length>0&&(x=w.result,N||L(w.result));typeof w.session_id=="string"&&(_=w.session_id),w.usage&&(T={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(M=w.num_turns),typeof w.message?.model=="string"?C=w.message.model:typeof w.model=="string"&&(C=w.model)}}}catch(A){if(F)b="task cancelled by operator",S="cancelled";else if(U)if(A instanceof Le)b=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,S="interrupted";else if(A instanceof Ne){let I=G(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);b=I.error,S=I.errorKind}else{let I=G(`persistent claude process error: ${A?.message||String(A)}`);b=I.error,S=I.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",H),null}finally{o&&o.removeEventListener("abort",H)}return F&&!b&&(b="task cancelled by operator",S="cancelled"),{content:F?"":x,error:b,errorKind:S,duration:Date.now()-c,usage:T,contextTokens:D,numTurns:M,billedModel:C,claudeSessionId:_}}function Js(s){return ie(s.autonomy)?s.taskId?Ms(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function mi(s,e,t,n,r,o,i){let a=e.autonomy,c=Rs(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let d=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:d,message:`${Dn(a)}
|
|
@@ -131,7 +131,7 @@ Agent: ${t.slice(0,1e3)}`}],{model:ji,maxTokens:512})).content.trim().match(/\[[
|
|
|
131
131
|
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(c){i={content:"",error:c?.message??String(c)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;if(a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let c=i.error?nt(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";ns().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:c,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(c){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${c?.message??c}`)}return i}async executeInternal(e,t,n,r){let o=ie(e.autonomy),i=o?null:br().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(i){let p=await i;if(p.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${p.sessionId}`),{content:p.text,viaAttachedSession:p.sessionId};this.log(`[${e.agentId}] attached session did not take it (${p.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 p=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(v=>v.id===e.agentId));if(p){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${p.peer}"`);try{let m=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(p.peer,e.message,e.agentId,{timeoutMs:m}),viaMesh:p.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${p.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",l;if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||c==="app"||c==="a2a"||c==="mcp"||c==="reminder"||c==="events"||o){let p=Date.now(),m=25*6e4,v=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-p>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(P=>setTimeout(P,v))}}else if(c==="voice"){let p=Date.now(),m=25*6e4,v=`${e.agentId}\0${d}`;for(;this.messageQueue.isBusy(e.agentId,c,d)||this.voiceClaims.has(v);){if(Date.now()-p>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(m/6e4)}m`};await new Promise(P=>setTimeout(P,500))}l=v,this.voiceClaims.add(v)}else{let p=a.def.queueMode||"collect",m=this.messageQueue.enqueue(e.agentId,c,d,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:d,originalContext:e.context,queuedAt:e.queuedAt});if(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let v=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${v}) behind=${a.runningTasks.map(P=>P.id).join(",")||"-"} chat=${c}:${d} at=${new Date().toISOString()}`),{content:"",error:es(m,v)}}}let u=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(p,m)=>{this.log(`[${e.agentId}] ${p} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/1e3))}s`)}});if(l&&this.voiceClaims.delete(l),!u.ok)return this.log(`[${e.agentId}] ${u.reason}`),{content:"",error:u.reason};if(e.queuedAt!==void 0){let p=dr(e.queuedAt);p&&(e.message=`${p}
|
|
132
132
|
${e.message}`),e.queuedAt=void 0}a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let g={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(g),e.runningTaskId=g.id,this.runningContexts.set(g.id,e.context??{}),e.onStart)try{e.onStart(g.id)}catch{}let f=new AbortController;this.taskAborts.set(g.id,{agentId:e.agentId,channel:g.channel,chatId:typeof g.chatId=="string"?g.chatId:"",originalMessage:e.message||"",controller:f});let y={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(g.id,y);let x=p=>{if(p){y.buffer+=p,y.buffer.length>Xr&&(y.buffer=y.buffer.slice(y.buffer.length-Xr));for(let m of y.subscribers)try{m(p)}catch{}}},b=xe();e.taskId=b;let S=new Map,T=(p,m,v)=>{try{V().emit("task:step",{taskId:b,agentId:e.agentId,name:"pipeline",action:p,status:v,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},D=0,M=!1,C=()=>{M||(M=!0,D&&T("first-event",D,"ok"))},_;if(t){let p=ac();_=m=>{C();let v=p(m);if(v&&x(v),Zr(b,e.agentId,m),Vr(S,m),r)try{r(m)}catch{}}}else _=p=>{if(C(),Zr(b,e.agentId,p),Vr(S,p),r)try{r(p)}catch{}};let N=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,E=N?setTimeout(()=>f.abort(new Error(`timed out after ${Math.round(N/1e3)}s`)),N):void 0;E?.unref?.();let L=(a.def.preSpawnTimeoutSec??ec)*1e3,F=setTimeout(()=>{f.abort(new Error(`timed out before spawn after ${Math.round(L/1e3)}s in step "${g.step??"start"}"`))},L);F.unref?.();let H=()=>{F&&clearTimeout(F),F=void 0},U=()=>`task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`,A;f.signal.addEventListener("abort",()=>{let p=yt(f.signal).message;/^timed out/.test(p)&&(A=g.step??"start"),this.log(`[${e.agentId}] task ${g.id} aborted in step "${g.step??"start"}" \u2014 ${p} ${U()}`)},{once:!0});let I=p=>{g.step=p,this.log(`[${e.agentId}] step ${p} ${U()}`)},w=(p,m,v=0)=>{if(f.signal.aborted)return Promise.reject(yt(f.signal));I(p),(p==="agent"||p==="workflow-auto-run")&&(H(),D=Date.now());let P=Date.now();return Qr(m(),f.signal,v).then(W=>(T(p,P,"ok"),W),W=>{throw T(p,P,"error"),W})},k=!1,O=p=>{if(k)return;k=!0,this.runReleases.delete(g.id),E&&clearTimeout(E),H(),a.activeTasks--;let m=a.runningTasks.findIndex(v=>v.id===g.id);m!==-1&&a.runningTasks.splice(m,1),this.runningContexts.delete(g.id),this.taskAborts.delete(g.id),y.done=!0,y.endedAt=new Date;for(let v of y.subscribers)try{v(`
|
|
133
133
|
[task finished]
|
|
134
|
-
`)}catch{}y.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(g.id),Va).unref?.();try{let v=y.endedAt,P={id:g.id,agentId:e.agentId,channel:g.channel,chatId:g.chatId,sender:g.sender,message:e.message||"",startedAt:g.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-g.startedAt.getTime(),ok:!p?.error,error:p?.error,...A?{status:"timeout",step:A}:{},responseText:p?.content||"",transcript:y.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let Q=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:v,ok:P.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(v=>{if(v.length!==0){this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let P of v){let W=P.originalContext||{channel:P.channel,sender:P.sender,chatId:P.chatId};this.execute({message:P.text,agentId:e.agentId,context:W,queuedAt:P.queuedAt??P.timestamp}).then(Q=>this.postQueuedResponseToChannel(e.agentId,W,Q)).catch(Q=>{this.log(`[${e.agentId}] queued message failed: ${Q.message}`)})}}}).catch(v=>{this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(g.id,O),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${U()}`);let h=e.context?.channel||"api",{evaluateRequest:ee,selectRequestContext:no}=await import("./request-planner-
|
|
134
|
+
`)}catch{}y.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(g.id),Va).unref?.();try{let v=y.endedAt,P={id:g.id,agentId:e.agentId,channel:g.channel,chatId:g.chatId,sender:g.sender,message:e.message||"",startedAt:g.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-g.startedAt.getTime(),ok:!p?.error,error:p?.error,...A?{status:"timeout",step:A}:{},responseText:p?.content||"",transcript:y.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let Q=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:v,ok:P.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(v=>{if(v.length!==0){this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let P of v){let W=P.originalContext||{channel:P.channel,sender:P.sender,chatId:P.chatId};this.execute({message:P.text,agentId:e.agentId,context:W,queuedAt:P.queuedAt??P.timestamp}).then(Q=>this.postQueuedResponseToChannel(e.agentId,W,Q)).catch(Q=>{this.log(`[${e.agentId}] queued message failed: ${Q.message}`)})}}}).catch(v=>{this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(g.id,O),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${U()}`);let h=e.context?.channel||"api",{evaluateRequest:ee,selectRequestContext:no}=await import("./request-planner-76NCBYBW.js"),ge=await w("request-gate",()=>ee(e.message,e.agentId,h));ge.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let $=e.context?.chatId||e.context?.group||e.context?.sender||"default",bt=e.context?.sender||"User",te=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,h,$),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${h}:${$}`),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"stale",at:new Date().toISOString()})),e.freshSession||await w("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,h,$,e.seedHistory));let so=[...this.sessions.getSession(e.agentId,h,$).messages].reverse().find(p=>p.role==="agent")?.content;Jr({agent:e.agentId,channel:h,chatId:$,message:e.message,previousReply:so,taskId:b}),this.sessions.addUserMessage(e.agentId,h,$,bt,e.message);let dn=Date.now();V().emit("task:started",{agentId:e.agentId,channel:h,chatId:$,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(dn).toISOString(),taskId:b,resumeOrigin:ar(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let X,wt,un=this.classifier;if(un&&h!=="a2a"&&!te){I("classify");let p=Date.now();wt=un.classify({text:e.message,channel:h,sender:e.context?.sender,chatId:$,agentId:e.agentId}).then(m=>{X=m||void 0,X?.path?.length&&(g.intentPath=X.path.slice()),T("classify",p,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),T("classify",p,"error")})}let ln=async p=>{if(!wt)return;let m;await Promise.race([wt,new Promise(v=>{m=setTimeout(v,p),m.unref?.()})]),m&&clearTimeout(m)};await ln(Ja);let Re=this.config.workflows?.matching,we;if(this.config.workflows?.enabled&&Re?.enabled&&!o)try{let p=new gs({baseDir:q(process.cwd(),this.config.workflows.dir)}),m=ps({agentId:e.agentId,channel:h,message:e.message,intentPath:X?.path},p.list());m&&m.confidence>=Re.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Re.mode} reasons=${m.reasons.join(",")||"n/a"}`),Re.mode==="auto"&&m.confidence>=Re.autoRunThreshold&&(this.workflowAutoRunner?we={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(p){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${p?.message||p}`)}let ro=this.wikiHub.getAgentWiki(e.agentId),gn=this.memoryStore.findRelevant(e.message,e.agentId,te?3:8),pn=this.memoryStore.buildContext(gn),hn=this.memoryStore.contextFacts(gn),oo=this.patternStore.findRelevant(e.message,e.agentId,5),io=this.patternStore.buildContext(oo),mn="";if(!te)try{let{loadLocalSkills:p,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),v=await w("skills",()=>p(a.def.workspace));mn=m(v,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,h,$):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,h,$):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,h,$):void 0;if(j&&this.sessions.isSessionStale(e.agentId,h,$)&&(this.log(`[${e.agentId}] session stale for ${h}:${$}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"stale"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,h,$)){let p=this.sessions.getLastTurnContextTokens(e.agentId,h,$);this.log(`[${e.agentId}] tier-2 rotation for ${h}:${$} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,h,$)){let p=this.sessions.getTurnCount(e.agentId,h,$);this.log(`[${e.agentId}] max-turns rotation for ${h}:${$} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let p=j;await w("rotate",()=>this.maybeRotateForContinuity(e,a,h,$,p))&&(j=void 0)}try{let p=await w("compact",()=>this.sessions.compactIfNeeded(e.agentId,h,$,this.memoryStore));if(p.compacted){let m=p.qualityScore??"?",v=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${h}:${$} (quality: ${m}%, ${v} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let P=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let ao=process.env.AGENTX_CONTEXT_SURGERY==="1",co=te?{maxMessages:8,maxChars:2400}:ao&&zr(h,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,uo=!j&&!te?rc(ro,e.agentId):void 0,Ge=j?void 0:this.sessions.buildHistoryContext(e.agentId,h,$,co),lo=j?void 0:this.sessions.getRotationMemo(e.agentId,h,$)??void 0,fn,yn=[];if(this.config.procedures?.injection?.enabled&&!j&&!te)try{let p=new We({baseDir:q(process.cwd(),this.config.procedures.dir)}),m=tn(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){fn=nn(m),yn=m.map(v=>({id:v.procedure.meta.id,title:v.procedure.meta.title}));for(let v of m)this.log(`[${e.agentId}] procedure match ${v.procedure.meta.id} score=${v.score.toFixed(2)} (${v.reasons.join(",")})`)}}catch(p){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${p?.message||p}`)}if(me&&me.cat)try{let m=this.sessions.getSession(e.agentId,h,$).messages,v=m[0],P=m[m.length-1],W=Ge===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${Ge.length}c/${Ge.split(`
|
|
135
135
|
`).length}L`,Q=`[${e.agentId}] ${h}:${$} ${W} | session.messages=${m.length}`+(m.length>0?` first=${v.timestamp.slice(11,19)}(${v.role}:${(v.content||"").slice(0,40).replace(/\n/g," ")}) last=${P.timestamp.slice(11,19)}(${P.role}:${(P.content||"").slice(0,40).replace(/\n/g," ")})`:"");me.cat("context",Q)}catch(p){me.cat("context",`[${e.agentId}] context-diag error: ${p?.message??p}`)}let bn;if(a.def.contextReferences&&!j)try{let p=a.def.workspace,m=this.referencesCache.get(p);if(!m){let[P,W]=await w("references",()=>Promise.all([Rt(a.def.workspace),Pt(a.def.workspace)]));if(P.byId.size===0&&W.recipes.length===0){let[Q,he]=await w("references",()=>Promise.all([Rt(process.cwd()),Pt(process.cwd())]));m={refs:Q,recipes:he}}else m={refs:P,recipes:W};this.referencesCache.set(p,m)}let v=ss({agentId:e.agentId,intentTags:X?.path,message:e.message},m.recipes,m.refs);v.cards.length>0&&(bn=ts(v.cards,500*4)),v.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${v.unresolvedIds.join(", ")}`)}catch(p){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${p?.message||p}`)}let wn=this.sessions.getCrossSessionSummary(e.agentId,h,$,e.message),xn,Je=Ys(e.message);if(Je)try{let p=this.sessions.recallTurns({agentId:e.agentId,channel:h,chatId:$,lookbackDays:Je.lookbackDays,limit:12});if(p.turns.length>0){let m=[`[Long-memory recall \u2014 last ${Je.lookbackDays}d on this chat (cue-triggered)]`],v=[...p.turns].sort((P,W)=>P.ts.localeCompare(W.ts));for(let P of v){let W=P.ts.slice(11,16)+" "+P.day,Q=P.role==="user"?P.senderName||"User":P.senderName||"Agent";m.push(`${W} ${Q}: ${P.content}`)}p.hasMore&&m.push(`[\u2026${p.totalScanned-p.turns.length}+ older turns available \u2014 call /recall with before=${p.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),xn=m.join(`
|
|
136
136
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Je.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let go=te?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",Tn,kn,In=!1;if(go==="planner"&&!ge.active&&h!=="voice"&&h!=="desktop"){try{let{planContext:p}=await import("./context-planner-JU7CNXCB.js"),m=await w("plan-context",()=>p({agentId:e.agentId,channel:h,chatId:$,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(In=!0,Tn=m.sessionHistory,pn=m.memoryContext,hn=m.memoryFacts,wn=m.crossChatContext,kn=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(p){this.log(`[${e.agentId}] planner failed (non-fatal): ${p.message} \u2014 falling back to layered (keeping --resume for continuity)`)}In&&j&&(this.sessions.clearClaudeSessionId(e.agentId,h,$),j=void 0)}let xt=`${e.agentId}:${h}:${$}`,Qe=Bn(e.message);Qe&&(Qe==="default"?(this.activeSouls.delete(xt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(xt,Qe),this.log(`[${e.agentId}] Soul switched to: ${Qe}`)));let po=this.activeSouls.get(xt),ho=jn(a.def.workspace,po),mo=Un(ho),fo=this.agentMemory.indexMarkdown(e.agentId),yo=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
|
|
137
137
|
Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",bo=cc(a.def.richMessages,h),Sn="";if(a.def.workspace){let p=q(a.def.workspace,"CLAUDE.md");if(Z(p))try{let m=qe(p,"utf-8");Sn=`[Project CLAUDE.md]
|
|
@@ -144,9 +144,9 @@ ${R}`),m+=R.length}catch{}}}let wo=Tt.length>0?Tt.join(`
|
|
|
144
144
|
|
|
145
145
|
`):"",kt=[a.def.systemPrompt||"",yo,bo,Sn,wo,mo||"",fo||""].filter(p=>p.trim().length>0).join(`
|
|
146
146
|
|
|
147
|
-
`)||void 0,vn={channel:h,chatId:$,channelScope:e.context?.group?"group":h==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,h),systemPrompt:a.def.systemPrompt,sender:bt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:te||zr(h,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:te?void 0:io||void 0,procedureContext:fn,references:bn,skillInjection:mn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Tn??Ge,memoryContext:pn||void 0,crossChatContext:wn||void 0,longMemoryRecall:xn||void 0,wikiContext:uo,handoverNote:this.buildHandoverNote(e.agentId,h,$),rotationMemo:lo,eventDigest:j?void 0:sc(e.agentId,this.config.agents[e.agentId]?.subscriptions??a.def.subscriptions),attachHint:(()=>{let p=hs(h,!j,a.def.richMessages);return p?oc(a.def.workspace,p):void 0})(),intent:X?{path:X.path,pathLabel:X.pathLabel,pathId:X.pathId,axes:X.axes,leaf:X.leaf,status:X.status}:void 0,message:e.message},Xe=ge.active&&ge.preprocess?await w("select-context",()=>no(vn)):{input:vn,excluded:[]};Xe.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Xe.excluded.join(", ")}`);let Ye=ir(Xe.input,te?{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),xo=Xn(Ye,{memory:hn,procedures:yn,wikiContext:Xe.input.wikiContext}),It=(Ye?.length??0)+(kt?.length??0)+(e.message?.length??0),Ve={history:Ye?.length??0,sysPrompt:kt?.length??0,message:e.message?.length??0},Cn=Ar(e.agentId,h,$);$r(Cn,It,Ve);let An=Mr(Cn);An&&this.log(`[${e.agentId}] ${An}`),It>16e3&&this.log(`[${e.agentId}] large context for ${h}:${$}: ${It} bytes (history=${Ve.history}, sysPrompt=${Ve.sysPrompt}, message=${Ve.message})`);let St,$n=Hn(a.def.tier,this.config.decisions.routing);if(!e.model&&$n&&(!ge.active||ge.preprocess))try{let{routeTaskModel:p}=await import("./routing-
|
|
147
|
+
`)||void 0,vn={channel:h,chatId:$,channelScope:e.context?.group?"group":h==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,h),systemPrompt:a.def.systemPrompt,sender:bt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:te||zr(h,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:te?void 0:io||void 0,procedureContext:fn,references:bn,skillInjection:mn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Tn??Ge,memoryContext:pn||void 0,crossChatContext:wn||void 0,longMemoryRecall:xn||void 0,wikiContext:uo,handoverNote:this.buildHandoverNote(e.agentId,h,$),rotationMemo:lo,eventDigest:j?void 0:sc(e.agentId,this.config.agents[e.agentId]?.subscriptions??a.def.subscriptions),attachHint:(()=>{let p=hs(h,!j,a.def.richMessages);return p?oc(a.def.workspace,p):void 0})(),intent:X?{path:X.path,pathLabel:X.pathLabel,pathId:X.pathId,axes:X.axes,leaf:X.leaf,status:X.status}:void 0,message:e.message},Xe=ge.active&&ge.preprocess?await w("select-context",()=>no(vn)):{input:vn,excluded:[]};Xe.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Xe.excluded.join(", ")}`);let Ye=ir(Xe.input,te?{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),xo=Xn(Ye,{memory:hn,procedures:yn,wikiContext:Xe.input.wikiContext}),It=(Ye?.length??0)+(kt?.length??0)+(e.message?.length??0),Ve={history:Ye?.length??0,sysPrompt:kt?.length??0,message:e.message?.length??0},Cn=Ar(e.agentId,h,$);$r(Cn,It,Ve);let An=Mr(Cn);An&&this.log(`[${e.agentId}] ${An}`),It>16e3&&this.log(`[${e.agentId}] large context for ${h}:${$}: ${It} bytes (history=${Ve.history}, sysPrompt=${Ve.sysPrompt}, message=${Ve.message})`);let St,$n=Hn(a.def.tier,this.config.decisions.routing);if(!e.model&&$n&&(!ge.active||ge.preprocess))try{let{routeTaskModel:p}=await import("./routing-EIGWDKH7.js"),m=await w("route-model",()=>p({message:e.message,agent:e.agentId,channel:h,isFollowUp:!!j,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,h,$),cheapModel:$n}));m.downgraded&&(St=m.model,this.log(`[${e.agentId}] ${m.reason}`))}catch{}let To={...e,systemPromptAppend:kt,...St?{model:St}:{}},pe,Mn=qr({agent:e.agentId,request:e.message,taskId:b,budgetMinutes:a.def.maxExecutionMinutes??20}),ko=_;_=p=>{Mn.observe(p),ko?.(p)};try{let p=this.workflowAutoRunner;if(we&&p){let B=we;try{let J=await w("workflow-auto-run",()=>p({workflowId:B.workflowId,agentId:e.agentId,channel:h,chatId:$,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:h,chatId:$,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:X?.path,matchedWorkflowId:B.workflowId,matchConfidence:B.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${we.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),pe={content:"",duration:0,metadata:{handledByWorkflow:we.workflowId,workflowRunId:J.runId,workflowMatchConfidence:we.confidence}},pe}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(a.def.tier==="claude-code"){I("dispatch-gate");let B=a.def.persistentProcess?ot():null,J=B!=null&&B.hasLive({agentId:e.agentId,channel:h,chatId:$}),oe=!!j||J,ne=[wr(oe),vr(oe)].find(_e=>_e&&_e.abort);if(ne){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ne.reason}`);let _e={content:"",error:ne.message,duration:0};if(!t){y.buffer=`[error] ${ne.message}`;for(let Io of y.subscribers)try{Io(y.buffer)}catch{}}return pe=_e,_e}Ir();let Pe=Cr();Pe&&this.log(`[${e.agentId}] ${Pe}`)}let m=a.def.tier==="claude-code",v=m?t:(B,J)=>{B&&x(B),t&&t(B,J)},P=!1,W=m?n:B=>{B&&(P?x(B):(x(`\u{1F4AD} ${B}`),P=!0)),n&&n(B)},Q=()=>{P&&(x(`
|
|
148
148
|
`),P=!1)},he=m?v:v?(B,J)=>{Q(),v(B,J)}:void 0,R=await w("agent",()=>Qs(a.def,To,this.providers,he,Ye,j,_,f.signal,W),Za);if(!R.error){let B=ic(a.def.toolUseRequired,S);if(B){let J=Array.from(S.entries()).map(([oe,Ze])=>`${oe}=${Ze}`).join(", ")||"none";R.error=`tool_required_not_called: ${B} (invoked: ${J})`,R.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${B}, observed ${J}`)}}let vt=this.interruptedRuns.get(g.id);vt&&(R.content="",R.error=vt,R.errorKind="interrupted"),pe=R;let re=R.usage?rr(R.usage):void 0;if(V().emit("task:completed",{taskId:b,agentId:e.agentId,channel:h,chatId:$,durationMs:Date.now()-dn,error:R.error||void 0,interrupted:vt?!0:void 0,inputTokens:re?.inputTokens,outputTokens:re?.outputTokens,cacheReadTokens:re?.cacheReadTokens,cacheCreateTokens:re?.cacheCreateTokens,tier2InputTokens:re?.tier2InputTokens,tier2OutputTokens:re?.tier2OutputTokens,tier2CacheReadTokens:re?.tier2CacheReadTokens,tier2CacheCreateTokens:re?.tier2CacheCreateTokens,resumed:!!j,resumeSessionId:j||void 0,jevArm:ge.arm,numTurns:R.numTurns,injectedContext:xo,finalResponse:R.content||void 0,billedModel:R.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&(R.content||R.error)){let B=R.error?`[error] ${R.error}`:R.content;y.buffer=B;for(let J of y.subscribers)try{J(B)}catch{}}if(R.error)a.errors++,this.log(`[${e.agentId}] error: ${R.error}`);else{if(this.sessions.addAgentMessage(e.agentId,h,$,R.content),Gr({agent:e.agentId,channel:h,chatId:$,request:e.message,reply:R.content,taskId:b}),R.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,h,$,R.claudeSessionId),R.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,h,$,R.codexSessionId),R.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,h,$,R.opencodeSessionId),(R.claudeSessionId||R.codexSessionId||R.opencodeSessionId)&&R.usage&&this.sessions.recordTurnUsage(e.agentId,h,$,R.usage,R.contextTokens),R.usage){let ne=R.contextTokens,Pe=(R.usage.inputTokens||0)+(R.usage.cacheReadTokens||0)+(R.usage.cacheCreateTokens||0);(ne??Pe)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${h}:${$}: context=${ne??"n/a"} tokens (cumulative turn total=${Pe}) \u2014 next turn will rotate`)}if(Kn({channel:h,content:`User: ${e.message}`,responseLength:R.content.length}).capture){await ln(Qa);try{let ne=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ne,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:h,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
149
149
|
|
|
150
150
|
Agent: ${R.content}`,meta:nc(X,e.context)})}catch{}Gn(e.agentId,e.message,R.content,{channel:h,chatId:$,sender:bt},this.memoryStore).catch(()=>{}),pr(e.agentId,e.message,R.content,{channel:h,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=R.billedModel||e.model||a.def.model,oe=e.context?.channel,Ze=oe&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${oe}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,R.duration||0,R.usage,e.message.length,R.content.length,!1,J,oe,Ze),this.log(`[${e.agentId}] completed in ${R.duration}ms`+(R.tokensUsed?` (${R.tokensUsed} tokens)`:"")+` ${U()}`)}return R}catch(p){a.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let m=st(p.message);return pe={content:"",error:rt(m),errorKind:m.kind},pe}finally{Mn.stop(),O(pe)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=q(process.cwd(),Me,this.safe(e.agentId),t);Z(n)||za(n,{recursive:!0});let r=q(n,`${this.safe(e.id)}.json`);Ya(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=q(process.cwd(),Me,this.safe(e));if(!Z(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[d,c]){let g=q(a,u);if(Z(g))try{for(let f of se(g)){if(!f.endsWith(".json"))continue;let y=f.split("-")[0],x=parseInt(y,10);if(!Number.isFinite(x)||x<i||x>n)continue;let b=Math.floor((n-x)/36e5),S=t-1-b;S>=0&&S<t&&o[S]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=q(process.cwd(),Me);if(!Z(e))return 0;let t=0;for(let n of se(e)){let r=q(e,n),o;try{o=se(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=q(r,i),c;try{c=se(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(qe(q(a,d),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let g=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:g,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=tc){let t=q(process.cwd(),Me);if(!Z(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of se(t)){let i=q(t,o),a;try{a=se(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Xa(q(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=q(process.cwd(),Me,this.safe(e));if(!Z(n))return[];let r=se(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=q(n,i),c;try{c=se(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let l=JSON.parse(qe(q(a,d),"utf-8")),{transcript:u,responseText:g,...f}=l;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let n=q(process.cwd(),Me,this.safe(e));if(!Z(n))return null;let r=this.safe(t),o=se(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=q(n,i,`${r}.json`);if(Z(a))try{return JSON.parse(qe(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=ls();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.errorKind==="interrupted"||nt(n.error))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(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}findRunningTurn(e,t={}){let n=this.agents.get(e);if(!n)return null;let r;if(t.taskId)r=n.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=n.runningTasks.filter(a=>a.channel===t.channel&&a.chatId===t.chatId);r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(n=>n.id)}:null}isChatBusy(e,t,n){return this.messageQueue.isBusy(e,t,n)}runningIntentPath(e,t,n){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==n||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}interruptRunning(e){let t=0;for(let[n,r]of this.taskAborts){this.interruptedRuns.set(n,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${n} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,l=o.controller.signal.aborted,u=!1;l&&d&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),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 g=this.messageQueue.pendingCount(i,a,c),f=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),f=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${g}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:f,edited:u,pending:g}}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(d=>{let l=!1,u=g=>{l||(l=!0,d(g))};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:g=>u({ok:!0,agentId:e,channel:a,chatId:c,taskId:g,queued:!1})}).then(g=>{nt(g.error)?u({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):g.error?u({ok:!1,status:500,error:g.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>u({ok:!1,status:500,error:g?.message??String(g)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function cc(s,e){return s===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
151
151
|
`)}export{xs as a,Ts as b,Tc as c,Is as d,Uo as e,Ss as f,As as g,Ec as h,Lc as i,Fc as j,ri as k,Ks as l,di as m,ui as n,li as o,Qs as p,ut as q,lt as r,pd as s,zt as t,V as u,hr as v,Ki as w,zi as x,yr as y,Rd as z,br as A,We as B,Ea as C,Da as D,Oa as E,Na as F,La as G,tn as H,ul as I,ll as J,nc as K,sc as L,rc as M,cn as N,Yr as O,Vr as P,ic as Q,Zr as R,eo as S,cc as T};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-OTMDMGHE.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as o}from"./chunk-EMRQ6W5J.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
|
|
2
|
+
//# sourceMappingURL=chunk-RCKICCTT.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{q as p}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{q as p}from"./chunk-5Y7QRFSL.js";import{b as i,c as u,d as l,e as c}from"./chunk-WLX4766Y.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
|
|
2
|
+
//# sourceMappingURL=chunk-SELIVR6U.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-
|
|
1
|
+
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-SELIVR6U.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-WLX4766Y.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
|
|
2
2
|
`)}async function k(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(u){return`Could not notify the operator (${u?.message??u}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),u=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let p=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(p).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>Q(i,f,u)).join(`
|
|
3
3
|
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!h.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||q;if(!B(g))return`Error: unknown timezone "${g}".`;let d=o||_(i.matched,f);if(!R(d))return`Error: invalid id "${d}" (letters, digits, "-" and "_" only).`;if(p[d])return`Error: a schedule "${d}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:u.toISOString()},L=b({parsed:i,agent:f,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),v=await m(U=>I(U,`crons.${d}`,L));if(!v.success)return`Error: ${v.error}`;let N=w(E(i.cron,g,u),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${d}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${f}`,$?`Notify: ${$.channel} ${$.chatId}`:"Notify: none",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${d}`,`Reject: agentx schedule reject ${d}`].join(`
|
|
4
4
|
`),H=await k(h,t,G);return[`Requested schedule "${d}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=p[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let d=await m($=>P($,`crons.${o}`));return d.success?`Withdrew the pending request "${o}".`:`Error: ${d.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:u.toISOString()},l=await m(d=>{if(!x(d,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(d,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${S(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,u),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await k(h,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
7
|
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),u=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),p=s(n.accountId);return{agentId:t,channel:u,chatId:h,...p?{accountId:p}:{}}}export{re as a,oe as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-SFWA67GQ.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{A as x,v as m,w as $}from"./chunk-AHOGFVHA.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
|
|
2
2
|
`);return{success:!1,path:o,error:`Validation failed:
|
|
3
3
|
${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
|
|
4
4
|
`)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{w as a,J as b,N as c,j as d,A as e};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-WLX4766Y.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-
|
|
1
|
+
import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-AAA6NGY5.js";import{b as R}from"./chunk-2GIDVZ4H.js";import{v as C,w as I}from"./chunk-DJMUP6TK.js";import{b as v,c as W}from"./chunk-QOYAX2FT.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function nt(n,a,o,t={}){let u=t.selectorModel??"haiku",g=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,s=t.maxArticles??8,h=t.timeoutMs??6e4,p=t.log??console.error.bind(console,"[wiki-query]"),m=t.messagePath?.length?t.messagePath:void 0,w=t.graphWeight??$,i=x(a.baseDir,"_index.md");if(!B(i))return A("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let e=Y(i,"utf-8"),d=Date.now(),f=[],y="";try{let c=await G(n,a,o,l,m,w);c?(f=c,y=`[wiki-rerank seat] ${c.map(k=>k.title).join(" | ")}`):(y=await Q(q(n,e,l,m),u,h),f=K(y))}catch(c){return p("selector failed:",c?.message),{...A("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-d,synthesisMs:0,selectorOutput:y}}}let S=Date.now()-d;if(f.length===0)return{...A("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let b=F(f,a,o,r,s);if(b.length===0)return{...A("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let M=Date.now(),P="";try{P=await Q(J(n,b),g,h*2)}catch(c){return p("synthesis failed:",c?.message),{...A("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:f,walked:b.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:S,synthesisMs:Date.now()-M,selectorOutput:y}}}let E=Date.now()-M;return{answer:P.trim(),citations:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:f,walked:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:S,synthesisMs:E,selectorOutput:y}}}function A(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,u){let g=new Map;for(let s of a.listArticles(o||""))g.set(s.meta.title.toLowerCase(),s.path);let l=new Map,r=[];for(let s of n)l.has(s.path)||r.push({path:s.path,hop:0});for(;r.length&&l.size<u;){let s=r.shift();if(l.has(s.path)||s.hop>t)continue;let h=o?a.readArticleAs(s.path,o):a.readArticle(s.path);if(h&&(l.set(s.path,{...h,hop:s.hop}),!(s.hop>=t)))for(let p of h.meta.related||[]){let m=g.get(p.toLowerCase());m&&!l.has(m)&&r.push({path:m,hop:s.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,u,g=$){try{let r=(a.rebuildIndex().articles??[]).filter(i=>i.path&&!i.path.includes("/_versions/"));if(r.length<2)return null;let h=H(n,r,u,g).slice(0,O).map(i=>({id:`k${i}`,title:r[i].title||r[i].path,tags:r[i].tags,excerpt:[r[i].type?`type: ${r[i].type}`:"",(r[i].related??[]).length?`related: ${(r[i].related??[]).join(", ")}`:"",(r[i].graphPath??[]).length?`graph: ${(r[i].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),p=await C(j,T({query:n,candidates:h,excerptChars:300}),D(h),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!p||p.mode!=="active")return null;let w=_(p.answers,h).ranked.slice(0,t).map(i=>r[Number(i.slice(1))]).filter(Boolean).map(i=>({title:i.title,path:i.path}));return w.length>0?w:null}catch{return null}}var $=.6;function H(n,a,o,t=$){let u=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),g=W(n,v(u)),l=g.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(g.map(e=>[e.docIndex,l>0?e.score/l:0])),s=!!o?.length,h=e=>s&&e.graphPath?.length?N(o,e.graphPath):0,p=(e,d)=>d.score-e.score||e.i-d.i,m=a.map((e,d)=>({i:d,score:(r.get(d)??0)*(1+t*h(e))})).filter(e=>r.has(e.i)).sort(p),w=a.map((e,d)=>({i:d,score:h(e)})).filter(e=>!r.has(e.i)&&e.score>0).sort(p),i=[...m,...w].map(e=>e.i);for(let e=0;e<a.length;e++)i.includes(e)||i.push(e);return i}function q(n,a,o,t){let u=t?.length?`
|
|
2
2
|
## Intent
|
|
3
3
|
|
|
4
4
|
The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
|
|
@@ -46,4 +46,4 @@ ${o}
|
|
|
46
46
|
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
47
47
|
|
|
48
48
|
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Q(n,a,o){let{writeFileSync:t,mkdirSync:u,rmSync:g}=await import("fs"),{tmpdir:l}=await import("os"),r=x(l(),`agentx-wiki-query-${process.pid}`);u(r,{recursive:!0});let s=x(r,`prompt-${Date.now()}.txt`);t(s,n);try{let h=`cat '${s}' | claude -p - --output-format json --max-turns 1 --model ${a} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,p=L(h,{env:R({...process.env}),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let m=JSON.parse(p);return String(m.result||m.content||"")}catch{return p}}finally{try{g(s,{force:!0})}catch{}}}export{nt as a,$ as b,H as c};
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-XJQNIFZ4.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as n}from"./chunk-
|
|
2
|
+
import{a as n}from"./chunk-MT3BD6WG.js";import"./chunk-BO4WLXXC.js";import"./chunk-IK2XG65P.js";import"./chunk-D233M73Q.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-3C2SQDIH.js";import"./chunk-JU67IZLC.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-4XBYHKYG.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-JBVABB26.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import"./chunk-OTMDMGHE.js";import"./chunk-6LTD7XL5.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-HXW4NAWF.js";import"./chunk-SFQUP3BP.js";import"./chunk-SELIVR6U.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-5Y7QRFSL.js";import"./chunk-WLX4766Y.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-K6CHA6JJ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-RCKICCTT.js";import"./chunk-EMRQ6W5J.js";import"./chunk-CECHWYJ2.js";import"./chunk-XJQNIFZ4.js";import"./chunk-AAA6NGY5.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-DJMUP6TK.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-AHOGFVHA.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";var r=["SIGINT","SIGTERM"];function o(t=process){for(let i of r)t.on(i,()=>{t.listenerCount(i)<=1&&t.exit(0)})}o();async function s(){let t=await n();if(process.argv.slice(2).length===0){t.outputHelp();return}t.parse()}s();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{A as i,r as a,s as b,t as c,u as d,v as e,w as f,x as g,y as h}from"./chunk-AHOGFVHA.js";import"./chunk-QIJLFPWE.js";i();export{a as INTEGRATION_KINDS,d as approvalsConfigSchema,c as callsSchema,e as daemonConfigSchema,b as eventSubscriptionSchema,f as expandEnvVars,g as loadDaemonConfig,h as validateWorkspaces};
|
|
2
|
+
//# sourceMappingURL=config-UY5K6SCL.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e}from"./chunk-IK2XG65P.js";import"./chunk-BYJ3A55Y.js";import"./chunk-AHOGFVHA.js";import"./chunk-QIJLFPWE.js";export{e as daemonVoiceCheck,b as doctor,a as runDoctorChecks,c as runNotificationChecks,d as runReminderChecks};
|
|
2
|
+
//# sourceMappingURL=doctor-GFPSIJGB.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -4082,6 +4082,38 @@ declare const daemonConfigSchema: z.ZodObject<{
|
|
|
4082
4082
|
accountId?: string | undefined;
|
|
4083
4083
|
} | undefined;
|
|
4084
4084
|
}>>;
|
|
4085
|
+
calls: z.ZodDefault<z.ZodObject<{
|
|
4086
|
+
/** Agents allowed to call: ids, or "*" for every agent on this node.
|
|
4087
|
+
* Empty: nobody can call until the owner allows it. */
|
|
4088
|
+
allow: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
|
|
4089
|
+
/** Most calls one agent may place in an hour. */
|
|
4090
|
+
maxPerHour: z.ZodDefault<z.ZodNumber>;
|
|
4091
|
+
/** How long a call rings before it counts as missed. */
|
|
4092
|
+
ringSeconds: z.ZodDefault<z.ZodNumber>;
|
|
4093
|
+
/** An answered call nobody hung up (widget quit or crashed, the Mac
|
|
4094
|
+
* slept, `agentx call answer` without a conversation) ends after this,
|
|
4095
|
+
* so the agent can call again. */
|
|
4096
|
+
maxCallMinutes: z.ZodDefault<z.ZodNumber>;
|
|
4097
|
+
/** Ring sound: a name from /System/Library/Sounds, without the extension. */
|
|
4098
|
+
ringSound: z.ZodDefault<z.ZodString>;
|
|
4099
|
+
/** After hang-up, ask the agent for a short summary and file it in the
|
|
4100
|
+
* dashboard's conversation history. */
|
|
4101
|
+
summary: z.ZodDefault<z.ZodBoolean>;
|
|
4102
|
+
}, "strip", z.ZodTypeAny, {
|
|
4103
|
+
summary: boolean;
|
|
4104
|
+
allow: string[];
|
|
4105
|
+
maxPerHour: number;
|
|
4106
|
+
maxCallMinutes: number;
|
|
4107
|
+
ringSeconds: number;
|
|
4108
|
+
ringSound: string;
|
|
4109
|
+
}, {
|
|
4110
|
+
summary?: boolean | undefined;
|
|
4111
|
+
allow?: string[] | undefined;
|
|
4112
|
+
maxPerHour?: number | undefined;
|
|
4113
|
+
maxCallMinutes?: number | undefined;
|
|
4114
|
+
ringSeconds?: number | undefined;
|
|
4115
|
+
ringSound?: string | undefined;
|
|
4116
|
+
}>>;
|
|
4085
4117
|
approvals: z.ZodDefault<z.ZodObject<{
|
|
4086
4118
|
/** A card without an `expires` gets this many days. */
|
|
4087
4119
|
defaultExpiryDays: z.ZodDefault<z.ZodNumber>;
|
|
@@ -6284,6 +6316,14 @@ declare const daemonConfigSchema: z.ZodObject<{
|
|
|
6284
6316
|
accountId?: string | undefined;
|
|
6285
6317
|
} | undefined;
|
|
6286
6318
|
};
|
|
6319
|
+
calls: {
|
|
6320
|
+
summary: boolean;
|
|
6321
|
+
allow: string[];
|
|
6322
|
+
maxPerHour: number;
|
|
6323
|
+
maxCallMinutes: number;
|
|
6324
|
+
ringSeconds: number;
|
|
6325
|
+
ringSound: string;
|
|
6326
|
+
};
|
|
6287
6327
|
approvals: {
|
|
6288
6328
|
digest: {
|
|
6289
6329
|
enabled: boolean;
|
|
@@ -6942,6 +6982,14 @@ declare const daemonConfigSchema: z.ZodObject<{
|
|
|
6942
6982
|
accountId?: string | undefined;
|
|
6943
6983
|
} | undefined;
|
|
6944
6984
|
} | undefined;
|
|
6985
|
+
calls?: {
|
|
6986
|
+
summary?: boolean | undefined;
|
|
6987
|
+
allow?: string[] | undefined;
|
|
6988
|
+
maxPerHour?: number | undefined;
|
|
6989
|
+
maxCallMinutes?: number | undefined;
|
|
6990
|
+
ringSeconds?: number | undefined;
|
|
6991
|
+
ringSound?: string | undefined;
|
|
6992
|
+
} | undefined;
|
|
6945
6993
|
approvals?: {
|
|
6946
6994
|
digest?: {
|
|
6947
6995
|
enabled?: boolean | undefined;
|
|
@@ -7800,6 +7848,7 @@ declare class AgentXDaemon {
|
|
|
7800
7848
|
private business?;
|
|
7801
7849
|
private httpServer?;
|
|
7802
7850
|
private attachSweep?;
|
|
7851
|
+
private callSweep?;
|
|
7803
7852
|
private webhooks;
|
|
7804
7853
|
private github?;
|
|
7805
7854
|
private webrtc?;
|
|
@@ -7810,6 +7859,8 @@ declare class AgentXDaemon {
|
|
|
7810
7859
|
private wfHealth?;
|
|
7811
7860
|
/** Shares the daemon's SQLite handle; absent when running without one. */
|
|
7812
7861
|
private _assistant?;
|
|
7862
|
+
/** Agents ringing the owner (src/calls); needs SQLite. */
|
|
7863
|
+
private calls?;
|
|
7813
7864
|
private assistantStore;
|
|
7814
7865
|
/** Workflow health for the monitor. Cached for a minute: the dashboard
|
|
7815
7866
|
* polls every 15s and dormancy does not change on that timescale. */
|
|
@@ -7953,6 +8004,10 @@ declare class AgentXDaemon {
|
|
|
7953
8004
|
* this `callId` to the stream.
|
|
7954
8005
|
*/
|
|
7955
8006
|
private handleWebRtcSSE;
|
|
8007
|
+
/** Calls from agents to the owner (#321). The notice path is notify's:
|
|
8008
|
+
* Focus holds a non-urgent one; the push goes through the router with
|
|
8009
|
+
* its title as the first line, as `agentx notify` sends it. */
|
|
8010
|
+
private createCallService;
|
|
7956
8011
|
/**
|
|
7957
8012
|
* Serve the minimal browser call page. Static HTML; no framework.
|
|
7958
8013
|
* The page does getUserMedia, RTCPeerConnection, and POSTs/listens signals.
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as L}from"./chunk-C245D4BZ.js";import{
|
|
1
|
+
import{a as L}from"./chunk-C245D4BZ.js";import{d as St,e as kt,ea as Tt,f as vt,fa as Mt,g as xt,h as $t,i as Ct,j as Pt,k as bt}from"./chunk-3C2SQDIH.js";import"./chunk-JU67IZLC.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-4XBYHKYG.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-JBVABB26.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import{S as yt,l as lt,m as ct,n as dt,o as mt,p as pt}from"./chunk-OTMDMGHE.js";import"./chunk-6LTD7XL5.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-HXW4NAWF.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-SELIVR6U.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-5Y7QRFSL.js";import"./chunk-WLX4766Y.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-K6CHA6JJ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-RCKICCTT.js";import{a as ht}from"./chunk-EMRQ6W5J.js";import"./chunk-CECHWYJ2.js";import"./chunk-XJQNIFZ4.js";import{f as gt,g as ft}from"./chunk-AAA6NGY5.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import{j as it,k as rt,l as at}from"./chunk-DJMUP6TK.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-5MUJZODV.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{A as nt,v as tt,x as st,y as ot}from"./chunk-AHOGFVHA.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
4
|
${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a}from"./chunk-MT3BD6WG.js";import"./chunk-BO4WLXXC.js";import"./chunk-IK2XG65P.js";import"./chunk-D233M73Q.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-3C2SQDIH.js";import"./chunk-JU67IZLC.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-4XBYHKYG.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-JBVABB26.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import"./chunk-OTMDMGHE.js";import"./chunk-6LTD7XL5.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-HXW4NAWF.js";import"./chunk-SFQUP3BP.js";import"./chunk-SELIVR6U.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-5Y7QRFSL.js";import"./chunk-WLX4766Y.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-K6CHA6JJ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-RCKICCTT.js";import"./chunk-EMRQ6W5J.js";import"./chunk-CECHWYJ2.js";import"./chunk-XJQNIFZ4.js";import"./chunk-AAA6NGY5.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-DJMUP6TK.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-AHOGFVHA.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as buildProgram};
|
|
2
|
+
//# sourceMappingURL=program-XMGZOYX3.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=promote-
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t}from"./chunk-JBVABB26.js";import"./chunk-DP7RTNDM.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-EMRQ6W5J.js";import"./chunk-CECHWYJ2.js";import"./chunk-AAA6NGY5.js";import"./chunk-WPNRDEHW.js";import"./chunk-DJMUP6TK.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-AHOGFVHA.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_PROMOTE_TYPES,a as PROMOTER_OWNER,c as PROMOTION_LEDGER_FILE,j as appendPromotionLedger,s as approveProposal,n as callPromotionLlm,p as estimateTokens,r as evidenceFor,m as getUnpromotedMemories,k as groupCandidates,h as listAllAgentMemories,d as memoryKey,e as memoryStamp,g as mergeSources,f as parseMemoryStamp,l as parsePromotionResponse,i as readPromotionLedger,t as rejectProposal,o as runPromotion,q as sourceKind};
|
|
2
|
+
//# sourceMappingURL=promote-YLKNYYIU.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=query-
|
|
1
|
+
import{a,b,c}from"./chunk-XJQNIFZ4.js";import"./chunk-AAA6NGY5.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-DJMUP6TK.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-AHOGFVHA.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_GRAPH_WEIGHT,a as agenticQuery,c as rankCatalogPool};
|
|
2
|
+
//# sourceMappingURL=query-CVRXEG43.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{I as a,J as b,K as c,L as d,M as e,N as f,O as g,P as h,Q as i,R as j,S as k,T as l}from"./chunk-OTMDMGHE.js";import"./chunk-6LTD7XL5.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-5Y7QRFSL.js";import"./chunk-WLX4766Y.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-K6CHA6JJ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-RCKICCTT.js";import"./chunk-EMRQ6W5J.js";import"./chunk-CECHWYJ2.js";import"./chunk-XJQNIFZ4.js";import"./chunk-AAA6NGY5.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-DJMUP6TK.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-AHOGFVHA.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{k as AgentRegistry,f as TRACE_STEP_SUMMARY_BYTES,c as buildEntryMeta,d as buildEventDigest,e as buildWikiContext,g as clipForTrace,j as emitTraceStepsFromStreamEvent,i as firstMissingRequiredTool,b as getGlobalRegistry,l as richReplyPrompt,a as setGlobalRegistry,h as tallyToolUses};
|
|
2
|
+
//# sourceMappingURL=registry-HZL363TA.js.map
|