agentix-cli 0.69.0 → 0.69.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-VQIC7O5T.js → agent-K7EPLYCP.js} +2 -2
- package/dist/{board-dashboard-ZPJHXX3U.js → board-dashboard-BWB2FLOA.js} +2 -2
- package/dist/{chunk-5AMQFDLE.js → chunk-37P3DKSX.js} +63 -63
- package/dist/{chunk-5AMQFDLE.js.map → chunk-37P3DKSX.js.map} +1 -1
- package/dist/{chunk-QDRAKJSY.js → chunk-3XEN24B7.js} +4 -4
- package/dist/chunk-ILEC3IAV.js +3 -0
- package/dist/chunk-ILEC3IAV.js.map +1 -0
- package/dist/chunk-KA2UIZXG.js +3 -0
- package/dist/chunk-KA2UIZXG.js.map +1 -0
- package/dist/{chunk-NVJHA63C.js → chunk-KSUCHOH2.js} +10 -10
- package/dist/chunk-KSUCHOH2.js.map +1 -0
- package/dist/chunk-KXR6GVL7.js +5 -0
- package/dist/chunk-KXR6GVL7.js.map +1 -0
- package/dist/{chunk-BYKF3UTL.js → chunk-PDGPHE35.js} +2 -2
- package/dist/{chunk-4NXIJEYU.js → chunk-USTQPX4Y.js} +3 -3
- package/dist/{chunk-B65FS265.js → chunk-X5BWHPR7.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/fact-proposals-LZWS5KFO.js +2 -0
- package/dist/index.js +1 -1
- package/dist/ledger-CH7R756S.js +2 -0
- package/dist/{program-6PFRDQFT.js → program-44FEGUCB.js} +2 -2
- package/dist/questions-ZATLU5AW.js +2 -0
- package/dist/{registry-KP3C4EZ4.js → registry-HMVIS6QJ.js} +2 -2
- package/dist/{rotation-memo-store-X63HYIMV.js → rotation-memo-store-A4YW6FSK.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-AU6FFC4I.js +0 -5
- package/dist/chunk-AU6FFC4I.js.map +0 -1
- package/dist/chunk-NVJHA63C.js.map +0 -1
- package/dist/chunk-ST6KPQOY.js +0 -3
- package/dist/chunk-ST6KPQOY.js.map +0 -1
- package/dist/chunk-ZXR6GNEK.js +0 -3
- package/dist/chunk-ZXR6GNEK.js.map +0 -1
- package/dist/fact-proposals-ERRQXV2J.js +0 -2
- package/dist/ledger-DHYRP4TN.js +0 -2
- package/dist/questions-QGITDLJY.js +0 -2
- /package/dist/{agent-VQIC7O5T.js.map → agent-K7EPLYCP.js.map} +0 -0
- /package/dist/{board-dashboard-ZPJHXX3U.js.map → board-dashboard-BWB2FLOA.js.map} +0 -0
- /package/dist/{chunk-QDRAKJSY.js.map → chunk-3XEN24B7.js.map} +0 -0
- /package/dist/{chunk-BYKF3UTL.js.map → chunk-PDGPHE35.js.map} +0 -0
- /package/dist/{chunk-4NXIJEYU.js.map → chunk-USTQPX4Y.js.map} +0 -0
- /package/dist/{chunk-B65FS265.js.map → chunk-X5BWHPR7.js.map} +0 -0
- /package/dist/{fact-proposals-ERRQXV2J.js.map → fact-proposals-LZWS5KFO.js.map} +0 -0
- /package/dist/{ledger-DHYRP4TN.js.map → ledger-CH7R756S.js.map} +0 -0
- /package/dist/{program-6PFRDQFT.js.map → program-44FEGUCB.js.map} +0 -0
- /package/dist/{questions-QGITDLJY.js.map → questions-ZATLU5AW.js.map} +0 -0
- /package/dist/{registry-KP3C4EZ4.js.map → registry-HMVIS6QJ.js.map} +0 -0
- /package/dist/{rotation-memo-store-X63HYIMV.js.map → rotation-memo-store-A4YW6FSK.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as qn,b as Kn,d as Jn,f as Ze,l as os,r as is,x as as,z as cs}from"./chunk-
|
|
1
|
+
import{a as qn,b as Kn,d as Jn,f as Ze,l as os,r as is,x as as,z as cs}from"./chunk-KSUCHOH2.js";import{a as It}from"./chunk-N6EWZGIX.js";import{a as Wn}from"./chunk-WP6KLXTP.js";import{b as Gn}from"./chunk-DP7RTNDM.js";import{a as rs}from"./chunk-W4YR2RO2.js";import{b as zn,c as Ct,d as Yn,e as Vn,h as Zn}from"./chunk-JHWBCDD2.js";import{a as St,b as Qn}from"./chunk-J3SOEFRE.js";import{a as vt,b as Xn}from"./chunk-SIU6STB2.js";import{e as es,i as ts,j as ns,k as ss}from"./chunk-X5C5W3E4.js";import{a as _n}from"./chunk-Q2WW2HF4.js";import{a as En,b as Dn,c as On,d as Nn,f as Ln}from"./chunk-DWADWDMU.js";import{a as Fn,b as Hn}from"./chunk-NO2HOK4B.js";import{a as Bn}from"./chunk-S4ASFOJU.js";import{b as jn,c as Un}from"./chunk-CUZWGTXT.js";import{a as Ve,c as _e}from"./chunk-2GIDVZ4H.js";import{q as Mn,t as Rn,v as we,w as Pn}from"./chunk-VOS2IW4V.js";import{a as Pe,b as Ye,f as kt}from"./chunk-72SZI2UW.js";import{a as be,b as xt}from"./chunk-FCPTN6NF.js";import{c as In,d as Sn}from"./chunk-QOYAX2FT.js";import{e as pe}from"./chunk-DSYKYZMT.js";import{d as vn,e as oe,f as Cn,g as An,h as Tt,s as $n,z as fo}from"./chunk-N5NPJ6DJ.js";Pn();kt();var ds="session-continuity",us={continues:Pe("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:Pe("Does the new request refer to something stated earlier in the conversation?")};function ls(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:At(s.message,1200),previousRequest:s.previousMessage?At(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>At(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function gs(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function At(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as yo,execFile as bo}from"node:child_process";import{createHash as wo,randomBytes as xo}from"node:crypto";import{createInterface as To}from"node:readline";import{promisify as ko}from"node:util";var Io=ko(bo),ie=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},$t=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=Io("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new ie("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=wo("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([d],[l])=>d.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new ie("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let p=[...this.entries].find(([,y])=>!y.busy);if(!p)throw new ie("Warm server capacity reached",!0);this.close(p[1]),this.entries.delete(p[0])}let d={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:xo(32).toString("hex")},l=yo("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:d,stdio:["pipe","pipe","pipe"]});o={child:l,env:d,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let u=o;l.stderr.resume(),l.on("exit",()=>this.close(u)),l.on("error",()=>this.close(u));try{await new Promise((p,y)=>{let b=To({input:l.stdout}),x=()=>k(new ie("OpenCode server failed before dispatch",!0)),w=()=>k(new Error("task cancelled by operator")),I=setTimeout(x,15e3),k=_=>{clearTimeout(I),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",w),b.close(),l.stdout.resume(),_?y(_):p()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",w,{once:!0}),b.on("line",_=>{try{let A=new URL(JSON.parse(_).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;u.url=A.origin,k()}catch{}}),e.signal?.aborted&&w()})}catch(p){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),p}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(d=!1)=>{c||(c=!0,a.busy=!1,d||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},ps=new $t;import{execa as ot}from"execa";import{spawn as So}from"node:child_process";import{createHash as vo}from"node:crypto";import{createInterface as Co}from"node:readline";var ae=class extends Error{},Ao=s=>So("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Mt=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(),Co({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Rt=class{constructor(e=Ao,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=vo("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[I])=>w.localeCompare(I))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ae("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let w=[...this.entries].find(([,I])=>!I.connection.busy);if(!w)throw new ae("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:n,connection:new Mt(e,this.launchProcess)}}catch{throw new ae("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,l,u,p=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),x=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let w={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(x),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let k=new Promise((_,A)=>{i.failTurn=A,i.notify=(v,R)=>{if(R?.threadId!==l)return;let N=R.item,M={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...R,type:v.replace("/","."),...N?{item:{...N,type:M[N.type]||N.type}}:{}}),v==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),v==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=R.delta,e.onDelta?.(R.delta,c)),v==="thread/tokenUsage/updated"){let O=R.tokenUsage.last,F=O.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(O.inputTokens||0)-F),outputTokens:(u?.outputTokens||0)+(O.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+F,cacheCreateTokens:(u?.cacheCreateTokens||0)+(O.cacheWriteInputTokens||0)}}v==="turn/completed"&&(R.turn.status==="completed"?_():A(new Error(R.turn.error?.message||`Codex turn ${R.turn.status}`)))}});return k.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await k,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new ae(w.message);return{content:c,codexSessionId:l,usage:u,error:w.message,duration:Date.now()-t}}finally{clearTimeout(x),clearTimeout(b),e.signal?.removeEventListener("abort",y),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},hs=new Rt;import{execFile as Bo}from"child_process";import{StringDecoder as Oe}from"string_decoder";import{mkdtempSync as $s,readFileSync as Ms,rmSync as Rs}from"fs";import{join as st}from"path";import{tmpdir as Ps}from"os";function et(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function tt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var ms=null;function nt(){return ms}function ic(s){ms=s}function Ee(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var xe=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},fs=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let n=Ee(e),r=this.handles.get(n);if(r&&r.state()!=="dead")return r.claim?.(),r;if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new xe(`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 xe(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=Ee(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Ee(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Ee(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=Ee(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as $o}from"child_process";import{existsSync as Mo,readFileSync as Ro}from"fs";import{resolve as Po}from"path";function _o(s){let e=Po(s,"CLAUDE.md");if(!Mo(e))return null;try{let t=Ro(e,"utf8");return Ln(t)}catch{return null}}var Eo=20*60*1e3,Do=5e3,De=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}};function Oo(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var ys=class{constructor(e={}){this.opts=e}spawn(e,t){return new Pt(e,t,this.opts)}},Pt=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=$o(r,o,{cwd:t.workspace,env:_e(Oo({...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:_o(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
3
|
`);let a=e.deadlineMs??Eo,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new De(a));try{for(;;){let l=c-Date.now();if(l<=0)throw d();let u=await this.nextEvent(l);if(u===null&&!this.exited)throw d();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Do);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};Tt();import{resolve as bs,join as ws}from"path";xt();var No=4e3;function xs(s){try{let e=ws(bs(s.root),".agentx","db.sqlite"),t=It({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=be(),r=s.input.command?s.input.command.slice(0,No):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -27,7 +27,7 @@ ${s}`}function Wo(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
|
|
|
27
27
|
`,u)}};A.stdout?.on("data",g=>{M+=F.write(g);let T=M.split(`
|
|
28
28
|
`);M=T.pop()||"";for(let E of T)H(E)}),A.stderr?.on("data",g=>{O+=D.write(g)});let C=await A;if(i&&i.removeEventListener("abort",N),M+=F.end(),M.trim()&&H(M),O+=D.end(),v)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:y};if(C.exitCode!==0||b){let g=C,T;return g.timedOut?T=`OpenCode timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:b?T=b:g.code==="ENOENT"||/ENOENT|spawn opencode/i.test((g.shortMessage||"")+" "+O)?T=vs():T=O.trim()||`OpenCode exited with code ${g.exitCode??"unknown"}`,{content:"",...K(T),duration:Date.now()-c,usage:p,opencodeSessionId:y}}return w=!1,{content:u.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||s.model,opencodeSessionId:y}}catch(k){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(k?.message||"")?vs():k?.message;return{content:u,...K(_||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:y}}finally{I?.(),x?.release(w)}}async function ei(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=de(s,e,n),c="",d=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of d)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...K(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function ti(s,e,t,n,r,o,i,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,y=()=>{let w=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(w))}catch{}};a&&(a.aborted?y():a.addEventListener("abort",y,{once:!0}));let b=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);b.unref?.();let x=()=>({content:"",...K(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let w=s.provider||"claude-code",I=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,k=e.context?.sender,_=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),A=e.context?.channel==="web-chat"&&_?{userId:k,agentId:e.agentId||"acme-public"}:void 0,v=Nn(s),R=Object.keys(v).length>0,N={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:R?v:void 0};if(r){let{generateStream:H}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,k=e.context?.sender,_=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),A=e.context?.channel==="web-chat"&&_?{userId:k,agentId:e.agentId||"acme-public"}:void 0,v=Nn(s),R=Object.keys(v).length>0,N={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:R?v:void 0};if(r){let{generateStream:H}=await import("./agent-K7EPLYCP.js"),C="",g,T,E,L;for await(let m of H(N)){if(c)try{c(m)}catch{}if(m.type==="text_delta")C+=m.text,r(m.text,C);else if(m.type==="thinking_delta")m.text&&i&&i(m.text);else if(m.type==="generate_result"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}g=m.result.tokensUsed,m.result.inputTokens!=null&&(T=m.result.inputTokens),m.result.outputTokens!=null&&(E=m.result.outputTokens)}else if(m.type==="done"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}m.result.tokensUsed!=null&&(g=m.result.tokensUsed)}else m.type==="error"&&(L=m.error)}return L&&!C?p?x():L==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${L}`),duration:Date.now()-d}:((T===void 0||E===void 0)&&g&&(T=Math.round(g*.7),E=g-T),{content:C||"Done.",tokensUsed:g,usage:T!==void 0||E!==void 0?{inputTokens:T||0,outputTokens:E||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:M}=await import("./agent-K7EPLYCP.js"),O=await M(N),F=O.inputTokens,D=O.outputTokens;if((F===void 0||D===void 0)&&O.tokensUsed){let H=O.tokensUsed;F=Math.round(H*.7),D=H-F}return{content:O.content||"Done.",tokensUsed:O.tokensUsed,usage:F!==void 0||D!==void 0?{inputTokens:F||0,outputTokens:D||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(w){return p?x():w?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${w.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",y)}}async function ni(s,e,t,n,r,o,i){let a=nt();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:d,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,y=!1;try{let C=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:d,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),y=a.list().length>C}catch(C){return C instanceof xe,null}y&&Lt(e.agentId,s,e.model,n,"persistent");let b=de(s,e,t),x="",w,I,k,_,A,v,R,N="",M="",O=C=>{if(!i||!C)return;let g;if(M&&C.startsWith(M)?g=C.slice(M.length):g=N&&!N.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
33
|
${C}`:C,M=C,!!g){N+=g;try{i(g,N)}catch{}}},F=!1,D=()=>{F=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?D():o.addEventListener("abort",D,{once:!0}));let H=!1;try{let C=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let g of p.runTurn({message:b,taskId:e.taskId??"unknown",deadlineMs:C})){if(H=!0,r)try{r(g.raw)}catch{}if(g.type==="assistant"){let T=g.raw.message?.content??[];for(let L of T)L.type==="text"&&typeof L.text=="string"?(x=L.text,O(L.text)):L.type==="tool_use"&&(M="");let E=g.raw.message?.usage;if(E){let L=(E.input_tokens||0)+(E.cache_read_input_tokens||0)+(E.cache_creation_input_tokens||0);L>0&&(_=L)}}if(g.type==="result"){let T=g.raw;if(T.is_error){let E=K(typeof T.result=="string"?T.result:"claude error");w=E.error,I=E.errorKind}else typeof T.result=="string"&&T.result.length>0&&(x=T.result,N||O(T.result));typeof T.session_id=="string"&&(R=T.session_id),T.usage&&(k={inputTokens:T.usage.input_tokens||0,outputTokens:T.usage.output_tokens||0,cacheReadTokens:T.usage.cache_read_input_tokens||0,cacheCreateTokens:T.usage.cache_creation_input_tokens||0}),typeof T.num_turns=="number"&&(A=T.num_turns),typeof T.message?.model=="string"?v=T.message.model:typeof T.model=="string"&&(v=T.model)}}}catch(C){if(F)w="task cancelled by operator",I="cancelled";else if(H)if(C instanceof De){let g=K(`Claude Code timed out after ${Math.round(C.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);w=g.error,I=g.errorKind}else{let g=K(`persistent claude process error: ${C?.message||String(C)}`);w=g.error,I=g.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${C?.message||C}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",D),null}finally{o&&o.removeEventListener("abort",D)}return F&&!w&&(w="task cancelled by operator",I="cancelled"),{content:F?"":x,error:w,errorKind:I,duration:Date.now()-c,usage:k,contextTokens:_,numTurns:A,billedModel:v,claudeSessionId:R}}function js(s){return oe(s.autonomy)?s.taskId?ks(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function si(s,e,t,n,r,o,i){let a=e.autonomy,c=Is(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let d=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:d,message:`${An(a)}
|
|
@@ -127,7 +127,7 @@ Agent: ${t.slice(0,1e3)}`}],{model:$i,maxTokens:512})).content.trim().match(/\[[
|
|
|
127
127
|
\u2192 ${i}(${a})
|
|
128
128
|
`}return r}if(n==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Be(i,800)}
|
|
129
129
|
`}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
130
|
-
`:""}}var Jr=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Gn;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new qn;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new at(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Bn(void 0,void 0,"unified"),this.memoryStore=new Kn,this.patternStore=new ut,this.rateLimiter=new ct,this.tokenTracker=new Ce,this.messageQueue=new dt,hr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new jn({baseDir:B(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Un({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();n.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,o){let i=null,a=null,c=[];try{let p=this.sessions.getSession(e.agentId,n,r);i=Ks(p.messages,e.message??""),c=Gs(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await we(ds,ls(d),us,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!gs(l.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,r),ee().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-5MTSJ4FH.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let{storeRotationMemo:d}=await import("./rotation-memo-store-
|
|
130
|
+
`:""}}var Jr=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Gn;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new qn;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new at(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Bn(void 0,void 0,"unified"),this.memoryStore=new Kn,this.patternStore=new ut,this.rateLimiter=new ct,this.tokenTracker=new Ce,this.messageQueue=new dt,hr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new jn({baseDir:B(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Un({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();n.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,o){let i=null,a=null,c=[];try{let p=this.sessions.getSession(e.agentId,n,r);i=Ks(p.messages,e.message??""),c=Gs(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await we(ds,ls(d),us,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!gs(l.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,r),ee().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-5MTSJ4FH.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let{storeRotationMemo:d}=await import("./rotation-memo-store-A4YW6FSK.js"),l=d(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:c.memo});l.error&&this.log(`[${e}] memo claims not proposed: ${l.error}`),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars, ${l.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let n=[];for(let[r,o]of this.agents)r!==e&&n.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
|
|
131
131
|
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(a){i={content:"",error:a?.message??String(a)}}if(e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let a=i.error?Ze(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";zn().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,r){let o=oe(e.autonomy),i=o?null:lr().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(i){let h=await i;if(h.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${h.sessionId}`),{content:h.text,viaAttachedSession:h.sessionId};this.log(`[${e.agentId}] attached session did not take it (${h.reason}) \u2014 spawning`)}let a=this.agents.get(e.agentId);if(!a){if(o)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(this.meshFallback){let h=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(S=>S.id===e.agentId));if(h){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${h.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(h.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:h.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${h.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",l;if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||c==="app"||c==="a2a"||c==="mcp"||c==="reminder"||c==="events"||o){let h=Date.now(),f=25*6e4,S=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(P=>setTimeout(P,S))}}else if(c==="voice"){let h=Date.now(),f=25*6e4,S=`${e.agentId}\0${d}`;for(;this.messageQueue.isBusy(e.agentId,c,d)||this.voiceClaims.has(S);){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(P=>setTimeout(P,500))}l=S,this.voiceClaims.add(S)}else{let h=a.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,c,d,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:d,originalContext:e.context,queuedAt:e.queuedAt});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let S=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${S}) behind=${a.runningTasks.map(P=>P.id).join(",")||"-"} chat=${c}:${d} at=${new Date().toISOString()}`),{content:"",error:Jn(f,S)}}}let u=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(h,f)=>{this.log(`[${e.agentId}] ${h} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(l&&this.voiceClaims.delete(l),!u.ok)return this.log(`[${e.agentId}] ${u.reason}`),{content:"",error:u.reason};if(e.queuedAt!==void 0){let h=nr(e.queuedAt);h&&(e.message=`${h}
|
|
132
132
|
${e.message}`),e.queuedAt=void 0}a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let p={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};if(a.runningTasks.push(p),e.runningTaskId=p.id,this.runningContexts.set(p.id,e.context??{}),e.onStart)try{e.onStart(p.id)}catch{}let y=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:y});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,b);let x=h=>{if(h){b.buffer+=h,b.buffer.length>Wr&&(b.buffer=b.buffer.slice(b.buffer.length-Wr));for(let f of b.subscribers)try{f(h)}catch{}}},w=be();e.taskId=w;let I=new Map,k;if(t){let h=Ga();k=f=>{let S=h(f);if(S&&x(S),Gr(w,e.agentId,f),Kr(I,f),r)try{r(f)}catch{}}}else k=h=>{if(Gr(w,e.agentId,h),Kr(I,h),r)try{r(h)}catch{}};let _=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,A=_?setTimeout(()=>y.abort(new Error(`timed out after ${Math.round(_/1e3)}s`)),_):void 0;A?.unref?.();let v=(a.def.preSpawnTimeoutSec??Ha)*1e3,R=setTimeout(()=>{y.abort(new Error(`timed out before spawn after ${Math.round(v/1e3)}s in step "${p.step??"start"}"`))},v);R.unref?.();let N=()=>{R&&clearTimeout(R),R=void 0},M=()=>`task=${p.id} chat=${c}:${d} at=${new Date().toISOString()}`,O;y.signal.addEventListener("abort",()=>{let h=ht(y.signal).message;/^timed out/.test(h)&&(O=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${h} ${M()}`)},{once:!0});let F=h=>{p.step=h,this.log(`[${e.agentId}] step ${h} ${M()}`)},D=(h,f,S=0)=>y.signal.aborted?Promise.reject(ht(y.signal)):(F(h),(h==="agent"||h==="workflow-auto-run")&&N(),Ur(f(),y.signal,S)),H=!1,C=h=>{if(H)return;H=!0,this.runReleases.delete(p.id),A&&clearTimeout(A),N(),a.activeTasks--;let f=a.runningTasks.findIndex(S=>S.id===p.id);f!==-1&&a.runningTasks.splice(f,1),this.runningContexts.delete(p.id),this.taskAborts.delete(p.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
|
|
133
133
|
[task finished]
|
|
@@ -149,4 +149,4 @@ ${$}`),f+=$.length}catch{}}}let lo=ft.length>0?ft.join(`
|
|
|
149
149
|
|
|
150
150
|
Agent: ${$.content}`,meta:Ua(Y,e.context)})}catch{}Hn(e.agentId,e.message,$.content,{channel:g,chatId:m,sender:X},this.memoryStore).catch(()=>{}),ir(e.agentId,e.message,$.content,{channel:g,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let G=$.billedModel||e.model||a.def.model,re=e.context?.channel,Xe=re&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${re}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,G,re,Xe),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${M()}`)}return $}catch(h){a.errors++,this.log(`[${e.agentId}] unexpected error: ${h.message}`);let f=et(h.message);return le={content:"",error:tt(f),errorKind:f.kind},le}finally{kn.stop(),C(le)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=B(process.cwd(),Ae,this.safe(e.agentId),t);V(n)||Da(n,{recursive:!0});let r=B(n,`${this.safe(e.id)}.json`);Na(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=B(process.cwd(),Ae,this.safe(e));if(!V(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[d,c]){let p=B(a,u);if(V(p))try{for(let y of ne(p)){if(!y.endsWith(".json"))continue;let b=y.split("-")[0],x=parseInt(b,10);if(!Number.isFinite(x)||x<i||x>n)continue;let w=Math.floor((n-x)/36e5),I=t-1-w;I>=0&&I<t&&o[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=B(process.cwd(),Ae);if(!V(e))return 0;let t=0;for(let n of ne(e)){let r=B(e,n),o;try{o=ne(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=B(r,i),c;try{c=ne(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(Ue(B(a,d),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let p=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:p,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=ja){let t=B(process.cwd(),Ae);if(!V(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ne(t)){let i=B(t,o),a;try{a=ne(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Oa(B(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return[];let r=ne(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=B(n,i),c;try{c=ne(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let l=JSON.parse(Ue(B(a,d),"utf-8")),{transcript:u,responseText:p,...y}=l;o.push(y)}catch{}}}return o}getTaskRecord(e,t){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return null;let r=this.safe(t),o=ne(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=B(n,i,`${r}.json`);if(V(a))try{return JSON.parse(Ue(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=rs();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||Ze(n.error))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}findRunningTurn(e,t={}){let n=this.agents.get(e);if(!n)return null;let r;if(t.taskId)r=n.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=n.runningTasks.filter(a=>a.channel===t.channel&&a.chatId===t.chatId);r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(n=>n.id)}:null}isChatBusy(e,t,n){return this.messageQueue.isBusy(e,t,n)}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,l=o.controller.signal.aborted,u=!1;l&&d&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let p=this.messageQueue.pendingCount(i,a,c),y=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:y,edited:u,pending:p}}async continueFinishedTask(e,t,n,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let l=!1,u=p=>{l||(l=!0,d(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>u({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{Ze(p.error)?u({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>u({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Ja(s,e){return s===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
151
151
|
`)}export{ps as a,hs as b,ic as c,fs as d,_o as e,ys as f,xs as g,bc as h,kc as i,Ic as j,Qo as k,Fs as l,Zo as m,ei as n,ti as o,Us as p,at as q,ct as r,Vc as s,Wt as t,ee as u,ar as v,Ei as w,Li as x,ur as y,md as z,lr as A,je as B,Ta as C,ka as D,Ia as E,Sa as F,va as G,zt as H,Qu as I,zu as J,Ua as K,Ba as L,Wa as M,tn as N,qr as O,Kr as P,Ka as Q,Gr as R,Jr as S,Ja as T};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-3XEN24B7.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{createHash as f}from"crypto";import{existsSync as g,mkdirSync as c,readFileSync as p,writeFileSync as h}from"fs";import{dirname as m,resolve as v}from"path";function d(o){let e=process.env.AGENTX_AGENT_ID?.trim();if(e)throw new Error(`only a person can ${o}; this is running as agent "${e}". Ask the owner instead.`)}function w(o,e,i,s){return f("sha1").update([o,e,i.toLowerCase().trim(),s??""].join("\0")).digest("hex").slice(0,12)}var l=class{file;constructor(e){this.file=v(e,"_questions.json")}get path(){return this.file}load(){if(!g(this.file))return{version:1,questions:[]};try{let e=JSON.parse(p(this.file,"utf-8"));return Array.isArray(e?.questions)?{version:1,questions:e.questions}:{version:1,questions:[],unreadable:"no questions list"}}catch(e){return{version:1,questions:[],unreadable:String(e?.message??e)}}}refuse(e){return e.unreadable?(console.error(`[wiki-questions] ${this.file} is unreadable (${e.unreadable}); not writing to it. Repair or move it aside.`),!0):!1}save(e){if(e.unreadable)throw new Error(`${this.file} is unreadable; not writing to it`);c(m(this.file),{recursive:!0}),h(this.file,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`)}list(e){let i=this.load().questions;return e?i.filter(s=>s.status===e):i}add(e){let i=this.load();if(this.refuse(i))return{added:0,skipped:e.length};let s=new Set(i.questions.map(n=>n.id)),r=0,t=0,a=new Date().toISOString();for(let n of e){let u=w(n.kind,n.agentId,n.subject,n.field);if(s.has(u)){t++;continue}s.add(u),i.questions.push({...n,id:u,status:"open",asked:a}),r++}return r>0&&this.save(i),{added:r,skipped:t}}resolve(e,i,s){let r=this.load(),t=r.questions.find(a=>a.id===e||a.id.startsWith(e));return t?(t.kind==="contradiction"&&d(`${i==="dismissed"?"dismiss":"answer"} a fact disagreement`),t.status=i,t.answered=new Date().toISOString(),s!==void 0&&(t.answer=s),this.save(r),t):null}};export{d as a,w as b,l as c};
|
|
3
|
+
//# sourceMappingURL=chunk-ILEC3IAV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/questions.ts","../src/wiki/facts/person.ts"],"sourcesContent":["import { createHash } from \"crypto\"\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport { assertPerson } from \"./facts/person\"\n\n// The gaps a lookup cannot close.\n//\n// Two things were producing gap signal and throwing it away. Absorb has\n// always emitted a `gaps` array — entities it referenced but has no\n// article for — and the command printed it and moved on, so the signal\n// lived in a cron log nobody reads. And the field grader can now name a\n// missing `role` or `ourOwner` that no system of record holds.\n//\n// Both are the same thing: a question only a person can answer. They\n// get one queue rather than two, because a second parallel store is\n// precisely what the wiki-as-source-of-truth decision rules out.\n//\n// Stored as JSON beside the other wiki sidecars (_index.json,\n// _backlinks.json), because this is derived state that is rebuilt and\n// rewritten, not knowledge. The knowledge is what lands in the article\n// once the question is answered.\n\nexport type QuestionStatus = \"open\" | \"answered\" | \"dismissed\"\n\nexport interface WikiQuestion {\n id: string\n /** \"field\" — a named gap in an existing article.\n * \"article\" — absorb referenced something with no article at all.\n * \"contradiction\" — a write disagreed with a wiki fact and could not\n * replace it (facts/ledger.ts); the answer is the true value. */\n kind: \"field\" | \"article\" | \"contradiction\"\n agentId: string\n /** Article path for a field question; empty for a missing article. */\n path: string\n /** Article title, or the referenced name for a missing article. */\n subject: string\n /** Required-field key, for `kind: \"field\"`. */\n field?: string\n /** What tier of the build this gap sits at, so asking can be ordered. */\n tier?: string\n question: string\n /** For a contradiction: the wiki fact and the value that was refused. */\n factId?: string\n proposed?: { value: string; source: string; verifiedAt: string; verifiedBy: string }\n status: QuestionStatus\n asked: string\n answered?: string\n answer?: string\n}\n\nexport interface QuestionsFile {\n version: 1\n questions: WikiQuestion[]\n /** The file exists but could not be read. It is then never written. */\n unreadable?: string\n}\n\n/**\n * Stable across runs, so re-grading the same article does not ask the\n * same question twice and cannot resurrect one already dismissed.\n */\nexport function questionId(kind: string, agentId: string, subject: string, field?: string): string {\n return createHash(\"sha1\")\n .update([kind, agentId, subject.toLowerCase().trim(), field ?? \"\"].join(\"\\u0000\"))\n .digest(\"hex\")\n .slice(0, 12)\n}\n\nexport class QuestionStore {\n private readonly file: string\n\n constructor(wikiDir: string) {\n this.file = resolve(wikiDir, \"_questions.json\")\n }\n\n get path(): string { return this.file }\n\n load(): QuestionsFile {\n if (!existsSync(this.file)) return { version: 1, questions: [] }\n try {\n const parsed = JSON.parse(readFileSync(this.file, \"utf-8\")) as Partial<QuestionsFile>\n if (!Array.isArray(parsed?.questions)) return { version: 1, questions: [], unreadable: \"no questions list\" }\n return { version: 1, questions: parsed.questions as WikiQuestion[] }\n } catch (e) {\n // A corrupt queue must not stop an absorb, and must not be\n // replaced by an empty one on the next save either: reads see no\n // questions, writes are refused until a person repairs the file.\n return { version: 1, questions: [], unreadable: String((e as Error)?.message ?? e) }\n }\n }\n\n private refuse(f: QuestionsFile): boolean {\n if (!f.unreadable) return false\n console.error(`[wiki-questions] ${this.file} is unreadable (${f.unreadable}); not writing to it. Repair or move it aside.`)\n return true\n }\n\n private save(f: QuestionsFile): void {\n if (f.unreadable) throw new Error(`${this.file} is unreadable; not writing to it`)\n mkdirSync(dirname(this.file), { recursive: true })\n writeFileSync(this.file, `${JSON.stringify(f, null, 2)}\\n`)\n }\n\n list(status?: QuestionStatus): WikiQuestion[] {\n const all = this.load().questions\n return status ? all.filter((q) => q.status === status) : all\n }\n\n /**\n * Add questions that are not already on the queue.\n *\n * An existing id is left completely alone — including an answered or\n * dismissed one. Re-asking something a person has already dealt with\n * is how a queue becomes noise and then becomes ignored.\n */\n add(items: Array<Omit<WikiQuestion, \"id\" | \"status\" | \"asked\">>): { added: number; skipped: number } {\n const f = this.load()\n if (this.refuse(f)) return { added: 0, skipped: items.length }\n const seen = new Set(f.questions.map((q) => q.id))\n let added = 0, skipped = 0\n const now = new Date().toISOString()\n\n for (const item of items) {\n const id = questionId(item.kind, item.agentId, item.subject, item.field)\n if (seen.has(id)) { skipped++; continue }\n seen.add(id)\n f.questions.push({ ...item, id, status: \"open\", asked: now })\n added++\n }\n if (added > 0) this.save(f)\n return { added, skipped }\n }\n\n /** Returns the question so the caller can act on its subject/field. */\n resolve(id: string, status: \"answered\" | \"dismissed\", answer?: string): WikiQuestion | null {\n const f = this.load()\n const q = f.questions.find((x) => x.id === id || x.id.startsWith(id))\n if (!q) return null\n // A fact disagreement is the owner's signal that an agent's check\n // differs from a confirmed value: an agent may not close it, answered\n // or dismissed.\n if (q.kind === \"contradiction\") assertPerson(`${status === \"dismissed\" ? \"dismiss\" : \"answer\"} a fact disagreement`)\n q.status = status\n q.answered = new Date().toISOString()\n if (answer !== undefined) q.answer = answer\n this.save(f)\n return q\n }\n}\n","/** Refuse when running as an agent: the runtime sets AGENTX_AGENT_ID for\n * every agent process, so confirming a fact, approving a proposal or\n * settling a fact disagreement stays with a person. */\nexport function assertPerson(action: string): void {\n const agent = process.env.AGENTX_AGENT_ID?.trim()\n if (agent) throw new Error(`only a person can ${action}; this is running as agent \"${agent}\". Ask the owner instead.`)\n}\n"],"mappings":"AAAA,OAAS,cAAAA,MAAkB,SAC3B,OAAS,cAAAC,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,KACnE,OAAS,WAAAC,EAAS,WAAAC,MAAe,OCC1B,SAASC,EAAaC,EAAsB,CACjD,IAAMC,EAAQ,QAAQ,IAAI,iBAAiB,KAAK,EAChD,GAAIA,EAAO,MAAM,IAAI,MAAM,qBAAqBD,gCAAqCC,4BAAgC,CACvH,CDuDO,SAASC,EAAWC,EAAcC,EAAiBC,EAAiBC,EAAwB,CACjG,OAAOC,EAAW,MAAM,EACrB,OAAO,CAACJ,EAAMC,EAASC,EAAQ,YAAY,EAAE,KAAK,EAAGC,GAAS,EAAE,EAAE,KAAK,IAAQ,CAAC,EAChF,OAAO,KAAK,EACZ,MAAM,EAAG,EAAE,CAChB,CAEO,IAAME,EAAN,KAAoB,CACR,KAEjB,YAAYC,EAAiB,CAC3B,KAAK,KAAOC,EAAQD,EAAS,iBAAiB,CAChD,CAEA,IAAI,MAAe,CAAE,OAAO,KAAK,IAAK,CAEtC,MAAsB,CACpB,GAAI,CAACE,EAAW,KAAK,IAAI,EAAG,MAAO,CAAE,QAAS,EAAG,UAAW,CAAC,CAAE,EAC/D,GAAI,CACF,IAAMC,EAAS,KAAK,MAAMC,EAAa,KAAK,KAAM,O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AK,CAAE,GAAGY,EAAM,GAAAC,EAAI,OAAQ,OAAQ,MAAOF,CAAI,CAAC,EAC5DF,IAEF,OAAIA,EAAQ,GAAG,KAAK,KAAKT,CAAC,EACnB,CAAE,MAAAS,EAAO,QAAAC,CAAQ,CAC1B,CAGA,QAAQG,EAAYT,EAAkCU,EAAsC,CAC1F,IAAMd,EAAI,KAAK,KAAK,EACdM,EAAIN,EAAE,UAAU,KAAMe,GAAMA,EAAE,KAAOF,GAAME,EAAE,GAAG,WAAWF,CAAE,CAAC,EACpE,OAAKP,GAIDA,EAAE,OAAS,iBAAiBU,EAAa,GAAGZ,IAAW,YAAc,UAAY,8BAA8B,EACnHE,EAAE,OAASF,EACXE,EAAE,SAAW,IAAI,KAAK,EAAE,YAAY,EAChCQ,IAAW,SAAWR,EAAE,OAASQ,GACrC,KAAK,KAAKd,CAAC,EACJM,GATQ,IAUjB,CACF","names":["createHash","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","resolve","assertPerson","action","agent","questionId","kind","agentId","subject","field","createHash","QuestionStore","wikiDir","resolve","existsSync","parsed","readFileSync","f","mkdirSync","dirname","writeFileSync","status","all","q","items","seen","added","skipped","now","item","id","answer","x","assertPerson"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{b as F,c as S,d as $,f as x}from"./chunk-GQ76J72O.js";import{a as B,b as j,c as v}from"./chunk-ILEC3IAV.js";import{createHash as X}from"crypto";import{existsSync as z,statSync as G}from"fs";import{resolve as K}from"path";import{closeSync as D,existsSync as q,mkdirSync as C,openSync as M,readFileSync as N,renameSync as _,statSync as J,unlinkSync as g,writeFileSync as H}from"fs";import{dirname as E}from"path";var l=class extends Error{constructor(e,i){super(`fact ledger ${e} is unreadable (${i}). Nothing was written to it. Repair the JSON, or move the file aside to start an empty ledger.`);this.file=e;this.name="LedgerCorruptError"}},I=["id","subject","attribute","value","source","verifiedAt","verifiedBy","volatility"],W=["id","status","claim","source","verifiedAt","agentId"],L=(r,t)=>!!r&&typeof r=="object"&&!Array.isArray(r)&&t.every(e=>typeof r[e]=="string");function O(r){if(!q(r))return null;let t;try{t=JSON.parse(N(r,"utf-8"))}catch(s){throw new l(r,String(s?.message??s))}if(!t||typeof t!="object"||!Array.isArray(t.facts)||t.proposals!==void 0&&!Array.isArray(t.proposals))throw new l(r,"not a ledger: expected { facts: [], proposals: [] }");let e=t.facts.findIndex(s=>!L(s,I));if(e>=0)throw new l(r,`fact #${e+1} is missing ${I.join("/")}`);let i=(t.proposals??[]).findIndex(s=>!L(s,W));if(i>=0)throw new l(r,`proposal #${i+1} is missing ${W.join("/")}`);return{facts:t.facts,proposals:t.proposals??[]}}function P(r,t){C(E(r),{recursive:!0});let e=`${r}.${process.pid}.tmp`;H(e,JSON.stringify(t,null,2)+`
|
|
2
|
+
`),_(e,r)}var Q=r=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r),p=new Set,w=(r,t)=>{try{return Date.now()-J(r).mtimeMs>t}catch{return!1}};function U(r,t){let e=`${r}.takeover`;if(w(e,t))try{g(e)}catch{}let i;try{i=M(e,"wx")}catch{return}try{w(r,t)&&g(r)}catch{}finally{D(i);try{g(e)}catch{}}}function R(r,t,e={}){let i=`${r}.lock`;if(p.has(i))return t();let s=e.timeoutMs??3e3,o=e.staleMs??15e3;C(E(i),{recursive:!0});let a=Date.now()+s,c;for(;c===void 0;)try{c=M(i,"wx")}catch(u){if(u?.code!=="EEXIST")throw u;if(w(i,o)&&U(i,o),Date.now()>a)throw new Error(`fact ledger is busy (${i}). If no agentx command is running, delete that lock and try again.`);Q(25)}p.add(i);try{return t()}finally{p.delete(i),D(c);try{g(i)}catch{}}}var d=r=>r.toLowerCase().replace(/\s+/g," ").trim();function V(r,t){return"f-"+X("sha1").update(`${d(r)}\0${d(t)}`).digest("hex").slice(0,10)}var T=class{constructor(t){this.wikiDir=t;this.file=K(t,"_facts.json")}file;cache;reported;load(){if(!z(this.file))return{version:1,facts:[],proposals:[]};let t=G(this.file).mtimeMs;if(this.cache?.mtimeMs===t)return structuredClone(this.cache.data);let e;try{e=O(this.file)}catch(s){throw this.reported!==t&&(this.reported=t,console.error(`[wiki-facts] ${s.message}`)),s}let i={version:1,facts:e?.facts??[],proposals:e?.proposals??[]};return this.cache={mtimeMs:t,data:i},structuredClone(i)}update(t){return R(this.file,()=>{this.cache=void 0;let e=this.load(),{save:i,result:s}=t(e);return i&&(P(this.file,e),this.cache=void 0),s})}list(){return this.load().facts}get(t){return this.list().find(e=>e.id===t||t.length>=6&&e.id.startsWith(t))??null}write(t,e={}){e.confirmedBy&&B("confirm a fact");let i=e.now??Date.now(),s=new Date(i).toISOString();if(!t.source?.trim())throw new Error('a fact needs a source: a system, URL, command or "owner said"');if(!t.subject?.trim()||!t.attribute?.trim()||!t.value?.trim())throw new Error("a fact needs a subject, an attribute and a value");let o=t.verifiedAt==="now"?i:Date.parse(t.verifiedAt??""),a=Number.isFinite(o),c=a?new Date(Math.min(o,i)).toISOString():s,u=F(t.volatility)?t.volatility:$(t.attribute,`${t.subject} ${t.attribute} is ${t.value}`),h={source:t.source.trim(),verifiedAt:c,verifiedBy:t.verifiedBy||"unknown",volatility:u,...typeof t.ttlDays=="number"?{ttlDays:t.ttlDays}:{}},b=V(t.subject,t.attribute),m=this.update(f=>{let n=f.facts.find(y=>y.id===b);if(!n){let y={id:b,subject:t.subject.trim(),attribute:t.attribute.trim(),value:t.value.trim(),...h,createdAt:s,updatedAt:s,...!a&&!e.confirmedBy?{undated:!0}:{},...e.confirmedBy?{confirmedBy:e.confirmedBy}:{}};return f.facts.push(y),{save:!0,result:{status:"created",fact:y}}}let A=Date.parse(n.verifiedAt),k=a&&(n.undated||!Number.isFinite(A)||Date.parse(c)>A);return d(n.value)===d(t.value)?!k&&!e.confirmedBy?{save:!1,result:{status:"unchanged",fact:n}}:(Object.assign(n,h,{updatedAt:s},e.confirmedBy?{confirmedBy:e.confirmedBy}:{}),delete n.undated,{save:!0,result:{status:"verified",fact:n}}):!e.confirmedBy&&(!k||n.confirmedBy)?{save:!1,result:{contradiction:n}}:(n.history=[...n.history??[],{value:n.value,source:n.source,verifiedAt:n.verifiedAt,verifiedBy:n.verifiedBy,replacedAt:s}].slice(-10),n.value=t.value.trim(),Object.assign(n,h,{updatedAt:s}),delete n.undated,e.confirmedBy?n.confirmedBy=e.confirmedBy:delete n.confirmedBy,{save:!0,result:{status:"updated",fact:n}})});if("contradiction"in m){let f=Y(this.wikiDir,m.contradiction,{...t,verifiedAt:a?c:"undated"});return{status:"contradiction",fact:m.contradiction,questionId:f.id,questionClosed:f.closed}}return m}};function Y(r,t,e){let i=new v(r),s={kind:"contradiction",agentId:e.verifiedBy||"unknown",path:"_facts.json",subject:t.subject,field:`${t.attribute}=${d(e.value)}`,tier:"pillar",factId:t.id,proposed:{value:e.value.trim(),source:e.source.trim(),verifiedAt:e.verifiedAt,verifiedBy:e.verifiedBy},question:`${t.subject} \xB7 ${t.attribute}: the wiki says "${t.value}" (${t.source}, checked ${t.verifiedAt.slice(0,10)}), but ${e.verifiedBy} reports "${e.value.trim()}" (${e.source.trim()}, checked ${e.verifiedAt.slice(0,10)}). Which is true?`},o=j(s.kind,s.agentId,s.subject,s.field);i.add([s]);let a=i.list().find(c=>c.id===o);return a?a.status==="answered"||a.status==="dismissed"?{closed:a.status}:{id:o}:{}}function dt(r){return new v(r).list("open").filter(t=>t.kind==="contradiction").map(t=>({type:"contradiction",articles:[`_facts.json#${t.factId??"?"}`],message:`[${t.id}] ${t.question}`,confidence:"high"}))}function ut(r,t=Date.now()){return r.undated===!0||x(r,t)}function lt(r,t){let e=d(r),i=null;for(let s of t){let o=d(s.subject);if(o.length<3||!e.includes(o))continue;let a=d(s.attribute).split(" ").filter(u=>u.length>2);(e.includes(d(s.value))||s.volatility!=="stable"&&S(r)===s.volatility||a.length>0&&a.every(u=>e.includes(u)))&&(!i||s.subject.length>i.subject.length)&&(i=s)}return i}export{R as a,V as b,T as c,dt as d,ut as e,lt as f};
|
|
3
|
+
//# sourceMappingURL=chunk-KA2UIZXG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/facts/ledger.ts","../src/wiki/facts/ledger-file.ts"],"sourcesContent":["import { createHash } from \"crypto\"\nimport { existsSync, statSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { readLedger, withLock, writeLedger } from \"./ledger-file\"\nimport { classifyAttribute, classifyFact, isFactClass, isPastTtl, type FactClass, type Provenance } from \"@/agents/fact-freshness\"\nimport type { ContradictionIssue } from \"../lint-contradictions\"\nimport { QuestionStore, questionId } from \"../questions\"\n\n// --- The wiki fact ledger: durable facts with provenance (#273) ---\n//\n// Articles are prose. A fact an agent states to a person (\"the vendor\n// account is past due\") needs more than prose: where it came from, when\n// it was last checked, by whom, and how long it stays true. This is that\n// record — one small JSON sidecar beside `_questions.json`, skipped by the\n// article index like every `_` file.\n//\n// Every other store references it: memory lines that restate a ledger\n// fact are replaced by a reference at injection (agents/memory-context),\n// and memo claims wait here as proposals (fact-proposals.ts) instead of\n// becoming memory.\n//\n// Overwrite safety: a write that disagrees with the current value needs a\n// check newer than the current one, or a person's confirmation. Otherwise\n// the old value stays and a contradiction question joins the wiki's\n// question queue (`agentx wiki questions`), where the answer is written\n// back through here.\n\nexport interface WikiFact extends Provenance {\n id: string\n subject: string\n attribute: string\n value: string\n createdAt: string\n updatedAt: string\n /** Set when a person confirmed the value over a newer-dated one. */\n confirmedBy?: string\n /** Recorded with no check time: never counts as checked, so it is\n * always shown UNVERIFIED until a dated check or a person confirms it. */\n undated?: true\n /** Earlier values, newest last. Nothing is replaced silently. */\n history?: Array<{ value: string; source: string; verifiedAt: string; verifiedBy: string; replacedAt: string }>\n}\n\nexport interface FactInput {\n subject: string\n attribute: string\n value: string\n source: string\n verifiedBy: string\n /** When the source was checked (ISO date, or \"now\"). Without it the\n * write is undated and never counts as newer than an existing fact. */\n verifiedAt?: string\n volatility?: FactClass\n ttlDays?: number\n}\n\nexport type WriteStatus = \"created\" | \"verified\" | \"unchanged\" | \"updated\" | \"contradiction\"\n\nexport interface WriteResult {\n status: WriteStatus\n fact: WikiFact\n /** The queued question, for a contradiction. */\n questionId?: string\n /** Set instead of questionId when a person already answered or\n * dismissed this same claim, so it is not asked again. */\n questionClosed?: \"answered\" | \"dismissed\"\n}\n\nexport interface LedgerFile {\n version: 1\n facts: WikiFact[]\n proposals: import(\"./fact-proposals\").FactProposal[]\n}\n\nconst norm = (s: string) => s.toLowerCase().replace(/\\s+/g, \" \").trim()\n\n/**\n * Confirming a fact is a person's act. A process an agent runs carries\n * AGENTX_AGENT_ID (the runtime sets it for every agent), so a confirmation\n * from inside one is refused: an agent can't outrank a person, or itself.\n */\nimport { assertPerson } from \"./person\"\nexport { assertPerson }\n\n/** Stable per subject and attribute, so a re-check lands on the same fact. */\nexport function factId(subject: string, attribute: string): string {\n return \"f-\" + createHash(\"sha1\").update(`${norm(subject)}\\u0000${norm(attribute)}`).digest(\"hex\").slice(0, 10)\n}\n\nexport class FactLedger {\n readonly file: string\n private cache?: { mtimeMs: number; data: LedgerFile }\n private reported?: number\n\n constructor(readonly wikiDir: string) {\n this.file = resolve(wikiDir, \"_facts.json\")\n }\n\n /** The ledger as stored. Throws LedgerCorruptError on a file that does\n * not parse: it is never read as empty, so it is never overwritten. */\n load(): LedgerFile {\n if (!existsSync(this.file)) return { version: 1, facts: [], proposals: [] }\n const mtimeMs = statSync(this.file).mtimeMs\n if (this.cache?.mtimeMs === mtimeMs) return structuredClone(this.cache.data)\n let raw\n try {\n raw = readLedger(this.file)\n } catch (e) {\n // Once per version of the bad file, not once per prompt.\n if (this.reported !== mtimeMs) {\n this.reported = mtimeMs\n console.error(`[wiki-facts] ${(e as Error).message}`)\n }\n throw e\n }\n const data: LedgerFile = { version: 1, facts: (raw?.facts ?? []) as WikiFact[], proposals: (raw?.proposals ?? []) as LedgerFile[\"proposals\"] }\n this.cache = { mtimeMs, data }\n return structuredClone(data)\n }\n\n /**\n * Load, change and save under the ledger's lock, so concurrent writers\n * (a daemon proposing memo claims, a CLI `set`) can't drop each other's\n * change. `fn` returns whether to save, and a result.\n */\n update<T>(fn: (data: LedgerFile) => { save: boolean; result: T }): T {\n return withLock(this.file, () => {\n this.cache = undefined\n const data = this.load()\n const { save, result } = fn(data)\n if (save) {\n writeLedger(this.file, data)\n this.cache = undefined\n }\n return result\n })\n }\n\n list(): WikiFact[] { return this.load().facts }\n\n get(id: string): WikiFact | null {\n return this.list().find((f) => f.id === id || (id.length >= 6 && f.id.startsWith(id))) ?? null\n }\n\n /**\n * Record a checked fact. Refuses a fact with no source. A different value\n * replaces the current one only with a dated check newer than the current\n * one, or `confirmedBy`. A value a person confirmed is replaced only by\n * another confirmation. Otherwise the current value stays and a\n * contradiction question is raised.\n *\n * A write with no `verifiedAt` is undated: it can create a fact, but it\n * never counts as newer than a fact already there.\n */\n write(input: FactInput, opts: { confirmedBy?: string; now?: number } = {}): WriteResult {\n if (opts.confirmedBy) assertPerson(\"confirm a fact\")\n const now = opts.now ?? Date.now()\n const nowIso = new Date(now).toISOString()\n if (!input.source?.trim()) throw new Error(\"a fact needs a source: a system, URL, command or \\\"owner said\\\"\")\n if (!input.subject?.trim() || !input.attribute?.trim() || !input.value?.trim()) {\n throw new Error(\"a fact needs a subject, an attribute and a value\")\n }\n const checked = input.verifiedAt === \"now\" ? now : Date.parse(input.verifiedAt ?? \"\")\n const dated = Number.isFinite(checked)\n // A check can't be dated after it happened.\n const verifiedAt = dated ? new Date(Math.min(checked, now)).toISOString() : nowIso\n const volatility = isFactClass(input.volatility)\n ? input.volatility\n : classifyAttribute(input.attribute, `${input.subject} ${input.attribute} is ${input.value}`)\n const provenance: Provenance = {\n source: input.source.trim(), verifiedAt, verifiedBy: input.verifiedBy || \"unknown\", volatility,\n ...(typeof input.ttlDays === \"number\" ? { ttlDays: input.ttlDays } : {}),\n }\n const id = factId(input.subject, input.attribute)\n\n const out = this.update<WriteResult | { contradiction: WikiFact }>((data) => {\n const existing = data.facts.find((f) => f.id === id)\n if (!existing) {\n const fact: WikiFact = {\n id, subject: input.subject.trim(), attribute: input.attribute.trim(), value: input.value.trim(),\n ...provenance, createdAt: nowIso, updatedAt: nowIso,\n ...(!dated && !opts.confirmedBy ? { undated: true as const } : {}),\n ...(opts.confirmedBy ? { confirmedBy: opts.confirmedBy } : {}),\n }\n data.facts.push(fact)\n return { save: true, result: { status: \"created\", fact } }\n }\n\n const prior = Date.parse(existing.verifiedAt)\n // Any dated check beats a fact that was never dated.\n const newer = dated && (existing.undated || !Number.isFinite(prior) || Date.parse(verifiedAt) > prior)\n if (norm(existing.value) === norm(input.value)) {\n if (!newer && !opts.confirmedBy) return { save: false, result: { status: \"unchanged\", fact: existing } }\n Object.assign(existing, provenance, { updatedAt: nowIso }, opts.confirmedBy ? { confirmedBy: opts.confirmedBy } : {})\n delete existing.undated\n return { save: true, result: { status: \"verified\", fact: existing } }\n }\n\n // A person's confirmation outranks any agent's date.\n if (!opts.confirmedBy && (!newer || existing.confirmedBy)) {\n return { save: false, result: { contradiction: existing } }\n }\n\n existing.history = [...(existing.history ?? []), {\n value: existing.value, source: existing.source, verifiedAt: existing.verifiedAt,\n verifiedBy: existing.verifiedBy, replacedAt: nowIso,\n }].slice(-10)\n existing.value = input.value.trim()\n Object.assign(existing, provenance, { updatedAt: nowIso })\n delete existing.undated\n if (opts.confirmedBy) existing.confirmedBy = opts.confirmedBy\n else delete existing.confirmedBy\n return { save: true, result: { status: \"updated\", fact: existing } }\n })\n\n if (\"contradiction\" in out) {\n const q = raiseContradiction(this.wikiDir, out.contradiction, { ...input, verifiedAt: dated ? verifiedAt : \"undated\" })\n return { status: \"contradiction\", fact: out.contradiction, questionId: q.id, questionClosed: q.closed }\n }\n return out\n }\n}\n\nfunction raiseContradiction(wikiDir: string, current: WikiFact, input: FactInput & { verifiedAt: string }): { id?: string; closed?: \"answered\" | \"dismissed\" } {\n const store = new QuestionStore(wikiDir)\n const item = {\n kind: \"contradiction\" as const,\n agentId: input.verifiedBy || \"unknown\",\n path: \"_facts.json\",\n subject: current.subject,\n // One question per refused value: a second, different claim is a new\n // question, while repeating the same claim does not ask twice.\n field: `${current.attribute}=${norm(input.value)}`,\n tier: \"pillar\",\n factId: current.id,\n proposed: { value: input.value.trim(), source: input.source.trim(), verifiedAt: input.verifiedAt, verifiedBy: input.verifiedBy },\n question:\n `${current.subject} · ${current.attribute}: the wiki says \"${current.value}\" ` +\n `(${current.source}, checked ${current.verifiedAt.slice(0, 10)}), but ${input.verifiedBy} reports ` +\n `\"${input.value.trim()}\" (${input.source.trim()}, checked ${input.verifiedAt.slice(0, 10)}). Which is true?`,\n }\n const id = questionId(item.kind, item.agentId, item.subject, item.field)\n store.add([item])\n // Undefined when the queue could not take it (an unreadable file): the\n // old value still stands, and the caller says the question is missing.\n // Only an open question is one the owner will see. A person who already\n // answered or dismissed this same claim is not asked again; a question\n // that is missing altogether means the queue could not take it (an\n // unreadable file), and the old value still stands.\n const q = store.list().find((x) => x.id === id)\n if (!q) return {}\n if (q.status === \"answered\" || q.status === \"dismissed\") return { closed: q.status }\n return { id }\n}\n\n/** Open fact contradictions, in the shape `wiki lint` reports. */\nexport function factContradictions(wikiDir: string): ContradictionIssue[] {\n return new QuestionStore(wikiDir).list(\"open\")\n .filter((q) => q.kind === \"contradiction\")\n .map((q) => ({\n type: \"contradiction\" as const,\n articles: [`_facts.json#${q.factId ?? \"?\"}`],\n message: `[${q.id}] ${q.question}`,\n confidence: \"high\" as const,\n }))\n}\n\n/** A fact is stale when it is past its class TTL. */\nexport function isStaleFact(f: WikiFact, now = Date.now()): boolean {\n return f.undated === true || isPastTtl(f, now)\n}\n\n/**\n * The ledger fact a memory line restates, if any. The line must name the\n * fact's subject, and either repeat its value, share its volatility class,\n * or name its attribute.\n */\nexport function matchFact(content: string, facts: WikiFact[]): WikiFact | null {\n const text = norm(content)\n let best: WikiFact | null = null\n for (const f of facts) {\n const subject = norm(f.subject)\n if (subject.length < 3 || !text.includes(subject)) continue\n const attrWords = norm(f.attribute).split(\" \").filter((w) => w.length > 2)\n const hit = text.includes(norm(f.value))\n || (f.volatility !== \"stable\" && classifyFact(content) === f.volatility)\n || (attrWords.length > 0 && attrWords.every((w) => text.includes(w)))\n if (hit && (!best || f.subject.length > best.subject.length)) best = f\n }\n return best\n}\n","import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"fs\"\nimport { dirname } from \"path\"\n\n// --- The fact ledger's file: strict reads, locked writes (#273) ---\n//\n// Two rules keep the ledger from losing facts with nobody watching:\n// 1. A file that does not parse is never treated as empty. Reading it\n// throws LedgerCorruptError, so no write can replace it; the file is\n// left exactly as it is for a person to repair.\n// 2. load → modify → save runs under a lockfile, so a daemon proposing\n// memo claims and a CLI `set` or `approve` can't drop each other's\n// write.\n\nexport class LedgerCorruptError extends Error {\n constructor(readonly file: string, cause: string) {\n super(\n `fact ledger ${file} is unreadable (${cause}). Nothing was written to it. ` +\n `Repair the JSON, or move the file aside to start an empty ledger.`,\n )\n this.name = \"LedgerCorruptError\"\n }\n}\n\nexport interface RawLedger {\n facts: unknown[]\n proposals: unknown[]\n}\n\nconst FACT_FIELDS = [\"id\", \"subject\", \"attribute\", \"value\", \"source\", \"verifiedAt\", \"verifiedBy\", \"volatility\"]\nconst PROPOSAL_FIELDS = [\"id\", \"status\", \"claim\", \"source\", \"verifiedAt\", \"agentId\"]\n\nconst hasStrings = (o: unknown, keys: string[]) =>\n !!o && typeof o === \"object\" && !Array.isArray(o) && keys.every((k) => typeof (o as Record<string, unknown>)[k] === \"string\")\n\n/** Null when the file does not exist; throws when it exists but is not a ledger. */\nexport function readLedger(file: string): RawLedger | null {\n if (!existsSync(file)) return null\n let raw: any\n try {\n raw = JSON.parse(readFileSync(file, \"utf-8\"))\n } catch (e) {\n throw new LedgerCorruptError(file, String((e as Error)?.message ?? e))\n }\n if (!raw || typeof raw !== \"object\" || !Array.isArray(raw.facts) || (raw.proposals !== undefined && !Array.isArray(raw.proposals))) {\n throw new LedgerCorruptError(file, \"not a ledger: expected { facts: [], proposals: [] }\")\n }\n // Every entry is read by prompt rendering; one malformed entry must stop\n // the ledger being used, not crash a prompt or be dropped on the next save.\n const bad = raw.facts.findIndex((f: any) => !hasStrings(f, FACT_FIELDS))\n if (bad >= 0) throw new LedgerCorruptError(file, `fact #${bad + 1} is missing ${FACT_FIELDS.join(\"/\")}`)\n const badP = (raw.proposals ?? []).findIndex((p: any) => !hasStrings(p, PROPOSAL_FIELDS))\n if (badP >= 0) throw new LedgerCorruptError(file, `proposal #${badP + 1} is missing ${PROPOSAL_FIELDS.join(\"/\")}`)\n return { facts: raw.facts, proposals: raw.proposals ?? [] }\n}\n\nexport function writeLedger(file: string, data: unknown): void {\n mkdirSync(dirname(file), { recursive: true })\n const tmp = `${file}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(data, null, 2) + \"\\n\")\n renameSync(tmp, file)\n}\n\nconst sleep = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)\n\n/** Locks this process holds, so a caller already inside one (approve →\n * write) re-enters instead of waiting on itself. */\nconst held = new Set<string>()\n\nconst isStale = (path: string, staleMs: number) => {\n try { return Date.now() - statSync(path).mtimeMs > staleMs } catch { return false }\n}\n\n/**\n * Take over a crashed holder's lock. Only one waiter may do it at a time\n * (a second `.takeover` lock), and it re-checks under that lock, so two\n * waiters that both saw the old lock can't both delete it — the second\n * would otherwise delete the first one's fresh lock.\n */\nexport function takeOver(lock: string, staleMs: number): void {\n const guard = `${lock}.takeover`\n if (isStale(guard, staleMs)) { try { unlinkSync(guard) } catch { /* another waiter did */ } }\n let fd: number\n try { fd = openSync(guard, \"wx\") } catch { return }\n try {\n if (isStale(lock, staleMs)) unlinkSync(lock)\n } catch {\n // Not removable (a directory, a permission): the wait times out with\n // an error naming the lock, rather than spinning.\n } finally {\n closeSync(fd)\n try { unlinkSync(guard) } catch { /* gone */ }\n }\n}\n\n/**\n * Run `fn` holding `<file>.lock`. Waits up to `timeoutMs` for another\n * holder; a lock older than `staleMs` is a crashed holder and is taken\n * over. Re-entrant within one process.\n */\nexport function withLock<T>(file: string, fn: () => T, opts: { timeoutMs?: number; staleMs?: number } = {}): T {\n const lock = `${file}.lock`\n if (held.has(lock)) return fn()\n const timeoutMs = opts.timeoutMs ?? 3000\n const staleMs = opts.staleMs ?? 15_000\n mkdirSync(dirname(lock), { recursive: true })\n const deadline = Date.now() + timeoutMs\n let fd: number | undefined\n while (fd === undefined) {\n try {\n fd = openSync(lock, \"wx\")\n } catch (e: any) {\n if (e?.code !== \"EEXIST\") throw e\n if (isStale(lock, staleMs)) takeOver(lock, staleMs)\n if (Date.now() > deadline) {\n throw new Error(`fact ledger is busy (${lock}). If no agentx command is running, delete that lock and try again.`)\n }\n sleep(25)\n }\n }\n held.add(lock)\n try {\n return fn()\n } finally {\n held.delete(lock)\n closeSync(fd)\n try { unlinkSync(lock) } catch { /* already gone */ }\n }\n}\n"],"mappings":"mHAAA,OAAS,cAAAA,MAAkB,SAC3B,OAAS,cAAAC,EAAY,YAAAC,MAAgB,KACrC,OAAS,WAAAC,MAAe,OCFxB,OAAS,aAAAC,EAAW,cAAAC,EAAY,aAAAC,EAAW,YAAAC,EAAU,gBAAAC,EAAc,cAAAC,EAAY,YAAAC,EAAU,cAAAC,EAAY,iBAAAC,MAAqB,KAC1H,OAAS,WAAAC,MAAe,OAYjB,IAAMC,EAAN,cAAiC,KAAM,CAC5C,YAAqBC,EAAcC,EAAe,CAChD,MACE,eAAeD,oBAAuBC,kGAExC,EAJmB,UAAAD,EAKnB,KAAK,KAAO,oBACd,CACF,EAOME,EAAc,CAAC,KAAM,UAAW,YAAa,QAAS,SAAU,aAAc,aAAc,YAAY,EACxGC,EAAkB,CAAC,KAAM,SAAU,QAAS,SAAU,aAAc,SAAS,EAE7EC,EAAa,CAACC,EAAYC,IAC9B,CAAC,CAACD,GAAK,OAAOA,GAAM,UAAY,CAAC,MAAM,QAAQA,CAAC,GAAKC,EAAK,MAAOC,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OAASiC,EAAK,QAAQ,UAASA,EAAOjC,GAEvE,OAAOiC,CACT","names":["createHash","existsSync","statSync","resolve","closeSync","existsSync","mkdirSync","openSync","readFileSync","renameSync","statSync","unlinkSync","writeFileSync","dirname","LedgerCorruptError","file","cause","FACT_FIELDS","PROPOSAL_FIELDS","hasStrings","o","keys","k","readLedger","raw","e","bad","f","badP","p","writeLedger","data","tmp","sleep","ms","held","isStale","path","staleMs","takeOver","lock","guard","fd","withLock","fn","opts","timeoutMs","deadline","norm","s","factId","subject","attribute","createHash","norm","FactLedger","wikiDir","resolve","existsSync","mtimeMs","statSync","raw","readLedger","e","data","fn","withLock","save","result","writeLedger","id","f","input","opts","assertPerson","now","nowIso","checked","dated","verifiedAt","volatility","isFactClass","classifyAttribute","provenance","out","existing","fact","prior","newer","q","raiseContradiction","current","store","QuestionStore","item","questionId","x","factContradictions","isStaleFact","isPastTtl","matchFact","content","facts","text","best","attrWords","w","classifyFact"]}
|