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.
Files changed (47) hide show
  1. package/dist/{agent-VQIC7O5T.js → agent-K7EPLYCP.js} +2 -2
  2. package/dist/{board-dashboard-ZPJHXX3U.js → board-dashboard-BWB2FLOA.js} +2 -2
  3. package/dist/{chunk-5AMQFDLE.js → chunk-37P3DKSX.js} +63 -63
  4. package/dist/{chunk-5AMQFDLE.js.map → chunk-37P3DKSX.js.map} +1 -1
  5. package/dist/{chunk-QDRAKJSY.js → chunk-3XEN24B7.js} +4 -4
  6. package/dist/chunk-ILEC3IAV.js +3 -0
  7. package/dist/chunk-ILEC3IAV.js.map +1 -0
  8. package/dist/chunk-KA2UIZXG.js +3 -0
  9. package/dist/chunk-KA2UIZXG.js.map +1 -0
  10. package/dist/{chunk-NVJHA63C.js → chunk-KSUCHOH2.js} +10 -10
  11. package/dist/chunk-KSUCHOH2.js.map +1 -0
  12. package/dist/chunk-KXR6GVL7.js +5 -0
  13. package/dist/chunk-KXR6GVL7.js.map +1 -0
  14. package/dist/{chunk-BYKF3UTL.js → chunk-PDGPHE35.js} +2 -2
  15. package/dist/{chunk-4NXIJEYU.js → chunk-USTQPX4Y.js} +3 -3
  16. package/dist/{chunk-B65FS265.js → chunk-X5BWHPR7.js} +2 -2
  17. package/dist/cli.js +1 -1
  18. package/dist/fact-proposals-LZWS5KFO.js +2 -0
  19. package/dist/index.js +1 -1
  20. package/dist/ledger-CH7R756S.js +2 -0
  21. package/dist/{program-6PFRDQFT.js → program-44FEGUCB.js} +2 -2
  22. package/dist/questions-ZATLU5AW.js +2 -0
  23. package/dist/{registry-KP3C4EZ4.js → registry-HMVIS6QJ.js} +2 -2
  24. package/dist/{rotation-memo-store-X63HYIMV.js → rotation-memo-store-A4YW6FSK.js} +2 -2
  25. package/package.json +1 -1
  26. package/dist/chunk-AU6FFC4I.js +0 -5
  27. package/dist/chunk-AU6FFC4I.js.map +0 -1
  28. package/dist/chunk-NVJHA63C.js.map +0 -1
  29. package/dist/chunk-ST6KPQOY.js +0 -3
  30. package/dist/chunk-ST6KPQOY.js.map +0 -1
  31. package/dist/chunk-ZXR6GNEK.js +0 -3
  32. package/dist/chunk-ZXR6GNEK.js.map +0 -1
  33. package/dist/fact-proposals-ERRQXV2J.js +0 -2
  34. package/dist/ledger-DHYRP4TN.js +0 -2
  35. package/dist/questions-QGITDLJY.js +0 -2
  36. /package/dist/{agent-VQIC7O5T.js.map → agent-K7EPLYCP.js.map} +0 -0
  37. /package/dist/{board-dashboard-ZPJHXX3U.js.map → board-dashboard-BWB2FLOA.js.map} +0 -0
  38. /package/dist/{chunk-QDRAKJSY.js.map → chunk-3XEN24B7.js.map} +0 -0
  39. /package/dist/{chunk-BYKF3UTL.js.map → chunk-PDGPHE35.js.map} +0 -0
  40. /package/dist/{chunk-4NXIJEYU.js.map → chunk-USTQPX4Y.js.map} +0 -0
  41. /package/dist/{chunk-B65FS265.js.map → chunk-X5BWHPR7.js.map} +0 -0
  42. /package/dist/{fact-proposals-ERRQXV2J.js.map → fact-proposals-LZWS5KFO.js.map} +0 -0
  43. /package/dist/{ledger-DHYRP4TN.js.map → ledger-CH7R756S.js.map} +0 -0
  44. /package/dist/{program-6PFRDQFT.js.map → program-44FEGUCB.js.map} +0 -0
  45. /package/dist/{questions-QGITDLJY.js.map → questions-ZATLU5AW.js.map} +0 -0
  46. /package/dist/{registry-KP3C4EZ4.js.map → registry-HMVIS6QJ.js.map} +0 -0
  47. /package/dist/{rotation-memo-store-X63HYIMV.js.map → rotation-memo-store-A4YW6FSK.js.map} +0 -0
