agentix-cli 0.211.1 → 0.212.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-RIXKQIO7.js → App-WS5BTNNP.js} +2 -2
- package/dist/{ChatApp-2TKXDJGQ.js → ChatApp-DRMZZ3RJ.js} +2 -2
- package/dist/{absorb-eval-5YZOYFF4.js → absorb-eval-IZOPUQE7.js} +2 -2
- package/dist/{adapter-Q76GO2I7.js → adapter-3JMPFQ25.js} +2 -2
- package/dist/{agent-GW6Z6OFF.js → agent-YA2EBSW4.js} +2 -2
- package/dist/{board-dashboard-RPZJBHL3.js → board-dashboard-KFEVHD3Z.js} +4 -4
- package/dist/{chunk-323KMXT4.js → chunk-27DVJFFR.js} +2 -2
- package/dist/{chunk-XWMHNDED.js → chunk-2PYRRBLW.js} +2 -2
- package/dist/{chunk-6BINQY52.js → chunk-4FL6B3B7.js} +5 -5
- package/dist/{chunk-FLNSBODK.js → chunk-5E6JVFHV.js} +2 -2
- package/dist/{chunk-MKQI5WL2.js → chunk-6KAP6IHP.js} +2 -2
- package/dist/{chunk-6VHORIGB.js → chunk-6LOXNAZD.js} +2 -2
- package/dist/{chunk-F3HVONL6.js → chunk-6UVU47FA.js} +2 -2
- package/dist/{chunk-XWOXXVVX.js → chunk-BITJXYHB.js} +2 -2
- package/dist/{chunk-YZD6EZMU.js → chunk-DD4YKQGF.js} +2 -2
- package/dist/{chunk-ISRY3GAD.js → chunk-DZ3Z3ZAK.js} +2 -2
- package/dist/{chunk-ZWO36TCN.js → chunk-EGKAE6VD.js} +2 -2
- package/dist/{chunk-Y65DB3PF.js → chunk-EJXHHFZJ.js} +2 -2
- package/dist/{chunk-MHRVTFLZ.js → chunk-ETDYJ52Z.js} +3 -3
- package/dist/{chunk-JJC2HBWC.js → chunk-KUB5F67E.js} +2 -2
- package/dist/{chunk-CUX7BF7B.js → chunk-MVDB76JV.js} +2 -2
- package/dist/{chunk-EPIKS3WL.js → chunk-OHZ2ETAY.js} +2 -2
- package/dist/{chunk-YRBJ4KB7.js → chunk-PAOXBAYJ.js} +2 -2
- package/dist/{chunk-2FXHWT5U.js → chunk-PJHJFZJ4.js} +6 -6
- package/dist/{chunk-LYY7G6LO.js → chunk-QDZWSALI.js} +2 -2
- package/dist/{chunk-Y4BNOZWQ.js → chunk-RFMBLJN3.js} +2 -2
- package/dist/{chunk-W4K3DFAX.js → chunk-SYEC2RCV.js} +2 -2
- package/dist/{chunk-PYTNMX2D.js → chunk-UODNQNDK.js} +2 -2
- package/dist/{chunk-FLDMRYZD.js → chunk-UZEH2A2F.js} +2 -2
- package/dist/{chunk-WNE4GRXY.js → chunk-VZFFEGVQ.js} +2 -2
- package/dist/{chunk-OAVJMZLF.js → chunk-W7D2N55Y.js} +2 -2
- package/dist/{chunk-GUID2ZA2.js → chunk-X5UWEMFI.js} +21 -21
- package/dist/{chunk-GUID2ZA2.js.map → chunk-X5UWEMFI.js.map} +1 -1
- package/dist/{chunk-QQKPZKQT.js → chunk-XUOFCIAE.js} +2 -2
- package/dist/{chunk-UYG7UOVQ.js → chunk-YXGYLWD5.js} +8 -8
- package/dist/chunk-YXGYLWD5.js.map +1 -0
- package/dist/{chunk-BQIZN5JU.js → chunk-ZD2DD7I2.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-AIQ7D7VU.js → client-NSZL7HQZ.js} +2 -2
- package/dist/config-LE57YRFQ.js +2 -0
- package/dist/{config-mutate-XUBGMDIU.js → config-mutate-XWOE7TCY.js} +2 -2
- package/dist/{config-mutator-G62RKREK.js → config-mutator-RZB5O7ES.js} +2 -2
- package/dist/{contributions-RQZO4V36.js → contributions-REWGLEPA.js} +2 -2
- package/dist/{doctor-DVMX6632.js → doctor-JNQHNUSO.js} +2 -2
- package/dist/{follow-up-tool-MS4FSM2J.js → follow-up-tool-WJ5MHV3O.js} +2 -2
- package/dist/{hub-RKX3L5LU.js → hub-LWUTWLBA.js} +2 -2
- package/dist/index.d.ts +45 -0
- package/dist/index.js +1 -1
- package/dist/{org-tool-NA6U3IJJ.js → org-tool-R6U5LUUB.js} +2 -2
- package/dist/program-OT7WYMVD.js +928 -0
- package/dist/program-OT7WYMVD.js.map +1 -0
- package/dist/{promote-OV2OD55V.js → promote-DYDETYJ4.js} +2 -2
- package/dist/{query-6FK2A4K2.js → query-JF3BQNUR.js} +2 -2
- package/dist/{query-settings-RE2BTERX.js → query-settings-2FPH2NQ7.js} +2 -2
- package/dist/{registry-APVJFCDJ.js → registry-FX4C6RHG.js} +2 -2
- package/dist/{request-planner-23FPTJLW.js → request-planner-NKP7YFUN.js} +2 -2
- package/dist/{review-candidates-FCRNGU2S.js → review-candidates-YL7QGFP2.js} +2 -2
- package/dist/{routing-W7AOH7QM.js → routing-KW42OGIW.js} +2 -2
- package/dist/schedule-tool-B3PPRW6J.js +2 -0
- package/dist/{scheduler-3CJD7UF4.js → scheduler-LYSUXKAB.js} +2 -2
- package/dist/{seat-BIVMGYMR.js → seat-HCXOUS5H.js} +2 -2
- package/dist/{select-LWTPLTCE.js → select-KTQNUTOG.js} +2 -2
- package/dist/{set-enabled-OKG7Q5WY.js → set-enabled-PAQ7ZXFL.js} +2 -2
- package/dist/{sprint-tool-YLQADXQH.js → sprint-tool-YGOAJSZQ.js} +2 -2
- package/dist/{tool-YCCQX7BT.js → tool-7FFPIOO5.js} +2 -2
- package/dist/{tool-ZXIRHFRB.js → tool-IJIYPMOA.js} +2 -2
- package/dist/{tool-XZU2IJUI.js → tool-OWGDFDVG.js} +2 -2
- package/dist/{tool-5T5SSYMB.js → tool-UNSJJ4MO.js} +2 -2
- package/dist/{wiki-2BVHRZX5.js → wiki-PYWKCJ2Y.js} +2 -2
- package/dist/wiki-enrich-JFVS7NYY.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-UYG7UOVQ.js.map +0 -1
- package/dist/config-TSSRDRCK.js +0 -2
- package/dist/program-YIX4NQZV.js +0 -901
- package/dist/program-YIX4NQZV.js.map +0 -1
- package/dist/schedule-tool-RXX26TI4.js +0 -2
- package/dist/wiki-enrich-BHPD4BOV.js +0 -2
- /package/dist/{App-RIXKQIO7.js.map → App-WS5BTNNP.js.map} +0 -0
- /package/dist/{ChatApp-2TKXDJGQ.js.map → ChatApp-DRMZZ3RJ.js.map} +0 -0
- /package/dist/{absorb-eval-5YZOYFF4.js.map → absorb-eval-IZOPUQE7.js.map} +0 -0
- /package/dist/{adapter-Q76GO2I7.js.map → adapter-3JMPFQ25.js.map} +0 -0
- /package/dist/{agent-GW6Z6OFF.js.map → agent-YA2EBSW4.js.map} +0 -0
- /package/dist/{board-dashboard-RPZJBHL3.js.map → board-dashboard-KFEVHD3Z.js.map} +0 -0
- /package/dist/{chunk-323KMXT4.js.map → chunk-27DVJFFR.js.map} +0 -0
- /package/dist/{chunk-XWMHNDED.js.map → chunk-2PYRRBLW.js.map} +0 -0
- /package/dist/{chunk-6BINQY52.js.map → chunk-4FL6B3B7.js.map} +0 -0
- /package/dist/{chunk-FLNSBODK.js.map → chunk-5E6JVFHV.js.map} +0 -0
- /package/dist/{chunk-MKQI5WL2.js.map → chunk-6KAP6IHP.js.map} +0 -0
- /package/dist/{chunk-6VHORIGB.js.map → chunk-6LOXNAZD.js.map} +0 -0
- /package/dist/{chunk-F3HVONL6.js.map → chunk-6UVU47FA.js.map} +0 -0
- /package/dist/{chunk-XWOXXVVX.js.map → chunk-BITJXYHB.js.map} +0 -0
- /package/dist/{chunk-YZD6EZMU.js.map → chunk-DD4YKQGF.js.map} +0 -0
- /package/dist/{chunk-ISRY3GAD.js.map → chunk-DZ3Z3ZAK.js.map} +0 -0
- /package/dist/{chunk-ZWO36TCN.js.map → chunk-EGKAE6VD.js.map} +0 -0
- /package/dist/{chunk-Y65DB3PF.js.map → chunk-EJXHHFZJ.js.map} +0 -0
- /package/dist/{chunk-MHRVTFLZ.js.map → chunk-ETDYJ52Z.js.map} +0 -0
- /package/dist/{chunk-JJC2HBWC.js.map → chunk-KUB5F67E.js.map} +0 -0
- /package/dist/{chunk-CUX7BF7B.js.map → chunk-MVDB76JV.js.map} +0 -0
- /package/dist/{chunk-EPIKS3WL.js.map → chunk-OHZ2ETAY.js.map} +0 -0
- /package/dist/{chunk-YRBJ4KB7.js.map → chunk-PAOXBAYJ.js.map} +0 -0
- /package/dist/{chunk-2FXHWT5U.js.map → chunk-PJHJFZJ4.js.map} +0 -0
- /package/dist/{chunk-LYY7G6LO.js.map → chunk-QDZWSALI.js.map} +0 -0
- /package/dist/{chunk-Y4BNOZWQ.js.map → chunk-RFMBLJN3.js.map} +0 -0
- /package/dist/{chunk-W4K3DFAX.js.map → chunk-SYEC2RCV.js.map} +0 -0
- /package/dist/{chunk-PYTNMX2D.js.map → chunk-UODNQNDK.js.map} +0 -0
- /package/dist/{chunk-FLDMRYZD.js.map → chunk-UZEH2A2F.js.map} +0 -0
- /package/dist/{chunk-WNE4GRXY.js.map → chunk-VZFFEGVQ.js.map} +0 -0
- /package/dist/{chunk-OAVJMZLF.js.map → chunk-W7D2N55Y.js.map} +0 -0
- /package/dist/{chunk-QQKPZKQT.js.map → chunk-XUOFCIAE.js.map} +0 -0
- /package/dist/{chunk-BQIZN5JU.js.map → chunk-ZD2DD7I2.js.map} +0 -0
- /package/dist/{client-AIQ7D7VU.js.map → client-NSZL7HQZ.js.map} +0 -0
- /package/dist/{config-TSSRDRCK.js.map → config-LE57YRFQ.js.map} +0 -0
- /package/dist/{config-mutate-XUBGMDIU.js.map → config-mutate-XWOE7TCY.js.map} +0 -0
- /package/dist/{config-mutator-G62RKREK.js.map → config-mutator-RZB5O7ES.js.map} +0 -0
- /package/dist/{contributions-RQZO4V36.js.map → contributions-REWGLEPA.js.map} +0 -0
- /package/dist/{doctor-DVMX6632.js.map → doctor-JNQHNUSO.js.map} +0 -0
- /package/dist/{follow-up-tool-MS4FSM2J.js.map → follow-up-tool-WJ5MHV3O.js.map} +0 -0
- /package/dist/{hub-RKX3L5LU.js.map → hub-LWUTWLBA.js.map} +0 -0
- /package/dist/{org-tool-NA6U3IJJ.js.map → org-tool-R6U5LUUB.js.map} +0 -0
- /package/dist/{promote-OV2OD55V.js.map → promote-DYDETYJ4.js.map} +0 -0
- /package/dist/{query-6FK2A4K2.js.map → query-JF3BQNUR.js.map} +0 -0
- /package/dist/{query-settings-RE2BTERX.js.map → query-settings-2FPH2NQ7.js.map} +0 -0
- /package/dist/{registry-APVJFCDJ.js.map → registry-FX4C6RHG.js.map} +0 -0
- /package/dist/{request-planner-23FPTJLW.js.map → request-planner-NKP7YFUN.js.map} +0 -0
- /package/dist/{review-candidates-FCRNGU2S.js.map → review-candidates-YL7QGFP2.js.map} +0 -0
- /package/dist/{routing-W7AOH7QM.js.map → routing-KW42OGIW.js.map} +0 -0
- /package/dist/{schedule-tool-RXX26TI4.js.map → schedule-tool-B3PPRW6J.js.map} +0 -0
- /package/dist/{scheduler-3CJD7UF4.js.map → scheduler-LYSUXKAB.js.map} +0 -0
- /package/dist/{seat-BIVMGYMR.js.map → seat-HCXOUS5H.js.map} +0 -0
- /package/dist/{select-LWTPLTCE.js.map → select-KTQNUTOG.js.map} +0 -0
- /package/dist/{set-enabled-OKG7Q5WY.js.map → set-enabled-PAQ7ZXFL.js.map} +0 -0
- /package/dist/{sprint-tool-YLQADXQH.js.map → sprint-tool-YGOAJSZQ.js.map} +0 -0
- /package/dist/{tool-YCCQX7BT.js.map → tool-7FFPIOO5.js.map} +0 -0
- /package/dist/{tool-ZXIRHFRB.js.map → tool-IJIYPMOA.js.map} +0 -0
- /package/dist/{tool-XZU2IJUI.js.map → tool-OWGDFDVG.js.map} +0 -0
- /package/dist/{tool-5T5SSYMB.js.map → tool-UNSJJ4MO.js.map} +0 -0
- /package/dist/{wiki-2BVHRZX5.js.map → wiki-PYWKCJ2Y.js.map} +0 -0
- /package/dist/{wiki-enrich-BHPD4BOV.js.map → wiki-enrich-JFVS7NYY.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{fa as y,ha as v,na as w,oa as C,qa as E,ra as R,sa as I}from"./chunk-
|
|
1
|
+
import{fa as y,ha as v,na as w,oa as C,qa as E,ra as R,sa as I}from"./chunk-X5UWEMFI.js";I();v();var L=1e4,T=["issues","prs","all"],W=/^[\w.-]+(?:\/[\w.-]+)+$/,m=e=>typeof e=="string"?e.trim():"";function f(e){let t=m(e.provider).toLowerCase();if(t!=="github"&&t!=="gitlab")return"count.provider must be github or gitlab";let r=m(e.project),n=r.split("/");if(!W.test(r)||n.some(o=>o==="."||o==="..")||t==="github"&&n.length!==2)return t==="github"?'count.project must be "owner/repo"':'count.project must be "group/project"';let s=(m(e.what)||"issues").toLowerCase();if(!T.includes(s))return`count.what must be one of ${T.join(", ")}`;let i=e.max===void 0||e.max===null||e.max===""?0:Number(e.max);return!Number.isInteger(i)||i<0?"count.max must be a whole number, 0 or more":{provider:t,project:r,what:s,max:i}}function S(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=f(t);return typeof r=="string"?null:r}catch{return null}}var _=e=>e==="issues"?"open issues":e==="prs"?"open pull requests":"open issues and pull requests";function $(e){return`${_(e.what)} in ${e.provider} ${e.project} \u2264 ${e.max}`}async function Y(e,t){if(!t)return{verdict:"unverifiable",detail:`no ${e.provider} connector on this node`};try{let r=e.what==="all"?["issues","prs"]:[e.what],n=0;for(let i of r){let o=await t(e.provider,e.project,i);if(typeof o!="number")return{verdict:"unverifiable",detail:`${e.project}: ${o.error}`};n+=o}let s=`${n} ${_(e.what)} in ${e.project}`;return{verdict:n<=e.max?"met":"not_met",detail:s,count:n}}catch(r){return{verdict:"unverifiable",detail:`the count check failed: ${String(r?.message??r).slice(0,200)}`}}}function B(e,t=fetch){return async(r,n,s)=>{let i;if(r==="github"){let a=e.github;if(!a)return{error:"no github connector on this node (channels.github or requests.checkers.github)"};let d=encodeURIComponent(`repo:${n} is:open is:${s==="prs"?"pr":"issue"}`);i=`${a.apiUrl.replace(/\/$/,"")}/search/issues?q=${d}&per_page=1`}else{let a=e.gitlab;if(!a)return{error:"no gitlab connector on this node (channels.gitlab or requests.checkers.gitlab)"};i=`${a.url.replace(/\/$/,"")}/api/v4/projects/${encodeURIComponent(n)}/${s==="prs"?"merge_requests":"issues"}?state=opened&per_page=1`}let o;try{o=await t(i,{headers:y(r,e),signal:AbortSignal.timeout(L)})}catch(a){return{error:`could not be reached: ${String(a?.message??a).slice(0,200)}`}}if(!o.ok)return{error:o.status===404?"not found (or not visible to the connector)":`HTTP ${o.status}`};if(r==="gitlab"){let a=Number(o.headers.get("x-total"));return Number.isInteger(a)&&a>=0?a:{error:"no X-Total in the answer"}}let c=await o.json().catch(()=>null),l=Number(c?.total_count);return Number.isInteger(l)&&l>=0?l:{error:"no total_count in the answer"}}}var F=["active","done","dropped"],Q=300,A=500;function ee(e,t=w,r=Date.now()){if(e&&typeof e=="object"&&!Array.isArray(e)&&String(e.kind).trim().toLowerCase()==="count"){let s=f(e);return typeof s=="string"?s:{kind:"count",...s}}let n=C(e,t,r);return typeof n!="string"?n:/^closeWhen(\.kind)? must be/.test(n)?"check must be an object with a kind: url, issue, git-ancestor, reply or count":n.replace(/^closeWhen/,"check")}function U(e){if(!e)return null;try{if(JSON.parse(e)?.kind==="count"){let t=S(e);return t?{kind:"count",...t}:null}}catch{return null}return R(e)}function j(e){return e.kind==="count"?$(e):E(e)}function k(e){return{id:e.id,title:e.title,ownerAgent:e.owner_agent??null,state:e.state,doneWhen:e.done_when??null,check:U(e.check_spec),evidence:e.evidence??null,lastCheck:e.last_check??null,lastCheckAt:e.last_check_at??null,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??null}}var N=class{constructor(t){this.db=t;t.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS goals (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
title TEXT NOT NULL,
|
|
@@ -17,4 +17,4 @@ import{fa as y,ha as v,na as w,oa as C,qa as E,ra as R,sa as I}from"./chunk-GUID
|
|
|
17
17
|
`)}get(t){let r=this.db.prepare("SELECT * FROM goals WHERE id = ?").get(t);return r?k(r):null}list(t=F,r=200){let n=t.map(()=>"?").join(", ");return this.db.prepare(`SELECT * FROM goals WHERE state IN (${n}) ORDER BY updated_at DESC, rowid DESC LIMIT ?`).all(...t,r).map(k)}ensure(t,r,n){return this.db.prepare("INSERT INTO goals (id, title, owner_agent, state, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?) ON CONFLICT(id) DO NOTHING").run(t.id,t.title,r,n,n),this.get(t.id)}upsert(t,r){let n=this.get(t.id);return n?this.db.prepare("UPDATE goals SET title = ?, owner_agent = ?, done_when = ?, check_spec = ?, updated_at = ? WHERE id = ?").run(t.title||n.title,t.ownerAgent!==void 0?t.ownerAgent:n.ownerAgent,t.doneWhen!==void 0?t.doneWhen:n.doneWhen,t.check!==void 0?t.check?JSON.stringify(t.check):null:n.check?JSON.stringify(n.check):null,r,t.id):this.db.prepare("INSERT INTO goals (id, title, owner_agent, state, done_when, check_spec, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?, ?, ?)").run(t.id,t.title,t.ownerAgent??null,t.doneWhen??null,t.check?JSON.stringify(t.check):null,r,r),this.get(t.id)}close(t,r,n,s){return this.db.prepare("UPDATE goals SET state = ?, evidence = ?, closed_at = ?, updated_at = ? WHERE id = ? AND state = 'active'").run(r,n?n.slice(0,A):null,s,s,t).changes>0}markChecked(t,r,n){this.db.prepare("UPDATE goals SET last_check = ?, last_check_at = ? WHERE id = ?").run(r.slice(0,A),n,t)}dueChecks(t){return this.db.prepare("SELECT * FROM goals WHERE state = 'active' AND check_spec IS NOT NULL AND (last_check_at IS NULL OR last_check_at <= ?) ORDER BY last_check_at ASC LIMIT 50").all(t).map(k)}};async function te(e,t,r,n,s=()=>{}){let i=[];for(let o of e.dueChecks(n-r*6e4)){let c;try{c=await t(o.check)}catch(l){c={verdict:"unverifiable",detail:String(l?.message??l)}}e.markChecked(o.id,c.detail,n),c.verdict==="met"&&e.close(o.id,"done",`check: ${c.detail}`,n)?(i.push(o.id),s(`[goals] ${o.id} done: ${c.detail}`)):c.verdict==="unverifiable"&&s(`[goals] ${o.id}: check failed: ${c.detail}`)}return i}function ne(e,t){let r=[`[Goal] ${e.title} (${e.id}): ${e.state}${e.ownerAgent?`, owner ${e.ownerAgent}`:""}.`];return e.doneWhen&&r.push(`Done when: ${e.doneWhen}`),e.check&&r.push(`Check: ${j(e.check)}${e.lastCheck?`; last seen: ${e.lastCheck}${e.lastCheckAt?` (${new Date(e.lastCheckAt).toISOString().slice(0,16).replace("T"," ")} UTC)`:""}`:""}`),t&&r.push(`Requests under it: ${t.open} open, ${t.done} done.`),r.join(`
|
|
18
18
|
`)}var g="Africa/Tunis";function b(e,t=g){let r=Object.fromEntries(new Intl.DateTimeFormat("en-GB",{timeZone:t,hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(new Date(e)).map(s=>[s.type,s.value])),n=(Number(r.hour)%24*3600+Number(r.minute)*60+Number(r.second))*1e3+e%1e3;return e-n}var M=(e,t)=>new Intl.DateTimeFormat("en-GB",{timeZone:t,hour12:!1,hour:"2-digit",minute:"2-digit"}).format(new Date(e));function q(e,t=10){let r=e.replace(/\s+/g," ").trim().split(" ");return r.slice(0,t).join(" ")+(r.length>t?" \u2026":"")}var H=new Set(["issue","idea","approval","erp","card"]);function oe(e,t={}){let r=e.map(n=>{let s=[],i=(o,c)=>{s.some(l=>l.kind===o&&l.ref===c)||s.push({kind:o,ref:c})};for(let o of n.links??[])H.has(o.kind)&&i(o.kind,o.ref);return n.home&&i(n.home.kind,n.home.link),t.hasPlan?.(n.id)&&i("plan",n.id),n.evidence&&i("evidence",n.evidence),{id:n.id,time:M(n.createdAt,t.zone??g),words:q(n.text),state:n.state,owner:n.agentId,landed:s,noHome:s.length===0&&n.state!=="declined"&&n.state!=="dropped"}});return[...r.filter(n=>n.noHome),...r.filter(n=>!n.noHome)]}var x={timeZone:g,days:7},X=90,D=5,G=120,P=(e,t)=>new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e));function Z(e,t){return{day:P(e,t),start:e,asked:0,done:0,dropped:0,moving:0,waiting:0,stuck:0,rate:null,dropReasons:[],moreReasons:0,resent:0,resentDone:0}}function ie(e,t={}){let r=t.zone??x.timeZone,n=Math.min(Math.max(Math.floor(t.days??x.days),1),X),s=t.now??Date.now(),i=[b(s,r)];for(;i.length<n;)i.unshift(b(i[0]-1,r));let o=i.map(a=>Z(a,r)),c=o.map(()=>new Map),l=0;for(let a of e.flowRows(i[0])){for(;l+1<o.length&&a.createdAt>=o[l+1].start;)l++;let d=o[l];if(d.asked++,a.state==="done")d.done++;else if(a.state==="declined"||a.state==="dropped"){d.dropped++;let p=(a.closeReason??"").replace(/\s+/g," ").trim(),u=p.length>G?`${p.slice(0,G-1)}\u2026`:p||"no reason given";c[l].set(u,(c[l].get(u)??0)+1)}else a.state==="in_progress"||a.state==="waiting_other"?d.moving++:a.state==="waiting_owner"?d.waiting++:a.state==="needs_attention"&&d.stuck++;a.resentAt!==null&&(d.resent++,a.state==="done"&&d.resentDone++)}return o.forEach((a,d)=>{a.rate=a.asked?(a.done+a.dropped)/a.asked:null;let p=[...c[d]].sort((u,h)=>h[1]-u[1]);a.dropReasons=p.slice(0,D).map(([u,h])=>({reason:u,count:h})),a.moreReasons=p.slice(D).reduce((u,[,h])=>u+h,0)}),{zone:r,days:o,today:o[o.length-1]}}var O=e=>e===null?"\u2013":`${Math.round(e*100)}%`;function ce(e){let t=e.today,r=[`Today (${t.day}, ${e.zone}): ${t.asked?`${t.done+t.dropped} of ${t.asked} closed, ${O(t.rate)}`:"nothing asked yet"}.`,` ${t.done} done, ${t.dropped} dropped, ${t.moving} moving, ${t.waiting} waiting on the owner, ${t.stuck} stuck.`+(t.resent?` ${t.resent} resent once on its own, ${t.resentDone} of them done.`:"")];if(t.dropReasons.length){r.push(" Dropped because:");for(let n of t.dropReasons)r.push(` ${n.count} \xD7 ${n.reason}`);t.moreReasons&&r.push(` ${t.moreReasons} more`)}if(e.days.length>1){r.push("","Day asked done dropped moving waiting stuck rate");for(let n of e.days){let s=[n.asked,n.done,n.dropped,n.moving,n.waiting,n.stuck].map(String);r.push(`${n.day} ${s[0].padStart(5)} ${s[1].padStart(4)} ${s[2].padStart(7)} ${s[3].padStart(6)} ${s[4].padStart(7)} ${s[5].padStart(5)} ${O(n.rate).padStart(4)}`)}}return r.join(`
|
|
19
19
|
`)}export{f as a,S as b,$ as c,Y as d,B as e,Q as f,A as g,ee as h,j as i,N as j,te as k,ne as l,b as m,oe as n,x as o,X as p,ie as q,ce as r};
|
|
20
|
-
//# sourceMappingURL=chunk-
|
|
20
|
+
//# sourceMappingURL=chunk-27DVJFFR.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as _,b as q}from"./chunk-RKPAVWXF.js";import{a as R,b as O,c as B,d as b,f as k,g as z,h as v,i as w,j as S,k as m}from"./chunk-
|
|
1
|
+
import{a as _,b as q}from"./chunk-RKPAVWXF.js";import{a as R,b as O,c as B,d as b,f as k,g as z,h as v,i as w,j as S,k as m}from"./chunk-UZEH2A2F.js";import{a as x,b as C,c as E,d as P,e as D}from"./chunk-RFMBLJN3.js";import{existsSync as J,readFileSync as M}from"fs";var V=new Set(["cron","heartbeat","api","a2a","mesh"]),W=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=W){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Y(n){let e=x(n);if(!J(e))throw new Error(`config not found at ${e}`);return JSON.parse(M(e,"utf-8"))}function Z(n,e){return n?.agents?.[e]?.admin===!0}function K(n,e,t){return Z(n,t.agentId)||e?.createdBy===t.agentId}function Q(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 j(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&&!V.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function ee(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!m(e)?S(w(e.schedule,r,t),r):"\u2014",p=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",h=[`- ${n} [${p}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&h.push(` notify: ${e.notify.channel} ${e.notify.chatId} ${z(e)}`),e.command?h.push(` command: ${A(String(e.command))}`):e.prompt&&h.push(` prompt: ${A(String(e.prompt))}`),h.join(`
|
|
2
2
|
`)}async function L(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(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function ae(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,p;try{p=Y(t.configPath)}catch(a){return`Error: ${a.message}`}let h=p.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(h).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>ee(i,f,d)).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(!p.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),I=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=_(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!p.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||R;if(!b(g))return`Error: unknown timezone "${g}".`;let u=o||q(i.matched,f);if(!B(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(h[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=j(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let y=s(n.report);if(y&&y!=="always"&&y!=="exceptions")return'Error: `report` must be "always" or "exceptions".';let G={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},H=k({parsed:i,agent:f,prompt:l,timezone:g,notify:$,report:y,enabled:!1,createdBy:e.agentId,approval:G}),N=await I(F=>E(F,`crons.${u}`,H));if(!N.success)return`Error: ${N.error}`;let T=S(w(i.cron,g,d),g),U=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${T}`,`Agent: ${f}`,$?`${y==="exceptions"?"Exceptions":"Results"} and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
|
|
4
4
|
`),X=await L(p,t,U);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${T}.`,"It is saved DISABLED and will not run until the operator approves it.",X].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=h[o];if(!c)return`Error: schedule "${o}" not found.`;if(!K(p,c,e))return Q(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&m(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 I(i=>E(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(m(c)&&c.approval.requestedBy===e.agentId){let u=await I($=>D($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(m(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:d.toISOString()},l=await I(u=>{if(!P(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);E(u,`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: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?S(w(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await L(p,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 ie(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)),d=s(r?e.AGENTX_CHANNEL:n.channel),p=s(r?e.AGENTX_CHAT_ID:n.chatId),h=s(n.accountId);return{agentId:t,channel:d,chatId:p,...h?{accountId:h}:{}}}export{ae as a,ie as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-2PYRRBLW.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ba as Lo,Da as No,G as Io,N as Ut,O as To,V as Ht,X as ko,a as no,b as so,d as Bn,f as We,ha as vo,i as yo,ia as Ao,j as wo,ja as $o,k as Bt,la as Co,ma as Mo,n as Ft,na as Ro,oa as _o,q as bo,r as xo,ra as Po,sa as Eo,v as So,va as Oo,wa as Do}from"./chunk-
|
|
1
|
+
import{Ba as Lo,Da as No,G as Io,N as Ut,O as To,V as Ht,X as ko,a as no,b as so,d as Bn,f as We,ha as vo,i as yo,ia as Ao,j as wo,ja as $o,k as Bt,la as Co,ma as Mo,n as Ft,na as Ro,oa as _o,q as bo,r as xo,ra as Po,sa as Eo,v as So,va as Oo,wa as Do}from"./chunk-6KAP6IHP.js";import{b as ro}from"./chunk-MEFPXHQJ.js";import{a as jn}from"./chunk-W4YR2RO2.js";import{a as to}from"./chunk-IH65GDJR.js";import{b as io,d as Hn,e as co,f as st,i as uo}from"./chunk-KUB5F67E.js";import{a as Fn,b as oo}from"./chunk-J3SOEFRE.js";import{a as Un,b as ao}from"./chunk-SIU6STB2.js";import{e as lo,i as go,j as po,k as mo}from"./chunk-X5C5W3E4.js";import{d as fo}from"./chunk-KWWBDLE6.js";import{f as ho}from"./chunk-LIY5CHUV.js";import{h as Vr,i as eo}from"./chunk-BE64IJWM.js";import{a as Dr,c as Lr}from"./chunk-MYVHVJWZ.js";import{a as Nr,b as Br,c as Fr,d as Ur,l as Wr,q as qr}from"./chunk-3AHYZLGE.js";import{a as Hr,b as jr}from"./chunk-LY4G7PCW.js";import{a as Gr,b as zr}from"./chunk-DPG6VHPX.js";import{c as Kr}from"./chunk-BERWTVG2.js";import{a as Jr,b as Nn}from"./chunk-A7JSRDJL.js";import{d as Qr}from"./chunk-HPRLRD4P.js";import{a as Zr}from"./chunk-UODNQNDK.js";import{g as Xr,h as Yr}from"./chunk-W7D2N55Y.js";import{c as fr,d as hr}from"./chunk-AHWWJ7AF.js";import{c as _r,f as Pr}from"./chunk-DD4YKQGF.js";import{s as Mr,v as Nt,w as Rr,y as Se,z as Ln}from"./chunk-QDZWSALI.js";import{a as nt,b as He,f as Lt}from"./chunk-72SZI2UW.js";import{a as Ue,b as Pn}from"./chunk-FCPTN6NF.js";import{d as Or}from"./chunk-7IW25T4K.js";import{e as je,h as Er,i as _e}from"./chunk-QUFIUXMQ.js";import{e as Re}from"./chunk-DSYKYZMT.js";import{$a as Tr,Ta as Ir,Wa as Dn,Ya as Dc,_ as Sr,_b as Nc,ba as Ec,eb as Lc,kb as kr,lb as Dt,mb as vr,nb as tt,ob as Ar,pb as $r,vb as Cr}from"./chunk-X5UWEMFI.js";import{f as xr,g as et,h as Pc}from"./chunk-KEUW6YLL.js";import{j as On,r as Oc}from"./chunk-N47Y5ADQ.js";import{a as yr,b as me,c as wr,d as br,e as En}from"./chunk-VQRY4IDI.js";Ln();Lt();var jt="tool-set",Bo=["answer","code","full"],Fo={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Bc=.1;function Ho(n){return{task:Uo(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Uo(n.agentPrompt,600)}:{}}}var jo={bundle:He({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Wo(n,e=Bc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Wn(s.answer),o=Wn(s.code),i=Wn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function qo(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Fo.answer.includes(t))?"answer":e.every(t=>Fo.code.includes(t))?"code":"full"}function Go(n,e){return Bo.indexOf(n)<Bo.indexOf(e)}function Wn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Uo(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Ko=!1;function Jo(n,e){let t=Nt(jt);if(t!=="off")return t==="active"&&!Ko&&(Ko=!0,e(`[decisions] seat "${jt}" is set to active, but only shadow is built: it records and changes nothing`)),Se(jt,Ho(n),jo,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Wo(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function zo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=qo(r);Rr(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Go(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Fc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Qo(n,e){let t=Fc(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function qn(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}Ln();Lt();var Xo="session-continuity",Yo={continues:nt("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:nt("Does the new request refer to something stated earlier in the conversation?")};function Zo(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Gn(n.message,1200),previousRequest:n.previousMessage?Gn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Gn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Vo(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function Gn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}function ei(n,e){let t=Or(n,e,"gitlab-user","tokenEnv");return t.status==="ok"&&t.value?{token:t.value,source:`integrations(${t.envVar})`}:{source:t.status}}function sf(n,e){let t=n.channels.gitlab?.token;if(!e)return{token:t,source:"global"};let s=(n.channels.gitlab?.agentMappings||[]).find(o=>o.agentId===e);if(s?.token)return{token:s.token,source:"agentMappings"};let r=ei(n,e);return r.token?{token:r.token,source:r.source}:t?{token:t,source:"global"}:{token:void 0,source:r.source}}function rf(n,e){let t=(n.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);return t?.token?t.token:ei(n,e).token}var ti=null;function of(n){ti=n}function Wt(n,e){let t;try{t=ti?.(e)}catch{t=void 0}return t&&(n.GITLAB_TOKEN=t,n.GITLAB_ACCESS_TOKEN=t),n}import{execa as Yt}from"execa";import{spawn as Uc}from"node:child_process";import{createHash as Hc}from"node:crypto";import{createInterface as jc}from"node:readline";var Ie=class extends Error{},Wc=n=>Uc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),Kn=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(),jc({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Jn=class{constructor(e=Wc,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=Hc("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[E])=>x.localeCompare(E))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new Ie("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let x=[...this.entries].find(([,E])=>!E.connection.busy);if(!x)throw new Ie("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new Kn(e,this.launchProcess)}}catch{throw new Ie("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,p,f=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),A=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 x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(A),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let H=new Promise((b,_)=>{i.failTurn=_,i.notify=(R,M)=>{if(M?.threadId!==u)return;let L=M.item,N={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...M,type:R.replace("/","."),...L?{item:{...L,type:N[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),R==="item/agentMessage/delta"&&(f||(f=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=M.delta,e.onDelta?.(M.delta,c)),R==="thread/tokenUsage/updated"){let j=M.tokenUsage.last;p=j.inputTokens;let q=j.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(j.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(j.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(j.cacheWriteInputTokens||0)}}R==="turn/completed"&&(M.turn.status==="completed"?b():_(new Error(M.turn.error?.message||`Codex turn ${M.turn.status}`)))}});return H.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await H,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new Ie(x.message);return{content:c,codexSessionId:u,usage:l,contextTokens:p,error:x.message,duration:Date.now()-t}}finally{clearTimeout(A),clearTimeout(y),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},ni=new Jn;import{execFile as lu}from"child_process";import{StringDecoder as dt}from"string_decoder";import{mkdtempSync as xi,readFileSync as Si,rmSync as Ii}from"fs";import{join as Qt}from"path";import{tmpdir as Ti}from"os";function qt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let 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]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),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 Gt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Kt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var Pe=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}};var si=null;function rt(){return si}function ff(n){si=n}function fe(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function qc(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var qe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},ri=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=fe(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=qc(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new qe(`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 qe(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=fe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=fe(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=fe(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}closeIdle(e){let t=Date.now(),s=[];for(let[o,i]of this.handles.entries()){if(i.state()!=="idle")continue;let a=i.snapshot();if((a.backgroundTasks??0)>0||a.unaskedTurn)continue;let c=t-Math.max(a.lastTurnAt,a.lastActivityAt??0);c<e.minQuietMs||e.skip?.(i.key)||s.push({ks:o,handle:i,quietFor:c})}let r=s.sort((o,i)=>i.quietFor-o.quietFor).slice(0,e.max);if(e.dryRun)return r.map(o=>o.handle.key);for(let{ks:o,handle:i,quietFor:a}of r){let c=`quiet ${Math.round(a/1e3)}s, ${e.reason}`;this.handles.delete(o),this.handleWorkspace.delete(o),this.cfg.log(`[process-registry] closed idle ${o}: ${c}`),i.kill(`closed idle (${c})`).catch(d=>{this.cfg.log(`[process-registry] closing ${o} failed: ${d?.message||d}`)})}return r.map(o=>o.handle.key)}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot();if((i.backgroundTasks??0)>0||i.unaskedTurn)continue;let a=i.lastTurnAt;a<s&&(s=a,t=o)}if(!t)return!1;let r=fe(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt,i=r.backgroundTasks??0;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t);let c=i>0?`, ${i} background task(s) open`:"";s.kill(`stale (idle ${Math.round(o/1e3)}s${c})`),this.cfg.log(`[process-registry] killed stale ${t}${c}`);continue}if(i>0||r.unaskedTurn)continue;let a=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(a>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(a/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let c=this.handleWorkspace.get(t);if(c){let d=null;try{d=this.cfg.currentWorkspaceHash(s.key,c)}catch(u){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${u?.message||u}`);continue}if(d!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let u=r.claudeMdHash??"unmarked",l=d??"unmarked";s.kill(`claude-md drifted (${u} \u2192 ${l})`),this.cfg.log(`[process-registry] killed drifted ${t} (${u} \u2192 ${l})`)}}}}}};import{spawn as Gc}from"child_process";import{randomUUID as Kc}from"crypto";import{existsSync as Jc,readFileSync as zc}from"fs";import{resolve as Qc}from"path";function Xc(n){let e=Qc(n,"CLAUDE.md");if(!Jc(e))return null;try{let t=zc(e,"utf8");return qr(t)}catch{return null}}var Yc=20*60*1e3,Zc=5e3,ot=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},it=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Vc(n,e){return n.AGENTX_AGENT_ID=e.agentId,Wt(n,e.agentId),n.AGENTX_GUARD="required",n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var oi=class{constructor(e={}){this.opts=e}spawn(e,t){return new zn(e,t,this.opts)}},zn=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=Gc(r,o,{cwd:t.workspace,env:_e(Vc({...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:Xc(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();background=new Pe;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(f=>{t=f}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=Kc(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
3
|
`);let c=e.deadlineMs??Yc,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new ot(c)),l=!1,p=null;try{for(;;){let f=d-Date.now();if(f<=0)throw u();let h=await this.nextEvent(f);if(h===null&&this.killReason)throw new it(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let y=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${y.length} chars): ${y.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let f=this.snap.state==="busy";this.snap={...this.snap,...f?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Zc);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.noteActivity(r),this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}noteActivity(e){this.background.observe(e);let t=this.snap.unaskedTurn??!1;e.type==="system"&&e.subtype==="init"&&this.snap.state!=="busy"?t=!0:e.type==="result"&&(t=!1),this.snap={...this.snap,lastActivityAt:Date.now(),backgroundTasks:this.background.pending,unaskedTurn:t}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};En();Oc();Pn();import{resolve as ii,join as ai}from"path";var eu=4e3;function Jt(n){try{let e=ai(ii(n.root),".agentx","db.sqlite"),t=On({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ue(),r=n.input.command?n.input.command.slice(0,eu):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -31,7 +31,7 @@ ${n}`}function pu(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
|
|
|
31
31
|
`,l)}};b.stdout?.on("data",v=>{L+=j.write(v);let S=L.split(`
|
|
32
32
|
`);L=S.pop()||"";for(let B of S)J(B)}),b.stderr?.on("data",v=>{N+=q.write(v)});let $=await b;if(i&&i.removeEventListener("abort",M),L+=j.end(),L.trim()&&J(L),N+=q.end(),_)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if($.exitCode!==0||h){let v=$,S;return v.timedOut?S=`OpenCode timed out after ${Math.round(E/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?S=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+N)?S=yi():S=N.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Z(S),duration:Date.now()-c,usage:p,opencodeSessionId:f}}return A=!1,{content:l.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||n.model,opencodeSessionId:f}}catch(E){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let H=/ENOENT|spawn opencode/i.test(E?.message||"")?yi():E?.message;return{content:l,...Z(H||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:f}}finally{x?.(),y?.release(A)}}async function ku(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Te(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function vu(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,f=()=>{let A=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(A))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let A=n.provider||"claude-code",x=s?`${s}
|
|
33
33
|
|
|
34
|
-
${e.message}`:e.message,E=e.context?.sender,H=typeof E=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E),b=e.context?.channel==="web-chat"&&H?{userId:E,agentId:e.agentId||"acme-public"}:void 0,_=Ur(n),R=Object.keys(_).length>0,M={task:x,cwd:e.cwd??n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:b,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(J,$)=>Wr(J,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-
|
|
34
|
+
${e.message}`:e.message,E=e.context?.sender,H=typeof E=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E),b=e.context?.channel==="web-chat"&&H?{userId:E,agentId:e.agentId||"acme-public"}:void 0,_=Ur(n),R=Object.keys(_).length>0,M={task:x,cwd:e.cwd??n.workspace,provider:A,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:b,providerOpts:o,abortSignal:l.signal,mcpServers:R?_:void 0,beforeMcpCall:R?(J,$)=>Wr(J,$,_,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-YA2EBSW4.js"),$="",v,S,B,W;for await(let P of J(M)){if(c)try{c(P)}catch{}if(P.type==="text_delta")$+=P.text,r(P.text,$);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==$){let Q=P.result.content.slice($.length);Q?($=P.result.content,r(Q,$)):$=P.result.content}v=P.result.tokensUsed,P.result.inputTokens!=null&&(S=P.result.inputTokens),P.result.outputTokens!=null&&(B=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==$){let Q=P.result.content.slice($.length);Q?($=P.result.content,r(Q,$)):$=P.result.content}P.result.tokensUsed!=null&&(v=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!$?p?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${W}`),duration:Date.now()-d}:((S===void 0||B===void 0)&&v&&(S=Math.round(v*.7),B=v-S),{content:$||"Done.",tokensUsed:v,usage:S!==void 0||B!==void 0?{inputTokens:S||0,outputTokens:B||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-YA2EBSW4.js"),N=await L(M),j=N.inputTokens,q=N.outputTokens;if((j===void 0||q===void 0)&&N.tokensUsed){let J=N.tokensUsed;j=Math.round(J*.7),q=J-j}return{content:N.content||"Done.",tokensUsed:N.tokensUsed,usage:j!==void 0||q!==void 0?{inputTokens:j||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(A){return p?y():A?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Z(`Orchestrator error: ${A.message}`),duration:Date.now()-d}}finally{clearTimeout(h),a&&a.removeEventListener("abort",f)}}var Au=1e3;async function $u(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),Au),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Cu(n,e,t,s,r,o,i){let a=rt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Vt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,f=!1;try{let $=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),f=a.list().length>$}catch($){return $ instanceof qe,null}f&&Vn(e.agentId,n,e.model,s,"persistent");let h=Te(n,e,t),y="",A,x,E,H,b,_,R,M="",L="",N=$=>{if(!i||!$)return;let v;if(L&&$.startsWith(L)?v=$.slice(L.length):v=M&&!M.endsWith(`
|
|
35
35
|
`)?`
|
|
36
36
|
|
|
37
37
|
${$}`:$,L=$,!!v){M+=v;try{i(v,M)}catch{}}},j=!1,q=()=>{j=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:$})){if(J=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let S=v.raw.message?.content??[];for(let W of S)W.type==="text"&&typeof W.text=="string"?(y=W.text,N(W.text)):W.type==="tool_use"&&(L="");let B=v.raw.message?.usage;if(B){let W=(B.input_tokens||0)+(B.cache_read_input_tokens||0)+(B.cache_creation_input_tokens||0);W>0&&(H=W)}}if(v.type==="result"){let S=v.raw;if(S.is_error){let B=Z(typeof S.result=="string"?S.result:"claude error");A=B.error,x=B.errorKind}else typeof S.result=="string"&&S.result.length>0&&(y=S.result,M||N(S.result));typeof S.session_id=="string"&&(R=S.session_id),S.usage&&(E={inputTokens:S.usage.input_tokens||0,outputTokens:S.usage.output_tokens||0,cacheReadTokens:S.usage.cache_read_input_tokens||0,cacheCreateTokens:S.usage.cache_creation_input_tokens||0}),typeof S.num_turns=="number"&&(b=S.num_turns),typeof S.message?.model=="string"?_=S.message.model:typeof S.model=="string"?_=S.model:_=Kt(S.modelUsage)||_}}}catch($){if(j)A="task cancelled by operator",x="cancelled";else if(J)if($ instanceof it)A=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,x="interrupted";else if($ instanceof ot){let v=Z(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);A=v.error,x=v.errorKind}else{let v=Z(`persistent claude process error: ${$?.message||String($)}`);A=v.error,x=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${$?.message||$}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return j&&!A&&(A="task cancelled by operator",x="cancelled"),{content:j?"":y,error:A,errorKind:x,duration:Date.now()-c,usage:E,contextTokens:H,numTurns:b,billedModel:_,claudeSessionId:R}}function Ei(n){let e=me(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?ui(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:fi(t.args,n.taskId,n.agentId)}function Mu(n){return me(n.autonomy)||!!n.personLimits}async function Ru(n,e,t,s,r,o,i){let a=me(e.autonomy)?e.autonomy:void 0,c=a&&li(a,n.tier)||e.personLimits&&hi(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${br(a)}
|
|
@@ -169,7 +169,7 @@ ${y}`,timeLimitRequest:y,timeLimitContinuation:u.continuation,timeLimitStartedAt
|
|
|
169
169
|
${e.message}`),e.queuedAt=void 0}let E=sa({message:e.message,home:e.context?.home}),H=na(d.runningTasks,E,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});H&&(this.log(`[${e.agentId}] ${H.slice(0,160)}`),e.message=`${H}
|
|
170
170
|
${e.message}`),d.totalTasks++,d.lastActive=new Date;let b={...E.length?{homes:E}:{},id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};d.runningTasks.push(b),e.runningTaskId=b.id;let _=Dt(this.config.people,e.context);if(e.context&&(_?e.context.person=_.id:delete e.context.person),this.runningContexts.set(b.id,e.context??{}),e.onStart)try{e.onStart(b.id)}catch{}let R=new AbortController;this.taskAborts.set(b.id,{agentId:e.agentId,channel:b.channel,chatId:typeof b.chatId=="string"?b.chatId:"",originalMessage:e.message||"",controller:R,sender:e.context?.sender,rootId:st()?.rootId,workflowRunId:e.workflowRunId??(typeof b.chatId=="string"&&b.chatId.startsWith("workflow:")&&b.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let M={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(b.id,M);let L=g=>{if(g){M.buffer+=g,M.buffer.length>tc&&(M.buffer=M.buffer.slice(M.buffer.length-tc));for(let m of M.subscribers)try{m(g)}catch{}}},N=Ue();e.taskId=N,b.traceId=N;let j=this.taskAborts.get(b.id);j&&(j.traceId=N);let q=new Map,J=(g,m,T)=>{try{V().emit("task:step",{taskId:N,agentId:e.agentId,name:"pipeline",action:g,status:T,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},$=0,v=!1,S=()=>{v||(v=!0,$&&J("first-event",$,"ok"))},B;if(t){let g=Km();B=m=>{S();let T=g(m);if(T&&L(T),rc(N,e.agentId,m),sc(q,m),ms(m,void 0,e.model||d.def.model),ps(m,void 0,e.agentId),r)try{r(m)}catch{}}}else B=g=>{if(S(),rc(N,e.agentId,g),sc(q,g),ms(g,void 0,e.model||d.def.model),ps(g,void 0,e.agentId),r)try{r(g)}catch{}};let W=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,P=W?setTimeout(()=>R.abort(new Error(`timed out after ${Math.round(W/1e3)}s`)),W):void 0;P?.unref?.();let Q=(d.def.preSpawnTimeoutSec??Nm)*1e3,re=setTimeout(()=>{R.abort(new Error(`timed out before spawn after ${Math.round(Q/1e3)}s in step "${b.step??"start"}"`))},Q);re.unref?.();let oe=()=>{re&&clearTimeout(re),re=void 0},D=()=>`task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`,te;R.signal.addEventListener("abort",()=>{let g=Ne(R.signal).message;/^timed out/.test(g)&&(te=b.step??"start"),this.log(`[${e.agentId}] task ${b.id} aborted in step "${b.step??"start"}" \u2014 ${g} ${D()}`)},{once:!0});let ne=g=>{b.step=g,this.log(`[${e.agentId}] step ${g} ${D()}`)},le=(g,m,T=0)=>{if(R.signal.aborted)return Promise.reject(Ne(R.signal));ne(g),(g==="agent"||g==="workflow-auto-run")&&(oe(),$=Date.now());let k=Date.now(),U=yd(m(),Rm[g]??0,g);return hd(U,R.signal,T).then(K=>(J(g,k,"ok"),K),K=>{throw J(g,k,"error"),K instanceof Qe&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${D()}`),K})},St=async(g,m,T,k=0)=>{try{return await le(g,m,k)}catch(U){if(U instanceof Qe)return T();throw U}},Os=!1,Sn=!1,Ds=g=>{if(!(!Os||Sn)){Sn=!0;try{V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-b.startedAt.getTime(),error:g?.error||(R.signal.aborted?Ne(R.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(b.id)?!0:void 0,stopped:!this.interruptedRuns.has(b.id)&&(this.stoppedRuns.has(b.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},Ls=!1,Ns=g=>{if(Ls)return;Ls=!0,Ds(g),this.runReleases.delete(b.id),P&&clearTimeout(P),oe(),d.activeTasks--,this.admissionTickets.get(e)?.release();let m=d.runningTasks.findIndex(k=>k.id===b.id);m!==-1&&d.runningTasks.splice(m,1),this.runningContexts.delete(b.id),this.taskAborts.delete(b.id);let T=this.runEndWaiters.get(b.id);this.runEndWaiters.delete(b.id);for(let k of T??[])try{k()}catch{}M.done=!0,M.endedAt=new Date;for(let k of M.subscribers)try{k(`
|
|
171
171
|
[task finished]
|
|
172
|
-
`)}catch{}M.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(b.id),Dm).unref?.();try{let k=M.endedAt,U={id:b.id,agentId:e.agentId,channel:b.channel,chatId:b.chatId,sender:b.sender,message:e.message||"",startedAt:b.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-b.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(b.id)||g?.errorKind==="stopped"?{status:"stopped"}:te?{status:"timeout",step:te}:{},responseText:g?.content||"",transcript:M.buffer};this.persistTaskRecord(U);let K=(U.responseText||U.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:k,ok:U.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`);let U=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:U,count:k.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:U,at:new Date().toISOString()});for(let X of k){let Ce=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:Ce,queuedAt:X.queuedAt??X.timestamp}).then(be=>(We(be.error)||K(),this.postQueuedResponseToChannel(e.agentId,Ce,be)),be=>{throw K(),be}).catch(be=>{this.log(`[${e.agentId}] queued message failed: ${be.message}`)})}}).catch(k=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(b.id,Ns),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${D()}`);let w=e.context?.channel||"api",{evaluateRequest:ac,selectRequestContext:dc}=await import("./request-planner-23FPTJLW.js"),Bs=St("request-gate",()=>ac(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),In=!1;Bs.then(()=>{In=!0},()=>{In=!0});let I=l,Tn=e.context?.sender||"User",de=d.def.tier==="codex-cli",Ze=Ha(this.config.session,w,d.def.tier),It=ja(this.config.session),ge=e.isolated===!0,Ve=!ge&&Ze==="lean"&&It.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let Tt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await St("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let cc=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;md({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:cc,taskId:N}),this.sessions.addUserMessage(e.agentId,w,I,Tn,e.message);let Fs=Date.now(),Us={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Fs).toISOString(),taskId:N,resumeOrigin:zi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Dn(e.context),..._?{person:_}:{},humanRoot:et(e.context),pickup:Ir(e.context),operator:Tr(e.context),dueAt:fd(e.context),taskType:fn(e.context)};V().emit("task:started",Us),Os=!0;let ee,kn,Hs=this.classifier;if(Hs&&w!=="a2a"&&!de){ne("classify");let g=Date.now();kn=Hs.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(b.intentPath=ee.path.slice()),J("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),J("classify",g,"error")})}let js=async g=>{if(!kn)return;let m;await Promise.race([kn,new Promise(T=>{m=setTimeout(T,g),m.unref?.()})]),m&&clearTimeout(m)};await js(km);let ve=this.config.workflows?.matching,we,Ws,qs=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&qs?.enabled&&(qs.agents[e.agentId]??!0)&&!i&&et(e.context))try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=(ve?.suggestThreshold??.65)&&(Ws=ko(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&ve?.enabled&&!i)try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=ve.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${ve.mode} reasons=${m.reasons.join(",")||"n/a"}`),ve.mode==="auto"&&m.confidence>=ve.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(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let Ae=vo(this.config.workflows,e.agentId)&&Ao(e)?this.workflowRuns:void 0;if(Ae&&!we&&!i&&this.workflowAutoRunner&&et(e.context))try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list()),T=ve?.autoRunThreshold??.85;m&&m.confidence>=T&&(we={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ce=Ae?Mm():void 0,uc=ce?$o(ce):void 0,vn=this.wikiHub.getAgentWiki(e.agentId),Gs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),Ks=this.memoryStore.buildContext(Gs),Js=this.memoryStore.contextFacts(Gs),lc=this.patternStore.findRelevant(e.message,e.agentId,5),gc=this.patternStore.buildContext(lc),zs="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),T=await le("skills",()=>g(d.def.workspace)),k=e.personLimits?.skills??[],U=k.length?T.filter(K=>!k.some(X=>tt(X,K.frontmatter.name))):T;zs=m(U,e.message)}catch{}let F=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(F&&this.sessions.isSessionStale(e.agentId,w,I,Tt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=Qo({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:Tt??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${qn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"cost");let T=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:T,at:new Date().toISOString()}),F=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${qn(m)}`)}}if(F&&d.def.tier==="claude-code"){let g=F;await St("rotate",()=>this.maybeRotateForContinuity(e,d,w,I,g),()=>!1)&&(F=void 0)}try{let g=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",T=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${m}%, ${T} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let k=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let pc=process.env.AGENTX_CONTEXT_SURGERY==="1",mc=de?{maxMessages:8,maxChars:2400}:pc&&ec(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,fc=!F&&!de?Wm(vn,e.agentId,{notesInbox:jm(this.config)}):void 0,Qs;if(!F&&!de)try{let g=this.config.wiki?.decisionApprovals?.required===!0,m=ho(vn.listArticles(e.agentId),vn.baseDir,g);Qs=fo(m,Date.now())||void 0}catch{}let kt=!F&&!Ve?this.sessions.buildHistoryContext(e.agentId,w,I,mc):void 0,hc=F?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,Xs,Ys=[];if(this.config.procedures?.injection?.enabled&&!F&&!de)try{let g=new pt({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=bs(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Xs=xs(m),Ys=m.map(T=>({id:T.procedure.meta.id,title:T.procedure.meta.title}));for(let T of m)this.log(`[${e.agentId}] procedure match ${T.procedure.meta.id} score=${T.score.toFixed(2)} (${T.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Re&&Re.cat)try{let m=this.sessions.getSession(e.agentId,w,I).messages,T=m[0],k=m[m.length-1],U=kt===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${kt.length}c/${kt.split(`
|
|
172
|
+
`)}catch{}M.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(b.id),Dm).unref?.();try{let k=M.endedAt,U={id:b.id,agentId:e.agentId,channel:b.channel,chatId:b.chatId,sender:b.sender,message:e.message||"",startedAt:b.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-b.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(b.id)||g?.errorKind==="stopped"?{status:"stopped"}:te?{status:"timeout",step:te}:{},responseText:g?.content||"",transcript:M.buffer};this.persistTaskRecord(U);let K=(U.responseText||U.error||"").trim();if(K){let X=K.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:X,at:k,ok:U.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${b.id} chat=${u}:${l} at=${new Date().toISOString()}`);let U=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:U,count:k.length,at:new Date().toISOString()});let K=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:U,at:new Date().toISOString()});for(let X of k){let Ce=X.originalContext||{channel:X.channel,sender:X.sender,chatId:X.chatId};this.execute({message:X.text,agentId:e.agentId,context:Ce,queuedAt:X.queuedAt??X.timestamp}).then(be=>(We(be.error)||K(),this.postQueuedResponseToChannel(e.agentId,Ce,be)),be=>{throw K(),be}).catch(be=>{this.log(`[${e.agentId}] queued message failed: ${be.message}`)})}}).catch(k=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(b.id,Ns),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${D()}`);let w=e.context?.channel||"api",{evaluateRequest:ac,selectRequestContext:dc}=await import("./request-planner-NKP7YFUN.js"),Bs=St("request-gate",()=>ac(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),In=!1;Bs.then(()=>{In=!0},()=>{In=!0});let I=l,Tn=e.context?.sender||"User",de=d.def.tier==="codex-cli",Ze=Ha(this.config.session,w,d.def.tier),It=ja(this.config.session),ge=e.isolated===!0,Ve=!ge&&Ze==="lean"&&It.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let Tt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await St("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let cc=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;md({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:cc,taskId:N}),this.sessions.addUserMessage(e.agentId,w,I,Tn,e.message);let Fs=Date.now(),Us={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Fs).toISOString(),taskId:N,resumeOrigin:zi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Dn(e.context),..._?{person:_}:{},humanRoot:et(e.context),pickup:Ir(e.context),operator:Tr(e.context),dueAt:fd(e.context),taskType:fn(e.context)};V().emit("task:started",Us),Os=!0;let ee,kn,Hs=this.classifier;if(Hs&&w!=="a2a"&&!de){ne("classify");let g=Date.now();kn=Hs.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(m=>{ee=m||void 0,ee?.path?.length&&(b.intentPath=ee.path.slice()),J("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),J("classify",g,"error")})}let js=async g=>{if(!kn)return;let m;await Promise.race([kn,new Promise(T=>{m=setTimeout(T,g),m.unref?.()})]),m&&clearTimeout(m)};await js(km);let ve=this.config.workflows?.matching,we,Ws,qs=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&qs?.enabled&&(qs.agents[e.agentId]??!0)&&!i&&et(e.context))try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=(ve?.suggestThreshold??.65)&&(Ws=ko(m.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&ve?.enabled&&!i)try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list());m&&m.confidence>=ve.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${ve.mode} reasons=${m.reasons.join(",")||"n/a"}`),ve.mode==="auto"&&m.confidence>=ve.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(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let Ae=vo(this.config.workflows,e.agentId)&&Ao(e)?this.workflowRuns:void 0;if(Ae&&!we&&!i&&this.workflowAutoRunner&&et(e.context))try{let g=new Ut({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Ht({agentId:e.agentId,channel:w,message:e.message,intentPath:ee?.path},g.list()),T=ve?.autoRunThreshold??.85;m&&m.confidence>=T&&(we={workflowId:m.workflow.id,confidence:m.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${m.workflow.id} fits (confidence=${m.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ce=Ae?Mm():void 0,uc=ce?$o(ce):void 0,vn=this.wikiHub.getAgentWiki(e.agentId),Gs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),Ks=this.memoryStore.buildContext(Gs),Js=this.memoryStore.contextFacts(Gs),lc=this.patternStore.findRelevant(e.message,e.agentId,5),gc=this.patternStore.buildContext(lc),zs="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),T=await le("skills",()=>g(d.def.workspace)),k=e.personLimits?.skills??[],U=k.length?T.filter(K=>!k.some(X=>tt(X,K.frontmatter.name))):T;zs=m(U,e.message)}catch{}let F=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(F&&this.sessions.isSessionStale(e.agentId,w,I,Tt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&d.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let m=Qo({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:Tt??0},g);if(m.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${qn(m)}`),this.captureRotationMemoAsync(e.agentId,d.def,F,w,I,"cost");let T=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:T,at:new Date().toISOString()}),F=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${qn(m)}`)}}if(F&&d.def.tier==="claude-code"){let g=F;await St("rotate",()=>this.maybeRotateForContinuity(e,d,w,I,g),()=>!1)&&(F=void 0)}try{let g=await le("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",T=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${m}%, ${T} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let k=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let pc=process.env.AGENTX_CONTEXT_SURGERY==="1",mc=de?{maxMessages:8,maxChars:2400}:pc&&ec(w,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,fc=!F&&!de?Wm(vn,e.agentId,{notesInbox:jm(this.config)}):void 0,Qs;if(!F&&!de)try{let g=this.config.wiki?.decisionApprovals?.required===!0,m=ho(vn.listArticles(e.agentId),vn.baseDir,g);Qs=fo(m,Date.now())||void 0}catch{}let kt=!F&&!Ve?this.sessions.buildHistoryContext(e.agentId,w,I,mc):void 0,hc=F?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,Xs,Ys=[];if(this.config.procedures?.injection?.enabled&&!F&&!de)try{let g=new pt({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=bs(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Xs=xs(m),Ys=m.map(T=>({id:T.procedure.meta.id,title:T.procedure.meta.title}));for(let T of m)this.log(`[${e.agentId}] procedure match ${T.procedure.meta.id} score=${T.score.toFixed(2)} (${T.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Re&&Re.cat)try{let m=this.sessions.getSession(e.agentId,w,I).messages,T=m[0],k=m[m.length-1],U=kt===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${kt.length}c/${kt.split(`
|
|
173
173
|
`).length}L`,K=`[${e.agentId}] ${w}:${I} ${U} | session.messages=${m.length}`+(m.length>0?` first=${T.timestamp.slice(11,19)}(${T.role}:${(T.content||"").slice(0,40).replace(/\n/g," ")}) last=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")})`:"");Re.cat("context",K)}catch(g){Re.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Zs;if(d.def.contextReferences&&!F)try{let g=d.def.workspace,m=this.referencesCache.get(g);if(!m){let[k,U]=await le("references",()=>Promise.all([Fn(d.def.workspace),Un(d.def.workspace)]));if(k.byId.size===0&&U.recipes.length===0){let[K,X]=await le("references",()=>Promise.all([Fn(process.cwd()),Un(process.cwd())]));m={refs:K,recipes:X}}else m={refs:k,recipes:U};this.referencesCache.set(g,m)}let T=ao({agentId:e.agentId,intentTags:ee?.path,message:e.message},m.recipes,m.refs);T.cards.length>0&&(Zs=oo(T.cards,500*4)),T.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${T.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Vs=ge||Ve?"":this.sessions.getCrossSessionSummary(e.agentId,w,I,e.message),er,vt=ge?null:Ni(e.message);if(vt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:I,lookbackDays:vt.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${vt.lookbackDays}d on this chat (cue-triggered)]`],T=[...g.turns].sort((k,U)=>k.ts.localeCompare(U.ts));for(let k of T){let U=k.ts.slice(11,16)+" "+k.day,K=k.role==="user"?k.senderName||"User":k.senderName||"Agent";m.push(`${U} ${K}: ${k.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),er=m.join(`
|
|
174
174
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${vt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let yc=de?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",tr,nr,sr=!1;In||ne("request-gate");let $e=await Bs;if($e.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),yc==="planner"&&!ge&&!$e.active&&!Ve&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-CVCRW5TV.js"),m=await le("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(sr=!0,tr=m.sessionHistory,Ks=m.memoryContext,Js=m.memoryFacts,Vs=m.crossChatContext,nr=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}sr&&F&&(this.sessions.clearClaudeSessionId(e.agentId,w,I),F=void 0)}let An=`${e.agentId}:${w}:${I}`,At=Fr(e.message);At&&(At==="default"?(this.activeSouls.delete(An),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(An,At),this.log(`[${e.agentId}] Soul switched to: ${At}`)));let wc=this.activeSouls.get(An),bc=Nr(d.def.workspace,wc),xc=Br(bc),Sc=ge?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Ic=Em(d.def.tier),Tc=Jm(d.def.richMessages,e.context?.via==="voice"?"voice":w),kc=d.def.tier==="claude-code"&&(ge||Ze!=="lean"||Wa(It)),rr="";if(d.def.workspace&&!kc){let g=G(d.def.workspace,"CLAUDE.md");if(ae(g))try{let m=bt(g,"utf-8");rr=`[Project CLAUDE.md]
|
|
175
175
|
${m.length>4e3?m.slice(0,4e3)+`
|
|
@@ -183,9 +183,9 @@ ${Ce}`),m+=Ce.length}catch{}}}let vc=$n.length>0?$n.join(`
|
|
|
183
183
|
|
|
184
184
|
`)||void 0,Ct={channel:w,chatId:I,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:d.def.systemPrompt,sender:Tn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:de||Ve||ec(w,d.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:de?void 0:gc||void 0,procedureContext:[Xs,Ws].filter(Boolean).join(`
|
|
185
185
|
|
|
186
|
-
`)||void 0,workflowRunContext:uc,references:Zs,skillInjection:zs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:tr??kt,memoryContext:Ks||void 0,crossChatContext:Vs||void 0,longMemoryRecall:er||void 0,contextOnDemand:Ve&&!F?Qa(w,I):void 0,wikiContext:fc,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(Us)}catch{return}})(),rotationMemo:hc,ownerDecisions:Qs,eventDigest:F?void 0:Hm(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=Lo(w,!F,d.def.richMessages);return g?qm(d.def.workspace,g):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message};ge&&Object.assign(Ct,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,ownerDecisions:void 0,eventDigest:void 0,attachHint:void 0});let Mt=e.model?void 0:Pr({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?Tt:null});Mt?.downgraded&&this.log(`[${e.agentId}] ${Mt.reason}`);let or=_r(d.def.tier,this.config.decisions.routing),ir=Mt?.downgraded?Promise.resolve(Mt.model):!e.model&&or&&(!$e.active||$e.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-
|
|
186
|
+
`)||void 0,workflowRunContext:uc,references:Zs,skillInjection:zs||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:tr??kt,memoryContext:Ks||void 0,crossChatContext:Vs||void 0,longMemoryRecall:er||void 0,contextOnDemand:Ve&&!F?Qa(w,I):void 0,wikiContext:fc,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(Us)}catch{return}})(),rotationMemo:hc,ownerDecisions:Qs,eventDigest:F?void 0:Hm(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=Lo(w,!F,d.def.richMessages);return g?qm(d.def.workspace,g):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message};ge&&Object.assign(Ct,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,ownerDecisions:void 0,eventDigest:void 0,attachHint:void 0});let Mt=e.model?void 0:Pr({tier:d.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?Tt:null});Mt?.downgraded&&this.log(`[${e.agentId}] ${Mt.reason}`);let or=_r(d.def.tier,this.config.decisions.routing),ir=Mt?.downgraded?Promise.resolve(Mt.model):!e.model&&or&&(!$e.active||$e.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-KW42OGIW.js"),m=await le("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!F,sessionIdleMs:F?Tt:null,cheapModel:or}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),ar=!1;ir.then(()=>{ar=!0});let Rt=$e.active&&$e.preprocess?await St("select-context",()=>dc(Ct),()=>({input:Ct,excluded:[]})):{input:Ct,excluded:[]};Rt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Rt.excluded.join(", ")}`);let _t=Ji(Rt.input,de?{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),Ac=to(_t,{memory:Js,procedures:Ys,wikiContext:Rt.input.wikiContext}),Mn=(_t?.length??0)+(Cn?.length??0)+(e.message?.length??0),Pt={history:_t?.length??0,sysPrompt:Cn?.length??0,message:e.message?.length??0},dr=Ea(e.agentId,w,I);Oa(dr,Mn,Pt);let cr=Da(dr);cr&&this.log(`[${e.agentId}] ${cr}`),Mn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${Mn} bytes (history=${Pt.history}, sysPrompt=${Pt.sysPrompt}, message=${Pt.message})`),ar||ne("route-model");let ur=await ir,lr=d.def.tier!=="claude-code"?void 0:ge?Ka():Ze==="lean"?Ga(d.def.workspace,It,void 0,w):za(d.def.workspace);Ze==="lean"&&!ge&&!F&&this.log(`[${e.agentId}] session profile for ${w}: ${Xa(Ze,It,w)}`);let gr=d.def.tier==="claude-code"&&!F?Jo({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:d.def.systemPrompt??null,taskId:N},g=>this.log(g)):void 0,$c={...e,systemPromptAppend:Cn,...lr?{claudeArgs:lr}:{},...ur?{model:ur}:{}},se,pr=ld({agent:e.agentId,request:e.message,taskId:N,budgetMinutes:d.def.maxExecutionMinutes??20}),Cc=B,mr=!1,Rn=!0;B=g=>{if(pr.observe(g),ce&&Rn)for(let m of Mo(g))Co(m.name,m.input)||(Rn=!1);Cc?.(g)};try{let g=this.workflowAutoRunner;if(we&&g){let O=we;try{let z=await le("workflow-auto-run",()=>g({workflowId:O.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...O.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:O.workflowId,matchConfidence:O.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${we.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:O.follow?`Started the workflow "${z.title??O.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:we.workflowId,workflowRunId:z.runId,workflowMatchConfidence:we.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ce&&Ae)try{let O=_o(Ae,e.resumedFrom);Ro(Ae,{runId:ce,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:N,...O?{continues:O}:{}}),mr=!0,b.workflow={runId:ce,workflowId:To}}catch(O){this.log(`[${e.agentId}] workflows.required: could not create run ${ce} (non-fatal): ${O?.message||O}`)}let m=()=>{if(d.def.tier!=="claude-code")return null;ne("dispatch-gate");let O=d.def.persistentProcess?rt():null,z=O!=null&&O.hasLive({agentId:e.agentId,channel:w,chatId:I}),pe=!!F||z,Fe=[wa(pe),_a(pe,void 0,e.model||d.def.model)].find(Me=>Me&&Me.abort);if(Fe){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${Fe.reason}`);let Me={content:"",error:Fe.message,errorKind:"dispatch_hold",duration:0};if(!t){M.buffer=`[error] ${Fe.message}`;for(let _c of M.subscribers)try{_c(M.buffer)}catch{}}return Me}Ta();let ue=Pa();return ue&&this.log(`[${e.agentId}] ${ue}`),null},T=Ft(e.agentId,void 0,Bt(e.agentId,e.context?.chatId));if(T){if(ne("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${T.reason}`),!t){M.buffer=`[error] ${T.message}`;for(let O of M.subscribers)try{O(M.buffer)}catch{}}return d.errors++,se={content:"",error:T.message,errorKind:"budget_cap",duration:0},se}let k=this.planCloudSession(d.def,e);if(k.route==="local"){let O=m();if(O)return d.errors++,se=O,O}let U=d.def.tier==="claude-code",K=U?t:(O,z)=>{O&&L(O),t&&t(O,z)},X=!1,Ce=U?s:O=>{O&&(X?L(O):(L(`\u{1F4AD} ${O}`),X=!0)),s&&s(O)},be=()=>{X&&(L(`
|
|
187
187
|
`),X=!1)},Mc=U?K:K?(O,z)=>{be(),K(O,z)}:void 0,C=await le("agent",async()=>{if(k.route!=="local"){let z=await this.runCloudSession(d.def,e,k,N);if(z)return z;let pe=m();if(pe)return pe}let O=await this.inTaskWorktree(d.def,$c);return Oi(O.def,O.task,this.providers,Mc,_t,O.fresh?void 0:F,B,R.signal,Ce)},Lm);if(!C.error){let O=Gm(d.def.toolUseRequired,q);if(O){let z=Array.from(q.entries()).map(([pe,Be])=>`${pe}=${Be}`).join(", ")||"none";C.error=`tool_required_not_called: ${O} (invoked: ${z})`,C.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${O}, observed ${z}`)}}gr&&zo(gr,{toolUses:q,eventsSeen:v,error:C.error,agentId:e.agentId},O=>this.log(O));let Et=this.interruptedRuns.get(b.id);Et&&(C.content="",C.error=Et,C.errorKind="interrupted");let _n=Et?void 0:this.stoppedRuns.get(b.id);_n&&(C.content="",C.error=_n,C.errorKind="stopped"),se=C;let xe=C.usage?Vr(C.usage):void 0,Rc=C.billedModel||e.model||d.def.model||void 0,Ot=C.costUsd??(C.usage?this.tokenTracker.runCost(C.usage,Rc,d.def.tier):void 0);if(Sn=!0,V().emit("task:completed",{taskId:N,agentId:e.agentId,channel:w,chatId:I,durationMs:Date.now()-Fs,error:C.error||void 0,errorKind:C.error?C.errorKind:void 0,interrupted:Et?!0:void 0,stopped:_n?!0:void 0,inputTokens:xe?.inputTokens,outputTokens:xe?.outputTokens,cacheReadTokens:xe?.cacheReadTokens,cacheCreateTokens:xe?.cacheCreateTokens,tier2InputTokens:xe?.tier2InputTokens,tier2OutputTokens:xe?.tier2OutputTokens,tier2CacheReadTokens:xe?.tier2CacheReadTokens,tier2CacheCreateTokens:xe?.tier2CacheCreateTokens,resumed:!!F,resumeSessionId:F||void 0,jevArm:$e.arm,numTurns:C.numTurns,costUsd:Ot!==void 0&&Number.isFinite(Ot)&&Ot>0?Ot:void 0,injectedContext:Ac,finalResponse:C.content||void 0,billedModel:C.billedModel||e.model||d.def.model||void 0,at:new Date().toISOString()}),!t&&(C.content||C.error)){let O=C.error?`[error] ${C.error}`:C.content;M.buffer=O;for(let z of M.subscribers)try{z(O)}catch{}}if(C.error)d.errors++,this.log(`[${e.agentId}] error: ${C.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,I,C.content),pd({agent:e.agentId,channel:w,chatId:I,request:e.message,reply:C.content,taskId:N}),C.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,I,C.claudeSessionId),C.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,I,C.codexSessionId),C.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,I,C.opencodeSessionId),(C.claudeSessionId||C.codexSessionId||C.opencodeSessionId)&&C.usage&&this.sessions.recordTurnUsage(e.agentId,w,I,C.usage,C.contextTokens),C.usage){let ue=C.contextTokens,Me=(C.usage.inputTokens||0)+(C.usage.cacheReadTokens||0)+(C.usage.cacheCreateTokens||0);(ue??Me)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${I}: context=${ue??"n/a"} tokens (cumulative turn total=${Me}) \u2014 next turn will rotate`)}let O=Gr({channel:w,content:`User: ${e.message}`,responseLength:C.content.length}),z=G(this.wikiHub.getBaseDir(),Ui);O.capture||Hi(z,e.agentId,O,ue=>this.log(ue)),O.capture&&(await js(vm),ji(z,e.agentId,()=>{let ue=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ue,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
188
188
|
|
|
189
189
|
Agent: ${C.content}`,meta:Um(ee,e.context)})},ue=>this.log(ue)),zr(e.agentId,e.message,C.content,{channel:w,chatId:I,sender:Tn},this.memoryStore).catch(()=>{}),aa(e.agentId,e.message,C.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let pe=C.billedModel||e.model||d.def.model,Be=e.context?.channel,Fe=Be&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${Be}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,C.duration||0,C.usage,e.message.length,C.content.length,!1,pe,Be,Fe),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${D()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=qt(g.message);return se={content:"",error:Gt(m),errorKind:m.kind},se}finally{if(pr.stop(),mr&&ce&&Ae)try{let g=se?.usage,m=Po(Ae,ce,{error:se?se.error||void 0:R.signal.aborted?Ne(R.signal).message:"run ended before completion",canceled:Eo(se?.errorKind)||this.stoppedRuns.has(b.id)||this.interruptedRuns.has(b.id)||!se&&R.signal.aborted,durationMs:Date.now()-b.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:Rn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});m&&m!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ce} ${m.status} (${m.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ce} (non-fatal): ${g?.message||g}`)}Ds(se),Ns(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?Om(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:Oo(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),Ye,this.safe(e.agentId),t);ae(s)||Am(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);Cm(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=G(process.cwd(),Ye,this.safe(e));if(!ae(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let p=G(a,l);if(ae(p))try{for(let f of ye(p)){if(!f.endsWith(".json"))continue;let h=f.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let A=Math.floor((s-y)/36e5),x=t-1-A;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Ye);if(!ae(e))return 0;let t=0;for(let s of ye(e)){let r=G(e,s),o;try{o=ye(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),c;try{c=ye(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(bt(G(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Fm){let t=G(process.cwd(),Ye);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ye(t)){let i=G(t,o),a;try{a=ye(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{$m(G(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return[];let r=ye(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(s,i),c;try{c=ye(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(bt(G(a,d),"utf-8")),{transcript:l,responseText:p,...f}=u;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),Ye,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=ye(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(s,i,`${r}.json`);if(ae(a))try{return JSON.parse(bt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Ft(t,void 0,Bt(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=jn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||We(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){_m.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Vt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator",o){let i=0;for(let[a,c]of this.taskAborts)c.agentId!==e||c.channel!==t||c.chatId!==s||o!==void 0&&c.sender!==o||this.cancelRunningTask(a,r)&&i++;return i}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let p=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:p,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let f=this.messageQueue.pendingCount(i,a,c);V().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:kr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${f}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:l,pending:f}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=p=>{u||(u=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{We(p.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Jm(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
190
190
|
`)}export{ei as a,sf as b,rf as c,of as d,ni as e,ff as f,ri as g,Xc as h,oi as i,Jt as j,Rf as k,Of as l,Df as m,Uf as n,Vt as o,wu as p,_i as q,Tu as r,ku as s,vu as t,Oi as u,tn as v,Ui as w,wh as x,nn as y,Qu as z,Th as A,kh as B,Ah as C,rn as D,sl as E,Mh as F,as as G,V as H,pa as I,Il as J,Al as K,ha as L,zh as M,ya as N,Sa as O,dy as P,cy as Q,$a as R,uy as S,Ca as T,ln as U,by as V,xy as W,pt as X,Fg as Y,Ug as Z,Hg as _,jg as $,Wg as aa,bs as ba,fn as ca,Xy as da,yn as ea,hn as fa,Id as ga,ft as ha,Td as ia,sw as ja,rw as ka,ow as la,iw as ma,aw as na,dw as oa,cw as pa,Sp as qa,Dd as ra,Xe as sa,Pm as ta,Em as ua,Zb as va,Vb as wa,Om as xa,Bm as ya,Um as za,Hm as Aa,Wm as Ba,Es as Ca,nc as Da,sc as Ea,Gm as Fa,rc as Ga,oc as Ha,Jm as Ia};
|
|
191
|
-
//# sourceMappingURL=chunk-
|
|
191
|
+
//# sourceMappingURL=chunk-4FL6B3B7.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{_b as $,wb as S}from"./chunk-X5UWEMFI.js";import{randomBytes as x}from"crypto";import{existsSync as b,mkdirSync as k,readdirSync as M,readFileSync as j,renameSync as E,unlinkSync as y,writeFileSync as C}from"fs";import{resolve as c}from"path";function m(t){return c(t,".agentx","email")}function u(t,e){k(c(t,".."),{recursive:!0});let r=`${t}.${process.pid}.tmp`;C(r,JSON.stringify(e,null,2)+`
|
|
2
2
|
`,{mode:384}),E(r,t)}function g(t){try{return JSON.parse(j(t,"utf-8"))}catch{return null}}var D=t=>c(m(t),"threads.json");function w(t){return g(D(t))??{}}function I(t,e){return w(t)[e.toLowerCase()]}function L(t,e){let r=w(t);r[e.to.toLowerCase()]=e,u(D(t),r)}var h=(t,e)=>c(m(t),"cursors",`${e}.json`);function z(t,e){return g(h(t,e))}function B(t,e,r){u(h(t,e),r)}var T=2e4,_=t=>c(m(t),"drafts"),N=t=>/^[a-z0-9-]{8,64}$/.test(t),a=(t,e)=>c(_(t),`${e}.json`);function U(t,e,r=Date.now()){let n=e.text.trim().slice(0,T);if(!n)throw new Error("empty reply");let s={...e,text:n,id:`${r.toString(36)}-${x(4).toString("hex")}`,status:"pending",created_at:new Date(r).toISOString()};return u(a(t,s.id),s),s}function v(t,e){return N(e)?g(a(t,e)):null}function V(t,e){let r=_(t);return b(r)?M(r).filter(n=>n.endsWith(".json")).map(n=>v(t,n.slice(0,-5))).filter(n=>!!n&&(!e||n.status===e)).sort((n,s)=>n.created_at.localeCompare(s.created_at)):[]}async function W(t,e,r,n){let s=v(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no email reply "${e}" is waiting`};let i=`${a(t,e)}.${process.pid}.${x(3).toString("hex")}.claim`;try{E(a(t,e),i)}catch{return{ok:!1,error:`email reply "${e}" is already being decided`}}let d=n.text!==void 0&&n.text.trim()!==""&&n.text.trim()!==s.text,o={...s,...d?{text:n.text.trim().slice(0,T),edited:!0}:{},decided_by:n.by??"operator",decided_at:new Date(n.now??Date.now()).toISOString()};if(r==="no")o.status="rejected";else{let f=await n.send(o).catch(p=>({ok:!1,error:String(p?.message??p)}));if(!f.ok){u(a(t,e),{...s,error:f.error});try{y(i)}catch{}return{ok:!1,error:`not sent: ${f.error}`}}o.status="sent",delete o.error}u(a(t,e),o);try{y(i)}catch{}return{ok:!0,draft:o}}$();function l(t,e){return(t??"").replace(/\$\{(\w+)\}/g,(r,n)=>e[n]??"")}function P(t,e=process.env){let r={host:t.imap.host,port:t.imap.port,secure:t.imap.secure,user:l(t.imap.user,e)||t.address,password:l(t.imap.password,e)},n={host:t.smtp.host,port:t.smtp.port,secure:t.smtp.secure,user:l(t.smtp.user,e)||r.user,password:l(t.smtp.password,e)||r.password};return{imap:r,smtp:n}}async function R(t,e,r,n=process.env){let{smtp:s}=P(t,n);if(!s.password)throw new Error(`no SMTP password for ${t.address}: set it in .env`);return J(s,{name:e,address:t.address},r,{"Auto-Submitted":"auto-replied"})}async function J(t,e,r,n){let{default:s}=await import("nodemailer"),i=s.createTransport({host:t.host,port:t.port,secure:t.secure,auth:{user:t.user,pass:t.password},connectionTimeout:2e4,greetingTimeout:2e4,socketTimeout:6e4});try{return(await i.sendMail({from:e,to:r.toName?{name:r.toName,address:r.to}:r.to,subject:r.subject,text:r.text,...r.inReplyTo?{inReplyTo:r.inReplyTo}:{},...r.references?{references:r.references}:{},headers:n})).messageId}finally{i.close()}}function G(t,e){return async r=>{let n=t?.channels?.email?.accounts?.[r.account];if(!n)return{ok:!1,error:`no email account "${r.account}" in agentx.json`};let s=S.safeParse(n);if(!s.success)return{ok:!1,error:`email account "${r.account}": ${s.error.issues[0]?.message}`};let i=s.data,d=i.name||t?.agents?.[r.agent]?.name||r.agent;return await R(i,d,{to:r.to,toName:r.to_name,subject:r.subject,inReplyTo:r.in_reply_to,references:r.references,text:r.text},e),{ok:!0}}}export{I as a,L as b,z as c,B as d,U as e,v as f,V as g,W as h,P as i,R as j,J as k,G as l};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-5E6JVFHV.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as fe}from"./chunk-7AB3QUGH.js";import{b as Ue}from"./chunk-AFRHKA7B.js";import{b as Bt,c as Kt}from"./chunk-IH65GDJR.js";import{b as Et,f as jt,g as Ct,j as Lt,l as Ut,m as Ht,s as qt}from"./chunk-
|
|
1
|
+
import{a as fe}from"./chunk-7AB3QUGH.js";import{b as Ue}from"./chunk-AFRHKA7B.js";import{b as Bt,c as Kt}from"./chunk-IH65GDJR.js";import{b as Et,f as jt,g as Ct,j as Lt,l as Ut,m as Ht,s as qt}from"./chunk-KUB5F67E.js";import{a as Ft}from"./chunk-GV7S5BAX.js";import{c as _t}from"./chunk-SZDACK6O.js";import{b as Ot,d as Dt,e as Mt}from"./chunk-5ONH4ITT.js";import{e as Tt,g as Wt,h as Nt,i as Le}from"./chunk-JRAG37V5.js";import{a as Rt,b as Ce,d as Fe,e as xt,f as _e}from"./chunk-BERWTVG2.js";import{a as ne,b as Pt}from"./chunk-A7JSRDJL.js";import{c as vt,d as $t}from"./chunk-AHWWJ7AF.js";import{y as At,z as $r}from"./chunk-QDZWSALI.js";import{b as St,f as vr}from"./chunk-72SZI2UW.js";import{Fa as Ir,ta as je}from"./chunk-X5UWEMFI.js";import{j as Ee,r as br}from"./chunk-N47Y5ADQ.js";import{existsSync as Sr,mkdirSync as Jt,readFileSync as Ar,writeFileSync as Rr,renameSync as xr}from"fs";import{resolve as zt,dirname as Pr}from"path";var Yt=class{filePath;log;constructor(e={}){let t=e.baseDir??zt(process.cwd(),".agentx");this.filePath=zt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Jt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Sr(this.filePath))return{version:1,overrides:{}};try{let e=Ar(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Jt(Pr(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Rr(t,JSON.stringify(e,null,2)),xr(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Xt,writeFileSync as He,appendFileSync as Or,mkdirSync as Dr,existsSync as en,statSync as Mr}from"fs";import{resolve as ge}from"path";var Gt="[Agent Memory \u2014 persistent facts from past conversations]",Tr=2400;function Vt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Wr(n,e=Date.now()){let t=Dt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Vt(t,Tt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Nr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(ne(n.content))return{line:`- [${n.category}] ${Pt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Nt(n,e);return{line:`- [${n.category}] ${Vt(o,Wt(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Qt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Gt.length,a=!1;for(let i of n){let d=e.length>0?Mt(i.content,e):null,u,c,p=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),u=Wr(d,t),c=d.id}else u=Nr(i,t),d&&(u.line+=` [differs from wiki ${d.id}]`);let f=u.unverified&&!a?Le.length:0;if(s+f+u.line.length>Tr)break;r.push({fact:i,...u,...c?{wikiRef:c}:{}}),s+=f+u.line.length,f&&(a=!0)}return r}function Zt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Le]:[];return[Gt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var tn=200,Er=7,nn=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ge(e,".agentx/memory"),this.ledger=new Ot(ge(e,".agentx/wiki")),en(this.memoryDir)||Dr(this.memoryDir,{recursive:!0})}filePath(e){return ge(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||Ce(t.content)||ne(t.content))return!1;let r=t.source.trust??Rt(t.source.channel),o=t.review??xt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Or(this.filePath(e),JSON.stringify(s)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!en(t))return[];try{let{mtimeMs:r,size:o}=Mr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Xt(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(_e);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=ge(this.memoryDir,`${t}_bm25_cache.json`),i=$t(s,a),d=vt(e,i),u=new Map(d.map(g=>[g.docIndex,g.score])),p=o.map((g,m)=>{let y=u.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(p.length===0)return o.slice(-r);let f=p.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Zt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Qt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&He(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
|
|
@@ -39,4 +39,4 @@ ${n.text}`}async function Pe(n,e){let t=n.channels[e.channel],r={channel:e.chann
|
|
|
39
39
|
`).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(wt(this.file))try{let e=JSON.parse(yt(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){nr(sr(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${ar(4).toString("hex")}.tmp`;or(t,JSON.stringify(e,null,2)+`
|
|
40
40
|
`,{encoding:"utf-8",mode:384}),rr(t,this.file)}};import{extname as li}from"path";var ur=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,lr=/<agentx-artifact>[\s\S]*$/i;function zu(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(ur,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let u=d.mime,c=u.startsWith("image/")?"image":u==="application/pdf"?"pdf":u.startsWith("text/")?"text":"file";r.push({type:c,filename:d.filename,mime:u})}}catch{}return""});return{text:(t?s.replace(lr,""):s).trim(),artifacts:r}}function Yu(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(ur,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(lr,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ci={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},Gu={bytes:20*1024*1024,perMessage:20,pathChars:512};function Vu(n){return ci[li(n).toLowerCase()]??null}var pi=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
41
41
|
`);function Qu(n,e,t){return n==="app"&&e&&t!==!1?pi:void 0}import{lstatSync as bt,mkdirSync as fi,readdirSync as gi,realpathSync as kt,unlinkSync as mi}from"fs";import{join as De,resolve as cr}from"path";var pr=".agentx/outbox",hi=7*24*60*60*1e3;function wi(n,e){try{let t=kt(cr(e,n)),r=De(t,pr);return kt(r)===r&&bt(r).isDirectory()?r:null}catch{return null}}function tl(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=kt(cr(t,n));bt(De(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||fi(De(o,pr),{recursive:!0})}catch{return 0}let r=wi(n,t);return r?fr(r,(e.now??Date.now())-(e.maxAgeMs??hi)):0}function fr(n,e){let t=0;for(let r of gi(n)){let o=De(n,r);try{let s=bt(o);s.isDirectory()?t+=fr(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(mi(o),t++)}catch{}}return t}export{Yt as a,nn as b,rn as c,Ei as d,Fr as e,ji as f,Lr as g,_i as h,Li as i,Ui as j,Hi as k,Bi as l,Ki as m,qi as n,Br as o,Ji as p,zi as q,Qi as r,Je as s,Qr as t,Zi as u,Xi as v,Zr as w,ea as x,cn as y,ra as z,oa as A,fn as B,gn as C,ro as D,ua as E,la as F,fa as G,ga as H,x as I,re as J,S as K,Ye as L,bo as M,Qe as N,U as O,et as P,nt as Q,ft as R,Ts as S,Es as T,mt as U,Lo as V,Gs as W,mu as X,hu as Y,wu as Z,yu as _,ku as $,Qs as aa,Zs as ba,bu as ca,Iu as da,vu as ea,$u as fa,Ru as ga,xu as ha,Pu as ia,Tu as ja,Wu as ka,Nu as la,Ou as ma,Du as na,Mu as oa,Eu as pa,ju as qa,oi as ra,Cu as sa,Fu as ta,_u as ua,Lu as va,dr as wa,zu as xa,Yu as ya,Gu as za,Vu as Aa,Qu as Ba,pr as Ca,tl as Da};
|
|
42
|
-
//# sourceMappingURL=chunk-
|
|
42
|
+
//# sourceMappingURL=chunk-6KAP6IHP.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-
|
|
1
|
+
import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-W7D2N55Y.js";import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{c as _,d as x}from"./chunk-AHWWJ7AF.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{y as C,z as K}from"./chunk-QDZWSALI.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
|
|
2
2
|
`)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
|
|
3
3
|
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
|
|
4
4
|
`));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
|
|
@@ -102,4 +102,4 @@ We use GitLab for version control.
|
|
|
102
102
|
There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
103
103
|
|
|
104
104
|
${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
|
|
105
|
-
//# sourceMappingURL=chunk-
|
|
105
|
+
//# sourceMappingURL=chunk-6LOXNAZD.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-UOK5MMKD.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-
|
|
1
|
+
import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-UOK5MMKD.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-LWUTWLBA.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-Q3HCFXDT.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-MZMIQ3SV.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-MZMIQ3SV.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
|
|
2
2
|
`).slice(0,12).map(n=>` | ${n}`).join(`
|
|
3
3
|
`)))}u.outcomes.length===0&&console.log(t.dim(" nothing to do: no entity of these types changed since the last run (--force redoes them)")),console.log(t.dim(` spent $${u.costUsd.toFixed(3)} of $${w}${u.capped?" \xB7 stopped at the cap":""}`))})}export{N as a,I as b};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-6UVU47FA.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{d as h}from"./chunk-
|
|
1
|
+
import{d as h}from"./chunk-EJXHHFZJ.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
|
|
2
2
|
`),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
|
|
3
3
|
`).filter(o=>o.trim()).length,a=c.split(`
|
|
4
4
|
`).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
|
|
5
5
|
`))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-BITJXYHB.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{y as l,z as T}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{y as l,z as T}from"./chunk-QDZWSALI.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
|
|
2
|
+
//# sourceMappingURL=chunk-DD4YKQGF.js.map
|