agentix-cli 0.214.0 → 0.215.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-KUCECPSZ.js → agent-KOKQSRAH.js} +2 -2
- package/dist/{board-dashboard-SHU4BWRO.js → board-dashboard-NVQUQSWI.js} +2 -2
- package/dist/{board-dashboard-SHU4BWRO.js.map → board-dashboard-NVQUQSWI.js.map} +1 -1
- package/dist/chunk-4BYJN2A3.js +4 -0
- package/dist/chunk-4BYJN2A3.js.map +1 -0
- package/dist/{chunk-SPXXLPAS.js → chunk-4DCQIHWU.js} +2 -2
- package/dist/{chunk-2KNI7ZRN.js → chunk-7AFXLWWW.js} +2 -2
- package/dist/chunk-7YOLZGB5.js +2 -0
- package/dist/chunk-7YOLZGB5.js.map +1 -0
- package/dist/chunk-GGAEFVXL.js +42 -0
- package/dist/chunk-GGAEFVXL.js.map +1 -0
- package/dist/chunk-HVMUYEQP.js +4 -0
- package/dist/chunk-HVMUYEQP.js.map +1 -0
- package/dist/{chunk-SBFMNAJG.js → chunk-JLH73NRM.js} +88 -88
- package/dist/chunk-JLH73NRM.js.map +1 -0
- package/dist/{chunk-C3O2ER6D.js → chunk-Q7Y5VQGX.js} +2 -2
- package/dist/{chunk-UNVZUWOY.js → chunk-QMICGPM6.js} +3 -3
- package/dist/{chunk-UNVZUWOY.js.map → chunk-QMICGPM6.js.map} +1 -1
- package/dist/{chunk-Z4WM7MKP.js → chunk-QOGZD6Z3.js} +268 -268
- package/dist/chunk-QOGZD6Z3.js.map +1 -0
- package/dist/chunk-Z5CMA4JN.js +6 -0
- package/dist/chunk-Z5CMA4JN.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/decision-approvals-SWZ4RWFI.js +2 -0
- package/dist/hub-V2AGLA7T.js +2 -0
- package/dist/index.d.ts +93 -0
- package/dist/index.js +1 -1
- package/dist/{program-L3BX5FJ3.js → program-WSGVQTFM.js} +153 -153
- package/dist/{program-L3BX5FJ3.js.map → program-WSGVQTFM.js.map} +1 -1
- package/dist/{query-runs-AENEZOM6.js → query-runs-2F6KHFBZ.js} +2 -2
- package/dist/{registry-D727ZQUP.js → registry-KRU6AWVW.js} +2 -2
- package/dist/timers-LAT4ZVXJ.js +2 -0
- package/dist/wiki-IDLRJ6WL.js +2 -0
- package/dist/wiki-enrich-XWLDJAZI.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-AFRHKA7B.js +0 -2
- package/dist/chunk-AFRHKA7B.js.map +0 -1
- package/dist/chunk-FR4DTMCA.js +0 -42
- package/dist/chunk-FR4DTMCA.js.map +0 -1
- package/dist/chunk-HPRLRD4P.js +0 -6
- package/dist/chunk-HPRLRD4P.js.map +0 -1
- package/dist/chunk-LIY5CHUV.js +0 -4
- package/dist/chunk-LIY5CHUV.js.map +0 -1
- package/dist/chunk-RMXG5GNW.js +0 -4
- package/dist/chunk-RMXG5GNW.js.map +0 -1
- package/dist/chunk-SBFMNAJG.js.map +0 -1
- package/dist/chunk-Z4WM7MKP.js.map +0 -1
- package/dist/decision-approvals-NJS2ARAF.js +0 -2
- package/dist/hub-PPQGFC35.js +0 -2
- package/dist/timers-KK7GF77Y.js +0 -2
- package/dist/wiki-FP4JMCYP.js +0 -2
- package/dist/wiki-enrich-3SPIVYSG.js +0 -2
- /package/dist/{agent-KUCECPSZ.js.map → agent-KOKQSRAH.js.map} +0 -0
- /package/dist/{chunk-SPXXLPAS.js.map → chunk-4DCQIHWU.js.map} +0 -0
- /package/dist/{chunk-2KNI7ZRN.js.map → chunk-7AFXLWWW.js.map} +0 -0
- /package/dist/{chunk-C3O2ER6D.js.map → chunk-Q7Y5VQGX.js.map} +0 -0
- /package/dist/{decision-approvals-NJS2ARAF.js.map → decision-approvals-SWZ4RWFI.js.map} +0 -0
- /package/dist/{hub-PPQGFC35.js.map → hub-V2AGLA7T.js.map} +0 -0
- /package/dist/{query-runs-AENEZOM6.js.map → query-runs-2F6KHFBZ.js.map} +0 -0
- /package/dist/{registry-D727ZQUP.js.map → registry-KRU6AWVW.js.map} +0 -0
- /package/dist/{timers-KK7GF77Y.js.map → timers-LAT4ZVXJ.js.map} +0 -0
- /package/dist/{wiki-FP4JMCYP.js.map → wiki-IDLRJ6WL.js.map} +0 -0
- /package/dist/{wiki-enrich-3SPIVYSG.js.map → wiki-enrich-XWLDJAZI.js.map} +0 -0
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as l}from"./chunk-ZRBTLW2B.js";import{resolve as s}from"path";import{existsSync as h,readdirSync as p,mkdirSync as u,readFileSync as f,writeFileSync as m,renameSync as S}from"fs";var y=g=>{try{return p(g,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},b=g=>{let t=s(g,"agents");return y(t).some(r=>y(s(t,r)).some(e=>h(s(t,r,e,"_index.md"))))};function w(g){for(let t of[g,s(g,".agentx/wiki")])if(b(t))return t;return null}var k=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=s(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),e="graph"){this.baseDir=t,this.agentsDir=s(t,"agents"),this.mode=e,this.log=r,u(this.agentsDir,{recursive:!0}),this.sharedStore=new l(t,r)}getMode(){return this.mode}getAgentWiki(t){let r=`${t}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let e=s(this.agentsDir,t,this.mode),i=new l(e,this.log);return this.agentStores.set(r,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(t){return[...this.listAgentDirs().filter(e=>e!==t).map(e=>({id:e,store:this.getAgentWiki(e)})),{id:"shared",store:this.sharedStore,skip:e=>e.startsWith("agents/")}]}listAgentDirs(){return h(this.agentsDir)?p(this.agentsDir).filter(t=>!t.startsWith("_")&&!t.startsWith(".")&&h(s(this.agentsDir,t,this.mode))).sort():[]}listAgents(t=this.sharedStore.listEntries()){let r=new Set;for(let e of t)r.add(e.agentId);if(h(this.agentsDir))for(let e of p(this.agentsDir))!e.startsWith("_")&&!e.startsWith(".")&&r.add(e);return[...r].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){return this.classifyEntries(t).pending}markProcessed(t,r,e){let i=new Set(e),d=this.readLedger(t),c=new Date().toISOString();for(let n of r)d.entries[n]={at:c,cited:i.has(n)};let o=this.ledgerPath(t);u(s(o,".."),{recursive:!0});let a=`${o}.tmp`;m(a,`${JSON.stringify(d,null,2)}
|
|
2
|
+
`),S(a,o)}summary(){let t=this.sharedStore.listEntries(),r=new Map;for(let e of t){let i=r.get(e.agentId);i?i.push(e):r.set(e.agentId,[e])}return this.listAgents(t).map(e=>{let{all:i,cited:d,read:c,pending:o,articles:a}=this.classifyEntries(e,r.get(e)??[]);return{agentId:e,totalEntries:i.length,totalArticles:a.length,cited:d.length,readNotCited:c.length,unabsorbed:o.length,articles:a}})}classifyEntries(t,r=this.getAgentEntries(t)){let e=this.getAgentWiki(t).rebuildIndex().articles,i=new Set;for(let n of e)if(n.sources)for(let W of n.sources)i.add(W);let d=this.readLedger(t).entries,c=[],o=[],a=[];for(let n of r)i.has(n.id)?c.push(n):d[n.id]?o.push(n):a.push(n);return{all:r,cited:c,read:o,pending:a,articles:e}}syncedFrom(t){let r=s(this.agentsDir,t,"_synced.json");if(!h(r))return null;try{return JSON.parse(f(r,"utf-8"))}catch(e){return this.log(`synced marker ${r} is not valid JSON: ${e.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(t,r){let e=s(this.agentsDir,t,"_synced.json");u(s(e,".."),{recursive:!0});let i=`${e}.tmp`;m(i,`${JSON.stringify(r,null,2)}
|
|
3
|
+
`),S(i,e)}ledgerPath(t){return s(this.agentsDir,t,"_absorbed.json")}readLedger(t){let r=this.ledgerPath(t);if(!h(r))return{entries:{}};try{return{entries:JSON.parse(f(r,"utf-8")).entries??{}}}catch(e){throw new Error(`absorb ledger ${r} is not valid JSON: ${e.message}`)}}};export{w as a,k as b};
|
|
4
|
+
//# sourceMappingURL=chunk-4BYJN2A3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/hub.ts"],"sourcesContent":["import { WikiStore } from \"./store\"\nimport { resolve } from \"path\"\nimport { existsSync, readdirSync, mkdirSync, readFileSync, writeFileSync, renameSync } from \"fs\"\nimport type { WikiEntry } from \"./types\"\nimport type { SharedWikiStore } from \"./query\"\n\nexport type WikiMode = \"flat\" | \"graph\" | \"unified\"\n\nconst subdirs = (dir: string) => {\n try { return readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name) } catch { return [] }\n}\n/** A wiki with a catalog: some agents/<id>/<mode>/_index.md. A bare agents/ folder left by an old run is not one. */\nconst holdsWiki = (dir: string) => {\n const agentsDir = resolve(dir, \"agents\")\n return subdirs(agentsDir).some((id) =>\n subdirs(resolve(agentsDir, id)).some((mode) => existsSync(resolve(agentsDir, id, mode, \"_index.md\"))))\n}\n\n/**\n * The wiki a query should read for `dir`, without creating anything:\n * `dir` itself when it holds a wiki with a catalog, else\n * `<dir>/.agentx/wiki` when that does (a node's folder given in place of\n * its wiki). Null when neither does. Opening a WikiHub creates folders, so\n * a query pointed at an agent's workspace used to leave an empty wiki\n * there and answer \"no catalog\", or crash when the folder could not be\n * written (#1820). Empty wikis those runs left behind (agents/ and nothing\n * else) count as no wiki, so they fall through to the next candidate.\n */\nexport function existingWikiDir(dir: string): string | null {\n for (const candidate of [dir, resolve(dir, \".agentx/wiki\")]) {\n if (holdsWiki(candidate)) return candidate\n }\n return null\n}\n\n/**\n * WikiHub: manages per-agent wikis with a shared raw entry pool.\n * Supports two compilation modes:\n * - flat: Karpathy pattern — tags, LLM-chosen paths, worldview, gap detection\n * - graph: Knowledge graph — kind, parent, hierarchy, events, entities\n *\n * Both modes share the same raw entries. Articles stored separately:\n * agents/<id>/flat/ ← Karpathy compilation\n * agents/<id>/graph/ ← Knowledge graph compilation\n */\nexport class WikiHub {\n private baseDir: string\n private agentsDir: string\n private mode: WikiMode\n private sharedStore: WikiStore\n private agentStores: Map<string, WikiStore> = new Map()\n private log: (...args: unknown[]) => void\n\n constructor(\n baseDir: string = resolve(process.cwd(), \".agentx/wiki\"),\n log: (...args: unknown[]) => void = console.error.bind(console, \"[wiki-hub]\"),\n mode: WikiMode = \"graph\",\n ) {\n this.baseDir = baseDir\n this.agentsDir = resolve(baseDir, \"agents\")\n this.mode = mode\n this.log = log\n\n mkdirSync(this.agentsDir, { recursive: true })\n this.sharedStore = new WikiStore(baseDir, log)\n }\n\n getMode(): WikiMode { return this.mode }\n\n /**\n * Get or create the wiki store for a specific agent (mode-aware).\n * flat: agents/<id>/flat/\n * graph: agents/<id>/graph/\n */\n getAgentWiki(agentId: string): WikiStore {\n const key = `${agentId}:${this.mode}`\n if (this.agentStores.has(key)) return this.agentStores.get(key)!\n\n const agentDir = resolve(this.agentsDir, agentId, this.mode)\n const store = new WikiStore(agentDir, this.log)\n this.agentStores.set(key, store)\n return store\n }\n\n /** The wiki root: shared sidecars (_facts.json, _questions.json) live here. */\n getBaseDir(): string {\n return this.baseDir\n }\n\n getSharedStore(): WikiStore {\n return this.sharedStore\n }\n\n /**\n * The wikis a query by `agentId` reads besides its own: every other\n * agent's articles and the root store's own (promoted lessons). Which\n * articles of theirs it may read is still decided per article by access.\n * Without this an agent's query missed answers the shared wiki had (#824).\n */\n sharedScope(agentId: string): SharedWikiStore[] {\n const others = this.listAgentDirs()\n .filter((id) => id !== agentId)\n .map((id) => ({ id, store: this.getAgentWiki(id) }))\n // The root store's walk also reaches agents/<id>/…; those are read\n // through their own store above.\n return [...others, { id: \"shared\", store: this.sharedStore, skip: (p: string) => p.startsWith(\"agents/\") }]\n }\n\n /** Agents with a wiki folder here, without reading the raw entries. */\n private listAgentDirs(): string[] {\n if (!existsSync(this.agentsDir)) return []\n return readdirSync(this.agentsDir)\n .filter((d) => !d.startsWith(\"_\") && !d.startsWith(\".\") && existsSync(resolve(this.agentsDir, d, this.mode)))\n .sort()\n }\n\n listAgents(entries: WikiEntry[] = this.sharedStore.listEntries()): string[] {\n const agents = new Set<string>()\n\n for (const e of entries) agents.add(e.agentId)\n\n if (existsSync(this.agentsDir)) {\n for (const dir of readdirSync(this.agentsDir)) {\n if (!dir.startsWith(\"_\") && !dir.startsWith(\".\")) {\n agents.add(dir)\n }\n }\n }\n\n return [...agents].sort()\n }\n\n getAgentEntries(agentId: string): WikiEntry[] {\n return this.sharedStore.listEntries({ agentId })\n }\n\n /**\n * Entries absorb has not dealt with yet: no article cites them and no\n * successful absorb run has read them. Without the second check an\n * entry absorb read and chose not to cite came back on every run, and\n * a backfill kept re-reading the head of the queue (#762).\n */\n getUnabsorbedEntries(agentId: string): WikiEntry[] {\n return this.classifyEntries(agentId).pending\n }\n\n /**\n * Record every entry handed to the model in a successful absorb run,\n * cited or not. Callers must not call this for a failed run, so those\n * entries are offered again.\n */\n markProcessed(agentId: string, entryIds: string[], citedIds: Iterable<string>): void {\n const cited = new Set(citedIds)\n const ledger = this.readLedger(agentId)\n const at = new Date().toISOString()\n for (const id of entryIds) ledger.entries[id] = { at, cited: cited.has(id) }\n\n const file = this.ledgerPath(agentId)\n mkdirSync(resolve(file, \"..\"), { recursive: true })\n const tmp = `${file}.tmp`\n writeFileSync(tmp, `${JSON.stringify(ledger, null, 2)}\\n`)\n renameSync(tmp, file)\n }\n\n /**\n * Counts and articles per agent, for `GET /wiki/agents` and the mesh.\n * The raw entries are read once and grouped here: reading them again\n * per agent made the endpoint take 25 to 75 s on a fleet with 30\n * agents and 10k entries, past the mesh client's 5 s timeout (#603).\n */\n summary(): AgentWikiSummary[] {\n const entries = this.sharedStore.listEntries()\n const byAgent = new Map<string, WikiEntry[]>()\n for (const e of entries) {\n const list = byAgent.get(e.agentId)\n if (list) list.push(e)\n else byAgent.set(e.agentId, [e])\n }\n return this.listAgents(entries).map(agentId => {\n const { all, cited, read, pending, articles } = this.classifyEntries(agentId, byAgent.get(agentId) ?? [])\n return {\n agentId,\n totalEntries: all.length,\n totalArticles: articles.length,\n cited: cited.length,\n readNotCited: read.length,\n unabsorbed: pending.length,\n articles,\n }\n })\n }\n\n /** Split an agent's entries into cited by an article, read but not cited, and pending. */\n private classifyEntries(agentId: string, all: WikiEntry[] = this.getAgentEntries(agentId)) {\n const articles = this.getAgentWiki(agentId).rebuildIndex().articles\n\n const citedIds = new Set<string>()\n for (const article of articles) {\n if (article.sources) {\n for (const s of article.sources) citedIds.add(s)\n }\n }\n const ledger = this.readLedger(agentId).entries\n\n const cited: WikiEntry[] = []\n const read: WikiEntry[] = []\n const pending: WikiEntry[] = []\n for (const e of all) {\n if (citedIds.has(e.id)) cited.push(e)\n else if (ledger[e.id]) read.push(e)\n else pending.push(e)\n }\n return { all, cited, read, pending, articles }\n }\n\n /**\n * The peer an agent's articles were copied from by `wiki sync --articles`,\n * or null for an agent this node absorbs itself. A copied agent is\n * read-only here: absorb and patch leave it to its home node.\n */\n syncedFrom(agentId: string): SyncedFrom | null {\n const file = resolve(this.agentsDir, agentId, \"_synced.json\")\n if (!existsSync(file)) return null\n try {\n return JSON.parse(readFileSync(file, \"utf-8\")) as SyncedFrom\n } catch (err) {\n // A damaged marker still means the agent lives elsewhere.\n this.log(`synced marker ${file} is not valid JSON: ${(err as Error).message}`)\n return { node: \"unknown\", peerUrl: \"\", at: \"\" }\n }\n }\n\n markSynced(agentId: string, from: SyncedFrom): void {\n const file = resolve(this.agentsDir, agentId, \"_synced.json\")\n mkdirSync(resolve(file, \"..\"), { recursive: true })\n const tmp = `${file}.tmp`\n writeFileSync(tmp, `${JSON.stringify(from, null, 2)}\\n`)\n renameSync(tmp, file)\n }\n\n /** agents/<id>/_absorbed.json — shared by every mode, like the raw entries. */\n private ledgerPath(agentId: string): string {\n return resolve(this.agentsDir, agentId, \"_absorbed.json\")\n }\n\n private readLedger(agentId: string): AbsorbLedger {\n const file = this.ledgerPath(agentId)\n if (!existsSync(file)) return { entries: {} }\n try {\n const parsed = JSON.parse(readFileSync(file, \"utf-8\")) as AbsorbLedger\n return { entries: parsed.entries ?? {} }\n } catch (err) {\n // Treating a damaged ledger as empty would let the next run\n // overwrite it and re-queue everything it recorded.\n throw new Error(`absorb ledger ${file} is not valid JSON: ${(err as Error).message}`)\n }\n }\n}\n\nexport interface SyncedFrom {\n /** The peer's node id. */\n node: string\n peerUrl: string\n /** When the last copy finished. */\n at: string\n}\n\ninterface AbsorbLedger {\n entries: Record<string, { at: string; cited: boolean }>\n}\n\nexport interface AgentWikiSummary {\n agentId: string\n totalEntries: number\n totalArticles: number\n /** Entries an article cites. */\n cited: number\n /** Entries a successful absorb run read and did not cite. */\n readNotCited: number\n /** Entries absorb has not read yet. */\n unabsorbed: number\n articles: Array<{ title: string; path: string; tags?: string[] }>\n}\n"],"mappings":"wCACA,OAAS,WAAAA,MAAe,OACxB,OAAS,cAAAC,EAAY,eAAAC,EAAa,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,EAAe,cAAAC,MAAkB,KAM5F,IAAMC,EAAWC,GAAgB,CAC/B,GAAI,CAAE,OAAON,EAAYM,EAAK,CAAE,cAAe,EAAK,CAAC,EAAE,OAAQC,GAAMA,EAAE,YAAY,CAAC,EAAE,IAAKA,GAAMA,EAAE,IAAI,CAAE,MAAE,CAAQ,MAAO,CAAC,CAAE,CAC/H,EAEMC,EAAaF,GAAgB,CACjC,IAAMG,EAAYX,EAAQQ,EAAK,QAAQ,EACvC,OAAOD,EAAQI,CAAS,EAAE,KAAMC,GAC9BL,EAAQP,EAAQW,EAAWC,CAAE,CAAC,EAAE,KAAMC,GAASZ,EAAWD,EAAQW,EAAWC,EAAIC,EAAM,WAAW,CAAC,CAAC,CAAC,CACzG,EAYO,SAASC,EAAgBN,EAA4B,CAC1D,QAAWO,IAAa,CAACP,EAAKR,EAAQQ,EAAK,cAAc,CAAC,EACxD,GAAIE,EAAUK,CAAS,EAAG,OAAOA,EAEnC,OAAO,IACT,CAYO,IAAMC,EAAN,KAAc,CACX,QACA,UACA,KACA,YACA,YAAsC,IAA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ACtE,CAAE,KAAM,UAAW,QAAS,GAAI,GAAI,EAAG,CAChD,CACF,CAEA,WAAWvB,EAAiBwB,EAAwB,CAClD,IAAMZ,EAAOhC,EAAQ,KAAK,UAAWoB,EAAS,cAAc,EAC5DjB,EAAUH,EAAQgC,EAAM,IAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EAClD,IAAMC,EAAM,GAAGD,QACf3B,EAAc4B,EAAK,GAAG,KAAK,UAAUW,EAAM,KAAM,CAAC;AAAA,CAAK,EACvDtC,EAAW2B,EAAKD,CAAI,CACtB,CAGQ,WAAWZ,EAAyB,CAC1C,OAAOpB,EAAQ,KAAK,UAAWoB,EAAS,gBAAgB,CAC1D,CAEQ,WAAWA,EAA+B,CAChD,IAAMY,EAAO,KAAK,WAAWZ,CAAO,EACpC,GAAI,CAACnB,EAAW+B,CAAI,EAAG,MAAO,CAAE,QAAS,CAAC,CAAE,EAC5C,GAAI,CAEF,MAAO,CAAE,QADM,KAAK,MAAM5B,EAAa4B,EAAM,OAAO,CAAC,EAC5B,SAAW,CAAC,CAAE,CACzC,OAASW,EAAP,CAGA,MAAM,IAAI,MAAM,iBAAiBX,wBAA4BW,EAAc,SAAS,CACtF,CACF,CACF","names":["resolve","existsSync","readdirSync","mkdirSync","readFileSync","writeFileSync","renameSync","subdirs","dir","d","holdsWiki","agentsDir","id","mode","existingWikiDir","candidate","WikiHub","baseDir","log","WikiStore","agentId","key","agentDir","store","p","entries","agents","entryIds","citedIds","cited","ledger","at","file","tmp","byAgent","list","all","read","pending","articles","article","s","e","err","from"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-UOK5MMKD.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-
|
|
1
|
+
import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-UOK5MMKD.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-V2AGLA7T.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-Q3HCFXDT.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-MZMIQ3SV.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-MZMIQ3SV.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
|
|
2
2
|
`).slice(0,12).map(n=>` | ${n}`).join(`
|
|
3
3
|
`)))}u.outcomes.length===0&&console.log(t.dim(" nothing to do: no entity of these types changed since the last run (--force redoes them)")),console.log(t.dim(` spent $${u.costUsd.toFixed(3)} of $${w}${u.capped?" \xB7 stopped at the cap":""}`))})}export{N as a,I as b};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-4DCQIHWU.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ft}from"./chunk-GTJIKXDB.js";import{H as kr,O as _r,k as K}from"./chunk-OQNJIIR2.js";import{f as Sr,g as $r,h as Er,l as Ar}from"./chunk-PSYHAO57.js";import{b as vr}from"./chunk-2VDO2HEK.js";import{t as wr,u as xr}from"./chunk-JEBU5JUM.js";import{d as br,e as yr}from"./chunk-AQASR6KR.js";import{h as pe,j as sr,l as ir,m as ar,n as lr}from"./chunk-RX5O5637.js";import{a as cr,c as dr,e as ur,f as dt,h as pr,j as gr,k as fr,l as ut,m as pt,n as gt}from"./chunk-5ELIX7BQ.js";import{c as mr,d as hr}from"./chunk-CSC45PA7.js";import{a as Qn,c as Zn}from"./chunk-KP7KDLZ2.js";import{Aa as
|
|
1
|
+
import{a as ft}from"./chunk-GTJIKXDB.js";import{H as kr,O as _r,k as K}from"./chunk-OQNJIIR2.js";import{f as Sr,g as $r,h as Er,l as Ar}from"./chunk-PSYHAO57.js";import{b as vr}from"./chunk-2VDO2HEK.js";import{t as wr,u as xr}from"./chunk-JEBU5JUM.js";import{d as br,e as yr}from"./chunk-AQASR6KR.js";import{h as pe,j as sr,l as ir,m as ar,n as lr}from"./chunk-RX5O5637.js";import{a as cr,c as dr,e as ur,f as dt,h as pr,j as gr,k as fr,l as ut,m as pt,n as gt}from"./chunk-5ELIX7BQ.js";import{c as mr,d as hr}from"./chunk-CSC45PA7.js";import{a as Qn,c as Zn}from"./chunk-KP7KDLZ2.js";import{Aa as Gn,Ba as U,Ca as ue,Ea as ct,b as it,f as Vn,s as at,u as lt,za as Te}from"./chunk-GGAEFVXL.js";import{a as _e,b as de,e as qn}from"./chunk-7AB3QUGH.js";import{h as er,i as tr,j as nr,l as rr,m as or}from"./chunk-H4DWZIU7.js";import{s as Kn}from"./chunk-CAH6TNC6.js";import{a as zn,b as Re,e as Xn}from"./chunk-N476XZD3.js";import{c as Ie,d as Jn,e as Yn}from"./chunk-XVV7ZZ77.js";import{b as ee}from"./chunk-5ONH4ITT.js";import{a as Hn,c as st}from"./chunk-ILEC3IAV.js";import{a as Ln,i as Un,l as jn,n as rt,o as ot,r as ce,s as Z,u as Bn}from"./chunk-OQQTV3OF.js";import{a as Pn,b as Mn,d as Fn,e as Wn}from"./chunk-4NZ4T3TQ.js";import{a as Nn}from"./chunk-7IW25T4K.js";import{a as On}from"./chunk-QUFIUXMQ.js";import{E as Ee,F as $n,Fa as Rn,G as En,H as bi,Ha as Tn,Ia as xi,Ib as nt,Sb as In,Tb as Dn,bc as Cn,ca as Ae,ea as An,f as Qe,g as C,i as $e,j as $,k as le,l as vn,o as Sn,p as Ze,ya as _n}from"./chunk-KAM4ZWRE.js";import{a as et,h as yi}from"./chunk-KEUW6YLL.js";import{j as tt,r as wi}from"./chunk-N47Y5ADQ.js";import{existsSync as ki,readdirSync as vi,readFileSync as Si,statSync as $i}from"fs";import{resolve as Ei}from"path";function Rr(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],d=a.filter(f=>n-f.at<=o),l=a.filter(f=>n-f.at>o&&n-f.at<=o*2),c=d.filter(f=>f.status==="failed").length,p=a.filter(f=>f.status==="paused").length,u=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?l.length>0&&d.length===0?"dormant":d.length>0&&c*2>=d.length?"failing":d.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:u,recent:d.length,prior:l.length,failed:c,paused:p}}).sort((i,a)=>{let d={dormant:0,failing:1,active:2,quiet:3,never:4};return d[i.state]-d[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var De=new Map;function Su(t,e=1e3){if(!ki(t))return[];let n=vi(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ei(t,s);return{path:i,mtime:$i(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of De.keys())r.has(s)||De.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=De.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Ai(s,i);De.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Ai(t,e){try{let n=Si(t,"utf-8").split(`
|
|
2
2
|
`).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Tr=7,_i={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},R={routines:200,summary:160,filters:6,filterValue:60,text:120},Ri=(t,e,n)=>{try{return Kn(t,e,n)}catch{return null}},Ir=864e5;function _u(t){let e=t.now??Date.now(),n={..._i,...t.thresholds},r=t.nextFire??Ri,o=[];for(let a of t.crons){let d=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",c=d.map(g=>({at:Date.parse(g.startedAt),status:g.status})),p=d[0],u={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:F(a.id,R.text),trigger:{schedule:F(a.schedule,R.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?mt(a.nextRun)??mt(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:Ni(p.status==="success"?void 0:p.errorSummary,R.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Dr(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Tr).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Cr(u,c,a.schedule,l,null,e,n,r),o.push(Or(u))}let s=new Map(Rr(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let d=i.get(a.workflowId);d?d.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let d=a.nodes.find(k=>k.type.startsWith("trigger."));if(!d||d.type!=="trigger.cron"&&d.type!=="trigger.hook")continue;let l=d.config??{},c=a.state||"active",p=c==="active",u=(i.get(a.id)??[]).slice().sort((k,D)=>D.at-k.at),g=u.map(k=>({at:k.at,status:Di(k.status)})),f=g[0],m=d.type==="trigger.cron",w=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",b={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:F(a.title||a.id,R.text),trigger:m?{schedule:F(w,R.text),timezone:x}:{event:F(typeof l.event=="string"?l.event:"",R.text),filters:Oi(l.filter,a)},agent:Ci(a),enabled:p,state:c,nextRunAt:m&&p&&w?mt(r(w,new Date(e),x)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let k=g.find(D=>D.status==="success");return k?new Date(k.at).toISOString():null})(),consecutiveFailures:Dr(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Tr).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=m?Cr(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):Ti(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Or(b))}return o.sort(Ii).slice(0,R.routines)}function Dr(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function Cr(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=Lr(l,o,s,i);return u&&d.push(u),d}if(t.consecutiveFailures>=i.failStreak&&d.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return d.push({reason:"never-ran",detail:"No persisted attempt"}),d;let c=new Date(l),p=null;for(let u=0;u<i.missedFires&&(p=a(n,c,r),!!p);u++)c=p;return p&&s>p.getTime()+i.graceMs&&d.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),d}function Ti(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Lr(i,n,r,o);return a&&s.push(a),s}return t.consecutiveFailures>=o.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function Lr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Ir?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Ir)} days`:"Disabled and never ran"}}function Or(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var Nr={critical:0,warning:1,info:2};function Ii(t,e){let n=t.attention?Nr[t.attention]:3,r=e.attention?Nr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Di(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Ci(t){if(t.ownerAgent)return F(t.ownerAgent,R.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?F(String(e.config.agentId),R.text):null}function Oi(t,e){let n=[],r=e?.project;if(r&&n.push(F(`project=${r}`,R.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(F(`${o}=${i.join(",")}`,R.filterValue))}return n.slice(0,R.filters)}function mt(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function F(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Ni(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as Li,readFileSync as Pi,renameSync as Mi,writeFileSync as Fi}from"fs";import{resolve as Wi}from"path";function Pr(t){return Wi(ot(t),"_state.json")}function O(t){try{let e=JSON.parse(Pi(Pr(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function ge(t,e){Li(ot(t),{recursive:!0});let n=Pr(t),r=`${n}.${process.pid}.tmp`;Fi(r,JSON.stringify(e,null,2)+`
|
|
3
3
|
`),Mi(r,n)}function Mr(t,e,n,r=Date.now()){let o=O(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),ge(t,{...o,snoozed:s})}function Cu(t,e){ge(t,{...O(t),lastDigest:e})}function ht(t,e,n,r=Date.now()){let o=O(t),s=new Set(n),i={};for(let[d,l]of Object.entries(o.popped??{}))s.has(d)&&(i[d]=l);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(d=>d!==e&&s.has(d));ge(t,{...o,popped:i,wanted:a})}function Fr(t,e){let n=O(t);ge(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function Ou(t,e=Date.now()){ge(t,{...O(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as Ui,readFileSync as ji}from"fs";Cn();yi();function Wr(t){let e=zn(t),n={};if(Ui(e))try{n=In(JSON.parse(ji(e,"utf-8")))}catch{n={}}let r=nt.safeParse(n?.requests);return r.success?r.data:nt.parse(void 0)}async function Wu(t,e={}){let n=(t.channels??[]).filter(r=>!et.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...et].join(", ")}`}:Re(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.autoResend){let s=o.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(s[i]=t.autoResend[i])}if(t.flow){let s=o.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(s[i]=t.flow[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as V,readdirSync as sa,readFileSync as wt,statSync as ia}from"fs";import{dirname as ro,resolve as _}from"path";import{randomBytes as Br}from"crypto";import{existsSync as Hi,mkdirSync as Vi,readdirSync as qi,readFileSync as zi,renameSync as Hr,unlinkSync as Xi,writeFileSync as Ki}from"fs";import{resolve as Vr}from"path";function Ur(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Bi=t=>t.trim().split(`
|
|
4
4
|
`).pop()?.slice(0,300)||"no output";async function jr(t,e,n,r=ft){let o=await r(t.bin,[...Ur(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Bi(o.stderr||o.stdout)}`}}async function Bu(t,e,n,r,o=ft){return(await o(t.bin,[...Ur(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Gi=2e3,Ji=t=>jr(t.wacli,t.to,t.text);function bt(t){return Vr(t,".agentx","whatsapp-triage","drafts")}var Yi=t=>/^[a-z0-9-]{8,64}$/.test(t),Ce=(t,e)=>Vr(bt(t),`${e}.json`);function qr(t,e){Vi(bt(t),{recursive:!0});let n=Ce(t,e.id),r=`${n}.${process.pid}.tmp`;Ki(r,JSON.stringify(e,null,2)+`
|
|
@@ -906,4 +906,4 @@ Document the arguments, commands, or files the skill expects. Example:
|
|
|
906
906
|
claude-code ${kn(t)} --arg value
|
|
907
907
|
\`\`\`
|
|
908
908
|
`}Cn();var gi={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function fi(t){return{...gi,...t??{},regions:{...t?.regions??{}},buffer:{...gi.buffer,...t?.buffer??{}}}}function Dh(t){try{return fi(Dn(t).screen)}catch{return fi(void 0)}}var xu=/^[a-z][\w-]*$/,mi=["window","screen","menubar","notifications"];function ke(t,e,n,r){let o=Number(t);if(t===""||t===null||!Number.isFinite(o)||!n(o))throw new Error(`${e} must be ${r}`);return o}var Je=(t,e)=>ke(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function hi(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Ch(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Je(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Je(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Je(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ke(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ke(e.changeThreshold,"changeThreshold",o=>o>=0&&o<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let o={...n.regions??{}};for(let[s,i]of Object.entries(e.regions)){if(!xu.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=hi(i)}n.regions=o}if(e.buffer&&typeof e.buffer=="object"){let o=e.buffer,s={...n.buffer??{}};"enabled"in o&&(s.enabled=!!o.enabled),"seconds"in o&&(s.seconds=ke(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ke(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Je(o.maxPixels,"buffer.maxPixels")),"region"in o&&(s.region=String(o.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!mi.includes(r)&&!n.regions?.[r])try{hi(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...mi,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Rr as a,Su as b,Kt as c,Zl as d,ec as e,ef as f,tf as g,nf as h,sf as i,af as j,lf as k,rs as l,os as m,cf as n,uf as o,z as p,ss as q,R as r,_u as s,ls as t,bf as u,xf as v,ds as w,kf as x,us as y,vf as z,he as A,$c as B,Sf as C,$f as D,gs as E,Bu as F,Ji as G,Ku as H,Xr as I,O as J,Cu as K,Ou as L,Wr as M,Wu as N,G as O,_p as P,co as Q,go as R,Rc as S,Af as T,Tc as U,_f as V,Rf as W,Jt as X,ms as Y,Df as Z,Qt as _,Cc as $,Oc as aa,Lf as ba,Ia as ca,Da as da,Ip as ea,Dp as fa,Fa as ga,Lp as ha,Ss as ia,Ff as ja,Fp as ka,Wp as la,Zo as ma,Wt as na,zl as oa,T as pa,Ps as qa,hm as ra,bm as sa,bd as ta,km as ua,Bs as va,vm as wa,Sm as xa,Tm as ya,Ad as za,Rd as Aa,Im as Ba,jp as Ca,Bp as Da,Hp as Ea,Vp as Fa,qp as Ga,zp as Ha,Xp as Ia,Kp as Ja,Jp as Ka,Yp as La,eg as Ma,tg as Na,ng as Oa,sg as Pa,ig as Qa,ag as Ra,lg as Sa,cg as Ta,dg as Ua,ug as Va,xg as Wa,Tt as Xa,kg as Ya,vg as Za,fe as _a,me as $a,Nd as ab,Wm as bb,Um as cb,jm as db,Bm as eb,cn as fb,Hm as gb,Ct as hb,Ot as ib,Be as jb,fl as kb,hl as lb,_g as mb,Lt as nb,Pt as ob,bl as pb,yl as qb,Fo as rb,Bo as sb,Rg as tb,kl as ub,Tg as vb,Tl as wb,Cl as xb,Mt as yb,Nl as zb,Ho as Ab,X as Bb,Zs as Cb,ei as Db,ti as Eb,un as Fb,Gm as Gb,Hd as Hb,ri as Ib,oi as Jb,ih as Kb,ah as Lb,su as Mb,lh as Nb,ii as Ob,Xo as Pb,gh as Qb,uu as Rb,mh as Sb,hh as Tb,He as Ub,Vg as Vb,zt as Wb,Yg as Xb,xh as Yb,kh as Zb,vh as _b,Sh as $b,$h as ac,Eh as bc,Ah as cc,_h as dc,Rh as ec,gi as fc,fi as gc,Dh as hc,mi as ic,Ch as jc};
|
|
909
|
-
//# sourceMappingURL=chunk-
|
|
909
|
+
//# sourceMappingURL=chunk-7AFXLWWW.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{existsSync as a,mkdirSync as m,readdirSync as p,readFileSync as f,unlinkSync as d,writeFileSync as l}from"fs";import{resolve as c}from"path";import{randomUUID as u}from"crypto";import{z as i}from"zod";var v=i.object({id:i.string(),runId:i.string(),workflowId:i.string(),nodeId:i.string(),fireAt:i.string(),cancelKey:i.string().optional(),createdAt:i.string()}),h=class{baseDir;tickIntervalMs;sweepIntervalMs;log;timer;sweepTimer;callback;sweeper;firedIds=new Set;constructor(e={}){let t=e.baseDir??c(process.cwd(),".agentx/workflows");this.baseDir=c(t,"_timers"),m(this.baseDir,{recursive:!0}),this.tickIntervalMs=e.tickIntervalMs??1e3,this.sweepIntervalMs=e.sweepIntervalMs??6e4,this.log=e.log??(()=>{})}onFire(e){this.callback=e}onSweep(e){this.sweeper=e}start(){this.timer||(this.log(`[timers] ticking every ${this.tickIntervalMs}ms \u2014 scanning ${this.baseDir}`),this.tick(),this.timer=setInterval(()=>this.tick(),this.tickIntervalMs),typeof this.timer.unref=="function"&&this.timer.unref(),this.sweep(),this.sweepTimer=setInterval(()=>this.sweep(),this.sweepIntervalMs),typeof this.sweepTimer.unref=="function"&&this.sweepTimer.unref())}stop(){this.sweepTimer&&(clearInterval(this.sweepTimer),this.sweepTimer=void 0),this.timer&&(clearInterval(this.timer),this.timer=void 0)}sweep(){if(this.sweeper)try{Promise.resolve(this.sweeper()).catch(e=>this.log(`[timers] recovery sweep threw: ${e?.message??e}`))}catch(e){this.log(`[timers] recovery sweep failed: ${e?.message??e}`)}}schedule(e){let t={id:u(),runId:e.runId,workflowId:e.workflowId,nodeId:e.nodeId,fireAt:e.fireAt,cancelKey:e.cancelKey,createdAt:new Date().toISOString()};return l(this.pathFor(t.id),JSON.stringify(t,null,2)),t}cancel(e){let t=0;for(let r of this.list())if(!(e.runId&&r.runId!==e.runId)&&!(e.nodeId&&r.nodeId!==e.nodeId)&&!(e.cancelKey&&r.cancelKey!==e.cancelKey))try{d(this.pathFor(r.id)),t++}catch{}return t}retime(e,t){let r=this.list().find(n=>n.cancelKey===e&&!this.firedIds.has(n.id));if(!r)return null;let s=this.pathFor(r.id);if(!a(s))return null;let o={...r,fireAt:t};return l(s,JSON.stringify(o,null,2)),o}list(){if(!a(this.baseDir))return[];let e=[];for(let t of p(this.baseDir,{withFileTypes:!0}))if(!(!t.isFile()||!t.name.endsWith(".json")))try{let r=JSON.parse(f(c(this.baseDir,t.name),"utf-8")),s=v.safeParse(r);s.success&&e.push(s.data)}catch{}return e}pathFor(e){return c(this.baseDir,`${e}.json`)}tick(){if(!this.callback)return;let e=Date.now();for(let t of this.list()){if(this.firedIds.has(t.id))continue;let r=Date.parse(t.fireAt);if(Number.isNaN(r)||r>e)continue;this.firedIds.add(t.id);let s=()=>{try{d(this.pathFor(t.id))}catch{}},o;try{o=Promise.resolve(this.callback(t))}catch(n){o=Promise.reject(n)}o.catch(n=>this.log(`[timers] fire callback threw: ${n?.message??n}`)).finally(s)}}};export{v as a,h as b};
|
|
2
|
+
//# sourceMappingURL=chunk-7YOLZGB5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/workflows/timers.ts"],"sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { randomUUID } from \"crypto\"\nimport { z } from \"zod\"\n\n// --- Durable timer service ---\n//\n// Persists pending timers under .agentx/workflows/_timers/<id>.json so a\n// daemon restart doesn't forget them. A 1s tick loop fires due timers by\n// invoking a registered callback. The workflow dispatcher registers its\n// resume-on-timer callback at boot.\n//\n// Timer model — v1:\n// - Each timer is keyed to a (runId, nodeId) pair so `timer.boundary`\n// nodes can be cancelled when the attached node completes before the\n// timer elapses.\n// - Fire-once semantics. No repeating timers at this layer (use\n// trigger.cron at the workflow level for recurrence).\n// - Best-effort delivery: a missed tick (daemon crash, clock skew) is\n// honoured on next startup by scanning persisted timers with fireAt\n// in the past. A timer's file is removed only after its callback has\n// settled, so a daemon that stops mid-fire fires it again on boot.\n// - Recovery sweep (#1816): an optional sweep callback runs at start and\n// every `sweepIntervalMs`. The dispatcher uses it to resume paused runs\n// whose timer is overdue but whose timer file is gone.\n\nexport const timerRecordSchema = z.object({\n id: z.string(),\n runId: z.string(),\n workflowId: z.string(),\n nodeId: z.string(),\n /** ISO-8601 instant when the timer should fire. */\n fireAt: z.string(),\n /** Optional key to cancel matching timers (e.g., when the attached node\n * completes normally and the escalation timer should be cancelled). */\n cancelKey: z.string().optional(),\n createdAt: z.string(),\n})\nexport type TimerRecord = z.infer<typeof timerRecordSchema>\n\nexport interface TimerCallback {\n (t: TimerRecord): void | Promise<void>\n}\n\nexport interface TimerServiceOptions {\n baseDir?: string\n /** Tick interval, in ms. Default 1000. */\n tickIntervalMs?: number\n /** Recovery sweep interval, in ms. Default 60000. */\n sweepIntervalMs?: number\n log?: (msg: string) => void\n}\n\nexport class TimerService {\n readonly baseDir: string\n readonly tickIntervalMs: number\n readonly sweepIntervalMs: number\n private readonly log: (msg: string) => void\n private timer?: ReturnType<typeof setInterval>\n private sweepTimer?: ReturnType<typeof setInterval>\n private callback?: TimerCallback\n private sweeper?: () => void | Promise<unknown>\n private firedIds: Set<string> = new Set()\n\n constructor(opts: TimerServiceOptions = {}) {\n const root = opts.baseDir ?? resolve(process.cwd(), \".agentx/workflows\")\n this.baseDir = resolve(root, \"_timers\")\n mkdirSync(this.baseDir, { recursive: true })\n this.tickIntervalMs = opts.tickIntervalMs ?? 1000\n this.sweepIntervalMs = opts.sweepIntervalMs ?? 60_000\n this.log = opts.log ?? (() => {})\n }\n\n /** Register the fire callback. Overwrites any prior callback. Typical\n * caller is the dispatcher's \"resume on timer\" path. */\n onFire(cb: TimerCallback): void {\n this.callback = cb\n }\n\n /** Register the recovery sweep, run at start and every sweepIntervalMs.\n * Overwrites any prior sweep. */\n onSweep(cb: () => void | Promise<unknown>): void {\n this.sweeper = cb\n }\n\n start(): void {\n if (this.timer) return\n this.log(`[timers] ticking every ${this.tickIntervalMs}ms — scanning ${this.baseDir}`)\n // Honour missed ticks on startup: scan all persisted timers once.\n this.tick()\n this.timer = setInterval(() => this.tick(), this.tickIntervalMs)\n // Don't hold the event loop open on daemon shutdown.\n if (typeof this.timer.unref === \"function\") this.timer.unref()\n // After the first tick, so timers still on disk resume the normal way\n // first; the sweep then catches runs whose timer file is gone.\n this.sweep()\n this.sweepTimer = setInterval(() => this.sweep(), this.sweepIntervalMs)\n if (typeof this.sweepTimer.unref === \"function\") this.sweepTimer.unref()\n }\n\n stop(): void {\n if (this.sweepTimer) { clearInterval(this.sweepTimer); this.sweepTimer = undefined }\n if (!this.timer) return\n clearInterval(this.timer)\n this.timer = undefined\n }\n\n private sweep(): void {\n if (!this.sweeper) return\n try {\n void Promise.resolve(this.sweeper()).catch((e: any) => this.log(`[timers] recovery sweep threw: ${e?.message ?? e}`))\n } catch (e: any) {\n this.log(`[timers] recovery sweep failed: ${e?.message ?? e}`)\n }\n }\n\n schedule(args: {\n runId: string\n workflowId: string\n nodeId: string\n fireAt: string\n cancelKey?: string\n }): TimerRecord {\n const record: TimerRecord = {\n id: randomUUID(),\n runId: args.runId,\n workflowId: args.workflowId,\n nodeId: args.nodeId,\n fireAt: args.fireAt,\n cancelKey: args.cancelKey,\n createdAt: new Date().toISOString(),\n }\n writeFileSync(this.pathFor(record.id), JSON.stringify(record, null, 2))\n return record\n }\n\n /** Cancel any timers matching the filter. Returns how many were removed. */\n cancel(filter: { runId?: string; nodeId?: string; cancelKey?: string }): number {\n let removed = 0\n for (const t of this.list()) {\n if (filter.runId && t.runId !== filter.runId) continue\n if (filter.nodeId && t.nodeId !== filter.nodeId) continue\n if (filter.cancelKey && t.cancelKey !== filter.cancelKey) continue\n try { unlinkSync(this.pathFor(t.id)); removed++ } catch { /* already gone */ }\n }\n return removed\n }\n\n /** Move a pending timer to a new fireAt, in place: same file, same id.\n * Never creates a timer. Returns the updated record, or null when no\n * unfired timer with that cancelKey exists (it fired or was cancelled). */\n retime(cancelKey: string, fireAt: string): TimerRecord | null {\n const t = this.list().find((x) => x.cancelKey === cancelKey && !this.firedIds.has(x.id))\n if (!t) return null\n const path = this.pathFor(t.id)\n if (!existsSync(path)) return null\n const updated = { ...t, fireAt }\n writeFileSync(path, JSON.stringify(updated, null, 2))\n return updated\n }\n\n list(): TimerRecord[] {\n if (!existsSync(this.baseDir)) return []\n const out: TimerRecord[] = []\n for (const entry of readdirSync(this.baseDir, { withFileTypes: true })) {\n if (!entry.isFile() || !entry.name.endsWith(\".json\")) continue\n try {\n const raw = JSON.parse(readFileSync(resolve(this.baseDir, entry.name), \"utf-8\"))\n const parsed = timerRecordSchema.safeParse(raw)\n if (parsed.success) out.push(parsed.data)\n } catch { /* skip malformed */ }\n }\n return out\n }\n\n private pathFor(id: string): string {\n return resolve(this.baseDir, `${id}.json`)\n }\n\n private tick(): void {\n if (!this.callback) return\n const now = Date.now()\n for (const t of this.list()) {\n if (this.firedIds.has(t.id)) continue\n const fireAtMs = Date.parse(t.fireAt)\n if (Number.isNaN(fireAtMs) || fireAtMs > now) continue\n // Mark fired BEFORE calling the callback so a callback that loops\n // back into the walk (and re-schedules siblings) doesn't re-trigger.\n this.firedIds.add(t.id)\n // Remove the file only once the callback has settled: a daemon that\n // stops between the fire and the run's resume fires it again on boot\n // instead of losing it (#1816). Resume paths check the run is still\n // paused on this timer, so a second fire is a no-op.\n const remove = () => { try { unlinkSync(this.pathFor(t.id)) } catch { /* may race with cancel */ } }\n let pending: Promise<void>\n try {\n pending = Promise.resolve(this.callback(t))\n } catch (e: any) {\n pending = Promise.reject(e)\n }\n void pending\n .catch((e: any) => this.log(`[timers] fire callback threw: ${e?.message ?? e}`))\n .finally(remove)\n }\n }\n}\n"],"mappings":"AAAA,OAAS,cAAAA,EAAY,aAAAC,EAAW,eAAAC,EAAa,gBAAAC,EAAc,cAAAC,EAAY,iBAAAC,MAAqB,KAC5F,OAAS,WAAAC,MAAe,OACxB,OAAS,cAAAC,MAAkB,SAC3B,OAAS,KAAAC,MAAS,MAuBX,IAAMC,EAAoBD,EAAE,OAAO,CACxC,GAAIA,EAAE,OAAO,EACb,MAAOA,EAAE,OAAO,EAChB,WAAYA,EAAE,OAAO,EACrB,OAAQA,EAAE,OAAO,EAEjB,OAAQA,EAAE,OAAO,EAGjB,UAAWA,EAAE,OAAO,EAAE,SAAS,EAC/B,UAAWA,EAAE,OAAO,CACtB,CAAC,EAgBYE,EAAN,KAAmB,CACf,QACA,eACA,gBACQ,IACT,MACA,WACA,SACA,QACA,SAAwB,IAAI,IAEpC,YAAYC,EAA4B,CAAC,EAAG,CAC1C,IAAMC,EAAOD,EAAK,SAAWL,EAAQ,Q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jC,OAAOH,CACT,CAEQ,QAAQI,EAAoB,CAClC,OAAOtB,EAAQ,KAAK,QAAS,GAAGsB,QAAS,CAC3C,CAEQ,MAAa,CACnB,GAAI,CAAC,KAAK,SAAU,OACpB,IAAMC,EAAM,KAAK,IAAI,EACrB,QAAW,KAAK,KAAK,KAAK,EAAG,CAC3B,GAAI,KAAK,SAAS,IAAI,EAAE,EAAE,EAAG,SAC7B,IAAMC,EAAW,KAAK,MAAM,EAAE,MAAM,EACpC,GAAI,OAAO,MAAMA,CAAQ,GAAKA,EAAWD,EAAK,SAG9C,KAAK,SAAS,IAAI,EAAE,EAAE,EAKtB,IAAME,EAAS,IAAM,CAAE,GAAI,CAAE3B,EAAW,KAAK,QAAQ,EAAE,EAAE,CAAC,CAAE,MAAE,CAAmC,CAAE,EAC/F4B,EACJ,GAAI,CACFA,EAAU,QAAQ,QAAQ,KAAK,SAAS,CAAC,CAAC,CAC5C,OAASC,EAAP,CACAD,EAAU,QAAQ,OAAOC,CAAC,CAC5B,CACKD,EACF,MAAOC,GAAW,KAAK,IAAI,iCAAiCA,GAAG,SAAWA,GAAG,CAAC,EAC9E,QAAQF,CAAM,EAErB,CACF","names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","writeFileSync","resolve","randomUUID","z","timerRecordSchema","TimerService","opts","root","cb","args","record","filter","removed","t","cancelKey","fireAt","x","path","updated","out","entry","raw","parsed","id","now","fireAtMs","remove","pending","e"]}
|