@@ -0,0 +1,5 @@
1
+ import{a as d,c as F}from"./chunk-KA2UIZXG.js";import{c as u,j as g,k as f}from"./chunk-GQ76J72O.js";import{a as l}from"./chunk-ILEC3IAV.js";import{createHash as w}from"crypto";var m=(t,r)=>"fp-"+w("sha1").update(`${t}\0${r.toLowerCase().replace(/\s+/g," ").trim()}`).digest("hex").slice(0,10);function b(t){let r=t.replace(/^[-*•]\s*/,"").replace(/\s*\((?:[^)]*)\)\s*$/,"").trim(),s=r.match(/^(.{2,60}?)\s+(?:is|are|was|were|has been|went|got)\s+(.{1,80})$/i);if(!s)return{};let a=u(r);return{subject:s[1].trim(),attribute:a==="stable"?"state":`${a} status`,value:s[2].trim()}}function y(t,r,s){let a=t.at??new Date().toISOString(),e=f(s),o=u(s);return{id:r,status:"pending",claim:s,...b(s),volatility:o==="stable"?"work-state":o,source:e?.source??`${t.origin} (unchecked summary)`,verifiedAt:e?.verifiedAt??a,verifiedBy:t.agentId,origin:t.origin,agentId:t.agentId,...t.chat?{chat:t.chat}:{},createdAt:a}}function I(t,r){return r.length===0?[]:t.update(s=>{let a=[],e=!1;for(let o of r){let i=o.claim.replace(/^[-*•]\s*/,"").trim();if(!i)continue;let c=m(o.agentId,i),n=s.proposals.find(v=>v.id===c);if(n){a.push(n);continue}let p=y(o,c,i);s.proposals.push(p),a.push(p),e=!0}return{save:e,result:a}})}function A(t,r){return t.load().proposals.filter(s=>!r||s.status===r)}var P=(t,r)=>t.id===r||r.length>=6&&t.id.startsWith(r);function j(t,r){return t.load().proposals.find(s=>P(s,r))}function h(t,r,s){return t.update(a=>{let e=a.proposals.find(o=>P(o,r));if(!e)throw new Error(`no fact proposal "${r}"`);if(e.status!=="pending")throw new Error(`proposal ${e.id} is already ${e.status}`);return Object.assign(e,s),{save:!0,result:e}})}function B(t,r,s,a={}){return l("approve a fact proposal"),d(t.file,()=>$(t,r,s,a))}function $(t,r,s,a){let e=j(t,r);if(!e)throw new Error(`no fact proposal "${r}"`);if(e.status!=="pending")throw new Error(`proposal ${e.id} is already ${e.status}`);let o=a.subject??e.subject,i=a.attribute??e.attribute,c=a.value??e.value;if(!o||!i||!c)throw new Error("could not read a subject, attribute and value from the claim; pass --subject, --attribute and --value");let n=t.write({subject:o,attribute:i,value:c,source:a.source??e.source,verifiedBy:e.verifiedBy,verifiedAt:e.verifiedAt,volatility:e.volatility},{confirmedBy:s});return{proposal:h(t,e.id,{status:"approved",decidedAt:new Date().toISOString(),decidedBy:s}),write:n}}function E(t,r,s,a){return l("reject a fact proposal"),h(t,r,{status:"rejected",decidedAt:new Date().toISOString(),decidedBy:s,...a?{reason:a}:{}})}function C(t,r,s){let{workState:a,claims:e}=g(r);if(e.length===0)return{workState:a.join(`
2
+ `),pinned:r,proposals:[]};let o=[],i;try{o=I(new F(t),e.map(n=>({claim:n,...s})))}catch(n){i=String(n?.message??n)}let c=e.map((n,p)=>`- UNVERIFIED claim (${o[p]?`wiki proposal ${o[p].id}`:"not checked"}): ${n.replace(/^[-*•]\s*/,"")}`);return{workState:a.join(`
3
+ `),pinned:[...a,...c].join(`
4
+ `),proposals:o,...i?{error:i}:{}}}export{b as a,I as b,A as c,B as d,E as e,C as f};
5
+ //# sourceMappingURL=chunk-KXR6GVL7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/facts/fact-proposals.ts"],"sourcesContent":["import { createHash } from \"crypto\"\nimport { citedCheck, classifyFact, splitMemo, type FactClass } from \"@/agents/fact-freshness\"\nimport { assertPerson, FactLedger, type FactInput, type WriteResult } from \"./ledger\"\nimport { withLock } from \"./ledger-file\"\n\n// --- Fact proposals: what a session summary claims, waiting for a check ---\n//\n// A rotation or continuity memo is a model's summary of a session. When it\n// says \"the vendor account is past due\", that is a claim nobody checked in\n// this form, and storing it as memory is how a stale note became a stated\n// fact (#273). So memo claims about outside systems come here instead,\n// with where they came from. They reach the ledger only when a person\n// approves one (a confirmation), never on their own.\n\nexport type FactProposalStatus = \"pending\" | \"approved\" | \"rejected\"\n\nexport interface FactProposal {\n id: string\n status: FactProposalStatus\n /** The line as the memo stated it. */\n claim: string\n /** Best guess at the structured fact, editable on approval. */\n subject?: string\n attribute?: string\n value?: string\n volatility: FactClass\n /** The check the memo cited, or where the claim came from. */\n source: string\n /** When that check happened, or when the memo was written. */\n verifiedAt: string\n verifiedBy: string\n /** e.g. \"rotation-memo:tier-2\" or \"continuity-memo\". */\n origin: string\n agentId: string\n chat?: string\n createdAt: string\n decidedAt?: string\n decidedBy?: string\n reason?: string\n}\n\nexport interface ProposalInput {\n claim: string\n agentId: string\n origin: string\n chat?: string\n at?: string\n}\n\nconst proposalId = (agentId: string, claim: string) =>\n \"fp-\" + createHash(\"sha1\").update(`${agentId}\\u0000${claim.toLowerCase().replace(/\\s+/g, \" \").trim()}`).digest(\"hex\").slice(0, 10)\n\n/** \"X is Y\" → subject X, value Y, attribute named after the class. */\nexport function parseClaim(claim: string): { subject?: string; attribute?: string; value?: string } {\n const text = claim.replace(/^[-*•]\\s*/, \"\").replace(/\\s*\\((?:[^)]*)\\)\\s*$/, \"\").trim()\n const m = text.match(/^(.{2,60}?)\\s+(?:is|are|was|were|has been|went|got)\\s+(.{1,80})$/i)\n if (!m) return {}\n const cls = classifyFact(text)\n return { subject: m[1].trim(), attribute: cls === \"stable\" ? \"state\" : `${cls} status`, value: m[2].trim() }\n}\n\nfunction newProposal(it: ProposalInput, id: string, claim: string): FactProposal {\n const at = it.at ?? new Date().toISOString()\n const cited = citedCheck(claim)\n const cls = classifyFact(claim)\n return {\n id, status: \"pending\", claim, ...parseClaim(claim),\n // A summary's claim is never stable: at best it was true that day.\n volatility: cls === \"stable\" ? \"work-state\" : cls,\n source: cited?.source ?? `${it.origin} (unchecked summary)`,\n verifiedAt: cited?.verifiedAt ?? at,\n verifiedBy: it.agentId,\n origin: it.origin, agentId: it.agentId,\n ...(it.chat ? { chat: it.chat } : {}),\n createdAt: at,\n }\n}\n\n/** Queue claims, under the ledger's lock. The same claim from the same\n * agent is kept once. Throws on an unreadable ledger rather than\n * writing over it. */\nexport function proposeFacts(ledger: FactLedger, items: ProposalInput[]): FactProposal[] {\n if (items.length === 0) return []\n return ledger.update((data) => {\n const out: FactProposal[] = []\n let added = false\n for (const it of items) {\n const claim = it.claim.replace(/^[-*•]\\s*/, \"\").trim()\n if (!claim) continue\n const id = proposalId(it.agentId, claim)\n const seen = data.proposals.find((p) => p.id === id)\n if (seen) { out.push(seen); continue }\n const p = newProposal(it, id, claim)\n data.proposals.push(p)\n out.push(p)\n added = true\n }\n return { save: added, result: out }\n })\n}\n\nexport function listFactProposals(ledger: FactLedger, status?: FactProposalStatus): FactProposal[] {\n return ledger.load().proposals.filter((p) => !status || p.status === status)\n}\n\nconst matches = (x: FactProposal, id: string) => x.id === id || (id.length >= 6 && x.id.startsWith(id))\n\nfunction findProposal(ledger: FactLedger, id: string): FactProposal | undefined {\n return ledger.load().proposals.find((x) => matches(x, id))\n}\n\n/** Decide a pending proposal under the ledger's lock. */\nfunction decide(ledger: FactLedger, id: string, fields: Partial<FactProposal>): FactProposal {\n return ledger.update((data) => {\n const p = data.proposals.find((x) => matches(x, id))\n if (!p) throw new Error(`no fact proposal \"${id}\"`)\n if (p.status !== \"pending\") throw new Error(`proposal ${p.id} is already ${p.status}`)\n Object.assign(p, fields)\n return { save: true, result: p }\n })\n}\n\n/**\n * Approve a claim: a person confirms it, so it is written to the ledger\n * with their name, even over a newer-dated value.\n */\nexport function approveFactProposal(\n ledger: FactLedger, id: string, by: string,\n edit: Partial<Pick<FactInput, \"subject\" | \"attribute\" | \"value\" | \"source\">> = {},\n): { proposal: FactProposal; write: WriteResult } {\n assertPerson(\"approve a fact proposal\")\n // One lock for the whole approval: the fact write and the decision\n // land together, or neither does (both re-enter this lock).\n return withLock(ledger.file, () => approveLocked(ledger, id, by, edit))\n}\n\nfunction approveLocked(\n ledger: FactLedger, id: string, by: string,\n edit: Partial<Pick<FactInput, \"subject\" | \"attribute\" | \"value\" | \"source\">>,\n): { proposal: FactProposal; write: WriteResult } {\n const p = findProposal(ledger, id)\n if (!p) throw new Error(`no fact proposal \"${id}\"`)\n if (p.status !== \"pending\") throw new Error(`proposal ${p.id} is already ${p.status}`)\n const subject = edit.subject ?? p.subject\n const attribute = edit.attribute ?? p.attribute\n const value = edit.value ?? p.value\n if (!subject || !attribute || !value) {\n throw new Error(\"could not read a subject, attribute and value from the claim; pass --subject, --attribute and --value\")\n }\n const write = ledger.write(\n { subject, attribute, value, source: edit.source ?? p.source, verifiedBy: p.verifiedBy, verifiedAt: p.verifiedAt, volatility: p.volatility },\n { confirmedBy: by },\n )\n const proposal = decide(ledger, p.id, { status: \"approved\", decidedAt: new Date().toISOString(), decidedBy: by })\n return { proposal, write }\n}\n\nexport function rejectFactProposal(ledger: FactLedger, id: string, by: string, reason?: string): FactProposal {\n assertPerson(\"reject a fact proposal\")\n return decide(ledger, id, { status: \"rejected\", decidedAt: new Date().toISOString(), decidedBy: by, ...(reason ? { reason } : {}) })\n}\n\n/**\n * Route a session memo: claims about outside systems become proposals;\n * the rest is work state. `pinned` is what the next fresh session reads,\n * with each claim marked unverified and pointing at its proposal.\n */\nexport function routeMemo(\n wikiDir: string, memo: string, ctx: { agentId: string; origin: string; chat?: string },\n): { workState: string; pinned: string; proposals: FactProposal[]; error?: string } {\n const { workState, claims } = splitMemo(memo)\n if (claims.length === 0) return { workState: workState.join(\"\\n\"), pinned: memo, proposals: [] }\n let proposals: FactProposal[] = []\n let error: string | undefined\n try {\n proposals = proposeFacts(new FactLedger(wikiDir), claims.map((claim) => ({ claim, ...ctx })))\n } catch (e) {\n // An unwritable wiki must not lose the memo: claims stay out of\n // memory and are pinned for this chat only, still marked.\n error = String((e as Error)?.message ?? e)\n }\n const flagged = claims.map((c, i) =>\n `- UNVERIFIED claim (${proposals[i] ? `wiki proposal ${proposals[i].id}` : \"not checked\"}): ${c.replace(/^[-*•]\\s*/, \"\")}`)\n return { workState: workState.join(\"\\n\"), pinned: [...workState, ...flagged].join(\"\\n\"), proposals, ...(error ? { error } : {}) }\n}\n"],"mappings":"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","names":["createHash","proposalId","agentId","claim","createHash","parseClaim","text","m","cls","classifyFact","newProposal","it","id","at","cited","citedCheck","proposeFacts","ledger","items","data","out","added","seen","p","listFactProposals","status","matches","x","findProposal","decide","fields","approveFactProposal","by","edit","assertPerson","withLock","approveLocked","subject","attribute","value","write","rejectFactProposal","reason","routeMemo","wikiDir","memo","ctx","workState","claims","splitMemo","proposals","error","FactLedger","e","flagged","c","i"]}
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-KP3C4EZ4.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-HMVIS6QJ.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-BYKF3UTL.js.map
126
+ //# sourceMappingURL=chunk-PDGPHE35.js.map
@@ -1,4 +1,4 @@
1
- import{$ as Gs,A as Xt,Aa as qa,Ba as Ya,C as ka,E as va,F as Fs,G as Sa,H as Me,I as $a,J as Us,Ka as Ws,L as Hs,La as Js,M as Ia,N as We,Na as Qa,O as Ma,R as ut,S as Pa,T as _a,U as Oa,V as Da,W as ja,_ as Na,a as Zo,aa as zt,b as Os,ca as ce,da as Kt,ea as Bs,f as Ds,fa as La,g as ea,ga as qt,h as ta,ha as Fa,i as Se,ia as pe,j as na,ja as Ua,ka as Ha,l as sa,la as Ga,m as ca,ma as Yt,na as Qt,oa as Ba,pa as Wa,qa as Ja,r as ua,ra as Va,s as ha,t as ga,ta as Xa,u as pa,v as ma,w as fa,x as ya,y as ba,z as wa}from"./chunk-B65FS265.js";import{m as ia,n as oa,o as Ns,p as Ls,q as aa,r as dt}from"./chunk-BYJ3A55Y.js";import{c as ht,d as za,e as Ka}from"./chunk-NMFXY3QU.js";import{c as qo,f as Yo,g as Qo}from"./chunk-F2DEKA2Q.js";import{a as Ca}from"./chunk-LQRBGQIR.js";import{a as ra}from"./chunk-ZVP6GB4G.js";import{o as js}from"./chunk-ART666G6.js";import{b as la,c as da}from"./chunk-2D3RYIDU.js";import{b as xa,c as Ta,d as Aa,e as Ra,f as Ea}from"./chunk-L53FTKEP.js";import{A as ee,B as Lo,C as Fo,D as Uo,E as Ho,F as Go,G as Bo,I as Vo,S as Xo,a as Hi,b as Gi,c as xs,d as Wi,e as zi,f as Ki,g as ct,i as Rs,j as Es,k as eo,r as to,s as ro,t as oo,u as H,w as go,x as po,y as mo,z as fo}from"./chunk-QDRAKJSY.js";import{a as no,c as io,e as Ce,f as Ut,l as bo,m as wo,o as Mo,p as Po,q as jo,s as No,t as Wo,z as Jo}from"./chunk-NVJHA63C.js";import{a as Ts,b as qi,c as Yi,d as As,e as Qi,f as Zi}from"./chunk-N6EWZGIX.js";import{b as To,c as Ao,d as Ps,f as Wt,g as Ro,h as Eo,i as Co,j as lt,k as Jt}from"./chunk-WP6KLXTP.js";import{a as Cs,b as so}from"./chunk-DP7RTNDM.js";import{A as zo,B as Vt,C as Ko,h as Pi,n as _i,o as ws}from"./chunk-BYKF3UTL.js";import{b as Ei}from"./chunk-SFQUP3BP.js";import{a as ko,b as Ms,c as vo,d as So,e as $o,i as Io}from"./chunk-76Z4VHDX.js";import{b as yo}from"./chunk-W4YR2RO2.js";import{b as Z,d as Be,f as Ht,g as Gt,i as re,j as xo,k as ke,l as ve,m as Do,s as _s}from"./chunk-JHWBCDD2.js";import{a as _o,b as Oo}from"./chunk-APKAW7LU.js";import{d as ao,e as co,f as lo,g as uo,h as ho,j as Bt}from"./chunk-X5C5W3E4.js";import{d as Ji,e as Vi,j as Xi}from"./chunk-DWADWDMU.js";import{b as Bi}from"./chunk-2GIDVZ4H.js";import{d as Oi,e as og,m as Li,n as dg,o as Fi,t as Ui,v as Ge,w as Ft}from"./chunk-VOS2IW4V.js";import{a as Ee,b as at,f as Is}from"./chunk-72SZI2UW.js";import{a as ks,b as ig}from"./chunk-FCPTN6NF.js";import{a as Nt,b as rg}from"./chunk-7I7IEX4S.js";import{a as Ci,d as Mi}from"./chunk-VDMYBPYB.js";import{e as Re}from"./chunk-DSYKYZMT.js";import{h as ag,i as Ue,j as Di,k as vs,l as cg,m as Lt,o as ji,p as He,q as Ss,w as $s,x as Ni,z as lg}from"./chunk-N5NPJ6DJ.js";import{d as Fe}from"./chunk-QIJLFPWE.js";import{existsSync as ug,readFileSync as hg}from"fs";var Za=["answer","narration","line"];function ec(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function tc(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),d=String(s.kind??"line");if(!c||!l||!Za.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${Za.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(l);if(!u)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:g,done:b}=r.enqueue({voice:u,text:c,agentId:l,kind:d});return s.wait!==!0?{status:202,body:{item:g}}:{status:200,body:{item:g,played:await b}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:Vs(i);case"front":return r.front(i)?{status:200,body:r.view()}:Vs(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:Vs(i)}default:return{status:404,body:{error:"Not found"}}}}function nc(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
1
+ import{$ as Gs,A as Xt,Aa as qa,Ba as Ya,C as ka,E as va,F as Fs,G as Sa,H as Me,I as $a,J as Us,Ka as Ws,L as Hs,La as Js,M as Ia,N as We,Na as Qa,O as Ma,R as ut,S as Pa,T as _a,U as Oa,V as Da,W as ja,_ as Na,a as Zo,aa as zt,b as Os,ca as ce,da as Kt,ea as Bs,f as Ds,fa as La,g as ea,ga as qt,h as ta,ha as Fa,i as Se,ia as pe,j as na,ja as Ua,ka as Ha,l as sa,la as Ga,m as ca,ma as Yt,na as Qt,oa as Ba,pa as Wa,qa as Ja,r as ua,ra as Va,s as ha,t as ga,ta as Xa,u as pa,v as ma,w as fa,x as ya,y as ba,z as wa}from"./chunk-X5BWHPR7.js";import{m as ia,n as oa,o as Ns,p as Ls,q as aa,r as dt}from"./chunk-BYJ3A55Y.js";import{c as ht,d as za,e as Ka}from"./chunk-NMFXY3QU.js";import{c as qo,f as Yo,g as Qo}from"./chunk-F2DEKA2Q.js";import{a as Ca}from"./chunk-LQRBGQIR.js";import{a as ra}from"./chunk-ZVP6GB4G.js";import{o as js}from"./chunk-ART666G6.js";import{b as la,c as da}from"./chunk-2D3RYIDU.js";import{b as xa,c as Ta,d as Aa,e as Ra,f as Ea}from"./chunk-L53FTKEP.js";import{A as ee,B as Lo,C as Fo,D as Uo,E as Ho,F as Go,G as Bo,I as Vo,S as Xo,a as Hi,b as Gi,c as xs,d as Wi,e as zi,f as Ki,g as ct,i as Rs,j as Es,k as eo,r as to,s as ro,t as oo,u as H,w as go,x as po,y as mo,z as fo}from"./chunk-3XEN24B7.js";import{a as no,c as io,e as Ce,f as Ut,l as bo,m as wo,o as Mo,p as Po,q as jo,s as No,t as Wo,z as Jo}from"./chunk-KSUCHOH2.js";import{a as Ts,b as qi,c as Yi,d as As,e as Qi,f as Zi}from"./chunk-N6EWZGIX.js";import{b as To,c as Ao,d as Ps,f as Wt,g as Ro,h as Eo,i as Co,j as lt,k as Jt}from"./chunk-WP6KLXTP.js";import{a as Cs,b as so}from"./chunk-DP7RTNDM.js";import{A as zo,B as Vt,C as Ko,h as Pi,n as _i,o as ws}from"./chunk-PDGPHE35.js";import{b as Ei}from"./chunk-SFQUP3BP.js";import{a as ko,b as Ms,c as vo,d as So,e as $o,i as Io}from"./chunk-76Z4VHDX.js";import{b as yo}from"./chunk-W4YR2RO2.js";import{b as Z,d as Be,f as Ht,g as Gt,i as re,j as xo,k as ke,l as ve,m as Do,s as _s}from"./chunk-JHWBCDD2.js";import{a as _o,b as Oo}from"./chunk-APKAW7LU.js";import{d as ao,e as co,f as lo,g as uo,h as ho,j as Bt}from"./chunk-X5C5W3E4.js";import{d as Ji,e as Vi,j as Xi}from"./chunk-DWADWDMU.js";import{b as Bi}from"./chunk-2GIDVZ4H.js";import{d as Oi,e as og,m as Li,n as dg,o as Fi,t as Ui,v as Ge,w as Ft}from"./chunk-VOS2IW4V.js";import{a as Ee,b as at,f as Is}from"./chunk-72SZI2UW.js";import{a as ks,b as ig}from"./chunk-FCPTN6NF.js";import{a as Nt,b as rg}from"./chunk-7I7IEX4S.js";import{a as Ci,d as Mi}from"./chunk-VDMYBPYB.js";import{e as Re}from"./chunk-DSYKYZMT.js";import{h as ag,i as Ue,j as Di,k as vs,l as cg,m as Lt,o as ji,p as He,q as Ss,w as $s,x as Ni,z as lg}from"./chunk-N5NPJ6DJ.js";import{d as Fe}from"./chunk-QIJLFPWE.js";import{existsSync as ug,readFileSync as hg}from"fs";var Za=["answer","narration","line"];function ec(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function tc(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),d=String(s.kind??"line");if(!c||!l||!Za.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${Za.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(l);if(!u)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:g,done:b}=r.enqueue({voice:u,text:c,agentId:l,kind:d});return s.wait!==!0?{status:202,body:{item:g}}:{status:200,body:{item:g,played:await b}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:Vs(i);case"front":return r.front(i)?{status:200,body:r.view()}:Vs(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:Vs(i)}default:return{status:404,body:{error:"Not found"}}}}function nc(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
2
2
  `)}var Vs=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});import{resolve as gg}from"path";var pg={name:"agentx",version:"0.1.0"},mg="2024-11-05",fg={tools:{},elicitation:{form:{}}},yg=0;async function sc(r,e){let t=++yg;return Pe({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{gt.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{gt.has(`elicit-${t}`)&&(gt.delete(`elicit-${t}`),n(null))},6e4)})}var gt=new Map,bg="http://localhost:19900",Xs;function wg(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=gg(process.cwd(),r);if(!ug(e))continue;let t=JSON.parse(hg(e,"utf-8"))?.node?.bind;if(typeof t!="string"||!t.includes(":"))continue;{let n=t.lastIndexOf(":"),s=t.slice(0,n),i=t.slice(n+1),o=!s||s==="0.0.0.0"||s==="::"||s==="*"?"127.0.0.1":s;if(i)return`http://${o}:${i}`}}catch{}return bg}function V(){return Xs===void 0&&(Xs=wg()),Xs}function rc(r=process.env){let e={};return r.AGENTX_TASK_ID&&(e.callerTaskId=r.AGENTX_TASK_ID),r.AGENTX_CHANNEL&&(e.callerChannel=r.AGENTX_CHANNEL),r.AGENTX_CHAT_ID&&(e.callerChatId=r.AGENTX_CHAT_ID),e}var kg=/\x1B\[[0-9;]*[A-Za-z]/g;function Je(r){return r.replace(kg,"")}function vg(r,e,t){if(!e.subscriptions)return`${r} has no event subscriptions. Add agents.${r}.subscriptions to agentx.json to receive events.`;let n=e.events??[];return n.length===0?`No new events match ${r}'s subscriptions.${e.next?` next: ${e.next}`:""}`:[...n.map(s=>`- ${t(s)} [id ${s.id}, root ${s.rootId}]`),`next: ${e.next}`].join(`
3
3
  `)}var Sg=[{name:"agentx_generate",description:"Generate code, components, pages, APIs, documents, tests, workflows, schemas, emails, diagrams, and more using AI. Understands the project's tech stack, schemas, and skills automatically.",inputSchema:{type:"object",properties:{task:{type:"string",description:"Describe what to generate (e.g., 'a responsive pricing card', 'REST API for users', 'GitHub Actions CI pipeline')"},type:{type:"string",description:"Output type: component, page, api, website, document, script, config, skill, media, report, test, workflow, schema, email, diagram, auto",default:"auto"},output_dir:{type:"string",description:"Optional output directory (relative to project root)"},cwd:{type:"string",description:"Project working directory (defaults to current directory)"}},required:["task"]}},{name:"agentx_inspect",description:"Analyze a project and return its tech stack, frameworks, databases, schemas, installed skills, and dependencies. Use this to understand a project before generating code.",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Project working directory (defaults to current directory)"}}}},{name:"agentx_skill_match",description:"Find installed skills that are relevant to a given task description. Returns matched skills with relevance scores.",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to match skills against"},cwd:{type:"string",description:"Project working directory"}},required:["task"]}},{name:"agentx_detect_output_type",description:"Auto-detect the best output type for a given task description based on keyword analysis.",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task description to analyze"}},required:["task"]}},{name:"agentx_channel_reply",description:"Reply to a channel (GitLab issue/MR comment, GitHub issue/PR comment, Telegram/WhatsApp message). PREFER THIS over raw curl/glab/HTTP \u2014 it auto-applies agent identity from agentMappings, the cascade-prevention marker, intent-ledger audit, and a 60s body-hash dedupe so an accidental retry within the window is a no-op. Returns the posted message id. For agent-to-agent delegation use agentx_send_agent. For arbitrary outbound sends use agentx_send.",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Channel name. gitlab | github | telegram | whatsapp | discord | slack"},chatId:{type:"string",description:"Stable chat id you received in this task's context. GitLab: 'org/repo:issue:123' or 'org/repo:merge_request:123'. GitHub: 'org/repo:issue:123' or 'org/repo:pull:123'. Telegram: numeric. WhatsApp: '+phone@s.whatsapp.net'."},text:{type:"string",description:"Reply body. Markdown for gitlab/github/discord; plain for sms/whatsapp."},agentId:{type:"string",description:"Optional posting identity. Defaults to channel-adapter resolution from agentMappings."},accountId:{type:"string",description:"Multi-account adapters (telegram) need this when the chat is reachable from more than one bot."},replyTo:{type:"string",description:"Optional reply-to message id for threaded channels."},idempotencyKey:{type:"string",description:"Optional explicit dedupe key. When omitted, a body hash is used. Use a stable key for 'overwrite my last status update' patterns."}},required:["channel","chatId","text"]}},{name:"agentx_channel_label",description:"Add and/or remove labels on a GitLab issue or merge_request through the canonical adapter (per-agent token, ledger). Use this instead of curl when changing labels on the entity that triggered the current task.",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Currently 'gitlab'.",default:"gitlab"},project:{type:"string",description:"GitLab project path \u2014 'org/repo'."},kind:{type:"string",description:"'issue' or 'merge_request'."},iid:{type:"string",description:"Numeric iid as a string."},add:{type:"array",items:{type:"string"},description:"Labels to add."},remove:{type:"array",items:{type:"string"},description:"Labels to remove."},agentId:{type:"string",description:"Optional posting identity."}},required:["project","kind","iid"]}},{name:"agentx_send",description:"Low-level outbound send when you ALREADY have a channel-native chatId (Telegram numeric chat id, GitLab 'group/project:issue:123', WhatsApp '+phone@s.whatsapp.net'). For sending to another agent by name, use agentx_send_agent instead. For sending to a human contact by name, use agentx_send_contact instead.",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Target channel: telegram, whatsapp, gitlab, discord"},chatId:{type:"string",description:'Chat ID. Telegram: numeric ("-1001234567890"). GitLab: "group/project:issue:123". WhatsApp: "+phone@s.whatsapp.net".'},text:{type:"string",description:"Message text to send"},agentId:{type:"string",description:"Agent ID to send as (determines bot account on Telegram, GitLab token, etc.)"}},required:["channel","chatId","text"]}},{name:"agentx_send_agent",description:"Send a message to ANOTHER AGENT by exact agentId \u2014 uses the AgentX A2A mesh (or local registry when the agent lives on this daemon). This is the deterministic path for agent-to-agent communication; it never falls through to a contact lookup, so an unknown agentId returns 404 with the list of known agents instead of silently sending to a similarly-named human. Use this when the target is a registered agent. When a person started this conversation, the call returns at once with a task id; tell the person who you asked, end your turn, and the answer arrives later as a new message in this conversation.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Exact agentId of the target agent (e.g. 'peer', 'atlas'). Must match an agent in this daemon's registry or in a healthy mesh peer's directory."},text:{type:"string",description:"Message to send to the target agent"},senderAgentId:{type:"string",description:"Optional. The agentId on whose behalf this call is being made. Recorded in route_traces and (with A2A protocolVersion >= 2) validated by the receiving daemon."}},required:["agentId","text"]}},{name:"agentx_recent",description:"Read the most recent messages from a chat across ALL agents that have sessions for it. Returns inbound + each agent's replies in chronological order, so you can see what's actually been said in a Telegram chat / GitLab thread / WhatsApp DM regardless of which agent recorded it. Use this BEFORE speculating about what was sent \u2014 the cx/devops/marketing thread on 2026-04-29 about a Marketing/CX bot mixup would have been resolved in one call instead of three agents speculating. Bounded by sinceISO (default: last 24h) and limit (default: 30, max: 200).",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Channel name. Examples: telegram, whatsapp, gitlab, github, discord, cron, api, a2a."},chatId:{type:"string",description:'Channel-native chat id. Telegram: numeric (e.g. "1816212449" for a DM, "-1001234567890" for a group). GitLab: "group/project:issue:123". WhatsApp: "+phone@s.whatsapp.net".'},sinceISO:{type:"string",description:"Optional ISO timestamp lower bound. Defaults to 24h ago."},limit:{type:"number",description:"Optional cap on returned messages. Default 30, max 200."}},required:["channel","chatId"]}},{name:"agentx_events",description:"Read what happened on this node that matches your event subscriptions (agents.<id>.subscriptions in agentx.json): tasks other agents finished or failed, workflow runs, mesh hand-offs. Use it to catch up after being idle instead of asking. Returns short summaries only (no prompts or answers), oldest first, at most 50. Pass the `next` value from the previous answer as `since` to read only newer events.",inputSchema:{type:"object",properties:{since:{type:"string",description:"An event id (events after it) or an ISO time. Default: the newest events in memory."},limit:{type:"number",description:"Most events to return. Default 20, max 50."},agentId:{type:"string",description:"Whose subscriptions to read. Ignored when the AgentX runtime already identifies you (AGENTX_AGENT_ID)."}}}},{name:"agentx_send_contact",description:"Send a message to a HUMAN CONTACT by name. Resolves through .agentx/contacts.json (id \u2192 exact alias \u2192 fuzzy substring). Refuses fuzzy matches without confirmed:true so the agent must ask the user to disambiguate before sending. Refuses when the name also matches a registered agent (use agentx_send_agent for those). Use this when the target is a person, not a bot.",inputSchema:{type:"object",properties:{contactName:{type:"string",description:"Free-form contact name. Tried as id first, then alias, then fuzzy substring."},text:{type:"string",description:"Message to send to the contact"},channel:{type:"string",description:"Optional explicit channel (telegram | whatsapp | gitlab | discord). Defaults to the first channel configured for the contact."},confirmed:{type:"boolean",description:"Pass true ONLY after the user has confirmed a fuzzy match. Without it, fuzzy matches return 409 with the candidate so you can ask the user."},agentId:{type:"string",description:"Optional agent identity used for the outbound send (determines bot account / token)."}},required:["contactName","text"]}},{name:"agentx_task",description:"Send a task to a specific agent on the daemon. The agent processes it and returns a response. Use to delegate work to specialized agents. When a person started this conversation, the call returns at once with a task id instead: tell the person who you asked and why, then end your turn. The answer arrives later as a new message in this same conversation.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to send the task to"},message:{type:"string",description:"Task message for the agent"},senderAgentId:{type:"string",description:"Optional caller agent id. Defaults to AGENTX_AGENT_ID when the MCP server was launched by an AgentX runtime."},freshSession:{type:"boolean",description:"Start the target agent with a clean AgentX-side conversation. Defaults to true for agent-to-agent delegation."},chatId:{type:"string",description:"Optional stable chat/session id for this delegated task. Omit for a one-off isolated delegation."}},required:["agent","message"]}},{name:"agentx_agents",description:"List all agents registered on the daemon with their status (active tasks, total tasks, errors, tier).",inputSchema:{type:"object",properties:{}}},{name:"agentx_voice_queue",description:"See what this host is saying out loud and what waits to be said: every agent's spoken answers, narration, talks and lessons share one speaking queue. Use it before speaking at length, or when asked who is talking.",inputSchema:{type:"object",properties:{}}},{name:"agentx_health",description:"Get the daemon health status including node info, agents, crons, mesh peers, and uptime.",inputSchema:{type:"object",properties:{}}},{name:"agentx_attach_next",description:"Take the next message queued for the agent identity THIS session is attached to (attach mode). Returns the message plus who sent it and on which channel, or nothing when the inbox is empty. After calling this, just answer normally \u2014 your reply is captured automatically and sent back to the channel. Use when the user runs /inbox or asks you to check for waiting messages.",inputSchema:{type:"object",properties:{}}},{name:"agentx_attach_answer",description:"Explicitly answer the message currently claimed by this session (attach mode). Usually unnecessary \u2014 replying normally after agentx_attach_next is captured automatically. Use this only when your reply to the channel should differ from what you told the user in the terminal.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The reply to send back to the channel, verbatim."}},required:["text"]}},{name:"agentx_crons",description:"List cron jobs and their health. Shows healthy, failing, disabled counts and per-job status with consecutive error counts.",inputSchema:{type:"object",properties:{}}},{name:"agentx_schedule",description:"Manage recurring routines (schedules) in plain English. Actions: list, create, pause, resume, delete. create and delete are REQUESTS: nothing takes effect until the operator approves (the operator is sent the parsed cron and next fire time). Tell the user it is pending approval. You can pause/resume/delete only routines you created, unless you are an admin agent. Example: {action:'create', when:'every monday at 10am', prompt:'Check the open invoices and summarise'}.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","create","pause","resume","delete"],description:"What to do. Default: list."},id:{type:"string",description:"Schedule id. Required for pause/resume/delete; optional for create (auto-generated)."},when:{type:"string",description:"create: plain-English timing, e.g. 'every monday at 10am', 'weekdays at 6pm', 'every 15 minutes', '1st of every month at noon'."},prompt:{type:"string",description:"create: what the agent should do at each run."},agent:{type:"string",description:"create: agent that runs the routine. Default: you."},timezone:{type:"string",description:"create: IANA timezone. Default: the node's schedule default."},notify:{type:"string",description:"create: where results/failures go. 'here' (default: the current chat), 'none', or 'channel:chatId'."},mine:{type:"boolean",description:"list: only routines you created."},channel:{type:"string",description:"Current chat's channel, from your task context. Used as the default notify target when the runtime didn't provide it."},chatId:{type:"string",description:"Current chat id, from your task context."},accountId:{type:"string",description:"Optional bot account for multi-account channels."},callerAgentId:{type:"string",description:"Your agent id. Ignored when the AgentX runtime already identifies you (AGENTX_AGENT_ID)."}}}},{name:"agentx_approval",description:"Ask the operator for a yes/no decision by raising a decision card in their Approvals inbox, instead of asking in chat. Lead with your recommendation. Every card expires: say what should happen if nobody answers (if_silent). You get a message with the result when it is decided or expires. You cannot approve anything with this tool. Actions: create (default), status. Example: {title:'Publish the launch post draft', ask:'Publish the draft on Monday?', recommend:'Yes: it is reviewed and the date is agreed', if_silent:'discard', expires:'2d', source:'https://example.com/drafts/42'}.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","status"],description:"create (default) or status."},title:{type:"string",description:"create: what it is, in one line (max 120 characters)."},ask:{type:"string",description:"create: the yes/no question (max 300 characters)."},recommend:{type:"string",description:"create: your advice and why, in one line (max 300 characters)."},if_silent:{type:"string",enum:["discard","keep","pause","approve"],description:"create: what applies if nobody answers before it expires."},expires:{type:"string",description:"create: when the default applies. ISO date/time, or relative like '12h' or '3d'. Default: the node's setting (3 days)."},source:{type:"string",description:"create: link to the draft, PR or issue."},id:{type:"string",description:"status: the card id you got from create."},channel:{type:"string",description:"Current chat's channel, from your task context, so the result can mention it."},chatId:{type:"string",description:"Current chat id, from your task context."},callerAgentId:{type:"string",description:"Your agent id. Ignored when the AgentX runtime already identifies you (AGENTX_AGENT_ID)."}}}},{name:"agentx_debug",description:"Toggle debug mode on the daemon. Enable verbose logging for specific categories (webhook, agent, channel, cron, mesh, context, memory, all) or disable it.",inputSchema:{type:"object",properties:{action:{type:"string",description:'"on", "off", or "status"',default:"status"},categories:{type:"string",description:'Comma-separated categories to enable (e.g. "webhook,agent"). Only used with action=on.'}}}},{name:"agentx_wiki_query",description:"Query the agentx institutional wiki: a cross-agent knowledge base organized by article type (person, project, place, concept, event, decision, pattern). Use this BEFORE grep/memory-search when the question is about who / what happened / what we decided / how we do something. The query walks the catalog + wikilink graph and returns a synthesized answer with citations.",inputSchema:{type:"object",properties:{question:{type:"string",description:"The question to answer from the wiki, in natural language."},agent:{type:"string",description:"Which agent's wiki to query (default: first agent with a catalog). Each agent has its own wiki dir under .agentx/wiki/agents/<id>/"},wiki_dir:{type:"string",description:"Wiki root dir (default: <cwd>/.agentx/wiki)."},max_hops:{type:"number",description:"Wikilink hops from candidates (default 2, max 3).",default:2}},required:["question"]}},{name:"agentx_wiki_patch",description:"Edit a single wiki article via an LLM-applied instruction and write the result. Use this for targeted fixes, additions, or clarifications to an existing article when you already know what's wrong. For brand-new articles, use `agentx_wiki_interview` instead.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose wiki owns the article (required)."},title_or_path:{type:"string",description:"Article title (case-insensitive) or relative path like 'people/alex.md'."},instruction:{type:"string",description:"Plain-English edit instruction (e.g. 'Add a section on the KSA Supabase rollout'). The LLM makes the minimum edit that satisfies it."},model:{type:"string",description:"Claude model for the patch (default: sonnet).",default:"sonnet"},dry_run:{type:"boolean",description:"Preview the patched body without writing.",default:!1}},required:["agent","title_or_path","instruction"]}},{name:"agentx_wiki_interview",description:"Run a scripted wiki interview \u2014 synthesize ONE typed article from a list of Q&A answers, and save it. Non-interactive: caller supplies the answers upfront. Use for capturing tacit knowledge (person/project/decision/pattern/...) that never hit a channel. For editing an existing article, use `agentx_wiki_patch`.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID that will own the new article (required)."},topic:{type:"string",description:"What the article is about \u2014 e.g. 'Globex deployment procedure', 'Jane Doe', 'DemoSite KSA migration'."},type:{type:"string",description:"Article type: person | project | place | concept | event | decision | pattern"},answers:{type:"array",description:"Answers to the type-specific question bank (one per question, in order). Empty string = skip that question. Final entry is typically 'save'.",items:{type:"string"}},model:{type:"string",description:"Synthesis model (default: sonnet).",default:"sonnet"},commit:{type:"boolean",description:"Write the article (true) or just preview (false).",default:!0}},required:["agent","topic","type","answers"]}},{name:"agentx_graph_review",description:"Triage pending intent-graph classifications via the configured review agent. The review agent sees each pending classification, may call `wiki query` for institutional context, and decides approve/reject/skip. Structural changes (new org, new unit) gate here; leaf additions auto-approve without this step.",inputSchema:{type:"object",properties:{max:{type:"number",description:"Cap reviews this run (default 20).",default:20},dry_run:{type:"boolean",description:"Show decisions but don't apply approvals/rejections.",default:!1},agent:{type:"string",description:"Override the review agent (defaults to graph.reviewAgent or graph.draftAgent)."}}}}];async function $g(r,e){let t=e.cwd||process.cwd();switch(r){case"agentx_generate":{let n=e.task,s=e.type||"auto",i=e.output_dir,o=await Vt({task:n,outputType:s,outputDir:i,cwd:t,overwrite:!0,dryRun:!1,context7:!0,interactive:!1,maxSteps:5}),a=[];return o.content&&a.push(o.content),o.files.written.length&&a.push(`
4
4
  Created ${o.files.written.length} file(s):
@@ -463,7 +463,7 @@ ${l}`)}let I={agentId:o,message:v,context:{channel:w,sender:f?"opencode":"openai
463
463
 
464
464
  `)}}function ol(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function al(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
465
465
 
466
- `)}function cl(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);hr(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function hr(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var vt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new vt(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(vt.levelOrder[e]<vt.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},kt=vt;Fe(kt,"levelOrder",{debug:0,info:1,warn:2,error:3});var Sn={version:"0.69.0",commit:"f884498",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};import{randomUUID as im}from"crypto";var $n=class{constructor(e=new oo){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!om.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};cm(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:im(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=am(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},om=["run","task","signal","mesh","channel","status"];function am(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function cm(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function dl(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as In,timingSafeEqual as ul}from"crypto";var xn=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let y={};for(let[v,I]of Object.entries(e.headers))(v.startsWith("x-hubspot")||v.startsWith("x-hub")||v.startsWith("x-github")||v.startsWith("x-gitlab")||v.startsWith("stripe")||v.startsWith("sentry")||v.startsWith("x-vercel")||v.startsWith("x-odoo")||v.startsWith("x-webhook")||v==="user-agent"||v==="content-type"||v==="host"||v==="x-forwarded-host"||v==="x-forwarded-proto"||v==="x-forwarded-for")&&(y[v]=I);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(y)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let g=this.extractEventType(l,c,e.headers),b=this.webhookEntries.find(y=>y.enabled&&y.agentId===i&&y.source===l),f=g&&b?.triggers?.[g]||b?.defaultWorkflow||null;if(await this.fireHookSafe(l,g,i,c),f&&this.workflowDispatcher)try{let y=await this.workflowDispatcher.dispatchWorkflow({workflowId:f,entityRef:{kind:"webhook",id:`${l}:${i}:${g??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:g,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${g??"\u2014"}] -> workflow=${f} (claimed=${y.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:g,workflow:f,claimed:y.claimed});return}catch(y){this.log(`Workflow dispatch failed [${l}/${g}/${f}]: ${y.message}`)}let w=this.webhookEntries.find(y=>y.enabled&&y.node&&y.agentId===i&&y.source===l);if(w?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:w.node,status:"accepted"}),this.mesh.sendTask(w.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(y=>this.log(`Mesh-forwarded webhook [${l}] -> ${w.node}/${i}: ${y?.slice(0,100)||"ok"}`),y=>this.log(`Mesh forward failed [${l}] -> ${w.node}/${i}: ${y.message}`));return}try{let y=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,y.error?500:200,{ok:!y.error,agent:i,source:l,response:y.content?.slice(0,500),error:y.error,duration:y.duration})}catch(y){this.sendJson(t,500,{error:y.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
466
+ `)}function cl(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);hr(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function hr(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var vt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new vt(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(vt.levelOrder[e]<vt.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},kt=vt;Fe(kt,"levelOrder",{debug:0,info:1,warn:2,error:3});var Sn={version:"0.69.1",commit:"69095d7",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};import{randomUUID as im}from"crypto";var $n=class{constructor(e=new oo){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!om.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};cm(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:im(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=am(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},om=["run","task","signal","mesh","channel","status"];function am(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function cm(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function dl(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as In,timingSafeEqual as ul}from"crypto";var xn=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let y={};for(let[v,I]of Object.entries(e.headers))(v.startsWith("x-hubspot")||v.startsWith("x-hub")||v.startsWith("x-github")||v.startsWith("x-gitlab")||v.startsWith("stripe")||v.startsWith("sentry")||v.startsWith("x-vercel")||v.startsWith("x-odoo")||v.startsWith("x-webhook")||v==="user-agent"||v==="content-type"||v==="host"||v==="x-forwarded-host"||v==="x-forwarded-proto"||v==="x-forwarded-for")&&(y[v]=I);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(y)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let g=this.extractEventType(l,c,e.headers),b=this.webhookEntries.find(y=>y.enabled&&y.agentId===i&&y.source===l),f=g&&b?.triggers?.[g]||b?.defaultWorkflow||null;if(await this.fireHookSafe(l,g,i,c),f&&this.workflowDispatcher)try{let y=await this.workflowDispatcher.dispatchWorkflow({workflowId:f,entityRef:{kind:"webhook",id:`${l}:${i}:${g??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:g,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${g??"\u2014"}] -> workflow=${f} (claimed=${y.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:g,workflow:f,claimed:y.claimed});return}catch(y){this.log(`Workflow dispatch failed [${l}/${g}/${f}]: ${y.message}`)}let w=this.webhookEntries.find(y=>y.enabled&&y.node&&y.agentId===i&&y.source===l);if(w?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:w.node,status:"accepted"}),this.mesh.sendTask(w.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(y=>this.log(`Mesh-forwarded webhook [${l}] -> ${w.node}/${i}: ${y?.slice(0,100)||"ok"}`),y=>this.log(`Mesh forward failed [${l}] -> ${w.node}/${i}: ${y.message}`));return}try{let y=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,y.error?500:200,{ok:!y.error,agent:i,source:l,response:y.content?.slice(0,500),error:y.error,duration:y.duration})}catch(y){this.sendJson(t,500,{error:y.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
467
467
  `)[0]||"no message"} (${d.author?.name||""})`)}let l=t.object_attributes;if(l?.title&&(s.push(`Title: ${l.title}`),s.push(`State: ${l.state||""}`),s.push(`Action: ${l.action||""}`),l.source_branch&&s.push(`Branch: ${l.source_branch} -> ${l.target_branch}`),l.url&&s.push(`URL: ${l.url}`)),l?.iid&&!l?.source_branch&&(s.push(`Issue #${l.iid}: ${l.title||""}`),l.description&&s.push(`Description: ${l.description.slice(0,200)}`)),t.object_kind==="pipeline"){let d=t.object_attributes;s.push(`Pipeline: ${d?.status||""} (${d?.ref||""})`),s.push(`Duration: ${d?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
468
468
  `)[0]||""} (${u.author?.name||""})`);let l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let l of a.slice(0,3)){let d=l.subscriptionType??"?",u=l.objectId??"?",g=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${g?`, ${g}`:""})`)}}else{let l=t.subscriptionType??"event",d=t.objectId??"?";s.push(`Event: ${l} (object ${d})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
469
469
  `)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(d=>d.enabled&&d.agentId===s&&d.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=d=>{let u=e[d.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let d=c("x-hub-signature-256");if(!d)return"missing X-Hub-Signature-256";let u="sha256="+In("sha256",a).update(t).digest("hex");return Ye(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?Ye(a,d):"missing X-Gitlab-Token"}if(n==="stripe"){let d=c("stripe-signature");if(!d)return"missing Stripe-Signature";let u=Object.fromEntries(d.split(",").map(b=>b.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let g=In("sha256",a).update(`${u.t}.${t}`).digest("hex");return Ye(g,u.v1)}if(n==="hubspot"){let d=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!d)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let g=parseInt(u,10);if(!Number.isFinite(g))return"malformed X-HubSpot-Request-Timestamp";let b=Date.now()-g;if(b>5*6e4)return`HubSpot webhook is ${Math.floor(b/1e3)}s old (>5min replay window)`;let f="POST",w=i||e["x-original-uri"]||e["x-forwarded-path"]||"",y=e["x-forwarded-host"],v=e.host,I=e["x-forwarded-proto"]||"https",T=new Set;y&&w&&T.add(`${I}://${y}${w}`),v&&w&&T.add(`https://${v}${w}`),v&&w&&T.add(`http://${v}${w}`),w&&T.add(w),T.add("");for(let P of T){let O=In("sha256",a).update(`${f}${P}${t}${u}`).digest("base64");if(d.length===O.length&&ul(Buffer.from(d),Buffer.from(O)))return null}return`signature mismatch (tried ${T.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let g=In("sha256",a).update(t).digest("hex"),b=d.startsWith("sha256=")?d.slice(7):d;return Ye(g,b)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?Ye(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?Ye(a,l):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function Ye(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return ul(t,n)?null:"signature mismatch"}ig();function lm(r){return{insertTaskHistory:r.prepare(`
@@ -1054,4 +1054,4 @@ data: ${JSON.stringify(_)}
1054
1054
  `)}catch{}},C=setInterval(()=>{try{t.write(`: ping
1055
1055
 
1056
1056
  `)}catch{}},15e3);C.unref?.();let E=new AbortController;t.on("close",()=>{t.writableEnded||E.abort()});try{for await(let x of this.mesh.sendTaskStream(h.peer,h.message,h.agent,{context:h.context,signal:E.signal}))M(x.event,x.data)}catch(x){M("error",{error:x?.message??String(x)})}finally{clearInterval(C);try{t.end()}catch{}}break}let k=h.context,S=typeof h.senderAgentId=="string"?h.senderAgentId:void 0;if(jh(h,!0)==="callback"){let M=this.delegationGate(e,h,{callee:h.agent,peer:h.peer,message:h.message,calleeContext:k});if(!("track"in M)){let C=cs(M);this.json(t,C.status,C.body);break}}if(h.async===!0){let M=k?.channel,C=k?.chatId;if(!M||!C){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let E=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:E,deliverTo:`${M}:${C}`,note:"result will be delivered to the originating chat when the peer finishes"});let x=h.peer,_=h.agent,N=this.mesh;(async()=>{let D=Date.now(),B;try{B=await N.sendTask(x,h.message,_,{context:k,senderAgentId:S}),this.log(`[mesh/task async ${E}] ${x}/${_??"default"} finished in ${Date.now()-D}ms`)}catch(G){B=`Delegation to ${x}/${_??"default"} failed: ${G?.message??G}`,this.log(`[mesh/task async ${E}] failed: ${G?.message??G}`)}try{await this.router.sendOutbound({channel:M,chatId:C,text:B,agentId:k?.agentId??S,accountId:k?.accountId})}catch(G){this.log(`[mesh/task async ${E}] delivery failed: ${G?.message??G}`)}})();break}let $=await this.mesh.sendTask(h.peer,h.message,h.agent,{context:k,senderAgentId:S});this.json(t,200,{response:$});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let p=await U(e);if(!p.kind||!p.callId||!p.from||!p.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let m=await this.webrtc.handleOutgoing(p);this.json(t,m.ok?200:400,m);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let p=await U(e);if(!p.kind||!p.callId||!p.from||!p.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let m=this.webrtc.handleIncoming(p);this.json(t,m.ok?200:400,m);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let h=await U(e),p=h.callId,m=h.target,k=h.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!p||!m||!k){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let S=await this.botManager.invite({callId:p,target:m,agentId:k});this.json(t,S.ok?200:500,S);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let h=this.config.channels.webrtc;if(!h?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...h.stunServers.map(p=>({urls:p})),...h.turnServers],peers:this.mesh?.directory().map(p=>({name:p.peer,healthy:p.healthy}))||[]});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(h=>{let p=this.config.agents[h.id]||{},m=typeof p.description=="string"&&p.description.trim()||zw(p.systemPrompt)||`Agent "${h.name}" (${h.tier})`,k=Array.isArray(p.mentions)?p.mentions.slice(0,4):[];return{id:h.id,name:h.name,description:m,tags:[h.tier,...k],color:ne(h.id,p).color}}),channels:this.router.getChannelNames(),defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let h=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:h.summary()});break}case"GET /wiki/entries":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent")||void 0,m=n.searchParams.get("after")||void 0,k=p?h.getAgentEntries(p):h.getSharedStore().listEntries({after:m});this.json(t,200,{nodeId:this.config.node.id,count:k.length,entries:k.map(S=>({id:S.id,date:S.date,agentId:S.agentId,source:S.source,sourceContext:S.sourceContext,content:S.content}))});break}case"GET /wiki/articles":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent");if(!p){this.json(t,400,{error:"?agent= required"});break}let k=h.getAgentWiki(p).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:p,articles:k.articles});break}case"GET /wiki/article":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent"),m=n.searchParams.get("path");if(!p||!m){this.json(t,400,{error:"?agent= and ?path= required"});break}let S=h.getAgentWiki(p).readArticle(m);if(!S){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:p,path:S.path,title:S.meta.title,tags:S.meta.tags,owner:S.meta.owner,created:S.meta.created,lastUpdated:S.meta.lastUpdated,sources:S.meta.sources,content:S.content});break}case"GET /graph/schema":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:h.loadSchema()});break}case"GET /graph/nodes":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...h.loadNodes()});break}case"GET /graph/classifications":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}let p=n.searchParams.get("status")||"approved",m=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),k=h.listByStatus(p,m);this.json(t,200,{nodeId:this.config.node.id,status:p,count:k.length,classifications:k});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await U(e);await ll(e,t,n,s,{execute:(i,o,a,c)=>this.registry.execute(i,o,a,c),agentIds:Object.keys(this.config.agents),cancel:(i,o,a,c)=>{let l=this.registry.list().find(d=>d.id===i)?.runningTasks.filter(d=>d.channel===o&&d.chatId===a)||[];for(let d of l)this.registry.cancelRunningTask(d.id,c)},log:i=>this.log(i)})}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveGitlabTokenForAgent(e){if(!e)return{token:this.config.channels.gitlab?.token,source:"global"};let t=(this.config.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);if(t?.token)return{token:t.token,source:"agentMappings"};let n=Jd(this.config,e,"gitlab-user","tokenEnv");return n.status==="ok"&&n.value?{token:n.value,source:`integrations(${n.envVar})`}:this.config.channels.gitlab?.token?{token:this.config.channels.gitlab.token,source:"global"}:{token:void 0,source:n.status}}resolveTodayUsage(){let e=Hl();if(e==="json")return this.registry.getTodayUsage();let t=Ul(this.db);return e==="sqlite"||Object.keys(t.agents).length>0?t:this.registry.getTodayUsage()}installAgentMemorySurface(){let e=parseInt(this.config.node.bind.split(":")[1]||"18800",10);for(let t of this.registry.list()){let n=t.workspace;if(!(!n||!ot(n)))try{let s=te(n,".claude","skills");ng(s,{recursive:!0});let i=te(s,zd);if(!ot(i))xi(i,jr(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=qd(Dt(i,"utf-8"),e);o&&(xi(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n)}catch(s){this.log(` memory-skill: ${t.id} install failed \u2014 ${s?.message??s}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!ot(n))continue;let s=Ji(t);try{switch(Xd(n,s)){case"installed":this.log(` mcp: installed ${Object.keys(s).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(s).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(s).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(i){this.log(` mcp: ${e} install failed \u2014 ${i?.message??i}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return Rd(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i)})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await Q(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let g=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${g}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let b=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:g}});this.log(`[workflows/mesh] dispatched broadcast: matched=${b.claimed.length} ${b.claimed.length?`(${b.claimed.map(f=>f.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:b.claimed.map(f=>f.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(g=>g.type.startsWith("trigger."))?.config??{},u={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async relayPush(e,t){let n=e.toLowerCase(),s=this.mesh?.directory().find(a=>a.peer.toLowerCase()===n);if(!s)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let i=await fetch(`${s.peerUrl}/channel/send`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(s.peer)},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!i.ok)throw new Error(`push: ${s.peer} /channel/send -> ${i.status} ${(await i.text().catch(()=>"")).slice(0,200)}`);return(await i.json().catch(()=>({}))).messageId??void 0}async handleChannelSend(e,t){let n;try{n=await Q(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}try{let c=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,relayed:n.relayed===!0?!0:void 0});this.json(t,200,{ok:!0,messageId:c??null})}catch(c){this.log(`[mesh] /channel/send "${s}" failed: ${c.message}`),this.json(t,500,{error:c.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let g of l)!g.id||s.has(g.id)||(s.add(g.id),i.push({...g,source:d}),u++);u>0&&o.push(`${d}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let u=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(d.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let g=await u.json();Array.isArray(g.chats)&&a(g.chats.map(b=>({id:b.id,name:b.name,kind:b.kind??"dm",accountId:b.accountId})),`mesh:${d.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s=this.workflowStore.get(n);if(!s){this.json(t,404,{error:`unknown workflow "${n}"`});return}let i=s.nodes.find(f=>f.type.startsWith("trigger."));if(!i){this.json(t,400,{error:`workflow "${n}" has no trigger node`});return}let o;try{o=await Q(e)}catch{o={}}let a=!!o?.force,c=o?.payload||{};if(i.type!=="trigger.manual"&&!a){this.json(t,409,{error:`workflow "${n}" trigger is "${i.type}"`,hint:'pass { "force": true } to fire anyway with a synthesized event (for testing)'});return}let l=i.config??{},d=a?String(l.source??"manual"):"manual",u=String(c.entityId||c.chatId||`manual-${Date.now().toString(36)}`),g={backend:a&&l.source?"channel":"manual",id:u},b=`manual:${n}:${u}:${Date.now()}`;try{let w=(await this.workflowDispatcher.dispatch({trigger:a?{source:d,project:l.filter?.project,repo:l.filter?.repo,chat:l.filter?.chat,labels:l.filter?.labels}:{source:"manual"},entityRef:g,event:{id:b,payload:c}})).runs[0]?.id;this.json(t,w?200:202,{ok:!0,runId:w,entityRef:g,source:d,force:a})}catch(f){this.log(`[workflows] manual run "${n}" failed: ${f.message}`),this.json(t,500,{error:f.message})}}},Ti=Ai;Fe(Ti,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/github/send-comment"]));function zw(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function Q(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function Kw(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function U(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}rg();function RC(r){typeof r=="string"&&(Nt.error(r),process.exit(1)),r instanceof Error&&(Nt.error(r.message),process.exit(1)),Nt.error("Something went wrong. Please try again."),process.exit(1)}export{ok as a,zs as b,_e as c,pt as d,yt as e,Ne as f,ln as g,Kv as h,Il as i,wm as j,km as k,El as l,Qe as m,Ze as n,Ie as o,R0 as p,Nl as q,Fl as r,j0 as s,N0 as t,Er as u,G$ as v,B$ as w,W$ as x,jd as y,Gf as z,K$ as A,q$ as B,jn as C,$t as D,uu as E,Hy as F,lx as G,Ru as H,Gn as I,ne as J,Bn as K,pb as L,Wu as M,mb as N,Et as O,zn as P,qn as Q,Qu as R,oi as S,be as T,he as U,oh as V,ah as W,ch as X,lh as Y,ms as Z,Xh as _,Si as $,Kh as aa,Dw as ba,VA as ca,Ti as da,RC as ea};
1057
- //# sourceMappingURL=chunk-4NXIJEYU.js.map
1057
+ //# sourceMappingURL=chunk-USTQPX4Y.js.map
@@ -1,4 +1,4 @@
1
- import{t as nt,u as rt}from"./chunk-ART666G6.js";import{b as ie,t as Xe,v as H,w as oe,y as ae}from"./chunk-NVJHA63C.js";import{g as qe,h as Je,i as Ye,k as Ze,l as Qe}from"./chunk-NEC4RXFT.js";import{d as et,e as tt}from"./chunk-AQASR6KR.js";import{q as Ge}from"./chunk-JHWBCDD2.js";import{w as Ke,z as An}from"./chunk-N5NPJ6DJ.js";import{existsSync as _n,readdirSync as Rn,readFileSync as Cn,statSync as Tn}from"fs";import{resolve as En}from"path";function st(t,e,n=Date.now(),s=7){let r=s*864e5,i=new Map;for(let o of e){let a=i.get(o.workflowId);a?a.push(o):i.set(o.workflowId,[o])}return t.map(o=>{let a=i.get(o.id)??[],c=a.filter(m=>n-m.at<=r),l=a.filter(m=>n-m.at>r&&n-m.at<=r*2),u=c.filter(m=>m.status==="failed").length,d=a.filter(m=>m.status==="paused").length,g=a.length?Math.max(...a.map(m=>m.at)):null,f=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:f,lastRunAt:g,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var z=new Map;function wi(t,e=1e3){if(!_n(t))return[];let n=Rn(t).filter(i=>i.endsWith(".jsonl")).map(i=>{let o=En(t,i);return{path:o,mtime:Tn(o).mtimeMs}}).sort((i,o)=>o.mtime-i.mtime).slice(0,e),s=new Set(n.map(i=>i.path));for(let i of z.keys())s.has(i)||z.delete(i);let r=[];for(let{path:i,mtime:o}of n){let a=z.get(i);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let c=Dn(i,o);z.set(i,{mtime:o,summary:c}),c&&r.push(c)}return r}function Dn(t,e){try{let n=Cn(t,"utf-8").split(`
1
+ import{t as nt,u as rt}from"./chunk-ART666G6.js";import{b as ie,t as Xe,v as H,w as oe,y as ae}from"./chunk-KSUCHOH2.js";import{g as qe,h as Je,i as Ye,k as Ze,l as Qe}from"./chunk-NEC4RXFT.js";import{d as et,e as tt}from"./chunk-AQASR6KR.js";import{q as Ge}from"./chunk-JHWBCDD2.js";import{w as Ke,z as An}from"./chunk-N5NPJ6DJ.js";import{existsSync as _n,readdirSync as Rn,readFileSync as Cn,statSync as Tn}from"fs";import{resolve as En}from"path";function st(t,e,n=Date.now(),s=7){let r=s*864e5,i=new Map;for(let o of e){let a=i.get(o.workflowId);a?a.push(o):i.set(o.workflowId,[o])}return t.map(o=>{let a=i.get(o.id)??[],c=a.filter(m=>n-m.at<=r),l=a.filter(m=>n-m.at>r&&n-m.at<=r*2),u=c.filter(m=>m.status==="failed").length,d=a.filter(m=>m.status==="paused").length,g=a.length?Math.max(...a.map(m=>m.at)):null,f=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:f,lastRunAt:g,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var z=new Map;function wi(t,e=1e3){if(!_n(t))return[];let n=Rn(t).filter(i=>i.endsWith(".jsonl")).map(i=>{let o=En(t,i);return{path:o,mtime:Tn(o).mtimeMs}}).sort((i,o)=>o.mtime-i.mtime).slice(0,e),s=new Set(n.map(i=>i.path));for(let i of z.keys())s.has(i)||z.delete(i);let r=[];for(let{path:i,mtime:o}of n){let a=z.get(i);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let c=Dn(i,o);z.set(i,{mtime:o,summary:c}),c&&r.push(c)}return r}function Dn(t,e){try{let n=Cn(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let s=JSON.parse(n[0]),r=s.run?.workflowId;if(!r)return null;let i=s.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),c=a.status??a.run?.status;if(c){i=c;break}}return{workflowId:r,status:i,at:e}}catch{return null}}var Ln={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},w={routines:200,summary:160,filters:6,filterValue:60,text:120},Pn=(t,e,n)=>{try{return Ge(t,e,n)}catch{return null}},it=864e5;function vi(t){let e=t.now??Date.now(),n={...Ln,...t.thresholds},s=t.nextFire??Pn,r=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",u=c.map(f=>({at:Date.parse(f.startedAt),status:f.status})),d=c[0],g={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,w.text),trigger:{schedule:$(a.schedule,w.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?le(a.nextRun)??le(s(a.schedule,new Date(e),l)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:Un(d.status==="success"?void 0:d.errorSummary,w.summary)}:null,lastSuccessAt:c.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:ot(u),sampledRuns:c.length,flags:[],attention:null};g.flags=at(g,u,a.schedule,l,null,e,n,s),r.push(lt(g))}let i=new Map(st(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let c=o.get(a.workflowId);c?c.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(A=>A.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},u=a.state||"active",d=u==="active",g=(o.get(a.id)??[]).slice().sort((A,se)=>se.at-A.at),f=g.map(A=>({at:A.at,status:Nn(A.status)})),m=f[0],h=c.type==="trigger.cron",y=typeof l.spec=="string"?l.spec:"",R=typeof l.timezone=="string"?l.timezone:"UTC",E={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,w.text),trigger:h?{schedule:$(y,w.text),timezone:R}:{event:$(typeof l.event=="string"?l.event:"",w.text),filters:Vn(l.filter,a)},agent:Mn(a),enabled:d,state:u,nextRunAt:h&&d&&y?le(s(y,new Date(e),R)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let A=f.find(se=>se.status==="success");return A?new Date(A.at).toISOString():null})(),consecutiveFailures:ot(f),sampledRuns:g.length,flags:[],attention:null},W=Date.parse(a.updated||a.created||"");E.flags=h?at(E,f,y,R,Number.isFinite(W)?W:null,e,n,s):On(E,i.get(a.id)?.state==="dormant",Number.isFinite(W)?W:null,e,n),r.push(lt(E))}return r.sort(jn).slice(0,w.routines)}function ot(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function at(t,e,n,s,r,i,o,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let g=ut(l,r,i,o);return g&&c.push(g),c}if(t.consecutiveFailures>=o.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let u=new Date(l),d=null;for(let g=0;g<o.missedFires&&(d=a(n,u,s),!!d);g++)u=d;return d&&i>d.getTime()+o.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${o.missedFires} scheduled fires missed`}),c}function On(t,e,n,s,r){let i=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=ut(o,n,s,r);return a&&i.push(a),i}return t.consecutiveFailures>=r.failStreak&&i.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===null?i.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&i.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),i}function ut(t,e,n,s){let r=Math.max(t??0,e??0);return r&&n-r<s.disabledDays*it?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/it)} days`:"Disabled and never ran"}}function lt(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var ct={critical:0,warning:1,info:2};function jn(t,e){let n=t.attention?ct[t.attention]:3,s=e.attention?ct[e.attention]:3;return n-s||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Nn(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Mn(t){if(t.ownerAgent)return $(t.ownerAgent,w.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),w.text):null}function Vn(t,e){let n=[],s=e?.project;if(s&&n.push($(`project=${s}`,w.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,i]of Object.entries(t)){let o=Array.isArray(i)?i.map(String):i==null?[]:[String(i)];o.length&&n.push($(`${r}=${o.join(",")}`,w.filterValue))}return n.slice(0,w.filters)}function le(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Un(t,e){return t===void 0?void 0:$(t,e)}import{createHash as Fn,randomBytes as dt}from"crypto";import{existsSync as Bn,mkdirSync as Wn,readFileSync as Hn,writeFileSync as zn}from"fs";import{resolve as Kn,dirname as Gn}from"path";var ce="agx_live_",Xn=".agentx/tokens.json",gt=class{file;constructor(e=process.cwd(),n=Xn){this.file=Kn(e,n)}load(){if(!Bn(this.file))return[];try{return JSON.parse(Hn(this.file,"utf-8"))}catch{return[]}}save(e){Wn(Gn(this.file),{recursive:!0}),zn(this.file,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8")}create(e){if(!e.name?.trim())throw new Error("Token name is required.");if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("At least one scope is required.");for(let o of e.scopes)if(!qn(o))throw new Error(`Invalid scope: ${o}`);let n=dt(32).toString("hex"),s=ce+n,r={id:"tok_"+dt(4).toString("hex"),name:e.name.trim(),prefix:ce+n.slice(0,4),hash:ft(s),scopes:[...e.scopes],createdAt:new Date().toISOString(),expiresAt:e.expiresInDays?new Date(Date.now()+e.expiresInDays*86400*1e3).toISOString():void 0},i=this.load();return i.push(r),this.save(i),{token:s,record:r}}list(){return this.load()}revoke(e){let n=this.load(),s=n.find(r=>r.id===e);return s?(s.revokedAt=new Date().toISOString(),this.save(n),s):null}isActive(e){let n=this.load().find(s=>s.id===e);return!!n&&!n.revokedAt&&!(n.expiresAt&&Date.parse(n.expiresAt)<Date.now())}verify(e){if(!e||!e.startsWith(ce))return null;let n=ft(e),s=this.load(),r=s.find(a=>a.hash===n);if(!r||r.revokedAt||r.expiresAt&&Date.parse(r.expiresAt)<Date.now())return null;let i=Date.now(),o=r.lastUsedAt?Date.parse(r.lastUsedAt):0;if(i-o>6e4){r.lastUsedAt=new Date(i).toISOString();try{this.save(s)}catch{}}return r}};function Ci(t,e){return!!(t.scopes.includes(e)||e.startsWith("agent:")&&t.scopes.includes("agent:*")||e==="dashboard:read"&&t.scopes.includes("dashboard:write"))}function qn(t){return t==="dashboard:read"||t==="dashboard:write"||t==="agent:*"||/^agent:[a-z0-9][a-z0-9_-]*$/.test(t)||t==="mesh:peer"||t==="app"}function ft(t){return"sha256:"+Fn("sha256").update(t).digest("hex")}function Ti(t){let e=t.headers.authorization,n=Array.isArray(e)?e[0]:e;if(n&&n.toLowerCase().startsWith("bearer "))return n.slice(7).trim();if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{}return null}import{existsSync as ue,readdirSync as gr,readFileSync as fr}from"fs";import{resolve as L}from"path";import{existsSync as Jn,mkdirSync as Yn,readdirSync as Zn,readFileSync as Qn,renameSync as er,writeFileSync as tr}from"fs";import{resolve as pt}from"path";var mt=["discard","keep","pause","approve"],v={title:120,ask:300,recommend:300,source:500,note:500,pendingPerAgent:25},nr={defaultExpiryDays:3,maxExpiryDays:30};function D(t){return pt(t,".agentx","approvals")}var rr=/^[a-z0-9][a-z0-9-]{0,80}$/;function ht(t){return rr.test(t)}function yt(t,e){if(!ht(e))throw new Error(`invalid card id: ${e}`);return pt(D(t),`${e}.json`)}function sr(t,e){let n=new Date(t).toISOString().slice(0,10),s=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${n}-${s||"card"}-${Math.random().toString(36).slice(2,6)}`}function K(t,e){Yn(D(t),{recursive:!0});let n=yt(t,e.id),s=`${n}.${process.pid}.tmp`;tr(s,JSON.stringify(e,null,2)+`
4
4
  `),er(s,n)}function M(t,e){if(!ht(e))return null;try{return JSON.parse(Qn(yt(t,e),"utf-8"))}catch{return null}}function V(t,e){let n=D(t);if(!Jn(n))return[];let s=[];for(let r of Zn(n).filter(i=>i.endsWith(".json")&&!i.startsWith("_")).sort()){let i=M(t,r.slice(0,-5));i&&(!e||i.status===e)&&s.push(i)}return s}function k(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function ir(t,e,n){let s=e+n.maxExpiryDays*864e5,r,i=k(t);if(!i)r=e+n.defaultExpiryDays*864e5;else{let o=/^(\d+)\s*([hd])$/i.exec(i);if(o)r=e+Number(o[1])*(o[2].toLowerCase()==="d"?864e5:36e5);else if(r=Date.parse(i),Number.isNaN(r))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${i}")`}}return r<=e?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(r,s)).toISOString()}}function or(t,e={}){let n=e.now??Date.now(),s=e.settings??nr,r=k(t.title),i=k(t.ask),o=k(t.recommend),a=k(t.raised_by);if(!r)return{ok:!1,error:"title is required"};if(!i)return{ok:!1,error:"ask is required: the yes/no question"};if(!o)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!a)return{ok:!1,error:"raised_by is required: the agent id"};if(r.length>v.title)return{ok:!1,error:`title is longer than ${v.title} characters`};if(i.length>v.ask)return{ok:!1,error:`ask is longer than ${v.ask} characters`};if(o.length>v.recommend)return{ok:!1,error:`recommend is longer than ${v.recommend} characters`};let c=k(t.if_silent).toLowerCase();if(!mt.includes(c))return{ok:!1,error:`if_silent must be one of ${mt.join(", ")}`};let l=ir(t.expires,n,s);if(!l.ok)return l;let u=k(t.source);if(u.length>v.source)return{ok:!1,error:`source is longer than ${v.source} characters`};if(u&&/^[a-z][a-z0-9+.-]*:/i.test(u)&&!/^https?:\/\//i.test(u))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let d,g=t.reply;return g&&typeof g=="object"&&k(g.channel)&&k(g.chatId)&&(d={channel:k(g.channel),chatId:k(g.chatId),...k(g.accountId)?{accountId:k(g.accountId)}:{}}),{ok:!0,card:{id:sr(n,r),title:r,ask:i,recommend:o,if_silent:c,expires:l.at,...u?{source:u}:{},raised_by:a,created_at:new Date(n).toISOString(),...d?{reply:d}:{},status:"pending"}}}function Pi(t,e,n={}){let s=or(e,n);if(!s.ok)return s;let r=V(t,"pending").filter(i=>i.raised_by===s.card.raised_by).length;return r>=v.pendingPerAgent?{ok:!1,error:`${s.card.raised_by} already has ${r} cards waiting; wait for decisions before raising more`}:(K(t,s.card),s)}function bt(t,e,n,s={}){let r=M(t,e);if(!r)return{ok:!1,error:`no card "${e}"`};if(r.status!=="pending")return{ok:!1,error:`card "${e}" is already ${r.status}`};let i=k(s.note).slice(0,v.note),o={...r,status:"decided",verdict:n,decided_by:s.by??"operator",decided_at:new Date(s.now??Date.now()).toISOString(),...i?{note:i}:{}};return K(t,o),{ok:!0,card:o}}function Oi(t,e=Date.now()){let n=[];for(let s of V(t,"pending")){if(Date.parse(s.expires)>e)continue;let r={...s,status:"expired",outcome:s.if_silent,decided_by:"expiry",decided_at:new Date(e).toISOString()};K(t,r),n.push(r)}return n}function ji(t){return V(t).filter(e=>e.status!=="pending"&&!e.agent_notified_at)}function Ni(t,e,n=Date.now()){let s=M(t,e);!s||s.agent_notified_at||K(t,{...s,agent_notified_at:new Date(n).toISOString()})}function Mi(t){let e=t.status==="decided"?t.verdict==="yes"?"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${t.outcome??t.if_silent}.`,n=[`[Approval result] Your decision card "${t.title}" (${t.id}) is closed.`,`Question: ${t.ask}`,e];return t.note&&n.push(`Operator note: ${t.note}`),t.source&&n.push(`Source: ${t.source}`),t.reply&&n.push(`You raised it from ${t.reply.channel} chat ${t.reply.chatId}; reply there if the requester should know.`),n.push("Act on this result now. Do not raise the same card again."),n.join(`
@@ -128,4 +128,4 @@ Document the arguments, commands, or files the skill expects. Example:
128
128
  claude-code ${ze(t)} --arg value
129
129
  \`\`\`
130
130
  `}An();var xn={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function $n(t){return{...xn,...t??{},regions:{...t?.regions??{}},buffer:{...xn.buffer,...t?.buffer??{}}}}function za(t){try{return $n(Ke(t).screen)}catch{return $n(void 0)}}var yi=/^[a-z][\w-]*$/,vn=["window","screen","menubar","notifications"];function B(t,e,n,s){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${s}`);return r}var re=(t,e)=>B(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function In(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Ka(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=re(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=re(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=re(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=B(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=B(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[i,o]of Object.entries(e.regions)){if(!yi.test(i))throw new Error(`region name "${i}" must be lowercase letters, digits, - or _`);o===null?delete r[i]:r[i]=In(o)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,i={...n.buffer??{}};"enabled"in r&&(i.enabled=!!r.enabled),"seconds"in r&&(i.seconds=B(r.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in r&&(i.fps=B(r.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in r&&(i.maxPixels=re(r.maxPixels,"buffer.maxPixels")),"region"in r&&(i.region=String(r.region).trim()),n.buffer=i}let s=n.buffer?.region;if(s!==void 0&&!vn.includes(s)&&!n.regions?.[s])try{In(s)}catch{throw new Error(`buffer.region "${s}" is not a region \u2014 use ${[...vn,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{st as a,wi as b,xe as c,Mr as d,Vr as e,Io as f,Ao as g,_o as h,Lt as i,Co as j,w as k,vi as l,gt as m,Ci as n,ft as o,Ti as p,mt as q,ht as r,M as s,Pi as t,Oi as u,ji as v,Ni as w,Mi as x,G as y,Wi as z,Qi as A,eo as B,Oo as C,Qr as D,jo as E,no as F,ro as G,so as H,io as I,oo as J,ao as K,co as L,uo as M,Re as N,zo as O,Z as P,Te as Q,_s as R,ta as S,na as T,ra as U,Zt as V,sa as W,C as X,nn as Y,rn as Z,ua as _,js as $,cn as aa,Us as ba,je as ca,fn as da,Hs as ea,zs as fa,pa as ga,Ks as ha,Ne as ia,Gs as ja,Xs as ka,dn as la,hn as ma,ha as na,Ys as oa,ya as pa,Ra as qa,Ca as ra,di as sa,Ta as ta,bn as ua,q as va,ho as wa,Tt as xa,fe as ya,we as za,$o as Aa,Pa as Ba,Oa as Ca,ja as Da,Na as Ea,Ma as Fa,Va as Ga,Ua as Ha,Fa as Ia,Ba as Ja,xn as Ka,$n as La,za as Ma,vn as Na,Ka as Oa};
131
- //# sourceMappingURL=chunk-B65FS265.js.map
131
+ //# sourceMappingURL=chunk-X5BWHPR7.js.map
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{a as n}from"./chunk-5AMQFDLE.js";import"./chunk-G3SOCQII.js";import"./chunk-APKKQGTG.js";import"./chunk-HEJOWP7O.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-4NXIJEYU.js";import"./chunk-B65FS265.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-F2DEKA2Q.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-ART666G6.js";import"./chunk-2D3RYIDU.js";import"./chunk-L53FTKEP.js";import"./chunk-QDRAKJSY.js";import"./chunk-NVJHA63C.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-BYKF3UTL.js";import"./chunk-SFQUP3BP.js";import"./chunk-NEC4RXFT.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-JHWBCDD2.js";import"./chunk-APKAW7LU.js";import"./chunk-ST6KPQOY.js";import"./chunk-GQ76J72O.js";import"./chunk-ZXR6GNEK.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-Q2WW2HF4.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-S4ASFOJU.js";import"./chunk-CUZWGTXT.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-KSDVKLHN.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-VOS2IW4V.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-SZJMS7K4.js";import"./chunk-7I7IEX4S.js";import"./chunk-VDMYBPYB.js";import"./chunk-DSYKYZMT.js";import"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";var r=["SIGINT","SIGTERM"];function o(t=process){for(let i of r)t.on(i,()=>{t.listenerCount(i)<=1&&t.exit(0)})}o();async function s(){let t=await n();if(process.argv.slice(2).length===0){t.outputHelp();return}t.parse()}s();
2
+ import{a as n}from"./chunk-37P3DKSX.js";import"./chunk-G3SOCQII.js";import"./chunk-APKKQGTG.js";import"./chunk-HEJOWP7O.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-USTQPX4Y.js";import"./chunk-X5BWHPR7.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-F2DEKA2Q.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-ART666G6.js";import"./chunk-2D3RYIDU.js";import"./chunk-L53FTKEP.js";import"./chunk-3XEN24B7.js";import"./chunk-KSUCHOH2.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-PDGPHE35.js";import"./chunk-SFQUP3BP.js";import"./chunk-NEC4RXFT.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-JHWBCDD2.js";import"./chunk-APKAW7LU.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-Q2WW2HF4.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-S4ASFOJU.js";import"./chunk-CUZWGTXT.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-KSDVKLHN.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-VOS2IW4V.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-SZJMS7K4.js";import"./chunk-7I7IEX4S.js";import"./chunk-VDMYBPYB.js";import"./chunk-DSYKYZMT.js";import"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";var r=["SIGINT","SIGTERM"];function o(t=process){for(let i of r)t.on(i,()=>{t.listenerCount(i)<=1&&t.exit(0)})}o();async function s(){let t=await n();if(process.argv.slice(2).length===0){t.outputHelp();return}t.parse()}s();
3
3
  //# sourceMappingURL=cli.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e,f}from"./chunk-KXR6GVL7.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-QIJLFPWE.js";export{d as approveFactProposal,c as listFactProposals,a as parseClaim,b as proposeFacts,e as rejectFactProposal,f as routeMemo};
2
+ //# sourceMappingURL=fact-proposals-LZWS5KFO.js.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as L}from"./chunk-Y57CULGE.js";import{a as St,b as kt,c as vt,d as xt,da as Tt,e as $t,ea as Mt,f as Ct,g as Pt,h as bt}from"./chunk-4NXIJEYU.js";import"./chunk-B65FS265.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-F2DEKA2Q.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-ART666G6.js";import"./chunk-2D3RYIDU.js";import"./chunk-L53FTKEP.js";import{S as yt,l as lt,m as ct,n as dt,o as mt,p as pt}from"./chunk-QDRAKJSY.js";import"./chunk-NVJHA63C.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-BYKF3UTL.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-NEC4RXFT.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-JHWBCDD2.js";import"./chunk-APKAW7LU.js";import"./chunk-ST6KPQOY.js";import"./chunk-GQ76J72O.js";import"./chunk-ZXR6GNEK.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-Q2WW2HF4.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-S4ASFOJU.js";import{a as gt,b as ft,e as ht}from"./chunk-CUZWGTXT.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-KSDVKLHN.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import{j as it,k as rt,l as at}from"./chunk-VOS2IW4V.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-SZJMS7K4.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{a as Fe,b as Le,c as A,d as De}from"./chunk-VDMYBPYB.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{u as tt,w as st,x as ot,z as nt}from"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
1
+ import{a as L}from"./chunk-Y57CULGE.js";import{a as St,b as kt,c as vt,d as xt,da as Tt,e as $t,ea as Mt,f as Ct,g as Pt,h as bt}from"./chunk-USTQPX4Y.js";import"./chunk-X5BWHPR7.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-F2DEKA2Q.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-ART666G6.js";import"./chunk-2D3RYIDU.js";import"./chunk-L53FTKEP.js";import{S as yt,l as lt,m as ct,n as dt,o as mt,p as pt}from"./chunk-3XEN24B7.js";import"./chunk-KSUCHOH2.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-PDGPHE35.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-NEC4RXFT.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-JHWBCDD2.js";import"./chunk-APKAW7LU.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-Q2WW2HF4.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-S4ASFOJU.js";import{a as gt,b as ft,e as ht}from"./chunk-CUZWGTXT.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-KSDVKLHN.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import{j as it,k as rt,l as at}from"./chunk-VOS2IW4V.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-SZJMS7K4.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{a as Fe,b as Le,c as A,d as De}from"./chunk-VDMYBPYB.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{u as tt,w as st,x as ot,z as nt}from"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
4
  ${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-EVHZ2R73.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
@@ -0,0 +1,2 @@
1
+ import{b,c,d,e,f}from"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import{a}from"./chunk-ILEC3IAV.js";import"./chunk-QIJLFPWE.js";export{c as FactLedger,a as assertPerson,d as factContradictions,b as factId,e as isStaleFact,f as matchFact};
2
+ //# sourceMappingURL=ledger-CH7R756S.js.map
@@ -1,2 +1,2 @@
1
- import{a}from"./chunk-5AMQFDLE.js";import"./chunk-G3SOCQII.js";import"./chunk-APKKQGTG.js";import"./chunk-HEJOWP7O.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-4NXIJEYU.js";import"./chunk-B65FS265.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-F2DEKA2Q.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-ART666G6.js";import"./chunk-2D3RYIDU.js";import"./chunk-L53FTKEP.js";import"./chunk-QDRAKJSY.js";import"./chunk-NVJHA63C.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-BYKF3UTL.js";import"./chunk-SFQUP3BP.js";import"./chunk-NEC4RXFT.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-JHWBCDD2.js";import"./chunk-APKAW7LU.js";import"./chunk-ST6KPQOY.js";import"./chunk-GQ76J72O.js";import"./chunk-ZXR6GNEK.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-Q2WW2HF4.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-S4ASFOJU.js";import"./chunk-CUZWGTXT.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-KSDVKLHN.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-VOS2IW4V.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-SZJMS7K4.js";import"./chunk-7I7IEX4S.js";import"./chunk-VDMYBPYB.js";import"./chunk-DSYKYZMT.js";import"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as buildProgram};
2
- //# sourceMappingURL=program-6PFRDQFT.js.map
1
+ import{a}from"./chunk-37P3DKSX.js";import"./chunk-G3SOCQII.js";import"./chunk-APKKQGTG.js";import"./chunk-HEJOWP7O.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-USTQPX4Y.js";import"./chunk-X5BWHPR7.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-F2DEKA2Q.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-ART666G6.js";import"./chunk-2D3RYIDU.js";import"./chunk-L53FTKEP.js";import"./chunk-3XEN24B7.js";import"./chunk-KSUCHOH2.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-PDGPHE35.js";import"./chunk-SFQUP3BP.js";import"./chunk-NEC4RXFT.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-JHWBCDD2.js";import"./chunk-APKAW7LU.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-Q2WW2HF4.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-S4ASFOJU.js";import"./chunk-CUZWGTXT.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-KSDVKLHN.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-VOS2IW4V.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-SZJMS7K4.js";import"./chunk-7I7IEX4S.js";import"./chunk-VDMYBPYB.js";import"./chunk-DSYKYZMT.js";import"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as buildProgram};
2
+ //# sourceMappingURL=program-44FEGUCB.js.map
@@ -0,0 +1,2 @@
1
+ import{b as a,c as b}from"./chunk-ILEC3IAV.js";import"./chunk-QIJLFPWE.js";export{b as QuestionStore,a as questionId};
2
+ //# sourceMappingURL=questions-ZATLU5AW.js.map
@@ -1,2 +1,2 @@
1
- import{I as a,J as b,K as c,L as d,M as e,N as f,O as g,P as h,Q as i,R as j,S as k,T as l}from"./chunk-QDRAKJSY.js";import"./chunk-NVJHA63C.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-JHWBCDD2.js";import"./chunk-APKAW7LU.js";import"./chunk-ST6KPQOY.js";import"./chunk-GQ76J72O.js";import"./chunk-ZXR6GNEK.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-Q2WW2HF4.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-S4ASFOJU.js";import"./chunk-CUZWGTXT.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-KSDVKLHN.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-VOS2IW4V.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-SZJMS7K4.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{k as AgentRegistry,f as TRACE_STEP_SUMMARY_BYTES,c as buildEntryMeta,d as buildEventDigest,e as buildWikiContext,g as clipForTrace,j as emitTraceStepsFromStreamEvent,i as firstMissingRequiredTool,b as getGlobalRegistry,l as richReplyPrompt,a as setGlobalRegistry,h as tallyToolUses};
2
- //# sourceMappingURL=registry-KP3C4EZ4.js.map
1
+ import{I as a,J as b,K as c,L as d,M as e,N as f,O as g,P as h,Q as i,R as j,S as k,T as l}from"./chunk-3XEN24B7.js";import"./chunk-KSUCHOH2.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-JHWBCDD2.js";import"./chunk-APKAW7LU.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-Q2WW2HF4.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-S4ASFOJU.js";import"./chunk-CUZWGTXT.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-KSDVKLHN.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-VOS2IW4V.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-SZJMS7K4.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{k as AgentRegistry,f as TRACE_STEP_SUMMARY_BYTES,c as buildEntryMeta,d as buildEventDigest,e as buildWikiContext,g as clipForTrace,j as emitTraceStepsFromStreamEvent,i as firstMissingRequiredTool,b as getGlobalRegistry,l as richReplyPrompt,a as setGlobalRegistry,h as tallyToolUses};
2
+ //# sourceMappingURL=registry-HMVIS6QJ.js.map
@@ -1,2 +1,2 @@
1
- import{f as o}from"./chunk-AU6FFC4I.js";import"./chunk-ST6KPQOY.js";import"./chunk-GQ76J72O.js";import"./chunk-ZXR6GNEK.js";import"./chunk-QIJLFPWE.js";function s(r,n,t){let e=o(t.wikiDir,t.memo,{agentId:t.agentId,origin:t.reason==="continuity"?"continuity-memo":`rotation-memo:${t.reason}`,chat:`${t.channel}:${t.chatId}`});if(e.workState.trim()){let a=t.chatId.split(/[:@.]/).filter(Boolean).slice(0,4);r.addMemory(t.agentId,{agentId:t.agentId,category:"task-state",content:`[Rotation memo \xB7 ${t.reason}] ${e.workState}`,keywords:["rotation-memo",t.channel,...a],source:{channel:t.channel,chatId:t.chatId,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}})}return n.setRotationMemo(t.agentId,t.channel,t.chatId,e.pinned,t.reason),{proposals:e.proposals.length,...e.error?{error:e.error}:{}}}export{s as storeRotationMemo};
2
- //# sourceMappingURL=rotation-memo-store-X63HYIMV.js.map
1
+ import{f as o}from"./chunk-KXR6GVL7.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-QIJLFPWE.js";function s(r,n,t){let e=o(t.wikiDir,t.memo,{agentId:t.agentId,origin:t.reason==="continuity"?"continuity-memo":`rotation-memo:${t.reason}`,chat:`${t.channel}:${t.chatId}`});if(e.workState.trim()){let a=t.chatId.split(/[:@.]/).filter(Boolean).slice(0,4);r.addMemory(t.agentId,{agentId:t.agentId,category:"task-state",content:`[Rotation memo \xB7 ${t.reason}] ${e.workState}`,keywords:["rotation-memo",t.channel,...a],source:{channel:t.channel,chatId:t.chatId,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}})}return n.setRotationMemo(t.agentId,t.channel,t.chatId,e.pinned,t.reason),{proposals:e.proposals.length,...e.error?{error:e.error}:{}}}export{s as storeRotationMemo};
2
+ //# sourceMappingURL=rotation-memo-store-A4YW6FSK.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentix-cli",
3
- "version": "0.69.0",
3
+ "version": "0.69.1",
4
4
  "description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -1,5 +0,0 @@
1
- import{b as g}from"./chunk-ST6KPQOY.js";import{c as l,j as u,k as d}from"./chunk-GQ76J72O.js";import{createHash as w}from"crypto";var v=(t,r)=>"fp-"+w("sha1").update(`${t}\0${r.toLowerCase().replace(/\s+/g," ").trim()}`).digest("hex").slice(0,10);function P(t){let r=t.replace(/^[-*•]\s*/,"").replace(/\s*\((?:[^)]*)\)\s*$/,"").trim(),s=r.match(/^(.{2,60}?)\s+(?:is|are|was|were|has been|went|got)\s+(.{1,80})$/i);if(!s)return{};let a=l(r);return{subject:s[1].trim(),attribute:a==="stable"?"state":`${a} status`,value:s[2].trim()}}function m(t,r,s){let a=t.at??new Date().toISOString(),e=d(s),o=l(s);return{id:r,status:"pending",claim:s,...P(s),volatility:o==="stable"?"work-state":o,source:e?.source??`${t.origin} (unchecked summary)`,verifiedAt:e?.verifiedAt??a,verifiedBy:t.agentId,origin:t.origin,agentId:t.agentId,...t.chat?{chat:t.chat}:{},createdAt:a}}function b(t,r){return r.length===0?[]:t.update(s=>{let a=[],e=!1;for(let o of r){let i=o.claim.replace(/^[-*•]\s*/,"").trim();if(!i)continue;let c=v(o.agentId,i),n=s.proposals.find(h=>h.id===c);if(n){a.push(n);continue}let p=m(o,c,i);s.proposals.push(p),a.push(p),e=!0}return{save:e,result:a}})}function S(t,r){return t.load().proposals.filter(s=>!r||s.status===r)}var f=(t,r)=>t.id===r||r.length>=6&&t.id.startsWith(r);function y(t,r){return t.load().proposals.find(s=>f(s,r))}function F(t,r,s){return t.update(a=>{let e=a.proposals.find(o=>f(o,r));if(!e)throw new Error(`no fact proposal "${r}"`);if(e.status!=="pending")throw new Error(`proposal ${e.id} is already ${e.status}`);return Object.assign(e,s),{save:!0,result:e}})}function k(t,r,s,a={}){let e=y(t,r);if(!e)throw new Error(`no fact proposal "${r}"`);if(e.status!=="pending")throw new Error(`proposal ${e.id} is already ${e.status}`);let o=a.subject??e.subject,i=a.attribute??e.attribute,c=a.value??e.value;if(!o||!i||!c)throw new Error("could not read a subject, attribute and value from the claim; pass --subject, --attribute and --value");let n=t.write({subject:o,attribute:i,value:c,source:a.source??e.source,verifiedBy:e.verifiedBy,verifiedAt:e.verifiedAt,volatility:e.volatility},{confirmedBy:s});return{proposal:F(t,e.id,{status:"approved",decidedAt:new Date().toISOString(),decidedBy:s}),write:n}}function x(t,r,s,a){return F(t,r,{status:"rejected",decidedAt:new Date().toISOString(),decidedBy:s,...a?{reason:a}:{}})}function A(t,r,s){let{workState:a,claims:e}=u(r);if(e.length===0)return{workState:a.join(`
2
- `),pinned:r,proposals:[]};let o=[],i;try{o=b(new g(t),e.map(n=>({claim:n,...s})))}catch(n){i=String(n?.message??n)}let c=e.map((n,p)=>`- UNVERIFIED claim (${o[p]?`wiki proposal ${o[p].id}`:"not checked"}): ${n.replace(/^[-*•]\s*/,"")}`);return{workState:a.join(`
3
- `),pinned:[...a,...c].join(`
4
- `),proposals:o,...i?{error:i}:{}}}export{P as a,b,S as c,k as d,x as e,A as f};
5
- //# sourceMappingURL=chunk-AU6FFC4I.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/wiki/facts/fact-proposals.ts"],"sourcesContent":["import { createHash } from \"crypto\"\nimport { citedCheck, classifyFact, splitMemo, type FactClass } from \"@/agents/fact-freshness\"\nimport { FactLedger, type FactInput, type WriteResult } from \"./ledger\"\n\n// --- Fact proposals: what a session summary claims, waiting for a check ---\n//\n// A rotation or continuity memo is a model's summary of a session. When it\n// says \"the vendor account is past due\", that is a claim nobody checked in\n// this form, and storing it as memory is how a stale note became a stated\n// fact (#273). So memo claims about outside systems come here instead,\n// with where they came from. They reach the ledger only when a person\n// approves one (a confirmation), never on their own.\n\nexport type FactProposalStatus = \"pending\" | \"approved\" | \"rejected\"\n\nexport interface FactProposal {\n id: string\n status: FactProposalStatus\n /** The line as the memo stated it. */\n claim: string\n /** Best guess at the structured fact, editable on approval. */\n subject?: string\n attribute?: string\n value?: string\n volatility: FactClass\n /** The check the memo cited, or where the claim came from. */\n source: string\n /** When that check happened, or when the memo was written. */\n verifiedAt: string\n verifiedBy: string\n /** e.g. \"rotation-memo:tier-2\" or \"continuity-memo\". */\n origin: string\n agentId: string\n chat?: string\n createdAt: string\n decidedAt?: string\n decidedBy?: string\n reason?: string\n}\n\nexport interface ProposalInput {\n claim: string\n agentId: string\n origin: string\n chat?: string\n at?: string\n}\n\nconst proposalId = (agentId: string, claim: string) =>\n \"fp-\" + createHash(\"sha1\").update(`${agentId}\\u0000${claim.toLowerCase().replace(/\\s+/g, \" \").trim()}`).digest(\"hex\").slice(0, 10)\n\n/** \"X is Y\" → subject X, value Y, attribute named after the class. */\nexport function parseClaim(claim: string): { subject?: string; attribute?: string; value?: string } {\n const text = claim.replace(/^[-*•]\\s*/, \"\").replace(/\\s*\\((?:[^)]*)\\)\\s*$/, \"\").trim()\n const m = text.match(/^(.{2,60}?)\\s+(?:is|are|was|were|has been|went|got)\\s+(.{1,80})$/i)\n if (!m) return {}\n const cls = classifyFact(text)\n return { subject: m[1].trim(), attribute: cls === \"stable\" ? \"state\" : `${cls} status`, value: m[2].trim() }\n}\n\nfunction newProposal(it: ProposalInput, id: string, claim: string): FactProposal {\n const at = it.at ?? new Date().toISOString()\n const cited = citedCheck(claim)\n const cls = classifyFact(claim)\n return {\n id, status: \"pending\", claim, ...parseClaim(claim),\n // A summary's claim is never stable: at best it was true that day.\n volatility: cls === \"stable\" ? \"work-state\" : cls,\n source: cited?.source ?? `${it.origin} (unchecked summary)`,\n verifiedAt: cited?.verifiedAt ?? at,\n verifiedBy: it.agentId,\n origin: it.origin, agentId: it.agentId,\n ...(it.chat ? { chat: it.chat } : {}),\n createdAt: at,\n }\n}\n\n/** Queue claims, under the ledger's lock. The same claim from the same\n * agent is kept once. Throws on an unreadable ledger rather than\n * writing over it. */\nexport function proposeFacts(ledger: FactLedger, items: ProposalInput[]): FactProposal[] {\n if (items.length === 0) return []\n return ledger.update((data) => {\n const out: FactProposal[] = []\n let added = false\n for (const it of items) {\n const claim = it.claim.replace(/^[-*•]\\s*/, \"\").trim()\n if (!claim) continue\n const id = proposalId(it.agentId, claim)\n const seen = data.proposals.find((p) => p.id === id)\n if (seen) { out.push(seen); continue }\n const p = newProposal(it, id, claim)\n data.proposals.push(p)\n out.push(p)\n added = true\n }\n return { save: added, result: out }\n })\n}\n\nexport function listFactProposals(ledger: FactLedger, status?: FactProposalStatus): FactProposal[] {\n return ledger.load().proposals.filter((p) => !status || p.status === status)\n}\n\nconst matches = (x: FactProposal, id: string) => x.id === id || (id.length >= 6 && x.id.startsWith(id))\n\nfunction findProposal(ledger: FactLedger, id: string): FactProposal | undefined {\n return ledger.load().proposals.find((x) => matches(x, id))\n}\n\n/** Decide a pending proposal under the ledger's lock. */\nfunction decide(ledger: FactLedger, id: string, fields: Partial<FactProposal>): FactProposal {\n return ledger.update((data) => {\n const p = data.proposals.find((x) => matches(x, id))\n if (!p) throw new Error(`no fact proposal \"${id}\"`)\n if (p.status !== \"pending\") throw new Error(`proposal ${p.id} is already ${p.status}`)\n Object.assign(p, fields)\n return { save: true, result: p }\n })\n}\n\n/**\n * Approve a claim: a person confirms it, so it is written to the ledger\n * with their name, even over a newer-dated value.\n */\nexport function approveFactProposal(\n ledger: FactLedger, id: string, by: string,\n edit: Partial<Pick<FactInput, \"subject\" | \"attribute\" | \"value\" | \"source\">> = {},\n): { proposal: FactProposal; write: WriteResult } {\n const p = findProposal(ledger, id)\n if (!p) throw new Error(`no fact proposal \"${id}\"`)\n if (p.status !== \"pending\") throw new Error(`proposal ${p.id} is already ${p.status}`)\n const subject = edit.subject ?? p.subject\n const attribute = edit.attribute ?? p.attribute\n const value = edit.value ?? p.value\n if (!subject || !attribute || !value) {\n throw new Error(\"could not read a subject, attribute and value from the claim; pass --subject, --attribute and --value\")\n }\n const write = ledger.write(\n { subject, attribute, value, source: edit.source ?? p.source, verifiedBy: p.verifiedBy, verifiedAt: p.verifiedAt, volatility: p.volatility },\n { confirmedBy: by },\n )\n const proposal = decide(ledger, p.id, { status: \"approved\", decidedAt: new Date().toISOString(), decidedBy: by })\n return { proposal, write }\n}\n\nexport function rejectFactProposal(ledger: FactLedger, id: string, by: string, reason?: string): FactProposal {\n return decide(ledger, id, { status: \"rejected\", decidedAt: new Date().toISOString(), decidedBy: by, ...(reason ? { reason } : {}) })\n}\n\n/**\n * Route a session memo: claims about outside systems become proposals;\n * the rest is work state. `pinned` is what the next fresh session reads,\n * with each claim marked unverified and pointing at its proposal.\n */\nexport function routeMemo(\n wikiDir: string, memo: string, ctx: { agentId: string; origin: string; chat?: string },\n): { workState: string; pinned: string; proposals: FactProposal[]; error?: string } {\n const { workState, claims } = splitMemo(memo)\n if (claims.length === 0) return { workState: workState.join(\"\\n\"), pinned: memo, proposals: [] }\n let proposals: FactProposal[] = []\n let error: string | undefined\n try {\n proposals = proposeFacts(new FactLedger(wikiDir), claims.map((claim) => ({ claim, ...ctx })))\n } catch (e) {\n // An unwritable wiki must not lose the memo: claims stay out of\n // memory and are pinned for this chat only, still marked.\n error = String((e as Error)?.message ?? e)\n }\n const flagged = claims.map((c, i) =>\n `- UNVERIFIED claim (${proposals[i] ? `wiki proposal ${proposals[i].id}` : \"not checked\"}): ${c.replace(/^[-*•]\\s*/, \"\")}`)\n return { workState: workState.join(\"\\n\"), pinned: [...workState, ...flagged].join(\"\\n\"), proposals, ...(error ? { error } : {}) }\n}\n"],"mappings":"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","names":["createHash","proposalId","agentId","claim","createHash","parseClaim","text","m","cls","classifyFact","newProposal","it","id","at","cited","citedCheck","proposeFacts","ledger","items","data","out","added","seen","p","listFactProposals","status","matches","x","findProposal","decide","fields","approveFactProposal","by","edit","subject","attribute","value","write","rejectFactProposal","reason","routeMemo","wikiDir","memo","ctx","workState","claims","splitMemo","proposals","error","FactLedger","e","flagged","c","i"]}