agentix-cli 0.69.4 → 0.70.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-IDAWXA3K.js → agent-V223TG6H.js} +2 -2
- package/dist/{board-dashboard-MAP6A2N7.js → board-dashboard-HR3PQPFW.js} +2 -2
- package/dist/{board-dashboard-MAP6A2N7.js.map → board-dashboard-HR3PQPFW.js.map} +1 -1
- package/dist/{chunk-CKBAVCGU.js → chunk-3IY2YWXP.js} +2 -2
- package/dist/{chunk-J7HA7ZTU.js → chunk-3RC4LO2G.js} +2 -2
- package/dist/{chunk-M6GPRMCQ.js → chunk-6QDOUOKD.js} +2 -2
- package/dist/{chunk-64P4QHSZ.js → chunk-CECHWYJ2.js} +1 -1
- package/dist/{chunk-64P4QHSZ.js.map → chunk-CECHWYJ2.js.map} +1 -1
- package/dist/{chunk-K63IOY6A.js → chunk-FBDIJEKL.js} +4 -4
- package/dist/chunk-FBDIJEKL.js.map +1 -0
- package/dist/{chunk-OHRTBD7U.js → chunk-LHLNARRW.js} +9 -9
- package/dist/chunk-ML6CNRBK.js +105 -0
- package/dist/chunk-ML6CNRBK.js.map +1 -0
- package/dist/{chunk-5ONI54E6.js → chunk-PHDS2HIN.js} +118 -118
- package/dist/chunk-PHDS2HIN.js.map +1 -0
- package/dist/{chunk-2UYV24UD.js → chunk-SN5N2FPG.js} +2 -2
- package/dist/chunk-TLDQWTSW.js +49 -0
- package/dist/chunk-TLDQWTSW.js.map +1 -0
- package/dist/chunk-TTVVXBCM.js +2 -0
- package/dist/chunk-TTVVXBCM.js.map +1 -0
- package/dist/{chunk-IU6L4V3A.js → chunk-W7SEPJFH.js} +2 -2
- package/dist/chunk-WLMQ5JMX.js +6 -0
- package/dist/chunk-WLMQ5JMX.js.map +1 -0
- package/dist/{chunk-DQQ3BCJW.js → chunk-YK7GFEGO.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/graph-FJ53FDWK.js +2 -0
- package/dist/index.d.ts +20 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/migrate-v2-ZOIMGITH.js +4 -0
- package/dist/{migrate-v2-KOMPDC6U.js.map → migrate-v2-ZOIMGITH.js.map} +1 -1
- package/dist/program-UTELWTXC.js +2 -0
- package/dist/promote-B5AOKPQR.js +2 -0
- package/dist/query-QLJNQUUP.js +2 -0
- package/dist/registry-CTZFLXGB.js +2 -0
- package/dist/types-NZOBHQGS.js +2 -0
- package/dist/wiki-X76JUHXT.js +2 -0
- package/dist/wiki-X76JUHXT.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-4DRNEOOW.js +0 -2
- package/dist/chunk-4DRNEOOW.js.map +0 -1
- package/dist/chunk-535MLOSB.js +0 -109
- package/dist/chunk-535MLOSB.js.map +0 -1
- package/dist/chunk-5ONI54E6.js.map +0 -1
- package/dist/chunk-K63IOY6A.js.map +0 -1
- package/dist/chunk-V2TLFYKH.js +0 -45
- package/dist/chunk-V2TLFYKH.js.map +0 -1
- package/dist/migrate-v2-KOMPDC6U.js +0 -4
- package/dist/program-T275Y2V6.js +0 -2
- package/dist/promote-VZAUTV6E.js +0 -2
- package/dist/query-7QQZPMXM.js +0 -2
- package/dist/registry-WQ65MQEY.js +0 -2
- package/dist/types-S6NHM5C3.js +0 -2
- package/dist/wiki-J4MMCONT.js +0 -2
- /package/dist/{agent-IDAWXA3K.js.map → agent-V223TG6H.js.map} +0 -0
- /package/dist/{chunk-CKBAVCGU.js.map → chunk-3IY2YWXP.js.map} +0 -0
- /package/dist/{chunk-J7HA7ZTU.js.map → chunk-3RC4LO2G.js.map} +0 -0
- /package/dist/{chunk-M6GPRMCQ.js.map → chunk-6QDOUOKD.js.map} +0 -0
- /package/dist/{chunk-OHRTBD7U.js.map → chunk-LHLNARRW.js.map} +0 -0
- /package/dist/{chunk-2UYV24UD.js.map → chunk-SN5N2FPG.js.map} +0 -0
- /package/dist/{chunk-IU6L4V3A.js.map → chunk-W7SEPJFH.js.map} +0 -0
- /package/dist/{chunk-DQQ3BCJW.js.map → chunk-YK7GFEGO.js.map} +0 -0
- /package/dist/{program-T275Y2V6.js.map → graph-FJ53FDWK.js.map} +0 -0
- /package/dist/{promote-VZAUTV6E.js.map → program-UTELWTXC.js.map} +0 -0
- /package/dist/{query-7QQZPMXM.js.map → promote-B5AOKPQR.js.map} +0 -0
- /package/dist/{registry-WQ65MQEY.js.map → query-QLJNQUUP.js.map} +0 -0
- /package/dist/{types-S6NHM5C3.js.map → registry-CTZFLXGB.js.map} +0 -0
- /package/dist/{wiki-J4MMCONT.js.map → types-NZOBHQGS.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as o}from"./chunk-ML6CNRBK.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
|
|
2
|
+
//# sourceMappingURL=chunk-SN5N2FPG.js.map
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import{a as j,b as T,c as O,d as D,e as _}from"./chunk-TFVUOC2C.js";import{b as W}from"./chunk-2GIDVZ4H.js";import{b as v,c as C}from"./chunk-QOYAX2FT.js";import{f as N}from"./chunk-WLMQ5JMX.js";import{v as R,w as I}from"./chunk-BBIWAJRX.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function rt(n,a,o,t={}){let p=t.selectorModel??"haiku",u=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,i=t.maxArticles??8,g=t.timeoutMs??6e4,h=t.log??console.error.bind(console,"[wiki-query]"),e=t.messagePath?.length?t.messagePath:void 0,d=t.graphWeight??S,s=x(a.baseDir,"_index.md");if(!B(s))return k("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let A=Y(s,"utf-8"),$=Date.now(),y=[],m="";try{let c=await G(n,a,o,l,e,d);c?(y=c,m=`[wiki-rerank seat] ${c.map(f=>f.title).join(" | ")}`):(m=await Q(q(n,A,l,e),p,g),y=K(m))}catch(c){return h("selector failed:",c?.message),{...k("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-$,synthesisMs:0,selectorOutput:m}}}let b=Date.now()-$;if(y.length===0)return{...k("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:b,synthesisMs:0,selectorOutput:m}};let w=F(y,a,o,r,i);if(w.length===0)return{...k("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:y,trace:{selectorMs:b,synthesisMs:0,selectorOutput:m}};let M=Date.now(),P="";try{P=await Q(J(n,w),u,g*2)}catch(c){return h("synthesis failed:",c?.message),{...k("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:y,walked:w.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:b,synthesisMs:Date.now()-M,selectorOutput:m}}}let E=Date.now()-M;return{answer:P.trim(),citations:w.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:y,walked:w.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:b,synthesisMs:E,selectorOutput:m}}}function k(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,p){let u=new Map;for(let i of a.listArticles(o||""))u.set(i.meta.title.toLowerCase(),i.path);let l=new Map,r=[];for(let i of n)l.has(i.path)||r.push({path:i.path,hop:0});for(;r.length&&l.size<p;){let i=r.shift();if(l.has(i.path)||i.hop>t)continue;let g=o?a.readArticleAs(i.path,o):a.readArticle(i.path);if(g&&(l.set(i.path,{...g,hop:i.hop}),!(i.hop>=t)))for(let h of g.meta.related||[]){let e=u.get(h.toLowerCase());e&&!l.has(e)&&r.push({path:e,hop:i.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,p,u=S){try{let r=(a.rebuildIndex().articles??[]).filter(s=>s.path&&!s.path.includes("/_versions/"));if(r.length<2)return null;let g=H(n,r,p,u).slice(0,T).map(s=>({id:`k${s}`,title:r[s].title||r[s].path,tags:r[s].tags,excerpt:[r[s].type?`type: ${r[s].type}`:"",(r[s].related??[]).length?`related: ${(r[s].related??[]).join(", ")}`:"",(r[s].graphPath??[]).length?`graph: ${(r[s].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),h=await R(j,O({query:n,candidates:g,excerptChars:300}),D(g),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!h||h.mode!=="active")return null;let d=_(h.answers,g).ranked.slice(0,t).map(s=>r[Number(s.slice(1))]).filter(Boolean).map(s=>({title:s.title,path:s.path}));return d.length>0?d:null}catch{return null}}var S=.6;function H(n,a,o,t=S){let p=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),u=C(n,v(p)),l=u.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(u.map(e=>[e.docIndex,l>0?e.score/l:0])),i=!!o?.length,h=a.map((e,d)=>{let s=r.get(d)??0,A=i&&e.graphPath?.length?N(o,e.graphPath):0;return{i:d,score:i?(1-t)*s+t*A:s,scored:r.has(d)||A>0}}).filter(e=>e.scored).sort((e,d)=>d.score-e.score||e.i-d.i).map(e=>e.i);for(let e=0;e<a.length;e++)h.includes(e)||h.push(e);return h}function q(n,a,o,t){let p=t?.length?`
|
|
2
|
+
## Intent
|
|
3
|
+
|
|
4
|
+
The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
|
|
5
|
+
`:"";return`You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.
|
|
6
|
+
|
|
7
|
+
## Question
|
|
8
|
+
|
|
9
|
+
${n}
|
|
10
|
+
${p}
|
|
11
|
+
## Catalog (_index.md \u2014 articles grouped by type, with wikilink previews)
|
|
12
|
+
|
|
13
|
+
${a}
|
|
14
|
+
|
|
15
|
+
## Your task
|
|
16
|
+
|
|
17
|
+
Pick up to ${o} articles from the catalog that are most likely to answer the question. Prefer:
|
|
18
|
+
- Articles whose title directly names a subject in the question.
|
|
19
|
+
- Articles of the right type (e.g. a "who owns X" question \u2192 person or project; a "what happened on DATE" \u2192 event).
|
|
20
|
+
- Articles whose wikilinks suggest they sit at the center of a relevant subgraph.
|
|
21
|
+
|
|
22
|
+
Return ONLY valid JSON, no markdown fencing, no prose:
|
|
23
|
+
|
|
24
|
+
[
|
|
25
|
+
{"title": "Exact Article Title", "path": "path/from/catalog.md"},
|
|
26
|
+
...
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
If none of the articles match, return [].`}function J(n,a){let o=a.map(t=>{let p=`### ${t.meta.title} \u2014 ${t.meta.type||"untyped"} (${t.path}) [hop ${t.hop}]`,u=t.meta.related?.length?`Related: ${t.meta.related.join(", ")}`:"";return[p,u,"",t.content].filter(Boolean).join(`
|
|
30
|
+
`)}).join(`
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
`);return`You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.
|
|
35
|
+
|
|
36
|
+
## Question
|
|
37
|
+
|
|
38
|
+
${n}
|
|
39
|
+
|
|
40
|
+
## Articles (${a.length} walked from the catalog)
|
|
41
|
+
|
|
42
|
+
${o}
|
|
43
|
+
|
|
44
|
+
## Your task
|
|
45
|
+
|
|
46
|
+
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
47
|
+
|
|
48
|
+
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Q(n,a,o){let{writeFileSync:t,mkdirSync:p,rmSync:u}=await import("fs"),{tmpdir:l}=await import("os"),r=x(l(),`agentx-wiki-query-${process.pid}`);p(r,{recursive:!0});let i=x(r,`prompt-${Date.now()}.txt`);t(i,n);try{let g=`cat '${i}' | claude -p - --output-format json --max-turns 1 --model ${a} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,h=L(g,{env:W({...process.env}),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let e=JSON.parse(h);return String(e.result||e.content||"")}catch{return h}}finally{try{u(i,{force:!0})}catch{}}}export{rt as a,S as b,H as c};
|
|
49
|
+
//# sourceMappingURL=chunk-TLDQWTSW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/query.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { buildIndex, scoreAll } from \"@/memory/bm25\"\nimport { askSeat } from \"@/decisions/seat\"\nimport { ancestryScore } from \"@/graph\"\nimport {\n DEFAULT_SHORTLIST,\n WIKI_RERANK_SEAT,\n rerankQuestions,\n rerankState,\n toRanking,\n type RerankCandidate,\n} from \"@/decisions/seats/wiki-rerank\"\nimport { stripAnthropicApiKey } from \"@/utils/workspace-env\"\nimport { resolve } from \"path\"\nimport { execSync } from \"child_process\"\nimport type { WikiArticle } from \"./types\"\nimport type { WikiStore } from \"./store\"\n\n/**\n * Agentic wiki query — the \"Farzapedia-faithful\" retrieval path.\n *\n * Two LLM calls + a deterministic graph walk:\n * 1. Selector (cheap): read `_index.md` + question → pick up to `maxCandidates`\n * candidate articles by title + type.\n * 2. Walk (pure code): starting from candidates, follow `related` wikilinks\n * up to `maxHops`, capped at `maxArticles` total.\n * 3. Synthesis (main): answer the question from the walked subgraph.\n *\n * Returns an answer with citations and a trace of which articles were walked,\n * so callers can audit the retrieval path.\n */\n\nexport interface AgenticQueryOptions {\n /** Candidate-selection model (cheap). Defaults to \"haiku\". */\n selectorModel?: string\n /** Synthesis model (main). Defaults to \"sonnet\". */\n synthModel?: string\n /** Number of candidates the selector is asked to return. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from candidates. Default 2. */\n maxHops?: number\n /** Hard cap on total articles walked. Default 8. */\n maxArticles?: number\n /** Timeout per LLM call, ms. Default 60_000. */\n timeoutMs?: number\n /** Logger — defaults to console.error. */\n log?: (...args: unknown[]) => void\n /** Intent-graph path the question's request was classified under.\n * Articles on the same branch rank higher in candidate selection. */\n messagePath?: string[]\n /** Weight of the branch match against the text match, 0–1. Default 0.6\n * (`graph.retrievalWeights.graph`). */\n graphWeight?: number\n}\n\nexport interface AgenticQueryResult {\n answer: string\n citations: Array<{ title: string; path: string; type?: string }>\n /** Titles/paths the selector picked. */\n candidates: Array<{ title: string; path: string }>\n /** Full article subgraph the walk produced. */\n walked: Array<{ title: string; path: string; type?: string; hop: number }>\n /** \"no-catalog\" | \"no-candidates\" | \"ok\" */\n status: \"ok\" | \"no-catalog\" | \"no-candidates\" | \"error\"\n /** For operator debugging only. */\n trace?: {\n selectorMs: number\n synthesisMs: number\n selectorOutput?: string\n }\n error?: string\n}\n\n/**\n * Run an agentic query against a specific agent's WikiStore.\n *\n * `requesterId` is used for permission checks — only articles the requester\n * can read will be included in the synthesis input.\n */\nexport async function agenticQuery(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: AgenticQueryOptions = {},\n): Promise<AgenticQueryResult> {\n const selectorModel = opts.selectorModel ?? \"haiku\"\n const synthModel = opts.synthModel ?? \"sonnet\"\n const maxCandidates = opts.maxCandidates ?? 3\n const maxHops = opts.maxHops ?? 2\n const maxArticles = opts.maxArticles ?? 8\n const timeoutMs = opts.timeoutMs ?? 60_000\n const log = opts.log ?? console.error.bind(console, \"[wiki-query]\")\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n\n // --- Step 1: Load the catalog ---\n const catalogPath = resolve(store.baseDir, \"_index.md\")\n if (!existsSync(catalogPath)) {\n return emptyResult(\"no-catalog\", question, \"No _index.md found — run `agentx wiki status` to rebuild.\")\n }\n const catalog = readFileSync(catalogPath, \"utf-8\")\n\n // --- Step 2: Selector — pick candidates ---\n const selectorStart = Date.now()\n let candidates: Array<{ title: string; path: string }> = []\n let selectorOutput = \"\"\n try {\n const viaSeat = await selectCandidatesViaSeat(question, store, requesterId, maxCandidates, messagePath, graphWeight)\n if (viaSeat) {\n candidates = viaSeat\n selectorOutput = `[wiki-rerank seat] ${viaSeat.map((c) => c.title).join(\" | \")}`\n } else {\n selectorOutput = await runClaude(\n buildSelectorPrompt(question, catalog, maxCandidates, messagePath),\n selectorModel,\n timeoutMs,\n )\n candidates = parseCandidates(selectorOutput)\n }\n } catch (e: any) {\n log(\"selector failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Selector: ${e?.message || \"unknown\"}`), trace: { selectorMs: Date.now() - selectorStart, synthesisMs: 0, selectorOutput } }\n }\n const selectorMs = Date.now() - selectorStart\n\n if (candidates.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Selector returned no candidates.\"), trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 3: Walk the subgraph via `related` wikilinks ---\n const walked = walkSubgraph(candidates, store, requesterId, maxHops, maxArticles)\n\n if (walked.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Candidates did not resolve to readable articles.\"), candidates, trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 4: Synthesize the answer ---\n const synthStart = Date.now()\n let answer = \"\"\n try {\n answer = await runClaude(\n buildSynthesisPrompt(question, walked),\n synthModel,\n timeoutMs * 2,\n )\n } catch (e: any) {\n log(\"synthesis failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Synthesis: ${e?.message || \"unknown\"}`), candidates, walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })), trace: { selectorMs, synthesisMs: Date.now() - synthStart, selectorOutput } }\n }\n const synthesisMs = Date.now() - synthStart\n\n return {\n answer: answer.trim(),\n citations: walked.map(a => ({ title: a.meta.title, path: a.path, type: a.meta.type })),\n candidates,\n walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })),\n status: \"ok\",\n trace: { selectorMs, synthesisMs, selectorOutput },\n }\n}\n\n// --- Helpers ---\n\nfunction emptyResult(\n status: AgenticQueryResult[\"status\"],\n _question: string,\n error?: string,\n): AgenticQueryResult {\n return {\n answer: \"\",\n citations: [],\n candidates: [],\n walked: [],\n status,\n error,\n }\n}\n\nfunction walkSubgraph(\n candidates: Array<{ title: string; path: string }>,\n store: WikiStore,\n requesterId: string | undefined,\n maxHops: number,\n maxArticles: number,\n): Array<WikiArticle & { hop: number }> {\n // Build a title → path index from the store so wikilinks resolve.\n const titleIndex = new Map<string, string>()\n for (const article of store.listArticles(requesterId || \"\")) {\n titleIndex.set(article.meta.title.toLowerCase(), article.path)\n }\n\n const opened = new Map<string, WikiArticle & { hop: number }>()\n let frontier: Array<{ path: string; hop: number }> = []\n\n for (const c of candidates) {\n if (!opened.has(c.path)) frontier.push({ path: c.path, hop: 0 })\n }\n\n while (frontier.length && opened.size < maxArticles) {\n const next = frontier.shift()!\n if (opened.has(next.path)) continue\n if (next.hop > maxHops) continue\n\n const article = requesterId\n ? store.readArticleAs(next.path, requesterId)\n : store.readArticle(next.path)\n if (!article) continue\n\n opened.set(next.path, { ...article, hop: next.hop })\n if (next.hop >= maxHops) continue\n\n for (const target of article.meta.related || []) {\n const path = titleIndex.get(target.toLowerCase())\n if (path && !opened.has(path)) {\n frontier.push({ path, hop: next.hop + 1 })\n }\n }\n }\n\n return Array.from(opened.values())\n}\n\n// --- Prompts ---\n\n/**\n * Pick candidates with the wiki-rerank seat instead of a Claude CLI call.\n *\n * The selector is 56% of a wiki query — 14.1s of a 25s total, measured —\n * and its whole job is \"pick 3 articles from this catalog\", which is a\n * Choice with per-option probabilities. Jev answers that in about a\n * second. Synthesis stays on Sonnet; it writes prose, which Jev cannot.\n *\n * BM25 shortlists first because the shared catalog carries 971 entries,\n * past the 255-option cap. Same two-stage shape as findRelevantReranked,\n * and it reuses that seat rather than introducing a second one.\n *\n * Returns null whenever the seat is off, errors, or has nothing to rank,\n * and the caller falls back to the CLI selector — so this is strictly an\n * accelerator, never a new way to fail.\n */\nasync function selectCandidatesViaSeat(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n maxCandidates: number,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): Promise<Array<{ title: string; path: string }> | null> {\n try {\n const index = store.rebuildIndex()\n const pool = (index.articles ?? []).filter((a) => a.path && !a.path.includes(\"/_versions/\"))\n if (pool.length < 2) return null\n\n const shortlist = rankCatalogPool(question, pool, messagePath, graphWeight).slice(0, DEFAULT_SHORTLIST)\n\n const candidates: RerankCandidate[] = shortlist.map((i) => ({\n id: `k${i}`,\n title: pool[i].title || pool[i].path,\n tags: pool[i].tags,\n // The catalog has no body — a title, its type, its wikilinks and its\n // branch of the intent graph are what the selector chooses on.\n excerpt: [\n pool[i].type ? `type: ${pool[i].type}` : \"\",\n (pool[i].related ?? []).length ? `related: ${(pool[i].related ?? []).join(\", \")}` : \"\",\n (pool[i].graphPath ?? []).length ? `graph: ${(pool[i].graphPath ?? []).join(\" › \")}` : \"\",\n ].filter(Boolean).join(\" · \"),\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query: question, candidates, excerptChars: 300 }),\n rerankQuestions(candidates),\n { features: { agent: requesterId ?? \"unknown\", stage: \"catalog-selector\" } },\n )\n if (!result || result.mode !== \"active\") return null\n\n const ranking = toRanking(result.answers as never, candidates)\n const picked = ranking.ranked\n .slice(0, maxCandidates)\n .map((id) => pool[Number(id.slice(1))])\n .filter(Boolean)\n .map((a) => ({ title: a.title, path: a.path }))\n return picked.length > 0 ? picked : null\n } catch {\n return null\n }\n}\n\n/** Weight of the intent-graph branch match against the text match when\n * shortlisting catalog candidates. Mirrors `graph.retrievalWeights.graph`. */\nexport const DEFAULT_GRAPH_WEIGHT = 0.6\n\n/**\n * Order the catalog pool for a question: text match (BM25 over title, tags\n * and wikilinks, scaled to 0–1) plus, when the request was classified,\n * how much of the intent-graph path each article shares with it. Articles\n * the text match never scored keep their catalog order at the end.\n *\n * Exported for tests; the seat and the CLI selector both consume the order.\n */\nexport function rankCatalogPool(\n question: string,\n pool: Array<{ title: string; tags?: string[]; related?: string[]; graphPath?: string[] }>,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): number[] {\n const docs = pool.map((a) =>\n [a.title, (a.tags ?? []).join(\" \"), (a.related ?? []).join(\" \")].join(\" \"),\n )\n const bm25 = scoreAll(question, buildIndex(docs))\n const maxBm25 = bm25.reduce((m, r) => Math.max(m, r.score), 0)\n const text = new Map(bm25.map((r) => [r.docIndex, maxBm25 > 0 ? r.score / maxBm25 : 0]))\n const useGraph = !!messagePath?.length\n const combined = pool.map((a, i) => {\n const t = text.get(i) ?? 0\n const g = useGraph && a.graphPath?.length ? ancestryScore(messagePath!, a.graphPath) : 0\n return { i, score: useGraph ? (1 - graphWeight) * t + graphWeight * g : t, scored: text.has(i) || g > 0 }\n })\n const ranked = combined.filter((c) => c.scored).sort((x, y) => y.score - x.score || x.i - y.i).map((c) => c.i)\n for (let i = 0; i < pool.length; i++) if (!ranked.includes(i)) ranked.push(i)\n return ranked\n}\n\nfunction buildSelectorPrompt(question: string, catalog: string, maxCandidates: number, messagePath?: string[]): string {\n const branch = messagePath?.length\n ? `\\n## Intent\\n\\nThe request was classified under the intent-graph path \"${messagePath.join(\" › \")}\". Prefer articles filed under the same branch when their titles are equally plausible.\\n`\n : \"\"\n return `You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.\n\n## Question\n\n${question}\n${branch}\n## Catalog (_index.md — articles grouped by type, with wikilink previews)\n\n${catalog}\n\n## Your task\n\nPick up to ${maxCandidates} articles from the catalog that are most likely to answer the question. Prefer:\n- Articles whose title directly names a subject in the question.\n- Articles of the right type (e.g. a \"who owns X\" question → person or project; a \"what happened on DATE\" → event).\n- Articles whose wikilinks suggest they sit at the center of a relevant subgraph.\n\nReturn ONLY valid JSON, no markdown fencing, no prose:\n\n[\n {\"title\": \"Exact Article Title\", \"path\": \"path/from/catalog.md\"},\n ...\n]\n\nIf none of the articles match, return [].`\n}\n\nfunction buildSynthesisPrompt(\n question: string,\n articles: Array<WikiArticle & { hop: number }>,\n): string {\n const articlesBlock = articles\n .map(a => {\n const header = `### ${a.meta.title} — ${a.meta.type || \"untyped\"} (${a.path}) [hop ${a.hop}]`\n const related = a.meta.related?.length ? `Related: ${a.meta.related.join(\", \")}` : \"\"\n return [header, related, \"\", a.content].filter(Boolean).join(\"\\n\")\n })\n .join(\"\\n\\n---\\n\\n\")\n\n return `You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.\n\n## Question\n\n${question}\n\n## Articles (${articles.length} walked from the catalog)\n\n${articlesBlock}\n\n## Your task\n\nAnswer the question in 2–6 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.\n\nOutput ONLY the answer — no preamble, no \"here is my answer:\", no markdown fencing.`\n}\n\nfunction parseCandidates(raw: string): Array<{ title: string; path: string }> {\n const match = raw.match(/\\[[\\s\\S]*?\\]/)\n if (!match) return []\n try {\n const parsed = JSON.parse(match[0])\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter((x: any) => x && typeof x.title === \"string\" && typeof x.path === \"string\")\n .map((x: any) => ({ title: x.title, path: x.path }))\n } catch {\n return []\n }\n}\n\nasync function runClaude(prompt: string, model: string, timeoutMs: number): Promise<string> {\n // Use stdin via a temp-file pipe to avoid shell-escaping a huge prompt.\n // Prompts can exceed the `-E` arg buffer on macOS, so we always pipe.\n const { writeFileSync, mkdirSync, rmSync } = await import(\"fs\")\n const { tmpdir } = await import(\"os\")\n const dir = resolve(tmpdir(), `agentx-wiki-query-${process.pid}`)\n mkdirSync(dir, { recursive: true })\n const promptPath = resolve(dir, `prompt-${Date.now()}.txt`)\n writeFileSync(promptPath, prompt)\n try {\n const cmd = `cat '${promptPath}' | claude -p - --output-format json --max-turns 1 --model ${model} --disallowedTools \"Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit\"`\n const raw = execSync(cmd, { env: stripAnthropicApiKey({ ...process.env }), encoding: \"utf-8\", timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 })\n try {\n const envelope = JSON.parse(raw)\n return String(envelope.result || envelope.content || \"\")\n } catch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AU,UAAY,OAAOA,EAAE,MAAS,QAAQ,EACjF,IAAKA,IAAY,CAAE,MAAOA,EAAE,MAAO,KAAMA,EAAE,IAAK,EAAE,EAHlB,CAAC,CAItC,MAAE,CACA,MAAO,CAAC,CACV,CACF,CAEA,eAAehD,EAAU0D,EAAgBC,EAAe3E,EAAoC,CAG1F,GAAM,CAAE,cAAA4E,EAAe,UAAAC,EAAW,OAAAC,CAAO,EAAI,KAAM,QAAO,IAAI,EACxD,CAAE,OAAAC,CAAO,EAAI,KAAM,QAAO,IAAI,EAC9BC,EAAM5F,EAAQ2F,EAAO,EAAG,qBAAqB,QAAQ,KAAK,EAChEF,EAAUG,EAAK,CAAE,UAAW,EAAK,CAAC,EAClC,IAAMC,EAAa7F,EAAQ4F,EAAK,UAAU,KAAK,IAAI,OAAO,EAC1DJ,EAAcK,EAAYP,CAAM,EAChC,GAAI,CACF,IAAMQ,EAAM,QAAQD,+DAAwEN,6FACtFJ,EAAMlF,EAAS6F,EAAK,CAAE,IAAKC,EAAqB,CAAE,GAAG,QAAQ,GAAI,CAAC,EAAG,SAAU,QAAS,QAASnF,EAAW,UAAW,EAAI,KAAO,IAAK,CAAC,EAC9I,GAAI,CACF,IAAMoF,EAAW,KAAK,MAAMb,CAAG,EAC/B,OAAO,OAAOa,EAAS,QAAUA,EAAS,SAAW,EAAE,CACzD,MAAE,CACA,OAAOb,CACT,CACF,QAAE,CACA,GAAI,CAAEO,EAAOG,EAAY,CAAE,MAAO,EAAK,CAAC,CAAE,MAAE,CAAO,CACrD,CACF","names":["readFileSync","existsSync","init_seat","resolve","execSync","agenticQuery","question","store","requesterId","opts","selectorModel","synthModel","maxCandidates","maxHops","maxArticles","timeoutMs","log","messagePath","graphWeight","DEFAULT_GRAPH_WEIGHT","catalogPath","existsSync","emptyResult","catalog","readFileSync","selectorStart","candidates","selectorOutput","viaSeat","selectCandidatesViaSeat","c","runClaude","buildSelectorPrompt","parseCandidates","e","selectorMs","walked","walkSubgraph","synthStart","answer","buildSynthesisPrompt","w","synthesisMs","a","status","_question","error","titleIndex","article","opened","frontier","next","target","path","pool","rankCatalogPool","DEFAULT_SHORTLIST","i","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","picked","toRanking","id","docs","bm25","scoreAll","buildIndex","maxBm25","m","r","text","useGraph","ranked","t","g","ancestryScore","x","y","branch","articles","articlesBlock","header","related","raw","match","parsed","prompt","model","writeFileSync","mkdirSync","rmSync","tmpdir","dir","promptPath","cmd","stripAnthropicApiKey","envelope"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{z as e}from"zod";var i=e.enum(["enum","free","ref"]),a=e.object({name:e.string().regex(/^[a-z][a-z0-9_]*$/i,"axis name must be a simple identifier"),type:i,values:e.array(e.string()).optional(),refLevel:e.string().optional(),optional:e.boolean().optional(),description:e.string().optional()}),r=e.object({id:e.string().regex(/^[a-z][a-z0-9_-]*$/,"level id must be lowercase slug"),axes:e.array(a).min(1),description:e.string().optional()}),f=e.object({version:e.number().int().default(1),levels:e.array(r).min(1).max(5),leafInput:a.optional(),leafOutput:a.optional()}),t=e.string().regex(/^[a-z0-9][a-z0-9._-]*$/,"node id must be lowercase slug (alnum, '.', '_', '-')"),n=e.object({id:t,level:e.string(),parentId:t.nullable(),axes:e.record(e.string(),e.string()),createdAt:e.string(),createdBy:e.string().optional()}),o=e.enum(["llm","user","cache","seat"]),s=e.enum(["pending","approved","rejected"]),p=e.object({ts:e.string(),msgHash:e.string(),agentId:e.string().optional(),channel:e.string().optional(),sender:e.string().optional(),chatId:e.string().optional(),path:e.array(t),proposedAxes:e.record(e.string(),e.record(e.string(),e.string())).default({}),leaf:e.object({input:e.string().optional(),output:e.string().optional()}).partial().default({}),source:o,status:s,confidence:e.number().min(0).max(1).optional(),preview:e.string().optional()}),c=e.object({fingerprint:e.string(),path:e.array(t),leaf:p.shape.leaf,updatedAt:e.string()}),m=e.object({version:e.number().int().default(1),nodes:e.array(n).default([])}),d=e.object({version:e.number().int().default(1),entries:e.record(e.string(),c).default({})});export{i as a,a as b,r as c,f as d,t as e,n as f,o as g,s as h,p as i,c as j,m as k,d as l};
|
|
2
|
+
//# sourceMappingURL=chunk-TTVVXBCM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/graph/types.ts"],"sourcesContent":["import { z } from \"zod\"\n\n// --- Intent Knowledge Graph types + Zod schemas ---\n//\n// A hierarchical, enumerable intent taxonomy with fixed axes per level.\n// See plan: /Users/you/.claude/plans/delightful-floating-diffie.md\n//\n// Shape on disk (.agentx/graph/):\n// schema.json — level definitions + required axes per level\n// nodes.json — tree of nodes: { id, level, parentId, axes }\n// classifications.jsonl — append-only log of message → path decisions\n// index.json — fingerprint → pathId snap-to-path cache\n\nexport const axisTypeSchema = z.enum([\"enum\", \"free\", \"ref\"])\nexport type AxisType = z.infer<typeof axisTypeSchema>\n\nexport const axisDefSchema = z.object({\n name: z.string().regex(/^[a-z][a-z0-9_]*$/i, \"axis name must be a simple identifier\"),\n type: axisTypeSchema,\n /** For type=\"enum\": closed set of allowed values. */\n values: z.array(z.string()).optional(),\n /** For type=\"ref\": which level's nodes may be referenced. */\n refLevel: z.string().optional(),\n /** If true, this axis may be absent from a node without failing validation.\n * Use for axes that apply conditionally (e.g. a department's \"lead\" ref\n * doesn't apply to a person-kind unit). Absent/false = required. */\n optional: z.boolean().optional(),\n /** Optional human-readable help, shown as tooltip in the admin UI. */\n description: z.string().optional(),\n})\nexport type AxisDef = z.infer<typeof axisDefSchema>\n\nexport const levelDefSchema = z.object({\n id: z.string().regex(/^[a-z][a-z0-9_-]*$/, \"level id must be lowercase slug\"),\n /** Axes every node at this level MUST carry. Order matters for UI rendering. */\n axes: z.array(axisDefSchema).min(1),\n description: z.string().optional(),\n})\nexport type LevelDef = z.infer<typeof levelDefSchema>\n\nexport const graphSchemaSchema = z.object({\n version: z.number().int().default(1),\n /** Ordered from root to leaf. Max 5 to keep the taxonomy scannable. */\n levels: z.array(levelDefSchema).min(1).max(5),\n /** Axis describing where a leaf classification came from (channel, cron, etc.). */\n leafInput: axisDefSchema.optional(),\n /** Free-form description of the expected result of a leaf classification. */\n leafOutput: axisDefSchema.optional(),\n})\nexport type GraphSchema = z.infer<typeof graphSchemaSchema>\n\n// Allow dots so verb-level node ids like \"review.merge-request\" or\n// \"deploy.staging\" parse cleanly (Phase 1 of the classifier-retire plan).\n// Dots are dot-namespaced verbs only — never the leading char.\nexport const nodeIdSchema = z.string().regex(/^[a-z0-9][a-z0-9._-]*$/, \"node id must be lowercase slug (alnum, '.', '_', '-')\")\n\nexport const graphNodeSchema = z.object({\n id: nodeIdSchema,\n /** Matches a `levels[*].id` from the schema. */\n level: z.string(),\n /** null for root-level nodes (level[0]); otherwise the id of a node at level-1. */\n parentId: nodeIdSchema.nullable(),\n /** Values for every axis declared at this level's schema entry. `ref` axes\n * hold the id of another node; `enum` axes hold one of the declared values;\n * `free` axes hold any string. */\n axes: z.record(z.string(), z.string()),\n createdAt: z.string(),\n createdBy: z.string().optional(),\n})\nexport type GraphNode = z.infer<typeof graphNodeSchema>\n\n/** \"seat\": the intent-path decision seat picked an existing path. */\nexport const classificationSourceSchema = z.enum([\"llm\", \"user\", \"cache\", \"seat\"])\nexport type ClassificationSource = z.infer<typeof classificationSourceSchema>\n\nexport const classificationStatusSchema = z.enum([\"pending\", \"approved\", \"rejected\"])\nexport type ClassificationStatus = z.infer<typeof classificationStatusSchema>\n\nexport const classificationSchema = z.object({\n ts: z.string(),\n msgHash: z.string(),\n agentId: z.string().optional(),\n channel: z.string().optional(),\n sender: z.string().optional(),\n /** The conversation the message belongs to. Lets a tool running inside\n * that conversation find the path its request was filed under. */\n chatId: z.string().optional(),\n /** Node ids from root to leaf, one per level. Shorter-than-full paths are\n * allowed if the classifier was only confident down to a certain depth. */\n path: z.array(nodeIdSchema),\n /** Axis values asserted by the classifier for new nodes it proposed along\n * the path. Keyed by node id. */\n proposedAxes: z.record(z.string(), z.record(z.string(), z.string())).default({}),\n /** Leaf-level extras. */\n leaf: z.object({\n input: z.string().optional(),\n output: z.string().optional(),\n }).partial().default({}),\n source: classificationSourceSchema,\n status: classificationStatusSchema,\n confidence: z.number().min(0).max(1).optional(),\n /** Redacted first ~200 chars of the message, for the approval UI. */\n preview: z.string().optional(),\n})\nexport type Classification = z.infer<typeof classificationSchema>\n\n/** Row in the fingerprint → path snap cache. */\nexport const fingerprintEntrySchema = z.object({\n fingerprint: z.string(),\n path: z.array(nodeIdSchema),\n leaf: classificationSchema.shape.leaf,\n updatedAt: z.string(),\n})\nexport type FingerprintEntry = z.infer<typeof fingerprintEntrySchema>\n\n/** Nodes file is a plain list, not a nested tree — lookups are by id. */\nexport const nodesFileSchema = z.object({\n version: z.number().int().default(1),\n nodes: z.array(graphNodeSchema).default([]),\n})\nexport type NodesFile = z.infer<typeof nodesFileSchema>\n\n/** Index file — record of fingerprints. Hot path; kept as a map on disk. */\nexport const indexFileSchema = z.object({\n version: z.number().int().default(1),\n entries: z.record(z.string(), fingerprintEntrySchema).default({}),\n})\nexport type IndexFile = z.infer<typeof indexFileSchema>\n"],"mappings":"AAAA,OAAS,KAAAA,MAAS,MAaX,IAAMC,EAAiBD,EAAE,KAAK,CAAC,OAAQ,OAAQ,KAAK,CAAC,EAG/CE,EAAgBF,EAAE,OAAO,CACpC,KAAMA,EAAE,OAAO,EAAE,MAAM,qBAAsB,uCAAuC,EACpF,KAAMC,EAEN,OAAQD,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,SAAS,EAErC,SAAUA,EAAE,OAAO,EAAE,SAAS,EAI9B,SAAUA,EAAE,QAAQ,EAAE,SAAS,EAE/B,YAAaA,EAAE,OAAO,EAAE,SAAS,CACnC,CAAC,EAGYG,EAAiBH,EAAE,OAAO,CACrC,GAAIA,EAAE,OAAO,EAAE,MAAM,qBAAsB,iCAAiC,EAE5E,KAAMA,EAAE,MAAME,CAAa,EAAE,IAAI,CAAC,EAClC,YAAaF,EAAE,OAAO,EAAE,SAAS,CACnC,CA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,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,SAAS,EAE9C,QAASA,EAAE,OAAO,EAAE,SAAS,CAC/B,CAAC,EAIYU,EAAyBV,EAAE,OAAO,CAC7C,YAAaA,EAAE,OAAO,EACtB,KAAMA,EAAE,MAAMK,CAAY,EAC1B,KAAMI,EAAqB,MAAM,KACjC,UAAWT,EAAE,OAAO,CACtB,CAAC,EAIYW,EAAkBX,EAAE,OAAO,CACtC,QAASA,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,EACnC,MAAOA,EAAE,MAAMM,CAAe,EAAE,QAAQ,CAAC,CAAC,CAC5C,CAAC,EAIYM,EAAkBZ,EAAE,OAAO,CACtC,QAASA,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,EACnC,QAASA,EAAE,OAAOA,EAAE,OAAO,EAAGU,CAAsB,EAAE,QAAQ,CAAC,CAAC,CAClE,CAAC","names":["z","axisTypeSchema","axisDefSchema","levelDefSchema","graphSchemaSchema","nodeIdSchema","graphNodeSchema","classificationSourceSchema","classificationStatusSchema","classificationSchema","fingerprintEntrySchema","nodesFileSchema","indexFileSchema"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{b as Je,c as Ye}from"./chunk-WP6KLXTP.js";import{a as ne}from"./chunk-N6EWZGIX.js";import{b as ae}from"./chunk-AFRHKA7B.js";import{b as He,e as Ue,f as Ke,i as Be,k as ze,l as qe,q as Ge}from"./chunk-OPUPVGYP.js";import{c as Ce,e as _e,f as Le}from"./chunk-KA2UIZXG.js";import{e as Fe,g as je,h as Me,i as se}from"./chunk-GQ76J72O.js";import{a as Ee,b as re,c as oe,d as De,e as ie}from"./chunk-QD6IICK7.js";import{c as Te,d as Ne}from"./chunk-QOYAX2FT.js";import{v as We,w as Vt}from"./chunk-BBIWAJRX.js";import{b as Oe,f as Gt}from"./chunk-72SZI2UW.js";import{existsSync as Zt,mkdirSync as Ve,readFileSync as Qt,writeFileSync as Xt,renameSync as en}from"fs";import{resolve as Ze,dirname as tn}from"path";var Qe=class{filePath;log;constructor(e={}){let t=e.baseDir??Ze(process.cwd(),".agentx");this.filePath=Ze(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Ve(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Zt(this.filePath))return{version:1,overrides:{}};try{let e=Qt(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Ve(tn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Xt(t,JSON.stringify(e,null,2)),en(t,this.filePath)}get(e,t,r){let i=this.load().overrides[this.key(e,t,r)];if(i&&!(i.expiresAt&&Date.parse(i.expiresAt)<Date.now()))return i}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),i=this.key(e,t,r);return i in o.overrides?(delete o.overrides[i],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),i=o.overrides[this.key(e,t,r)];if(!i||!i.summary||i.summaryConsumedAt)return;let s=i.summary;return i.summaryConsumedAt=new Date().toISOString(),this.save(o),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as rt,writeFileSync as de,appendFileSync as sn,mkdirSync as an,existsSync as ot,statSync as dn}from"fs";import{resolve as L}from"path";var Xe="[Agent Memory \u2014 persistent facts from past conversations]",nn=2400;function et(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function rn(n,e=Date.now()){let t=_e(n,e),r=n.undated?"UNVERIFIED (never checked) ":et(t,Fe(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function on(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,o=Me(n,e);return{line:`- [${n.category}] ${et(o,je(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function tt(n,e=[],t=Date.now()){let r=[],o=new Set,i=Xe.length,s=!1;for(let a of n){let d=e.length>0?Le(a.content,e):null,c,u,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),c=rn(d,t),u=d.id}else c=on(a,t),d&&(c.line+=` [differs from wiki ${d.id}]`);let f=c.unverified&&!s?se.length:0;if(i+f+c.line.length>nn)break;r.push({fact:a,...c,...u?{wikiRef:u}:{}}),i+=f+c.line.length,f&&(s=!0)}return r}function nt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[se]:[];return[Xe,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var it=200,cn=7,st=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=L(e,".agentx/memory"),this.ledger=new Ce(L(e,".agentx/wiki")),ot(this.memoryDir)||an(this.memoryDir,{recursive:!0})}filePath(e){return L(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||re(t.content))return!1;let r=t.source.trust??Ee(t.source.channel),o=t.review??De(r),i={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return sn(this.filePath(e),JSON.stringify(i)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!ot(t))return[];try{let{mtimeMs:r,size:o}=dn(t),i=this.parsedCache.get(t);if(i&&i.mtimeMs===r&&i.size===o)return i.facts.slice();let a=rt(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:a}),a.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(ie);if(o.length===0)return[];let i=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),s=L(this.memoryDir,`${t}_bm25_cache.json`),a=Ne(i,s),d=Te(e,a),c=new Map(d.map(g=>[g.docIndex,g.score])),p=o.map((g,h)=>{let m=c.get(h)??0;return g.category==="commitment"&&(m+=1),{memory:g,score:m}}).filter(g=>g.score>0);if(p.length===0)return o.slice(-r);let f=p.sort((g,h)=>h.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return nt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return tt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),i=!1;for(let s of r)if(o.has(s.id)){s.accessCount=(s.accessCount||0)+1,s.lastAccessed=new Date().toISOString();let a=s.intervalDays||1;s.intervalDays=Math.min(a*2,30),s.nextReview=new Date(Date.now()+s.intervalDays*864e5).toISOString(),i=!0}i&&de(this.filePath(e),r.map(s=>JSON.stringify(s)).join(`
|
|
@@ -18,4 +18,4 @@ import{a as ne}from"./chunk-N6EWZGIX.js";import{b as Je,c as Ye}from"./chunk-WP6
|
|
|
18
18
|
`)}clearIndex(e){let t=this.indexPath(e);if(E(t))try{St(t)}catch{}}};import{existsSync as At,mkdirSync as Cn,readFileSync as _n,unlinkSync as Ln,writeFileSync as Hn}from"fs";import{resolve as he}from"path";import{z as D}from"zod";var Rt=D.object({version:D.literal(1),nodes:D.record(D.object({x:D.number(),y:D.number()}))}),we=class{baseDir;layoutsDir;constructor(e={}){this.baseDir=e.baseDir??he(process.cwd(),".agentx/workflows"),this.layoutsDir=he(this.baseDir,"_layouts"),Cn(this.layoutsDir,{recursive:!0})}pathFor(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return he(this.layoutsDir,`${t}.json`)}get(e){let t=this.pathFor(e);if(!At(t))return null;try{let r=Rt.safeParse(JSON.parse(_n(t,"utf-8")));return r.success?r.data:null}catch{return null}}save(e,t){let r=Rt.parse(t);return Hn(this.pathFor(e),JSON.stringify(r,null,2)+`
|
|
19
19
|
`),r}sync(e,t){let r=this.get(e);if(!r)return null;let o={};for(let s of t)r.nodes[s]&&(o[s]=r.nodes[s]);let i={version:1,nodes:o};return this.save(e,i)}delete(e){let t=this.pathFor(e);return At(t)?(Ln(t),!0):!1}};function $t(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Un(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let r of n)e.has(r)&&t++;return t/Math.max(n.size,e.size)}function Kn(n,e){let t=$t(n.message),r=e.filter(i=>i.state==="active"&&(i.status??"active")==="active"),o=null;for(let i of r){let s=0,a=[];if(i.ownerAgent&&i.ownerAgent===n.agentId&&(s+=.25,a.push("owner-agent")),n.channel&&i.tags.includes(n.channel)&&(s+=.15,a.push("channel-tag")),n.intentPath?.length&&i.intentPath.length){let p=n.intentPath.filter((f,g)=>i.intentPath[g]===f).length;p>0&&(s+=Math.min(.3,p*.1),a.push("intent-path"))}let d=[i.id,i.title,i.description??"",...i.tags].join(" "),c=Un(t,$t(d));c>0&&(s+=Math.min(.35,c),a.push("text-similarity")),(i.matchCount??0)>0&&(s+=Math.min(.1,i.matchCount*.01),a.push("prior-matches"));let u=Math.max(0,Math.min(1,s));(!o||u>o.confidence)&&(o={workflow:i,confidence:u,reasons:a})}return o&&o.confidence>0?o:null}function ye(n){let{workflow:e,fromNodeId:t,selectedPort:r}=n,o=e.nodes.find(a=>a.id===t);if(!o)return{nextPending:[]};let i=e.edges.filter(a=>a.from===t);return{nextPending:(o.type==="branch"?i.filter(a=>(a.fromPort??"")===(r??"")):i).map(a=>a.to)}}function ke(n,e){let t=n.config.cases??[],r=n.config.default??"";for(let o of t)if(Bn(o.when,e))return o.to;return r}function Bn(n,e){let t=n.params??{},r=String(t.path??""),o=q(e,r);switch(n.kind){case"equals":return o===t.value;case"contains":return typeof o=="string"?o.includes(String(t.value??"")):Array.isArray(o)?o.some(i=>i===t.value):!1;case"matches":{if(typeof o!="string")return!1;try{return new RegExp(String(t.regex??"")).test(o)}catch{return!1}}case"exists":return o!=null&&o!=="";default:return!1}}function q(n,e){if(!e)return;let t=e.split("."),r=n;for(let o of t){if(r==null||typeof r!="object")return;r=r[o]}return r}function J(n){let e=n.nodes.find(r=>r.type.startsWith("trigger."));if(!e)return null;let t=n.edges.filter(r=>r.from===e.id).map(r=>r.to);return{triggerId:e.id,pending:t}}function N(n,e){return n.nodes.find(t=>t.id===e)}Gt();Vt();function zn(n,e,t){let r=n.split(".");if(r[0]==="env"){if(r.length!==2)return"";let i=r[1];if(!t.has(i))return"";let s=process.env[i];return typeof s=="string"?s:""}let o=e;for(let i of r){if(o==null||typeof o!="object")return"";o=o[i]}return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}function A(n,e,t={}){let r=new Set(t.envAllow||[]);return n.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_.-]*)\s*\}\}/g,(o,i)=>zn(i,e,r))}function b(n,e,t={}){let r={};for(let[o,i]of Object.entries(n))typeof i=="string"?r[o]=A(i,e,t):Array.isArray(i)?r[o]=i.map(s=>typeof s=="string"?A(s,e,t):s):i&&typeof i=="object"?r[o]=b(i,e,t):r[o]=i;return r}var xt="workflow-classify",Y="unsure",Pt=async n=>{let e=n.node.config,t=n.run.context,r={envAllow:n.workflow.envAllow},o=A(String(e.input??""),t,r).trim();if(!o)return{error:`classify node "${n.node.id}" missing config.input`};let i=e.labels,s=Array.isArray(i)?Object.fromEntries(i.map(m=>[String(m),null])):typeof i=="object"&&i?Object.fromEntries(Object.entries(i).map(([m,y])=>[m,y==null?null:String(y)])):{},a=Object.keys(s);if(a.length<2)return{error:`classify node "${n.node.id}" needs at least two labels`};if(a.includes(Y))return{error:`classify node "${n.node.id}": "${Y}" is reserved for the low-confidence port`};let d=typeof e.minConfidence=="number"?e.minConfidence:.7,c=e.instructions?A(String(e.instructions),t,r):void 0,u={input:o};if(e.state&&typeof e.state=="object")for(let[m,y]of Object.entries(e.state)){let w=typeof y=="string"?A(y,t,r):y;(w===null||["string","number","boolean"].includes(typeof w))&&(u[m]=w)}let p=await We(xt,u,{label:Oe(s,c)},{features:{workflow:n.workflow.id,node:n.node.id}});if(!p)return{error:`classify node "${n.node.id}": decision seat unavailable (set decisions.seats.${xt}.mode)`};let f=p.answers.label,g=f.confidence>=d,h=g?f.choice:Y;return n.log(`[node:${n.node.id}] classify \u2192 ${f.choice} (${f.confidence.toFixed(2)})${g?"":` \u2014 below ${d}, routing to ${Y}`}`),{output:{result:f.choice,label:f.choice,confidence:f.confidence,probabilities:f.probabilities,unsure:!g,port:h},port:h}};var be=class{active=new Map;waiters=new Map;async acquire(e,t){let r=this.active.get(e)??0;if(r<t){this.active.set(e,r+1);return}return new Promise(o=>{let i=this.waiters.get(e)??[];i.push({resolve:()=>{this.active.set(e,(this.active.get(e)??0)+1),o()}}),this.waiters.set(e,i)})}release(e){let t=this.active.get(e)??0;this.active.set(e,Math.max(0,t-1));let r=this.waiters.get(e);r&&r.length>0&&r.shift().resolve()}stats(e){return{active:this.active.get(e)??0,waiting:this.waiters.get(e)?.length??0}}},G=new be;function Tt(n,e){return`${n}:${e}`}var F=async n=>({output:n.run.context[n.node.id]??{}}),qn=async n=>{let e=n.node.config,t=String(e.agentId??""),r=String(e.prompt??"");if(!t)return{error:`agent node "${n.node.id}" missing config.agentId`};let o=A(r,n.run.context,{envAllow:n.workflow.envAllow}),i=typeof e.timeoutMinutes=="number"?e.timeoutMinutes:void 0,s=e.autonomy===void 0||e.autonomy===null?void 0:String(e.autonomy);if(s!==void 0&&s!=="report"&&s!=="propose"&&s!=="act")return{error:`agent node "${n.node.id}" has invalid autonomy "${s}" (expected report, propose or act)`};let a=typeof e.maxConcurrent=="number"&&e.maxConcurrent>0?e.maxConcurrent:null,d=a?Tt(n.workflow.id,n.node.id):null;if(d&&a){let u=G.stats(d);u.active>=a&&n.log(`[node:${n.node.id}] gated: ${u.active} active (cap ${a}), ${u.waiting+1} waiting`),await G.acquire(d,a)}let c=Date.now();try{let u=await n.agents.execute({agentId:t,message:o,workflowRunId:n.run.id,timeoutMinutes:i,...s?{autonomy:s}:{}}),p=Date.now()-c;if(u.error){let h=u.errorKind??"unknown";return n.log(`[node:${n.node.id}] agent "${t}" failed (${h}): ${u.error}`),{error:`[${h}] ${u.error}`}}let g=String(e.resultParser??"acme-result-token")==="json"?hr(u.content):Ot(u.content);return{output:{reply:u.content,result:g.result,json:g.json,taskId:u.taskId,durationMs:p,...u.autonomyBlocks?.length?{autonomyBlocks:u.autonomyBlocks}:{}}}}catch(u){return n.log(`[node:${n.node.id}] agent "${t}" threw: ${u.message}`),{error:u.message}}finally{d&&G.release(d)}},Jn=async n=>{let e=ke(n.node,n.run.context);return e?{output:{port:e},port:e}:(n.log(`[node:${n.node.id}] branch matched no case and no default port`),{output:{port:null}})},Yn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.text??"");if(!t||!r){let a=String(n.node.config.chatId??""),d=String(n.node.config.channel??""),c=[];return t||c.push(`channel config="${d}" rendered=""`),r||c.push(`chatId config="${a}" rendered=""`),(/\{\{\s*env\./.test(a)||/\{\{\s*env\./.test(d))&&c.push("(env.* templates only resolve for names listed in workflow.envAllow and actually set in process.env)"),{error:`action.send "${n.node.id}" needs channel + chatId \u2014 ${c.join("; ")}`}}let i=Ie(n,e.accountId),s=n.channels[t];if(s?.send)try{return{output:{messageId:await s.send({channel:t,chatId:r,text:o,...i?{accountId:i}:{}})??null}}}catch(a){return{error:`action.send failed: ${a.message}`}}if(n.forwardChannelSend)try{return{output:{messageId:(await n.forwardChannelSend({channel:t,chatId:r,text:o,accountId:i})).messageId,viaMesh:!0}}}catch(a){return n.log(`[node:${n.node.id}] mesh-forward of "${t}" send failed: ${a.message}`),{error:`action.send via mesh failed: ${a.message}`}}return n.log(`[node:${n.node.id}] adapter "${t}" not available locally and no mesh forwarder`),{error:`channel "${t}" not available (no local adapter, no mesh route)`}},Gn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.title??""),i=String(e.description??""),s=Array.isArray(e.labels)?e.labels.map(String):[],a=Array.isArray(e.assignees)?e.assignees.map(String):[];if(!r||!o)return{error:`action.createIssue "${n.node.id}" needs project + title`};let d=Se(n),c=n.channels[t];if(!c?.createIssue)return{error:`channel "${t}" does not support createIssue`};try{let u=await c.createIssue({project:r,title:o,description:i,labels:s,assignees:a,agentId:d});return u?{output:{issue:{iid:u.iid,url:u.url,webUrl:u.url}}}:{error:"createIssue returned null (see adapter log)"}}catch(u){return{error:`action.createIssue failed: ${u.message}`}}},Vn=async()=>({output:{}}),Zn=async n=>{let e=n.node.config,t=String(e.name??n.node.id),r=e.waitFor??{},o=e.resumeMatch??{};return{paused:!0,pausedAt:{kind:"checkpoint",nodeId:n.node.id,checkpointName:t,resumeMatch:{...r,...o}}}},Qn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.iid??""),i=Array.isArray(e.add)?e.add.map(String):[],s=Array.isArray(e.remove)?e.remove.map(String):[];if(!r||!o)return{error:`action.setLabel "${n.node.id}" needs project + iid (try {{trigger.project}} / {{trigger.issue.iid}})`};if(i.length===0&&s.length===0)return{output:{skipped:!0,reason:"no labels to add or remove"}};let a=n.channels[t];if(!a?.setLabels)return{error:`channel "${t}" does not support setLabels`};let d=Se(n),c=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await a.setLabels({project:r,kind:c,iid:o,add:i,remove:s,agentId:d})??[],add:i,remove:s}}},Xn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.iid??"");if(!r||!o)return{error:`action.readLabel "${n.node.id}" needs project + iid`};let i=n.channels[t];if(!i?.getLabels)return{error:`channel "${t}" does not support getLabels`};let s=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await i.getLabels({project:r,kind:s,iid:o})??[]}}},er=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.messageId??""),i=String(e.emoji??"\u{1F440}");if(!t||!r||!o)return{error:`action.react "${n.node.id}" needs channel + chatId + messageId`};let s=Ie(n,e.accountId),a=n.channels[t];if(!a?.react)return{error:`channel "${t}" does not support react`};try{return await a.react(r,o,i,s),{output:{emoji:i}}}catch(d){return{error:`action.react failed: ${d.message}`}}},tr=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.messageId??""),i=String(e.text??""),s=e.parseMode?String(e.parseMode):void 0;if(!t||!r||!o||!i)return{error:`action.editMessage "${n.node.id}" needs channel + chatId + messageId + text`};let a=Ie(n,e.accountId),d=n.channels[t];if(!d?.editMessage)return{error:`channel "${t}" does not support editMessage`};try{return{output:{edited:await d.editMessage(r,o,i,s,a)}}}catch(c){return{error:`action.editMessage failed: ${c.message}`}}},nr=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.chatId??""),o=Number(e.durationMs??0);if(!r||!o)return{error:`action.logTime "${n.node.id}" needs chatId + durationMs`};let i=n.channels[t];if(!i?.logTimeSpent)return{error:`channel "${t}" does not support logTimeSpent`};let s=Se(n);try{return await i.logTimeSpent(r,o,s),{output:{durationMs:o}}}catch(a){return{error:`action.logTime failed: ${a.message}`}}},rr=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.url??"");if(!t)return{error:`action.callHTTP "${n.node.id}" needs url`};let r=String(e.method??"POST").toUpperCase(),o=e.headers&&typeof e.headers=="object"?e.headers:{"Content-Type":"application/json"},i;e.body!==void 0&&(i=typeof e.body=="string"?e.body:JSON.stringify(e.body));try{let s=await fetch(t,{method:r,headers:o,body:i}),a=await s.text(),d=a;try{d=JSON.parse(a)}catch{}return{output:{ok:s.ok,status:s.status,body:d}}}catch(s){return{error:`action.callHTTP failed: ${s.message}`}}},or=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.actionId??e.id??"");if(!t)return{error:`action.run "${n.node.id}" needs actionId`};let r=e.inputs&&typeof e.inputs=="object"?e.inputs:{},{ActionStore:o}=await import("./store-TWQPEM5V.js"),{runAction:i}=await import("./runner-56G3N7M4.js"),s=new o().get(t);if(!s)return{error:`action.run "${n.node.id}": no action "${t}" in registry`};try{let a=await i(s,r),d={ok:a.ok,output:a.output,status:a.status,durationMs:a.durationMs};return a.errors!==void 0&&(d.errors=a.errors),a.ok?{output:d}:{output:d,error:`action "${t}" failed (status=${a.status})`}}catch(a){return{error:`action.run failed: ${a.message}`}}},ir=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.name??"");if(!t)return{error:`action.builtin "${n.node.id}" needs a "name" (e.g. "http.fetch")`};let r=e.input&&typeof e.input=="object"?e.input:{},{runBuiltin:o,getBuiltin:i}=await import("./builtin-W6KNX7RS.js");if(!i(t))return{error:`action.builtin "${n.node.id}": unknown built-in "${t}"`};try{return{output:await o(t,r)}}catch(s){let a=s?.name==="ZodError"?`validation: ${s.message}`:s?.message||String(s);return{error:`action.builtin "${t}" failed: ${a}`}}},sr=async n=>{let e=n.node.config,t=n.run.context;return typeof e.path=="string"&&e.path?{output:{value:q(t,e.path)}}:e.template&&typeof e.template=="object"?{output:b(e.template,t,{envAllow:n.workflow.envAllow})}:{output:{}}};function ar(n){if(n!=null){if(typeof n=="number")return new Date(Date.now()+n*6e4).toISOString();if(typeof n=="object"&&n&&"minutes"in n){let e=Number(n.minutes);if(Number.isFinite(e))return new Date(Date.now()+e*6e4).toISOString()}if(typeof n=="string"){let e=/^P(?:([0-9]+)D)?(?:T(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?)?$/.exec(n);if(e){let t=Number(e[1]??0),r=Number(e[2]??0),o=Number(e[3]??0),i=Number(e[4]??0),s=((t*24+r)*60+o)*6e4+i*1e3;if(s>0)return new Date(Date.now()+s).toISOString()}}}}var dr=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.workflowId??"");if(!r)return{error:`subProcess "${n.node.id}" missing config.workflowId`};let o=n.run.depth??0,i=n.workflow.maxChildDepth??5;if(o+1>=i)return{error:`max child workflow depth ${i} exceeded at ${n.workflow.id} \u2192 ${r} (parent depth ${o})`};let s=e.inputMap,a={};if(s==="*")a={...n.run.context};else if(s&&typeof s=="object")for(let[d,c]of Object.entries(s))c&&typeof c=="object"&&!Array.isArray(c)?a[d]=b(c,n.run.context,{envAllow:n.workflow.envAllow}):typeof c=="string"&&(a[d]={value:A(c,n.run.context,{envAllow:n.workflow.envAllow})});return{paused:!0,pausedAt:{kind:"subProcess",nodeId:n.node.id,childRunId:"",childWorkflowId:r},spawnChild:{workflowId:r,input:a}}},cr=F,lr=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.name??"");if(!r)return{error:`signal.emit "${n.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=t.payload&&typeof t.payload=="object"?t.payload:{};return{output:{emittedAt:new Date().toISOString(),name:r,scope:o,payload:i},emitSignal:{name:r,scope:o,payload:i}}},ur=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.name??"");if(!r)return{error:`signal.wait "${n.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=e.match&&typeof e.match=="object"?e.match:{};return{paused:!0,pausedAt:{kind:"signalWait",nodeId:n.node.id,signalName:r,match:i,scope:o}}},pr=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=ar(t.after??e.after);return r?{paused:!0,pausedAt:{kind:"timerWait",nodeId:n.node.id,fireAt:r}}:{error:`timer.boundary "${n.node.id}" needs config.after (duration or minutes)`}},fr=async()=>({output:{}}),gr=async n=>{let e=n.node.config,r=(Array.isArray(e.inputs)?e.inputs:[]).map(s=>typeof s=="string"?A(s,n.run.context,{envAllow:n.workflow.envAllow}):s),o=Array.isArray(e.rules)?e.rules:[];for(let s of o){let a=Array.isArray(s.when)?s.when:[];if(a.length!==r.length)continue;let d=!0;for(let c=0;c<a.length;c++)if(!mr(a[c],r[c])){d=!1;break}if(d)return{output:{...s.output??{},matchedPort:s.to??""},port:s.to}}let i=e.default;return{output:{...i?.output??{},matchedPort:i?.to??""},port:i?.to}};function mr(n,e){if(n==null||n==="*")return!0;let t=String(n),r=typeof e=="number"?e:String(e??""),o=/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/.exec(t);if(o){let i=o[1],s=Number(o[2]),a=typeof r=="number"?r:Number(r);if(Number.isNaN(a))return!1;switch(i){case">":return a>s;case"<":return a<s;case">=":return a>=s;case"<=":return a<=s}}if(t.startsWith("!="))return String(r)!==t.slice(2);if(t.startsWith("/")&&t.endsWith("/")&&t.length>2)try{return new RegExp(t.slice(1,-1)).test(String(r))}catch{return!1}return String(r)===t}var Nt={"trigger.channel":F,"trigger.manual":F,"trigger.cron":F,"trigger.hook":F,"trigger.form":cr,agent:qn,classify:Pt,branch:Jn,transform:sr,"gateway.parallel":fr,rule:gr,"action.send":Yn,"action.createIssue":Gn,"action.setLabel":Qn,"action.readLabel":Xn,"action.react":er,"action.editMessage":tr,"action.logTime":nr,"action.callHTTP":rr,"action.run":or,"action.builtin":ir,subProcess:dr,"signal.emit":lr,"signal.wait":ur,"timer.boundary":pr,checkpoint:Zn,end:Vn};function ve(n){return Nt[n]}function Ie(n,e){if(typeof e=="string"&&e)return e;let t=n.workflow.nodes.find(i=>i.type.startsWith("trigger."));if(!t)return;let o=n.run.context[t.id]?.accountId;return typeof o=="string"&&o?o:void 0}function Se(n){for(let e=n.run.history.length-1;e>=0;e--){let t=n.run.history[e],r=n.workflow.nodes.find(o=>o.id===t.nodeId);if(r?.type==="agent")return r.config.agentId??void 0}}function Ot(n){if(!n)return{};let e=n.match(/\bRESULT:\s*([a-z][a-z0-9_-]*)/i);if(e)return{result:e[1].toLowerCase()};let t=n.match(/\[(APPROVED|REJECTED|CHANGES[-_]REQUESTED|DONE|FAILED|SKIPPED)\]/i);return t?{result:t[1].toLowerCase().replace("_","-")}:{}}function hr(n){let{result:e}=Ot(n);if(!n)return{result:e};let t=n.match(/```(?:json)?\s*([\s\S]*?)```/);if(!t)return{result:e};try{return{result:e,json:JSON.parse(t[1])}}catch{return{result:e}}}var j=class{handlers=new Set;subscribe(e){return this.handlers.add(e),()=>this.handlers.delete(e)}emit(e){for(let t of this.handlers)try{Promise.resolve(t(e)).catch(()=>{})}catch{}}};function V(n,e){if(n.name!==e.name||n.scope==="workflow"&&n.workflowId!==e.workflowId)return!1;for(let[t,r]of Object.entries(n.match??{}))if(!(r===void 0||r===""||r==="*")&&e.payload[t]!==r)return!1;return!0}function wr(n,e,t=Date.now){return{ts:t(),source:"workflow",sourceEventId:`${n.workflowId}:${n.eventId}`,project:n.project,subject:`workflow:${n.workflowId}:entity:${n.entityRef.backend}:${n.entityRef.id}`,intent:`workflow.${n.triggerSource}`,rawJson:e}}function yr(n){return n.claimed&&n.runId?{agentId:`workflow-run:${n.runId}`,outcome:"dispatched",reason:n.reason??"claimed"}:n.claimed&&!n.runId?{agentId:null,outcome:"halted",reason:n.reason??"claimed-but-no-run"}:{agentId:null,outcome:"halted",reason:n.reason??"not-claimed"}}function kr(n){return{decidedBy:"workflow-dispatcher",decide:()=>({agentId:n.agentId,outcome:n.outcome==="deduped"?"halted":n.outcome,reason:n.outcome==="deduped"?`legacy-dedup: ${n.reason??""}`.trim():n.reason??null})}}function Wt(n,e,t,r,o=Date.now){let i=wr(e,t,o),s=yr(r),a=kr(s),d=ze(n,i,a,o);return qe(n,"workflow",d,s,o),d}var br=4e3,vr=8,Ae=class{store;runs;nodeId;forwarder;channels;agents;log;timers;signals;events;ackTypingTimers=new Map;commitChains=new Map;constructor(e){this.store=e.store,this.runs=e.runs,this.nodeId=e.nodeId,this.forwarder=e.forwarder,this.channels=e.channels,this.agents=e.agents,this.log=e.log??(()=>{}),this.timers=e.timers??new ae({log:t=>this.log(t)}),this.signals=e.signals??new j,this.events=e.events,this.timers.onFire(t=>this.resumeFromTimer(t)),this.signals.subscribe(t=>this.resumeFromSignal(t))}emitRunEvent(e){if(this.events)try{this.events.publish({kind:"run",runId:e.runId,workflowId:e.workflowId,nodeId:e.nodeId,phase:e.phase,status:e.status,note:e.note,homeNode:e.homeNode,rootId:e.rootId})}catch{}}async commit(e,t){let o=(this.commitChains.get(e)??Promise.resolve()).then(()=>t(),()=>t());return this.commitChains.set(e,o.then(()=>{},()=>{})),o}emitSignal(e){let t={name:e.name,scope:e.scope??"global",workflowId:e.workflowId??"",payload:e.payload??{},emittedAt:new Date().toISOString()};if(this.signals.emit(t),this.events)try{this.events.publish({kind:"signal",name:t.name,scope:t.scope,workflowId:t.workflowId||void 0,payload:t.payload})}catch{}return t}async resumeFromSignal(e){let t=this.runs.list({limit:500});for(let r of t){if(r.status!=="paused"||!r.pausedAt||r.pausedAt.kind!=="signalWait")continue;let o={name:r.pausedAt.signalName,scope:r.pausedAt.scope,workflowId:r.workflowId,match:r.pausedAt.match??{}};if(!V(o,e))continue;let i=this.store.list().find(s=>s.id===r.workflowId);i&&(await this.commit(r.id,()=>{let s=this.runs.get(r.id);if(!s||s.status!=="paused"||!s.pausedAt||s.pausedAt.kind!=="signalWait"||!V({name:s.pausedAt.signalName,scope:s.pausedAt.scope,workflowId:s.workflowId,match:s.pausedAt.match??{}},e))return;let a=N(i,s.pausedAt.nodeId),d=a?i.edges.filter(u=>u.from===a.id).map(u=>u.to):[],c={receivedAt:new Date().toISOString(),name:e.name,payload:e.payload};this.runs.recordExecution({runId:s.id,entry:{at:c.receivedAt,nodeId:s.pausedAt.nodeId,inputKeys:[],status:"resumed",output:c,idempotencyKey:T(s.id,s.pausedAt.nodeId,`signal:${e.name}:${e.emittedAt}`)},nextPending:d,status:"running",pausedAt:null,context:{...s.context,[s.pausedAt.nodeId]:c}}),this.log(`[workflow:${i.id}] run ${s.id} resumed from signal "${e.name}"`),this.emitRunEvent({runId:s.id,workflowId:i.id,nodeId:s.pausedAt.nodeId,phase:"resumed",status:"running",note:`signal:${e.name}`,rootId:s.eventRootId})}),this.walk(i,r.id,`signal:${e.name}`).catch(s=>this.log(`[workflow:${i.id}] walk-after-signal failed: ${s.message}`)))}}async resumeFromTimer(e){let t=this.store.list().find(r=>r.id===(this.runs.get(e.runId)?.workflowId??""));t&&(await this.commit(e.runId,()=>{let r=this.runs.get(e.runId);if(!r||r.status!=="paused"||!r.pausedAt||r.pausedAt.kind!=="timerWait"||r.pausedAt.nodeId!==e.nodeId)return;let o=N(t,e.nodeId),i=o?t.edges.filter(d=>d.from===o.id).map(d=>d.to):[],s=new Date().toISOString(),a={firedAt:s,scheduledFor:e.fireAt};this.runs.recordExecution({runId:r.id,entry:{at:s,nodeId:e.nodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:T(r.id,e.nodeId,`timer:${e.id}`)},nextPending:i,status:"running",pausedAt:null,context:{...r.context,[e.nodeId]:a}}),this.log(`[workflow:${t.id}] run ${r.id} resumed from timer "${e.nodeId}" (fired ${s})`),this.emitRunEvent({runId:r.id,workflowId:t.id,nodeId:e.nodeId,phase:"resumed",status:"running",note:`timer:${e.id}`,rootId:r.eventRootId})}),this.walk(t,e.runId,`timer:${e.id}`).catch(r=>this.log(`[workflow:${t.id}] walk-after-timer failed: ${r.message}`)))}async dispatchWorkflow(e){let t=this.store.list().find(s=>s.id===e.workflowId);if(!t)return this.log(`[workflows] dispatchWorkflow: workflow "${e.workflowId}" not found`),{claimed:!1,run:null};let o=t.nodes.find(s=>s.type.startsWith("trigger."))?.config??{},i={source:e.trigger?.source??o.source??"hook",project:e.trigger?.project,repo:e.trigger?.repo,chat:e.trigger?.chat,labels:e.trigger?.labels};return this.dispatchOne(t,e.entityRef,e.event,i)}startChannelAck(e,t){let r=String(t.channel??""),o=String(t.chatId??"");if(!r||!o)return;let i=this.channels[r];if(!i)return;let s=typeof t.accountId=="string"?t.accountId:void 0,a=t.event,d=typeof a?.id=="string"?a.id:a?.id!=null?String(a.id):void 0;if(d&&i.react)try{Promise.resolve(i.react(o,d,"\u{1F440}",s)).catch(()=>{})}catch{}if(this.ackTypingTimers.has(e)||!i.sendTyping)return;let c=()=>{try{Promise.resolve(i.sendTyping(o,s)).catch(()=>{})}catch{}};c();let u=setInterval(c,br);this.ackTypingTimers.set(e,u)}stopChannelAck(e){let t=this.ackTypingTimers.get(e);t&&(clearInterval(t),this.ackTypingTimers.delete(e))}async dispatch(e){let t=this.matchByTrigger(e.trigger,e.fromRemote),o=t.some(a=>a.fanOut)?t:t.slice(0,1),i=[],s=[];for(let a of o){let d=await this.dispatchOne(a,e.entityRef,e.event,e.trigger);d.claimed&&i.push(a),d.run&&s.push(d.run)}return!e.fromRemote&&this.forwarder?.broadcastTrigger&&Promise.resolve(this.forwarder.broadcastTrigger({trigger:e.trigger,entityRef:e.entityRef,event:e.event})).catch(a=>this.log(`[mesh-broadcast] ${a?.message??a}`)),{claimed:i,runs:s}}matchByTrigger(e,t){let r=this.store.list(),o=[];for(let i of r){if(i.state&&i.state!=="active")continue;if(t){if(!i.mesh?.allowRemote)continue;let c=i.mesh.peers;if(c&&c.length>0&&!c.includes(t.peer))continue}let s=i.nodes.find(c=>c.type.startsWith("trigger."));if(!s)continue;let a=s.config;if(a.source!==e.source||i.project&&e.project&&i.project!==e.project)continue;let d=a.filter;if(d){if(d.project&&d.project!=="*"&&d.project!==e.project||d.repo&&d.repo!=="*"&&d.repo!==e.repo||d.chat&&d.chat!=="*"&&Z(e.source,d.chat)!==Z(e.source,e.chat))continue;if(d.labels?.length){let c=new Set(e.labels??[]);if(!d.labels.some(p=>c.has(p)))continue}}o.push(i)}return o.sort((i,s)=>s.priority-i.priority||i.id.localeCompare(s.id))}async dispatchOne(e,t,r,o){let i=await this.dispatchOneLegacy(e,t,r,o);if(Be("workflow")!=="off")try{Wt(He(),{workflowId:e.id,eventId:r.id,triggerSource:o.source,project:o.project??null,entityRef:t},JSON.stringify({event:r,trigger:o,entityRef:t}),{claimed:i.claimed,runId:i.run?.id??null})}catch(s){this.log(`[ledger] workflow ${e.id} run ${i.run?.id??"?"} record failed: ${s?.message??s}`)}return i}async dispatchOneLegacy(e,t,r,o){let i=this.runs.getActiveByEntity(t),s=i?this.runs.getHomeNodeByEntity(t):null;if(i&&s&&s!==this.nodeId){if(!this.forwarder)return this.log(`[workflow:${e.id}] run ${i} home'd on "${s}" but no forwarder \u2014 dropping`),{claimed:!1,run:null};try{await this.forwarder.forwardTransition(s,{workflowId:e.id,event:r,entityRef:t})}catch(d){this.log(`[workflow:${e.id}] forward to "${s}" failed: ${d.message}`)}return{claimed:!0,run:null}}let a=i?this.runs.get(i):null;if(a)if(a.status==="paused"&&a.pausedAt){if(a.pausedAt.kind!=="checkpoint")return this.log(`[workflow:${e.id}] run ${a.id} paused on ${a.pausedAt.kind} \u2014 channel event bypasses workflow`),{claimed:!1,run:null};if(!Sr(a.pausedAt.resumeMatch,o,r))return this.log(`[workflow:${e.id}] run ${a.id} paused but event doesn't match resumeMatch \u2014 dropping`),{claimed:!1,run:null};let d=N(e,a.pausedAt.nodeId),c=d?e.edges.filter(h=>h.from===d.id).map(h=>h.to):[],u={at:new Date().toISOString(),nodeId:a.pausedAt.nodeId,inputKeys:[],status:"resumed",output:{event:r.payload},idempotencyKey:T(a.id,a.pausedAt.nodeId,`resume:${r.id}`)},p={...a.context,[a.pausedAt.nodeId]:{event:r.payload}},f=a.pausedAt.checkpointName,g=this.runs.recordExecution({runId:a.id,entry:u,nextPending:c,status:"running",pausedAt:null,context:p});g&&(a=g),this.log(`[workflow:${e.id}] run ${a.id} resumed from checkpoint "${f}"`),o.source.endsWith("-message")&&this.startChannelAck(a.id,r.payload)}else return a.status==="running"?(this.log(`[workflow:${e.id}] run ${a.id} already running; dropping concurrent event ${r.id}`),{claimed:!0,run:null}):(this.log(`[workflow:${e.id}] run ${a.id} is ${a.status}; dropping event ${r.id}`),{claimed:!1,run:null});else{let d=J(e);if(!d)return this.log(`[workflow:${e.id}] no trigger node found`),{claimed:!1,run:null};a=this.runs.create({workflowId:e.id,initialPending:d.pending,entityRef:t,initialContext:{[d.triggerId]:r.payload}}),this.log(`[workflow:${e.id}] run ${a.id} created from trigger "${d.triggerId}" for ${t.id}`),this.emitRunEvent({runId:a.id,workflowId:e.id,phase:"created",status:a.status,homeNode:a.homeNode,rootId:a.eventRootId}),o.source.endsWith("-message")&&this.startChannelAck(a.id,r.payload)}return this.walk(e,a.id,r.id),{claimed:!0,run:a}}async walk(e,t,r){let o=this.runs.get(t)?.eventRootId,i=()=>this.walkInner(e,t,r);try{await(o?Ke({rootId:o},i):i())}finally{this.stopChannelAck(t)}}async walkInner(e,t,r){let o=this.runs.get(t);if(o)for(;o.status==="running"&&o.pending.length>0;){let i=o.pending.slice(0,vr);await Promise.allSettled(i.map(a=>this.executeNodeAndCommit(e,t,a,r)));let s=this.runs.get(t);if(!s||(o=s,o.status!=="running"))return}}async executeNodeAndCommit(e,t,r,o){let i=T(t,r,o),s=await this.commit(t,()=>{let m=this.runs.get(t);if(!m)return{kind:"done"};if(m.status!=="running")return{kind:"done"};let y=N(e,r);if(!y)return this.log(`[workflow:${e.id}] missing node "${r}" \u2014 marking run failed`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"failed",idempotencyKey:i,note:"node definition missing from workflow"},nextPending:m.pending.filter(R=>R!==r),status:"failed"}),{kind:"done"};let w=ve(y.type);return w?m.history.some(R=>R.idempotencyKey===i)?(this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"skipped",idempotencyKey:i+"_dedup",note:"duplicate execution dropped"},nextPending:m.pending.filter(R=>R!==r)}),{kind:"done"}):{kind:"go",run:m,node:y,handler:w}:(this.log(`[workflow:${e.id}] no handler for node type "${y.type}"`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"failed",idempotencyKey:i,note:`no handler for node type "${y.type}"`},nextPending:m.pending.filter(R=>R!==r),status:"failed"}),{kind:"done"})});if(s.kind==="done")return;let{run:a,node:d,handler:c}=s,u=e.edges.filter(m=>m.to===r).map(m=>m.from),p;if(d.type!=="agent"){let m=ne();if(m)try{p=Je(m,{agentId:`workflow:${d.type}`,channel:"workflow",chatId:`${e.id}:${r}`,workflowRunId:t,workflowId:e.id,workflowNodeId:r,messagePreview:`${d.type} ${r}`})}catch{}}let f=d.retry??{maxAttempts:1,backoffMs:1e3},g={error:"retry-loop did not run"},h=0;for(;h<f.maxAttempts;){h++;try{g=await c({workflow:e,run:a,node:d,channels:this.channels,agents:this.agents,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder),log:this.log})}catch(m){this.log(`[workflow:${e.id}] handler "${d.type}" threw: ${m.message}`),g={error:m.message}}if(!g.error||g.paused)break;if(h<f.maxAttempts){let m=f.backoffMs*Math.pow(2,h-1);this.log(`[workflow:${e.id}] node "${r}" failed (attempt ${h}/${f.maxAttempts}): ${g.error.slice(0,120)} \u2014 retrying in ${m}ms`),await new Promise(y=>setTimeout(y,m))}}if(p){let m=ne();if(m)try{Ye(m,p,{status:g.error?"error":"ok",error:g.error??null})}catch{}}await this.commit(t,async()=>{let m=this.runs.get(t);if(!m)return;let y=new Date().toISOString(),w=m.pending.filter(k=>k!==r);if(g.error){let k=m.status==="running"?"failed":void 0;this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:u,status:"failed",idempotencyKey:i,note:g.error.slice(0,200)},nextPending:w,status:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:"failed",status:k??m.status,note:g.error.slice(0,200)});return}if(g.paused&&g.pausedAt){let k=g.pausedAt,P=null;if(g.spawnChild&&k.kind==="subProcess"){if(P=await this.spawnChild({parent:m,parentNodeId:r,childWorkflowId:g.spawnChild.workflowId,input:g.spawnChild.input}),!P){this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:u,status:"failed",idempotencyKey:i,note:`subProcess: child workflow "${g.spawnChild.workflowId}" not found`},nextPending:w,status:"failed"});return}k={...k,childRunId:P.id}}if(this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:u,status:"paused",idempotencyKey:i},nextPending:w,status:"paused",pausedAt:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:"paused",status:"paused",note:k.kind}),P&&this.kickChildWalk(P),k.kind==="timerWait")try{this.timers.schedule({runId:t,workflowId:e.id,nodeId:k.nodeId,fireAt:k.fireAt,cancelKey:`${t}:${k.nodeId}`})}catch(Pe){this.log(`[workflow:${e.id}] timer schedule failed: ${Pe.message}`)}return}let R=g.output??{},Kt={...m.context,[r]:R},{nextPending:Bt}=ye({workflow:e,fromNodeId:r,selectedPort:g.port}),te=[],M={...m.joinCounters??{}};for(let k of Bt){let P=N(e,k);if(!(P?.type==="gateway.parallel"&&String(P.config?.mode??"fanOut")==="join")){te.push(k);continue}let _=M[k]??[];_.includes(r)||_.push(r),M[k]=_;let Jt=e.edges.filter(Yt=>Yt.to===k).length;_.length>=Jt&&(te.push(k),delete M[k])}let zt=[...w,...te],C=d.type==="end",qt=m.status==="running"?C?String(d.config.status??"completed"):"running":void 0,O=this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:u,status:"ok",output:R,idempotencyKey:i},nextPending:C?[]:zt,status:qt,context:Kt,joinCounters:M});this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:C?"completed":"ok",status:O?.status??m.status}),g.emitSignal&&this.emitSignal({name:g.emitSignal.name,scope:g.emitSignal.scope,workflowId:e.id,payload:g.emitSignal.payload}),C&&O&&O.parentRunId&&O.parentNodeId&&this.resumeParent({parentRunId:O.parentRunId,parentNodeId:O.parentNodeId,childRun:O}).catch(k=>this.log(`[workflow:${e.id}] resumeParent failed: ${k.message}`))})}async spawnChild(e){let t=this.store.list().find(a=>a.id===e.childWorkflowId);if(!t)return null;let r=J(t);if(!r)return this.log(`[workflow:${t.id}] no trigger node \u2014 cannot spawn as child`),null;let o={...e.input};o[r.triggerId]={...o[r.triggerId]??{},parentRunId:e.parent.id,parentNodeId:e.parentNodeId};let i={backend:"agentx-internal",id:`subprocess:${e.parent.id}:${e.parentNodeId}`},s=this.runs.create({workflowId:t.id,initialPending:r.pending,entityRef:i,initialContext:o,parentRunId:e.parent.id,parentNodeId:e.parentNodeId,rootRunId:e.parent.rootRunId??e.parent.id,depth:(e.parent.depth??0)+1});return this.log(`[workflow:${t.id}] child run ${s.id} spawned from ${e.parent.id}/${e.parentNodeId} (depth ${s.depth})`),s}kickChildWalk(e){let t=this.store.list().find(r=>r.id===e.workflowId);t&&this.walk(t,e.id,`spawn:${e.parentRunId}:${e.parentNodeId}`).catch(r=>this.log(`[workflow:${t.id}] child walk failed: ${r.message}`))}async resumeParent(e){let t=this.runs.get(e.parentRunId);if(!t)return;let r=this.store.list().find(o=>o.id===t.workflowId);r&&(await this.commit(e.parentRunId,()=>{let o=this.runs.get(e.parentRunId);if(!o||o.status!=="paused"||!o.pausedAt||o.pausedAt.kind!=="subProcess"||o.pausedAt.nodeId!==e.parentNodeId||o.pausedAt.childRunId!==e.childRun.id)return;let i=N(r,e.parentNodeId),s=i?r.edges.filter(d=>d.from===i.id).map(d=>d.to):[],a={childRunId:e.childRun.id,status:e.childRun.status,output:Ir(e.childRun)};this.runs.recordExecution({runId:o.id,entry:{at:new Date().toISOString(),nodeId:e.parentNodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:T(o.id,e.parentNodeId,`child:${e.childRun.id}`)},nextPending:s,status:"running",pausedAt:null,context:{...o.context,[e.parentNodeId]:a}}),this.log(`[workflow:${r.id}] parent run ${o.id} resumed from subProcess child ${e.childRun.id}`),this.emitRunEvent({runId:o.id,workflowId:r.id,nodeId:e.parentNodeId,phase:"resumed",status:"running",note:`child:${e.childRun.id}`,rootId:o.eventRootId})}),this.walk(r,e.parentRunId,`child:${e.childRun.id}`))}};function Ir(n){for(let e=n.history.length-1;e>=0;e--){let t=n.history[e];if(t.status==="ok"&&t.output&&Object.keys(t.output).length>0)return t.output}return{}}function Sr(n,e,t){let r=i=>{let s=n[i];if(s===void 0||s===""||s==="*")return!0;if(Array.isArray(s)){let a=new Set(e.labels??[]);return s.some(d=>a.has(String(d)))}return i==="chat"?Z(e.source,String(s))===Z(e.source,e.chat):e[i]===s};if(!r("source")||!r("project")||!r("repo")||!r("chat"))return!1;let o=n.eventIdLike;return!(typeof o=="string"&&o&&!t.id.includes(o))}function Z(n,e){return e==null?"":n==="whatsapp-message"?e.replace(/@s\.whatsapp\.net$|@g\.us$/i,"").replace(/[\s+()]/g,""):e}function Ar(n){return{"pre:channel-message":async e=>{let t=e.msg;if(!t)return{};let r=Rr(t.channel);if(!r)return{};let o=t.group?.id??t.sender.id,i={backend:t.channel,id:`${t.channel}:${o}`},{claimed:s}=await n.dispatch({trigger:{source:r,chat:o},entityRef:i,event:{id:`${t.channel}:${t.accountId}:${t.id}`,payload:$r(t)}});return s.length===0?{}:s.every(d=>d.nodes.find(u=>u.type.startsWith("trigger."))?.config?.passthrough===!0)?{}:{blocked:!0,message:`handled by workflow${s.length>1?"s":""}: ${s.map(d=>d.id).join(", ")}`}},"on:gitlab-issue":async e=>{let t=e.project,r=e.iid,o=e.issueEvent;if(!t||r===void 0)return{};let i=Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(d=>typeof d=="string"?d:d?.title).filter(Boolean):o?.labels?.map(d=>d?.title)??[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a={backend:"gitlab",id:`${t}#${r}`};return await n.dispatch({trigger:{source:"gitlab-issue",project:t,labels:i},entityRef:a,event:{id:`gitlab-issue:${t}:${r}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{issue:{iid:r,title:o?.object_attributes?.title,description:o?.object_attributes?.description,url:o?.object_attributes?.url,action:o?.object_attributes?.action,labels:i,assignees:s},project:t,channel:"gitlab",chatId:`${t}:issue:${r}`}}}),{}},"on:gitlab-mr":async e=>{let t=e.project,r=e.iid,o=e.mrEvent;if(!t||r===void 0)return{};let i=Array.isArray(e.labels)?e.labels:Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(c=>typeof c=="string"?c:c?.title).filter(Boolean):[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a=o?.reviewers??[],d={backend:"gitlab",id:`${t}!${r}`};return await n.dispatch({trigger:{source:"gitlab-mr",project:t,labels:i},entityRef:d,event:{id:`gitlab-mr:${t}:${r}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{mr:{iid:r,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i,assignees:s,reviewers:a},project:t,channel:"gitlab",chatId:`${t}:merge_request:${r}`,iid:r,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i}}}),{}},"on:gitlab-note":async e=>{let t=e.project,r=e.noteId,o=e.noteableType,i=e.noteableIid,s=e.text,a=e.authorUsername,d=e.mentions??[];if(!t||!r||!o||!i)return{};let c=o==="merge_request"?{backend:"gitlab",id:`${t}!${i}`}:{backend:"gitlab",id:`${t}#${i}`};return await n.dispatch({trigger:{source:"gitlab-note",project:t},entityRef:c,event:{id:`gitlab-note:${t}:${o}:${i}:${r}`,payload:{note:{id:r,text:s,author:a,mentions:d,noteableType:o,noteableIid:i,noteableTitle:e.noteableTitle},project:t,channel:"gitlab",chatId:`${t}:${o}:${i}`,noteId:r,noteableType:o,noteableIid:i,text:s,author:a,mentions:d}}}),{}},"on:gitlab-pipeline":async e=>{let t=e.project,r=e.pipelineId,o=e.status,i=e.ref;if(!t||!o)return{};let a=e.raw?.merge_request?.iid;if(!a)return{};let d={backend:"gitlab",id:`${t}!${a}`};return await n.dispatch({trigger:{source:"gitlab-pipeline",project:t},entityRef:d,event:{id:`gitlab-pipeline:${t}:${r}:${o}`,payload:{pipeline:{id:r,status:o,ref:i},project:t,channel:"gitlab",chatId:`${t}:merge_request:${a}`}}}),{}}}}function Rr(n){switch(n){case"telegram":return"telegram-message";case"whatsapp":return"whatsapp-message";case"discord":return"discord-message";case"slack":return"slack-message";default:return null}}function $r(n){let e=n.group?.id??n.sender.id;return{channel:n.channel,chatId:e,accountId:n.accountId,text:n.text,fromJid:n.sender.id,sender:{id:n.sender.id,name:n.sender.name,username:n.sender.username},contact:n.channelMeta?.facts?{facts:n.channelMeta.facts}:void 0,group:n.group?{id:n.group.id,name:n.group.name}:void 0,channelMeta:n.channelMeta,replyTo:n.replyTo,replyToText:n.replyToText,media:n.media,event:{id:n.id,timestamp:n.timestamp?.toISOString?.()??new Date().toISOString()}}}var Q=n=>n.trim().toLowerCase().replace(/^@/,"");function xr(n){let e=typeof n.author=="string"?n.author:typeof n.authorUsername=="string"?n.authorUsername:void 0;if(e)return Q(e);let r=n.payload?.sender?.login;return typeof r=="string"&&r?Q(r):void 0}function Pr(n,e){let t=typeof e.project=="string"?e.project:"";if(n==="on:gitlab-issue"||n==="on:gitlab-mr")return!t||e.iid==null?void 0:`gitlab:${t}${n==="on:gitlab-issue"?"#":"!"}${String(e.iid)}`;if(n==="on:gitlab-note"){let r=e.noteableIid!=null?String(e.noteableIid):"",o=typeof e.noteableType=="string"?e.noteableType:"";return!t||!r||!o?void 0:`gitlab:${t}${o==="issue"?"#":"!"}${r}`}if(n==="on:github-issue"||n==="on:github-pr"){let r=e.payload??{},o=typeof e.repo=="string"?e.repo:r.repository?.full_name,i=e.number??r.issue?.number??r.pull_request?.number;return typeof o!="string"||!o||i==null?void 0:`github:${o}#${String(i)}`}}function Tr(n){let e=new Set;for(let t of n.nodes){let r=t.type==="agent"?t.config.agentId:void 0;typeof r=="string"&&r&&e.add(r)}return[...e]}var X=class{constructor(e=2e3){this.maxKeys=e}fires=new Map;tryFire(e,t,r,o=Date.now()){let i=(this.fires.get(e)??[]).filter(s=>o-s<r);if(i.length>=t)return this.fires.set(e,i),!1;for(i.push(o),this.fires.delete(e),this.fires.set(e,i);this.fires.size>this.maxKeys;){let s=this.fires.keys().next().value;if(s===void 0)break;this.fires.delete(s)}return!0}get size(){return this.fires.size}};function Re(n,e,t){let r=n.logged??(n.logged=new Set);r.has(e)||(r.add(e),n.log(t))}function Et(n,e,t,r,o){let i=xr(t);if(i&&Array.isArray(r?.ignoreAuthors)&&r.ignoreAuthors.length>0&&r.ignoreAuthors.map(Q).includes(i))return{skip:!0,reason:"ignored-author",detail:`author @${i} is in filter.ignoreAuthors`};if(r?.skipSelfAuthored===!0){let a=Tr(n),d=typeof t.authorAgent=="string"?t.authorAgent:void 0;if(d&&a.includes(d))return{skip:!0,reason:"self-authored",detail:`author @${i??"?"} is agent "${d}" which this workflow runs`};if(i){let c=new Set(a.flatMap(u=>(o.forgeUsernames?.(u)??[]).map(Q)));if(c.has(i))return{skip:!0,reason:"self-authored",detail:`author @${i} is this workflow's own bot identity`};a.length===0?Re(o,`noagents:${n.id}`,`[workflows] ${n.id} has no agent node \u2014 self-authored skip can't resolve a bot identity; only filter.ignoreAuthors applies`):c.size===0&&!("authorAgent"in t)&&Re(o,`noident:${n.id}:${e}`,`[workflows] ${n.id} no forge username known for agent(s) ${a.join(", ")} on ${e} \u2014 self-authored skip inactive; only filter.ignoreAuthors applies`)}}let s=r?.maxFiresPerTarget;if(s&&typeof s.count=="number"&&s.count>0){let a=Pr(e,t);if(a){let d=typeof s.windowMinutes=="number"&&s.windowMinutes>0?s.windowMinutes:60,c=o.now?.()??Date.now();if(!o.fireWindow.tryFire(`${n.id}|${a}`,s.count,d*6e4,c))return{skip:!0,reason:"chain-limit",detail:`${a} already fired ${s.count}x within ${d}m (filter.maxFiresPerTarget)`}}else Re(o,`notarget:${n.id}:${e}`,`[workflows] ${n.id} filter.maxFiresPerTarget has no target key for ${e} \u2014 limit not applied`)}return{skip:!1}}function Nr(n){let e=n.store.list(),t={fireWindow:new X,log:n.log,forgeUsernames:n.forgeUsernames,logged:new Set},r=0,o=0;for(let i of e){if(i.state&&i.state!=="active"){n.log(`[workflows] ${i.id} state=${i.state} \u2014 skipping trigger registration`);continue}let s=i.nodes.find(a=>a.type.startsWith("trigger."));if(s){if(s.type==="trigger.cron"){let a=s.config;if(!a.spec){n.log(`[workflows] ${i.id} trigger.cron missing config.spec \u2014 skipping`);continue}Wr({workflowId:i.id,triggerNodeId:s.id,spec:a.spec,timezone:a.timezone??"UTC"},n.dispatcher,n.log),r++}else if(s.type==="trigger.hook"){let a=s.config;if(!a.event||!a.event.startsWith("on:")){n.log(`[workflows] ${i.id} trigger.hook config.event must start with "on:" \u2014 skipping`);continue}n.hooks.registerHandler(a.event,`workflows:${i.id}`,async d=>{try{let c=typeof d.project=="string"?d.project:void 0;if(i.project&&c&&i.project!==c)return{};if(a.filter){if(Array.isArray(a.filter.topic)&&a.filter.topic.length>0){let h=typeof d.topic=="string"?d.topic.toLowerCase():void 0;if(!h||!a.filter.topic.map(m=>m.toLowerCase()).includes(h))return{}}if(Array.isArray(a.filter.action)&&a.filter.action.length>0){let h=typeof d.action=="string"?d.action:void 0;if(!h||!a.filter.action.includes(h))return{}}if(Array.isArray(a.filter.mentions)&&a.filter.mentions.length>0){let h=Array.isArray(d.mentions)?d.mentions.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.mentions.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.noteableType)&&a.filter.noteableType.length>0){let h=typeof d.noteableType=="string"?d.noteableType.toLowerCase():void 0,m=a.filter.noteableType.map(y=>y.toLowerCase());if(!h||!m.includes(h))return{}}if(Array.isArray(a.filter.assigneesAdded)&&a.filter.assigneesAdded.length>0){let h=Array.isArray(d.assigneesAdded)?d.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.reviewersAdded)&&a.filter.reviewersAdded.length>0){let h=Array.isArray(d.reviewersAdded)?d.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.labelsAdded)&&a.filter.labelsAdded.length>0){let h=Array.isArray(d.labelsAdded)?d.labelsAdded.map(w=>w.toLowerCase()):[];if(!a.filter.labelsAdded.map(w=>w.toLowerCase()).some(w=>h.includes(w)))return{}}}let u=Et(i,a.event,d,a.filter,t);if(u.skip){if(n.log(`[workflows] ${i.id} skipping ${a.event} (${u.reason}): ${u.detail}`),a.passthrough)return{};let h=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(h)?h:[],i.id]}}}let p=Or(i.id,a.event,d);if(await n.dispatcher.dispatchWorkflow({workflowId:i.id,entityRef:{backend:"hook",id:p},event:{id:`hook:${a.event}:${Date.now().toString(36)}`,payload:{hookEvent:a.event,...d}}}),a.passthrough)return{};let f=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(f)?f:[],i.id]}}}catch(c){return n.log(`[workflows] ${i.id} hook dispatch failed: ${c.message}`),{}}},60),o++}}}return{cronTimers:r,hookSubscribers:o}}function Or(n,e,t){let r=typeof t.project=="string"?t.project:"",o=t.iid!=null?String(t.iid):"";if(e==="on:gitlab-issue"&&r&&o)return`${n}:${e}:${r}#${o}`;if(e==="on:gitlab-mr"&&r&&o)return`${n}:${e}:${r}!${o}`;if(e==="on:gitlab-pipeline"&&r){let i=t.pipelineId!=null?String(t.pipelineId):"";if(i)return`${n}:${e}:${r}@pipeline:${i}`}return`${n}:${e}:${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Wr(n,e,t){let r=()=>{let o;try{o=Ge(n.spec,new Date,n.timezone)}catch(s){t(`[workflows] ${n.workflowId} cron spec invalid: ${s.message}`);return}let i=Math.max(1e3,o.getTime()-Date.now());setTimeout(()=>{(async()=>{let s=`cron:${n.workflowId}:${o.toISOString()}`;try{await e.dispatchWorkflow({workflowId:n.workflowId,trigger:{source:"cron"},entityRef:{backend:"cron",id:`${n.workflowId}@${o.toISOString()}`},event:{id:s,payload:{now:o.toISOString(),spec:n.spec,workflowId:n.workflowId}}})}catch(a){t(`[workflows] ${n.workflowId} cron dispatch failed: ${a.message}`)}finally{r()}})()},i)};r()}function Dt(n){return n.nodes.find(r=>r.type.startsWith("trigger."))?.config?.inputSchema??null}function Ft(n,e){if(!n||!e?.properties)return{};let t=n.match(/^([^:]+\/[^:]+):([^:]+):(.+)$/);if(!t)return{};let[,r,o,i]=t,s={};if(e.properties.project&&(s.project=r),o==="push"){let a=i.match(/^refs\/heads\/(.+)$/);a&&e.properties.ref&&(s.ref=a[1])}else{let a=Number(i);Number.isFinite(a)&&(e.properties.id&&(s.id=a),e.properties.iid&&(s.iid=a),e.properties.mrId&&(s.mrId=a),e.properties.issueId&&(s.issueId=a),e.properties.prId&&(s.prId=a))}return s}function jt(n,e){if(!n?.properties)return e;let t={...e};for(let[r,o]of Object.entries(n.properties))t[r]===void 0&&o&&"default"in o&&(t[r]=o.default);return t}function Mt(n,e){return!n?.required||!Array.isArray(n.required)?[]:n.required.filter(t=>{let r=e[t];return r===void 0||r===""||r===null})}function Dr(n,e){let t=Dt(n);if(!t?.properties){let d={};for(let[c,u]of Object.entries(e))u!==void 0&&(d[c]=u);return{inputs:d,missing:[],filledFrom:{passthrough:Object.keys(d),chatId:[],defaults:[]}}}let r={};for(let d of["message","agentId","channel","chatId","senderId","senderUsername"])t.properties[d]&&e[d]!==void 0&&(r[d]=e[d]);let o=Ft(e.chatId,t),i={...r,...o},s={...i};i=jt(t,i);let a=Object.keys(i).filter(d=>s[d]===void 0&&i[d]!==void 0);return{inputs:i,missing:Mt(t,i),filledFrom:{passthrough:Object.keys(r),chatId:Object.keys(o),defaults:a}}}import{extname as Fr}from"path";var Ct=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,_t=/<agentx-artifact>[\s\S]*$/i;function Ci(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let i=o.replace(Ct,(s,a)=>{try{let d=JSON.parse(a.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let c=d.mime,u=c.startsWith("image/")?"image":c==="application/pdf"?"pdf":c.startsWith("text/")?"text":"file";r.push({type:u,filename:d.filename,mime:c})}}catch{}return""});return{text:(t?i.replace(_t,""):i).trim(),artifacts:r}}function _i(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(Ct,(i,s)=>{try{let a=JSON.parse(s.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});r=(e?o.replace(_t,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,i,s)=>i===void 0||s===void 0?o:`[${i||s}](${s})`)}var jr={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},Li={bytes:20*1024*1024,perMessage:20,pathChars:512};function Hi(n){return jr[Fr(n).toLowerCase()]??null}var Mr=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
20
20
|
`);function Ui(n,e,t){return n==="app"&&e&&t!==!1?Mr:void 0}import{lstatSync as xe,mkdirSync as Cr,readdirSync as _r,realpathSync as $e,unlinkSync as Lr}from"fs";import{join as ee,resolve as Lt}from"path";var Ht=".agentx/outbox",Hr=7*24*60*60*1e3;function Ur(n,e){try{let t=$e(Lt(e,n)),r=ee(t,Ht);return $e(r)===r&&xe(r).isDirectory()?r:null}catch{return null}}function qi(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=$e(Lt(t,n));xe(ee(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||Cr(ee(o,Ht),{recursive:!0})}catch{return 0}let r=Ur(n,t);return r?Ut(r,(e.now??Date.now())-(e.maxAgeMs??Hr)):0}function Ut(n,e){let t=0;for(let r of _r(n)){let o=ee(n,r);try{let i=xe(o);i.isDirectory()?t+=Ut(o,e):Math.max(i.mtimeMs,i.ctimeMs)<e&&(Lr(o),t++)}catch{}}return t}export{Qe as a,st as b,at as c,oo as d,pn as e,io as f,$ as g,ce as h,v as i,H as j,Rn as k,fe as l,me as m,we as n,Ae as o,Ar as p,Nr as q,Kn as r,Dr as s,Ci as t,_i as u,Li as v,Hi as w,Ui as x,Ht as y,qi as z};
|
|
21
|
-
//# sourceMappingURL=chunk-
|
|
21
|
+
//# sourceMappingURL=chunk-W7SEPJFH.js.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{d as E,i as $,j as V,k as O,l as j}from"./chunk-TTVVXBCM.js";import{t as C,v as R,w as B}from"./chunk-BBIWAJRX.js";import{a as z,b as te}from"./chunk-FX3D7YON.js";import{b as q,f as ee}from"./chunk-72SZI2UW.js";import{o as J,p as Z}from"./chunk-5MUJZODV.js";var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},G=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as P,writeFileSync as T,appendFileSync as re,existsSync as S,mkdirSync as M,renameSync as se,statSync as W}from"fs";import{resolve as k,dirname as Q}from"path";import{createHash as ne}from"crypto";var D=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??k(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),M(this.baseDir,{recursive:!0})}schemaPath(){return k(this.baseDir,"schema.json")}nodesPath(){return k(this.baseDir,"nodes.json")}indexPath(){return k(this.baseDir,"index.json")}classificationsPath(){return k(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let r=P(e,"utf-8"),t=E.safeParse(JSON.parse(r));if(!t.success)throw new Error(`Invalid ${e}: ${t.error.issues.map(n=>n.message).join("; ")}`);if((t.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${t.data.version??1}.bak.json`);try{T(n,r),this.log(`migrated graph schema v${t.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(o){this.log(`could not back up old schema: ${o?.message??o}`)}this.saveSchema(x);let i=this.nodesPath();if(S(i)){let o=i.replace(/\.json$/,".v1.bak.json");try{T(o,P(i,"utf-8")),this.log(`archived v1 nodes.json -> ${o}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=Y();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return t.data}saveSchema(e){let r=E.safeParse(e);if(!r.success)throw new Error(`Refusing to save invalid schema: ${r.error.issues.map(t=>t.message).join("; ")}`);U(this.schemaPath(),r.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let r=Y();return this.saveNodes(r),r}return structuredClone(this.readParsed(e,r=>{let t=O.safeParse(JSON.parse(r));if(!t.success)throw new Error(`Invalid ${e}: ${t.error.issues.map(n=>n.message).join("; ")}`);return t.data}))}saveNodes(e){let r=O.safeParse(e);if(!r.success)throw new Error(`Refusing to save invalid nodes file: ${r.error.issues.map(t=>t.message).join("; ")}`);this.writeParsed(this.nodesPath(),r.data)}readParsed(e,r){let{mtimeMs:t,size:n}=W(e),i=this.parsed.get(e);if(i&&i.mtimeMs===t&&i.size===n)return i.data;let o=r(P(e,"utf-8"));return this.parsed.set(e,{mtimeMs:t,size:n,data:o}),o}writeParsed(e,r){this.parsed.delete(e),U(e,r);let{mtimeMs:t,size:n}=W(e);this.parsed.set(e,{mtimeMs:t,size:n,data:r})}validateNode(e,r,t){let n=r.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let i=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(i.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${i.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!t.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=t.find(u=>u.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let o=r.levels.findIndex(s=>s.id===e.level);if(o===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=t.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=r.levels.findIndex(l=>l.id===s.level);if(c<0||c>=o)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,r,t,n){let i=[],o=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],u=this.loadNodes().nodes;if(u.find(p=>p.id===l)){o.push(l);continue}let h=0;for(let p=c-1;p>=0;p--){let y=e[p],N=u.find(w=>w.id===y)||i.find(w=>w.id===y);if(N){h=t.levels.findIndex(w=>w.id===N.level)+1;break}}let m=r[l]??{},d=null;for(let p=h;p<t.levels.length;p++){let y=t.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,h=p+1;break}}if(!d&&h<t.levels.length&&(d=t.levels[h].id,h++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${h}, levels=${t.levels.length})`);let f=null,v=t.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=u.find(I=>I.id===y)||i.find(I=>I.id===y);if(!N)continue;let w=t.levels.findIndex(I=>I.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),i.push(g)}return{added:i,skipped:o}}addNode(e){let r=this.loadSchema(),t=this.loadNodes();if(t.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,r,[...t.nodes,e]),t.nodes.push(e),this.saveNodes(t),e}appendClassification(e){let r=$.safeParse(e);if(!r.success){let i=r.error.issues.map(o=>`${o.path.join(".")}: ${o.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${i} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let t=JSON.stringify(r.data)+`
|
|
2
|
+
`,n=this.classificationsPath();return S(n)||M(Q(n),{recursive:!0}),re(n,t),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,r=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,r)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let t=P(e,"utf-8").split(`
|
|
3
|
+
`).filter(Boolean),n=new Map;for(let i of t)try{let o=$.safeParse(JSON.parse(i));if(!o.success)continue;n.set(o.data.msgHash,o.data)}catch{}return Array.from(n.values()).sort((i,o)=>i.ts<o.ts?1:-1)}updateClassificationStatus(e,r){let n=this.readAllCollapsed().find(o=>o.msgHash===e);if(!n)return null;let i={...n,status:r.status,ts:new Date().toISOString()};if(r.reviewer||r.reviewReason){let o=` \xB7 ${r.reviewer?`reviewer=${r.reviewer}`:""}${r.reviewReason?` \xB7 ${r.reviewReason}`:""}`;i.preview=((n.preview||"")+o).slice(0,500)}return this.appendClassification(i),i}readRecentClassifications(e=50){let r=this.classificationsPath();if(!S(r))return[];let n=P(r,"utf-8").split(`
|
|
4
|
+
`).filter(Boolean),i=[];for(let o=n.length-1;o>=0&&i.length<e;o--)try{let s=$.safeParse(JSON.parse(n[o]));s.success&&i.push(s.data)}catch{}return i}latestPathForChat(e,r,t,n=6*60*60*1e3){let i=Date.now()-n;for(let o of this.readRecentClassifications(300))if(!(o.agentId!==e||o.channel!==r||o.chatId!==t))return Date.parse(o.ts)<i?void 0:o.path.length?o.path.slice():void 0}fingerprint(e){let t=[ie(e.text),e.channel??""].join("");return ne("sha256").update(t).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let r=j.safeParse(e);if(!r.success)throw new Error(`Refusing to save invalid index: ${r.error.issues.map(t=>t.message).join("; ")}`);this.writeParsed(this.indexPath(),r.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,r=>{let t=j.safeParse(JSON.parse(r));if(!t.success)throw new Error(`Invalid ${e}: ${t.error.issues.map(n=>n.message).join("; ")}`);return t.data}):{version:1,entries:{}}}getFingerprint(e){let r=this.index().entries[e];return r&&structuredClone(r)}setFingerprint(e,r){let t=V.safeParse({...r,fingerprint:e,updatedAt:new Date().toISOString()});if(!t.success)throw new Error(`Refusing to save invalid index entry: ${t.error.issues.map(i=>i.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:t.data}})}updateNodeAxes(e,r){let t=this.loadSchema(),n=this.loadNodes(),i=n.nodes.find(s=>s.id===e);if(!i)throw new Error(`Node not found: ${e}`);let o={...i,axes:r};return this.validateNode(o,t,n.nodes.map(s=>s.id===e?o:s)),n.nodes=n.nodes.map(s=>s.id===e?o:s),this.saveNodes(n),o}deleteNode(e){let r=this.loadNodes(),t=r.nodes.find(i=>i.parentId===e);if(t)throw new Error(`Cannot delete "${e}" \u2014 child node "${t.id}" still points to it`);let n=r.nodes.find(i=>Object.values(i.axes).some(o=>o===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);r.nodes=r.nodes.filter(i=>i.id!==e),this.saveNodes(r)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let r=this.loadSchema(),t=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let i=e.path[n];if(t.has(i))continue;let o=r.levels[n]?.id;if(!o)break;let s=e.proposedAxes?.[i]??{},c=n===0?null:e.path[n-1];this.addNode({id:i,level:o,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),t.add(i)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function U(a,e){M(Q(a),{recursive:!0});let r=`${a}.tmp-${process.pid}`;T(r,JSON.stringify(e,null,2)),se(r,a)}function Y(){let a=new Date().toISOString(),e=[],r=new Set;for(let t of G)r.has(t.category)||(e.push({id:t.category,level:"category",parentId:null,axes:{kind:t.category},createdAt:a,createdBy:"starter"}),r.add(t.category));for(let t of G)e.push({id:t.verb,level:"verb",parentId:t.category,axes:{name:t.verb,...t.description?{description:t.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function ie(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}te();Z();B();import{createHash as ge}from"crypto";ee();B();var A="intent-path",oe=.5,ae=.3;function ce(a){return{message:he(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function X(a,e){let r={};for(let t of a)r[t.id]=pe(t);return q(r,e)}function de(a){return{category:X(a,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function le(a){return{verb:X(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function F(a,e,r={}){if(C(A)==="off")return null;let t=e.filter(m=>m.parentId===null);if(t.length<2)return null;let n=ce(a),i={agent:a.agent??"unknown",channel:a.channel??"unknown"},o=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await R(A,n,de(t),{incumbent:r.incumbent?.[0]?{category:r.incumbent[0]}:void 0,features:{...i,stage:"category"},links:o});if(!s)return null;let c=s.answers.category,l=c.pMax,u=c.pMax>=oe,b=[c.choice],h=e.filter(m=>m.parentId===c.choice);if(h.length>=2){let m=r.incumbent?.[0]===c.choice,d=await R(A,{...n,category:c.choice},le(h),{incumbent:m&&r.incumbent?.[1]?{verb:r.incumbent[1]}:void 0,features:{...i,stage:"verb",category:c.choice},links:o});if(!d)return null;let f=d.answers.verb;l=Math.min(l,f.pMax),u=u&&f.pMax>=ae,b.push(f.choice)}else h.length===1&&b.push(h[0].id);return{path:b,confidence:l,confident:u,mode:s.mode}}function pe(a){let e=a.axes?.description?.trim()||void 0,r=a.axes?.name?.trim(),t=r&&r!==a.id?r:void 0;return e&&t?`${t}: ${e}`:e??t??null}function he(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var _=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=J(this.classifierProviderName)),this.providerInstance}async classify(e){let r=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),t=this.store.getFingerprint(r);if(t)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:r,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:t.path,proposedAxes:{},leaf:t.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:t.path,pathId:L(t.path),pathLabel:H(t.path,this.store.loadNodes().nodes),axes:{},leaf:t.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),i=this.store.loadNodes().nodes,o=await this.propose(e,n,i);if(!o)return null;let{path:s,proposedAxes:c,confidence:l,leaf:u}=o;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:r,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:u,source:o.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},h=new Set(i.map(g=>g.id)),m=s.map((g,p)=>h.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,i,e.sender),this.store.setFingerprint(r,{path:s,leaf:u}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:L(s),pathLabel:H(s,this.store.loadNodes().nodes),axes:c,leaf:u,source:o.source,status:v,confidence:l}}async propose(e,r,t){let n=C(A),i={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await F(i,t).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let o=await this.proposePath(e,r,t).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&o&&F(i,t,{incumbent:o.path}).catch(()=>{}),o?{...o,source:"llm"}:null}async proposePath(e,r,t){let n=t.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),i=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(r,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
|
|
5
|
+
`),o=await this.callProvider(i),s=z(o);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,u=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=K(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(u.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??K(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let h={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(h.input=s.leaf.input),typeof s.leaf.output=="string"&&(h.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:u,proposedAxes:b,confidence:m,leaf:h}}commitNewNodes(e,r,t,n,i){this.store.commitNodesAlongPath(e,r,t,i)}async callProvider(e){let r=this.getProvider(),t=new AbortController,n=setTimeout(()=>t.abort(),3e4);try{return(await r.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:t.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function K(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function L(a){return ge("sha1").update(a.join("")).digest("hex").slice(0,16)}function H(a,e){return a.map(r=>{let t=e.find(i=>i.id===r);return t&&(t.axes?.name||t.axes?.what)||r}).join(" \u203A ")}function ue(a,e){if(a.length===0||e.length===0)return 0;let r=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)r++;if(r===0)return 0;let t=Math.max(a.length,e.length);return r/t}export{x as a,D as b,_ as c,L as d,H as e,ue as f};
|
|
6
|
+
//# sourceMappingURL=chunk-WLMQ5JMX.js.map
|