agentix-cli 0.190.0 → 0.191.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-6AHOJ2PO.js → App-Z4OZ4VAI.js} +2 -2
- package/dist/{ChatApp-MVSQX44C.js → ChatApp-7VLNOH2N.js} +2 -2
- package/dist/{absorb-eval-PHA44MPA.js → absorb-eval-QR3EEHDE.js} +2 -2
- package/dist/{adapter-RXZGBGFY.js → adapter-VWMQAALK.js} +2 -2
- package/dist/{agent-4CGWR2XJ.js → agent-RS4W545P.js} +2 -2
- package/dist/{board-dashboard-3CNZ3R6T.js → board-dashboard-RXOSENTD.js} +318 -317
- package/dist/{board-dashboard-3CNZ3R6T.js.map → board-dashboard-RXOSENTD.js.map} +1 -1
- package/dist/chunk-2HBEZV7L.js +24 -0
- package/dist/chunk-2HBEZV7L.js.map +1 -0
- package/dist/{chunk-YHRQQ4DB.js → chunk-34O2GH4J.js} +2 -2
- package/dist/{chunk-SOVWD6TL.js → chunk-3NMBTBNW.js} +2 -2
- package/dist/{chunk-EGKOB3ZM.js → chunk-54J6PXBG.js} +2 -2
- package/dist/{chunk-PE5V2LI7.js → chunk-5ONH4ITT.js} +2 -2
- package/dist/{chunk-ZJNEJRUU.js → chunk-6MU3OEII.js} +2 -2
- package/dist/chunk-A7JSRDJL.js +3 -0
- package/dist/chunk-A7JSRDJL.js.map +1 -0
- package/dist/{chunk-OBVLO6FV.js → chunk-AS4NDKUJ.js} +2 -2
- package/dist/{chunk-URWRA3EO.js → chunk-BWBTNBPS.js} +2 -2
- package/dist/{chunk-U2OGZDAN.js → chunk-CKHLBNMN.js} +2 -2
- package/dist/{chunk-ZYZ4VQUD.js → chunk-FRTU3ICQ.js} +2 -2
- package/dist/{chunk-FKT34MQ7.js → chunk-IGLJXEXX.js} +2 -2
- package/dist/chunk-JRAG37V5.js +3 -0
- package/dist/chunk-JRAG37V5.js.map +1 -0
- package/dist/{chunk-H7VI7OTS.js → chunk-KTGTKOLV.js} +2 -2
- package/dist/{chunk-A5KZSTYI.js → chunk-L3CWRXKQ.js} +2 -2
- package/dist/{chunk-POK4IPY3.js → chunk-MW75GECE.js} +94 -92
- package/dist/chunk-MW75GECE.js.map +1 -0
- package/dist/{chunk-WXJ25XH2.js → chunk-OTCMYGQR.js} +2 -2
- package/dist/{chunk-7BA4KCRW.js → chunk-RA4WCDGV.js} +2 -2
- package/dist/{chunk-QBR6TGRW.js → chunk-RQKLUGMS.js} +3 -3
- package/dist/{chunk-YLCMN4OA.js → chunk-RRGC6Y4L.js} +2 -2
- package/dist/{chunk-JE5KSD6Z.js → chunk-S3XUIVC2.js} +2 -2
- package/dist/{chunk-WILRVP4X.js → chunk-T2NPSEPJ.js} +2 -2
- package/dist/chunk-U5B275AU.js +143 -0
- package/dist/chunk-U5B275AU.js.map +1 -0
- package/dist/{chunk-UU77SLIS.js → chunk-WXSS7VIW.js} +302 -297
- package/dist/chunk-WXSS7VIW.js.map +1 -0
- package/dist/{chunk-J522P3Z3.js → chunk-XJEBJZLX.js} +2 -2
- package/dist/{chunk-Z55PWDYH.js → chunk-XJUBFPOM.js} +2 -2
- package/dist/chunk-XVV7ZZ77.js +6 -0
- package/dist/{chunk-4ZWZ42YE.js.map → chunk-XVV7ZZ77.js.map} +1 -1
- package/dist/{chunk-2MFBCDWL.js → chunk-YFJVQOWI.js} +2 -2
- package/dist/{chunk-FM5VBO3D.js → chunk-YMDGKFIG.js} +2 -2
- package/dist/{chunk-V2O4OQZC.js → chunk-YOMLHG33.js} +2 -2
- package/dist/{chunk-XIGFRLU5.js → chunk-ZCBTTYQN.js} +20 -20
- package/dist/chunk-ZCBTTYQN.js.map +1 -0
- package/dist/{chunk-YJDQK22T.js → chunk-ZJ74H5SV.js} +2 -2
- package/dist/{chunk-BSQIPD6F.js → chunk-ZU6W3CXO.js} +36 -36
- package/dist/chunk-ZU6W3CXO.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{client-YDESLBEL.js → client-N5YTG2K6.js} +2 -2
- package/dist/{compaction-R7VWQB6X.js → compaction-ZE2WYXHQ.js} +2 -2
- package/dist/{config-J7LIYG6O.js → config-WUB5SJPH.js} +2 -2
- package/dist/{config-mutate-WNWJL2BY.js → config-mutate-ZLPUEIVN.js} +2 -2
- package/dist/config-mutator-S5X4DOJK.js +2 -0
- package/dist/{contributions-VVKFLXVL.js → contributions-C4DKQJY6.js} +2 -2
- package/dist/{contributions-VVKFLXVL.js.map → contributions-C4DKQJY6.js.map} +1 -1
- package/dist/{doctor-IPU5KA2L.js → doctor-ND3OS575.js} +2 -2
- package/dist/fact-proposals-Z7HJG7QJ.js +2 -0
- package/dist/{follow-up-tool-NUXHITTB.js → follow-up-tool-TWOEAWOL.js} +2 -2
- package/dist/{hub-4SPXWMRT.js → hub-FUM7UY5S.js} +2 -2
- package/dist/index.d.ts +216 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/ledger-5GMBLR7W.js +2 -0
- package/dist/memory-extract-QYSXPK22.js +2 -0
- package/dist/memory-migrate-SO7RC5OU.js +2 -0
- package/dist/{memory-migrate-ED37IBEL.js.map → memory-migrate-SO7RC5OU.js.map} +1 -1
- package/dist/{program-5LBTVRBW.js → program-JLUZINRR.js} +201 -201
- package/dist/program-JLUZINRR.js.map +1 -0
- package/dist/{promote-A7VZBQUZ.js → promote-M5AJSWHZ.js} +2 -2
- package/dist/{query-5I6RBPPK.js → query-NPDKXBTN.js} +2 -2
- package/dist/{query-settings-QLLC46BO.js → query-settings-HXKZYIEV.js} +2 -2
- package/dist/registry-A2FFL4EA.js +2 -0
- package/dist/{request-planner-SF4GYBQE.js → request-planner-ANGZP4JL.js} +2 -2
- package/dist/{review-candidates-KPAZ3FYG.js → review-candidates-B7T2QA3R.js} +2 -2
- package/dist/{rotation-memo-6RP4Z3S5.js → rotation-memo-26CFE4JN.js} +4 -3
- package/dist/rotation-memo-26CFE4JN.js.map +1 -0
- package/dist/rotation-memo-store-WMDI7NND.js +2 -0
- package/dist/{rotation-memo-store-Z4D5KRA6.js.map → rotation-memo-store-WMDI7NND.js.map} +1 -1
- package/dist/{routing-RUJNJHM6.js → routing-2KWP5TAT.js} +2 -2
- package/dist/schedule-tool-2UNMXEBQ.js +2 -0
- package/dist/{scheduler-C44WJX4C.js → scheduler-VN7WDAKE.js} +2 -2
- package/dist/{seat-QY2GW3FI.js → seat-MAC3QGGD.js} +2 -2
- package/dist/{select-XJMJ2XVP.js → select-UYKEN4N4.js} +2 -2
- package/dist/{set-enabled-JC3TJ6VZ.js → set-enabled-JEUIINT3.js} +2 -2
- package/dist/{sprint-tool-NP4WN7KL.js → sprint-tool-MB2MPR4K.js} +2 -2
- package/dist/{tool-23ODBVYF.js → tool-L4CQCPRF.js} +2 -2
- package/dist/{tool-LZR4EOQJ.js → tool-SZ6C6EBP.js} +2 -2
- package/dist/{tool-KHD45TSF.js → tool-TLXKW55S.js} +2 -2
- package/dist/web/workflow-editor.global.js +12 -12
- package/dist/web/workflow-editor.global.js.map +1 -1
- package/dist/{wiki-N3JOY2NN.js → wiki-ZAHFGDKE.js} +2 -2
- package/dist/wiki-enrich-QLCQHV6B.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-4ZWZ42YE.js +0 -5
- package/dist/chunk-BSQIPD6F.js.map +0 -1
- package/dist/chunk-C5OCJCDC.js +0 -137
- package/dist/chunk-C5OCJCDC.js.map +0 -1
- package/dist/chunk-GQ76J72O.js +0 -3
- package/dist/chunk-GQ76J72O.js.map +0 -1
- package/dist/chunk-LE3BXIUF.js +0 -23
- package/dist/chunk-LE3BXIUF.js.map +0 -1
- package/dist/chunk-POK4IPY3.js.map +0 -1
- package/dist/chunk-UU77SLIS.js.map +0 -1
- package/dist/chunk-XIGFRLU5.js.map +0 -1
- package/dist/config-mutator-V3PSCM6Q.js +0 -2
- package/dist/fact-proposals-X2O4W7VN.js +0 -2
- package/dist/ledger-P62U3FHT.js +0 -2
- package/dist/memory-extract-NLVLQE7V.js +0 -2
- package/dist/memory-migrate-ED37IBEL.js +0 -2
- package/dist/program-5LBTVRBW.js.map +0 -1
- package/dist/registry-J724YF5H.js +0 -2
- package/dist/rotation-memo-6RP4Z3S5.js.map +0 -1
- package/dist/rotation-memo-store-Z4D5KRA6.js +0 -2
- package/dist/schedule-tool-PX5YULLG.js +0 -2
- package/dist/wiki-enrich-ZNFEO7BX.js +0 -2
- /package/dist/{App-6AHOJ2PO.js.map → App-Z4OZ4VAI.js.map} +0 -0
- /package/dist/{ChatApp-MVSQX44C.js.map → ChatApp-7VLNOH2N.js.map} +0 -0
- /package/dist/{absorb-eval-PHA44MPA.js.map → absorb-eval-QR3EEHDE.js.map} +0 -0
- /package/dist/{adapter-RXZGBGFY.js.map → adapter-VWMQAALK.js.map} +0 -0
- /package/dist/{agent-4CGWR2XJ.js.map → agent-RS4W545P.js.map} +0 -0
- /package/dist/{chunk-YHRQQ4DB.js.map → chunk-34O2GH4J.js.map} +0 -0
- /package/dist/{chunk-SOVWD6TL.js.map → chunk-3NMBTBNW.js.map} +0 -0
- /package/dist/{chunk-EGKOB3ZM.js.map → chunk-54J6PXBG.js.map} +0 -0
- /package/dist/{chunk-PE5V2LI7.js.map → chunk-5ONH4ITT.js.map} +0 -0
- /package/dist/{chunk-ZJNEJRUU.js.map → chunk-6MU3OEII.js.map} +0 -0
- /package/dist/{chunk-OBVLO6FV.js.map → chunk-AS4NDKUJ.js.map} +0 -0
- /package/dist/{chunk-URWRA3EO.js.map → chunk-BWBTNBPS.js.map} +0 -0
- /package/dist/{chunk-U2OGZDAN.js.map → chunk-CKHLBNMN.js.map} +0 -0
- /package/dist/{chunk-ZYZ4VQUD.js.map → chunk-FRTU3ICQ.js.map} +0 -0
- /package/dist/{chunk-FKT34MQ7.js.map → chunk-IGLJXEXX.js.map} +0 -0
- /package/dist/{chunk-H7VI7OTS.js.map → chunk-KTGTKOLV.js.map} +0 -0
- /package/dist/{chunk-A5KZSTYI.js.map → chunk-L3CWRXKQ.js.map} +0 -0
- /package/dist/{chunk-WXJ25XH2.js.map → chunk-OTCMYGQR.js.map} +0 -0
- /package/dist/{chunk-7BA4KCRW.js.map → chunk-RA4WCDGV.js.map} +0 -0
- /package/dist/{chunk-QBR6TGRW.js.map → chunk-RQKLUGMS.js.map} +0 -0
- /package/dist/{chunk-YLCMN4OA.js.map → chunk-RRGC6Y4L.js.map} +0 -0
- /package/dist/{chunk-JE5KSD6Z.js.map → chunk-S3XUIVC2.js.map} +0 -0
- /package/dist/{chunk-WILRVP4X.js.map → chunk-T2NPSEPJ.js.map} +0 -0
- /package/dist/{chunk-J522P3Z3.js.map → chunk-XJEBJZLX.js.map} +0 -0
- /package/dist/{chunk-Z55PWDYH.js.map → chunk-XJUBFPOM.js.map} +0 -0
- /package/dist/{chunk-2MFBCDWL.js.map → chunk-YFJVQOWI.js.map} +0 -0
- /package/dist/{chunk-FM5VBO3D.js.map → chunk-YMDGKFIG.js.map} +0 -0
- /package/dist/{chunk-V2O4OQZC.js.map → chunk-YOMLHG33.js.map} +0 -0
- /package/dist/{chunk-YJDQK22T.js.map → chunk-ZJ74H5SV.js.map} +0 -0
- /package/dist/{client-YDESLBEL.js.map → client-N5YTG2K6.js.map} +0 -0
- /package/dist/{compaction-R7VWQB6X.js.map → compaction-ZE2WYXHQ.js.map} +0 -0
- /package/dist/{config-J7LIYG6O.js.map → config-WUB5SJPH.js.map} +0 -0
- /package/dist/{config-mutate-WNWJL2BY.js.map → config-mutate-ZLPUEIVN.js.map} +0 -0
- /package/dist/{config-mutator-V3PSCM6Q.js.map → config-mutator-S5X4DOJK.js.map} +0 -0
- /package/dist/{doctor-IPU5KA2L.js.map → doctor-ND3OS575.js.map} +0 -0
- /package/dist/{fact-proposals-X2O4W7VN.js.map → fact-proposals-Z7HJG7QJ.js.map} +0 -0
- /package/dist/{follow-up-tool-NUXHITTB.js.map → follow-up-tool-TWOEAWOL.js.map} +0 -0
- /package/dist/{hub-4SPXWMRT.js.map → hub-FUM7UY5S.js.map} +0 -0
- /package/dist/{ledger-P62U3FHT.js.map → ledger-5GMBLR7W.js.map} +0 -0
- /package/dist/{memory-extract-NLVLQE7V.js.map → memory-extract-QYSXPK22.js.map} +0 -0
- /package/dist/{promote-A7VZBQUZ.js.map → promote-M5AJSWHZ.js.map} +0 -0
- /package/dist/{query-5I6RBPPK.js.map → query-NPDKXBTN.js.map} +0 -0
- /package/dist/{query-settings-QLLC46BO.js.map → query-settings-HXKZYIEV.js.map} +0 -0
- /package/dist/{registry-J724YF5H.js.map → registry-A2FFL4EA.js.map} +0 -0
- /package/dist/{request-planner-SF4GYBQE.js.map → request-planner-ANGZP4JL.js.map} +0 -0
- /package/dist/{review-candidates-KPAZ3FYG.js.map → review-candidates-B7T2QA3R.js.map} +0 -0
- /package/dist/{routing-RUJNJHM6.js.map → routing-2KWP5TAT.js.map} +0 -0
- /package/dist/{schedule-tool-PX5YULLG.js.map → schedule-tool-2UNMXEBQ.js.map} +0 -0
- /package/dist/{scheduler-C44WJX4C.js.map → scheduler-VN7WDAKE.js.map} +0 -0
- /package/dist/{seat-QY2GW3FI.js.map → seat-MAC3QGGD.js.map} +0 -0
- /package/dist/{select-XJMJ2XVP.js.map → select-UYKEN4N4.js.map} +0 -0
- /package/dist/{set-enabled-JC3TJ6VZ.js.map → set-enabled-JEUIINT3.js.map} +0 -0
- /package/dist/{sprint-tool-NP4WN7KL.js.map → sprint-tool-MB2MPR4K.js.map} +0 -0
- /package/dist/{tool-23ODBVYF.js.map → tool-L4CQCPRF.js.map} +0 -0
- /package/dist/{tool-LZR4EOQJ.js.map → tool-SZ6C6EBP.js.map} +0 -0
- /package/dist/{tool-KHD45TSF.js.map → tool-TLXKW55S.js.map} +0 -0
- /package/dist/{wiki-N3JOY2NN.js.map → wiki-ZAHFGDKE.js.map} +0 -0
- /package/dist/{wiki-enrich-ZNFEO7BX.js.map → wiki-enrich-QLCQHV6B.js.map} +0 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import{a as f}from"./chunk-A7JSRDJL.js";import{a as l,b as u}from"./chunk-BERWTVG2.js";var g=new Set(["cron","a2a","workflow","selftest"]),y=[[/^User:\s*You are\s/i,"role brief"],[/^User:\s*(Run|Execute)\s/i,"run instruction"],[/^User:\s*\[MISSED RUN/i,"missed cron run"],[/^User:\s*(\[[^\]]{0,40}\]:?\s*)?\[Recent group conversation\]/i,"group chat dump"]];function h(t){if(t.responseLength<=50)return{capture:!1,reason:"response too short"};let r=(t.channel??"").toLowerCase().split("@")[0];if(g.has(r))return{capture:!1,reason:`machine channel: ${r}`};let n=t.content.slice(0,400);for(let[o,i]of y)if(o.test(n))return{capture:!1,reason:i};return{capture:!0}}var w="claude-haiku-4-5-20251001",k=`You are a memory extraction system for an AI agent. Given a conversation exchange, extract facts worth remembering for future conversations across different chat sessions.
|
|
2
|
+
|
|
3
|
+
Extract ONLY facts that would help the agent in FUTURE, DIFFERENT conversations:
|
|
4
|
+
- User preferences and instructions ("never do X", "always use Y")
|
|
5
|
+
- Commitments the agent made ("I will deploy by Friday")
|
|
6
|
+
- Relationships ("Alex is the admin", "Marketing handles content")
|
|
7
|
+
- Task state ("GitLab tokens need deploying to peer-server")
|
|
8
|
+
- Important facts about infrastructure, config, or processes
|
|
9
|
+
|
|
10
|
+
SKIP:
|
|
11
|
+
- Credentials of any kind: passwords, tokens, API keys, private keys, connection strings. Never repeat one, not even partly. At most note that a credential exists and where it is kept, without its value.
|
|
12
|
+
- Routine greetings, acknowledgments, status updates
|
|
13
|
+
- Usage limits, plan windows, reset times, holds, and the state of this machine (memory, disk, installed versions): the node reports these live
|
|
14
|
+
- Information derivable from code or config files
|
|
15
|
+
- Transient conversation flow ("let me check", "here's what I found")
|
|
16
|
+
- Facts already obvious from the agent's system prompt
|
|
17
|
+
|
|
18
|
+
For each fact, output a JSON array:
|
|
19
|
+
[{"category":"fact|preference|commitment|task-state","content":"concise fact, 1-2 sentences","keywords":["keyword1","keyword2"]}]
|
|
20
|
+
|
|
21
|
+
If nothing worth remembering, output: []`;async function N(t,s,r,n,o){if(s.length<20&&r.length<50||!h({channel:n.channel,content:`User: ${s}`,responseLength:r.length}).capture)return;let{createProvider:m}=await import("./providers-F5GDJSYD.js"),c=(await m("claude").generate([{role:"system",content:k},{role:"user",content:`${n.sender} (via ${n.channel}): ${s}
|
|
22
|
+
|
|
23
|
+
Agent: ${r}`}],{model:w,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let a=JSON.parse(c[0]);if(!Array.isArray(a)||a.length===0)return;let d=new Date().toISOString().slice(0,10),p=l(n.channel);for(let e of a)typeof e?.content=="string"&&(e.category==="secret"||u(e.content)||f(e.content)||o.hasSimilar(t,e.content)||o.addMemory(t,{agentId:t,category:e.category,content:e.content,keywords:e.keywords||[],source:{...n,date:d,trust:p},expiresAt:e.category==="task-state"?new Date(Date.now()+7*24*60*60*1e3).toISOString():void 0}));Math.random()<.02&&o.prune(t)}export{h as a,N as b};
|
|
24
|
+
//# sourceMappingURL=chunk-2HBEZV7L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/capture-filter.ts","../src/agents/memory-extract.ts"],"sourcesContent":["// What deserves to become a raw wiki entry.\n//\n// Until now the only gate was `response.content.length > 50`. Every agent\n// task was captured, with the task's own message as the \"User:\" half — so\n// a cron's prompt became an entry, a role brief became an entry, and a\n// \"[MISSED RUN]\" notice became an entry.\n//\n// Measured over the 10,703 entries that produced: 30% arrived on a\n// machine-origin channel, 33% are prompt-shaped, and 47.5% are one or\n// both. That is the bulk of a corpus that has yielded 257 articles and is\n// read about three times a quarter.\n//\n// These rules are deterministic and free. They are deliberately\n// conservative — each one describes a shape that cannot contain knowledge\n// about the world, rather than guessing at value. Judging whether the\n// REMAINDER is worth keeping is a different question, and belongs to the\n// entry-triage seat, which costs money and can be wrong.\n\n/** Channels where both sides of the exchange are machines. A cron's\n * prompt is configuration, and its reply is a status report. */\nconst MACHINE_CHANNELS = new Set([\"cron\", \"a2a\", \"workflow\", \"selftest\"])\n\n/** Shapes that are an instruction to an agent, not a record of anything.\n * Anchored at the start of the captured content, which always begins\n * \"User: \" followed by the task message. */\nconst PROMPT_SHAPES: Array<[RegExp, string]> = [\n [/^User:\\s*You are\\s/i, \"role brief\"],\n [/^User:\\s*(Run|Execute)\\s/i, \"run instruction\"],\n [/^User:\\s*\\[MISSED RUN/i, \"missed cron run\"],\n // The bracketed prefix varies: some arrive as \"[Group, 09:43]: [Recent\n // group conversation]\". Anchoring on the bare marker missed 367 entries\n // in the first purge, so allow one leading bracketed segment.\n [/^User:\\s*(\\[[^\\]]{0,40}\\]:?\\s*)?\\[Recent group conversation\\]/i, \"group chat dump\"],\n]\n\nexport interface CaptureDecision {\n capture: boolean\n /** Why it was rejected, for logging and for counting what the filter\n * actually removes once it is live. */\n reason?: string\n}\n\nexport function shouldCaptureEntry(input: {\n channel: string | undefined\n content: string\n responseLength: number\n}): CaptureDecision {\n if (input.responseLength <= 50) return { capture: false, reason: \"response too short\" }\n\n const channel = (input.channel ?? \"\").toLowerCase()\n // Channels carry a node suffix: \"telegram@peer-server\".\n const base = channel.split(\"@\")[0]\n if (MACHINE_CHANNELS.has(base)) return { capture: false, reason: `machine channel: ${base}` }\n\n const head = input.content.slice(0, 400)\n for (const [shape, reason] of PROMPT_SHAPES) {\n if (shape.test(head)) return { capture: false, reason }\n }\n\n return { capture: true }\n}\n","import type { MemoryStore } from \"./memory-store\"\nimport { shouldCaptureEntry } from \"@/wiki/capture-filter\"\nimport { containsSecret, trustForChannel } from \"./memory-trust\"\nimport { isNodeFact } from \"./node-facts\"\n\n// --- Haiku-powered memory extraction ---\n// Fire-and-forget after each agent response.\n// Extracts memorable facts and writes them to the persistent store.\n\nconst EXTRACTION_MODEL = \"claude-haiku-4-5-20251001\"\n\nconst EXTRACTION_PROMPT = `You are a memory extraction system for an AI agent. Given a conversation exchange, extract facts worth remembering for future conversations across different chat sessions.\n\nExtract ONLY facts that would help the agent in FUTURE, DIFFERENT conversations:\n- User preferences and instructions (\"never do X\", \"always use Y\")\n- Commitments the agent made (\"I will deploy by Friday\")\n- Relationships (\"Alex is the admin\", \"Marketing handles content\")\n- Task state (\"GitLab tokens need deploying to peer-server\")\n- Important facts about infrastructure, config, or processes\n\nSKIP:\n- Credentials of any kind: passwords, tokens, API keys, private keys, connection strings. Never repeat one, not even partly. At most note that a credential exists and where it is kept, without its value.\n- Routine greetings, acknowledgments, status updates\n- Usage limits, plan windows, reset times, holds, and the state of this machine (memory, disk, installed versions): the node reports these live\n- Information derivable from code or config files\n- Transient conversation flow (\"let me check\", \"here's what I found\")\n- Facts already obvious from the agent's system prompt\n\nFor each fact, output a JSON array:\n[{\"category\":\"fact|preference|commitment|task-state\",\"content\":\"concise fact, 1-2 sentences\",\"keywords\":[\"keyword1\",\"keyword2\"]}]\n\nIf nothing worth remembering, output: []`\n\nexport async function extractMemories(\n agentId: string,\n userMessage: string,\n agentResponse: string,\n source: { channel: string; chatId: string; sender: string },\n store: MemoryStore,\n): Promise<void> {\n // Skip very short exchanges (unlikely to contain memorable facts)\n if (userMessage.length < 20 && agentResponse.length < 50) return\n\n // Same gate as wiki capture: machine channels (cron, a2a, workflow) and\n // prompt-shaped messages hold configuration, not facts about the world.\n const gate = shouldCaptureEntry({\n channel: source.channel,\n content: `User: ${userMessage}`,\n responseLength: agentResponse.length,\n })\n if (!gate.capture) return\n\n const { createProvider } = await import(\"@/agent/providers\")\n const provider = createProvider(\"claude\")\n\n const result = await provider.generate(\n [\n { role: \"system\", content: EXTRACTION_PROMPT },\n {\n role: \"user\",\n content: `${source.sender} (via ${source.channel}): ${userMessage}\\n\\nAgent: ${agentResponse}`,\n },\n ],\n { model: EXTRACTION_MODEL, maxTokens: 512 },\n )\n\n // Parse JSON array from response\n const content = result.content.trim()\n const jsonMatch = content.match(/\\[[\\s\\S]*\\]/)\n if (!jsonMatch) return\n\n const facts = JSON.parse(jsonMatch[0]) as Array<{\n category: string\n content: string\n keywords: string[]\n }>\n\n if (!Array.isArray(facts) || facts.length === 0) return\n\n const date = new Date().toISOString().slice(0, 10)\n const trust = trustForChannel(source.channel)\n\n for (const fact of facts) {\n if (typeof fact?.content !== \"string\") continue\n // The prompt says never to extract credentials; this holds when the\n // model does it anyway. addMemory refuses them too.\n if (fact.category === \"secret\" || containsSecret(fact.content)) continue\n // The node reports limits, resets and holds live (#1531).\n if (isNodeFact(fact.content)) continue\n // Skip duplicates\n if (store.hasSimilar(agentId, fact.content)) continue\n\n store.addMemory(agentId, {\n agentId,\n category: fact.category as any,\n content: fact.content,\n keywords: fact.keywords || [],\n source: { ...source, date, trust },\n expiresAt: fact.category === \"task-state\"\n ? new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString()\n : undefined,\n })\n }\n\n // Prune occasionally (every ~50 calls, probabilistic)\n if (Math.random() < 0.02) {\n store.prune(agentId)\n }\n}\n"],"mappings":"uFAoBA,IAAMA,EAAmB,IAAI,IAAI,CAAC,OAAQ,MAAO,WAAY,UAAU,CAAC,EAKlEC,EAAyC,CAC7C,CAAC,sBAAuB,YAAY,EACpC,CAAC,4BAA6B,iBAAiB,EAC/C,CAAC,yBAA0B,iBAAiB,EAI5C,CAAC,iEAAkE,iBAAiB,CACtF,EASO,SAASC,EAAmBC,EAIf,CAClB,GAAIA,EAAM,gBAAkB,GAAI,MAAO,CAAE,QAAS,GAAO,OAAQ,oBAAqB,EAItF,IAAMC,GAFWD,EAAM,SAAW,IAAI,YAAY,EAE7B,MAAM,GAAG,EAAE,CAAC,EACjC,GAAIH,EAAiB,IAAII,CAAI,EAAG,MAAO,CAAE,QAAS,GAAO,OAAQ,oBAAoBA,GAAO,EAE5F,IAAMC,EAAOF,EAAM,QAAQ,MAAM,EAAG,GAAG,EACvC,OAAW,CAACG,EAAOC,CAAM,IAAKN,EAC5B,GAAIK,EAAM,KAAKD,CAAI,EAAG,MAAO,CAAE,QAAS,GAAO,OAAAE,CAAO,EAGxD,MAAO,CAAE,QAAS,EAAK,CACzB,CCnDA,IAAMC,EAAmB,4BAEnBC,EAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0CAsB1B,eAAsBC,EACpBC,EACAC,EACAC,EACAC,EACAC,EACe,CAWf,GATIH,EAAY,OAAS,IAAMC,EAAc,OAAS,IASlD,CALSG,EAAmB,CAC9B,QAASF,EAAO,QAChB,QAAS,SAASF,IAClB,eAAgBC,EAAc,MAChC,CAAC,EACS,QAAS,OAEnB,GAAM,CAAE,eAAAI,CAAe,EAAI,KAAM,QAAO,yBAAmB,EAgBrDC,GAbS,MAFED,EAAe,QAAQ,EAEV,SAC5B,CACE,CAAE,KAAM,SAAU,QAASR,CAAkB,EAC7C,CACE,KAAM,OACN,QAAS,GAAGK,EAAO,eAAeA,EAAO,aAAaF;AAAA;AAAA,SAAyBC,GACjF,CACF,EACA,CAAE,MAAOL,EAAkB,UAAW,GAAI,CAC5C,GAGuB,QAAQ,KAAK,EACV,MAAM,aAAa,EAC7C,GAAI,CAACU,EAAW,OAEhB,IAAMC,EAAQ,KAAK,MAAMD,EAAU,CAAC,CAAC,EAMrC,GAAI,CAAC,MAAM,QAAQC,CAAK,GAAKA,EAAM,SAAW,EAAG,OAEjD,IAAMC,EAAO,IAAI,KAAK,EAAE,YAAY,EAAE,MAAM,EAAG,EAAE,EAC3CC,EAAQC,EAAgBR,EAAO,OAAO,EAE5C,QAAWS,KAAQJ,EACb,OAAOI,GAAM,SAAY,WAGzBA,EAAK,WAAa,UAAYC,EAAeD,EAAK,OAAO,GAEzDE,EAAWF,EAAK,OAAO,GAEvBR,EAAM,WAAWJ,EAASY,EAAK,OAAO,GAE1CR,EAAM,UAAUJ,EAAS,CACvB,QAAAA,EACA,SAAUY,EAAK,SACf,QAASA,EAAK,QACd,SAAUA,EAAK,UAAY,CAAC,EAC5B,OAAQ,CAAE,GAAGT,EAAQ,KAAAM,EAAM,MAAAC,CAAM,EACjC,UAAWE,EAAK,WAAa,aACzB,IAAI,KAAK,KAAK,IAAI,EAAI,EAAI,GAAK,GAAK,GAAK,GAAI,EAAE,YAAY,EAC3D,MACN,CAAC,GAIC,KAAK,OAAO,EAAI,KAClBR,EAAM,MAAMJ,CAAO,CAEvB","names":["MACHINE_CHANNELS","PROMPT_SHAPES","shouldCaptureEntry","input","base","head","shape","reason","EXTRACTION_MODEL","EXTRACTION_PROMPT","extractMemories","agentId","userMessage","agentResponse","source","store","shouldCaptureEntry","createProvider","jsonMatch","facts","date","trust","trustForChannel","fact","containsSecret","isNodeFact"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{y as l,z as T}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{y as l,z as T}from"./chunk-3NMBTBNW.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
|
|
2
|
+
//# sourceMappingURL=chunk-34O2GH4J.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-DCIYOPJF.js";import{Fb as tt,Gb as nt}from"./chunk-
|
|
1
|
+
import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-DCIYOPJF.js";import{Fb as tt,Gb as nt}from"./chunk-ZCBTTYQN.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
|
|
2
2
|
ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
|
|
3
3
|
INSERT INTO schema_version (v) VALUES (3);
|
|
4
4
|
`)}function Ot(e){e.exec(`
|
|
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
|
|
|
111
111
|
`)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Gt(e,t,r,n,o){let s=[r,ae(t)].join(`
|
|
112
112
|
`),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),cn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
|
|
113
113
|
${U(m.error)}`);let w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function un(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}y={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-3NMBTBNW.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-
|
|
1
|
+
import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-FRTU3ICQ.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
|
|
2
2
|
## Worldview
|
|
3
3
|
|
|
4
4
|
${r}
|
|
@@ -249,4 +249,4 @@ ${u}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
|
|
|
249
249
|
Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let m=[{role:"user",content:n}];s&&(m.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),m.push({role:"user",content:`Your previous response failed validation: ${s}
|
|
250
250
|
Re-emit the FULL corrected JSON object.`}));let u=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:m}),signal:i.signal});if(!u.ok){let a=await u.text().catch(()=>"");throw new Error(`anthropic API ${u.status}: ${a.slice(0,500)}`)}let d=await u.json(),e=(Array.isArray(d.content)?d.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
|
|
251
251
|
`).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...l)=>t(l.map(String).join(" "))),p=c.rebuildIndex(),m=z(r),u=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(u,p,m,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let d=p.articles.map(l=>({title:l.title,path:l.path,type:l.type})),g=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,d,g);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,d,g);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(l=>l.candidates),w=new Set(y.map(l=>l.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(l=>[l.stamp,l]));for(let l of f.articles){let A=c.readArticle(l.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${l.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(l.promotedFrom,T),S={id:Y(o,l.path),createdAt:v,status:"pending",article:l,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:l.path,title:l.title,type:l.type,stamps:l.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of l.promotedFrom)k.push({stamp:X,decision:"proposed",article:l.path,proposal:S.id,at:v})}for(let l of f.skipped)k.push({stamp:l.stamp,decision:"skipped",reason:l.reason,at:v}),i.skipped.push(l);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let m=s.now??Date.now(),u=new Date(m).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??u,lastUpdated:u,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let g=new Date(m).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:g}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:g};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
|
|
252
|
-
//# sourceMappingURL=chunk-
|
|
252
|
+
//# sourceMappingURL=chunk-54J6PXBG.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as B,c as k,d as A,f as j}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{b as B,c as k,d as A,f as j}from"./chunk-JRAG37V5.js";import{a as W,b as $,c as g}from"./chunk-ILEC3IAV.js";import{a as p,b as w,d as F}from"./chunk-OWNQ2FD4.js";import{createHash as I}from"crypto";import{existsSync as C,statSync as D}from"fs";import{resolve as L}from"path";var o=a=>a.toLowerCase().replace(/\s+/g," ").trim();function S(a,t){return"f-"+I("sha1").update(`${o(a)}\0${o(t)}`).digest("hex").slice(0,10)}var x=class{constructor(t){this.wikiDir=t;this.file=L(t,"_facts.json")}file;cache;reported;load(){if(!C(this.file))return{version:1,facts:[],proposals:[]};let t=D(this.file).mtimeMs;if(this.cache?.mtimeMs===t)return structuredClone(this.cache.data);let e;try{e=p(this.file)}catch(i){throw this.reported!==t&&(this.reported=t,console.error(`[wiki-facts] ${i.message}`)),i}let s={version:1,facts:e?.facts??[],proposals:e?.proposals??[]};return this.cache={mtimeMs:t,data:s},structuredClone(s)}update(t){return F(this.file,()=>{this.cache=void 0;let e=this.load(),{save:s,result:i}=t(e);return s&&(w(this.file,e),this.cache=void 0),i})}list(){return this.load().facts}get(t){return this.list().find(e=>e.id===t||t.length>=6&&e.id.startsWith(t))??null}write(t,e={}){e.confirmedBy&&W("confirm a fact");let s=e.now??Date.now(),i=new Date(s).toISOString();if(!t.source?.trim())throw new Error('a fact needs a source: a system, URL, command or "owner said"');if(!t.subject?.trim()||!t.attribute?.trim()||!t.value?.trim())throw new Error("a fact needs a subject, an attribute and a value");let c=t.verifiedAt==="now"?s:Date.parse(t.verifiedAt??""),n=Number.isFinite(c),d=n?new Date(Math.min(c,s)).toISOString():i,l=B(t.volatility)?t.volatility:A(t.attribute,`${t.subject} ${t.attribute} is ${t.value}`),v={source:t.source.trim(),verifiedAt:d,verifiedBy:t.verifiedBy||"unknown",volatility:l,...typeof t.ttlDays=="number"?{ttlDays:t.ttlDays}:{}},h=S(t.subject,t.attribute),f=this.update(u=>{let r=u.facts.find(m=>m.id===h);if(!r){let m={id:h,subject:t.subject.trim(),attribute:t.attribute.trim(),value:t.value.trim(),...v,createdAt:i,updatedAt:i,...!n&&!e.confirmedBy?{undated:!0}:{},...e.confirmedBy?{confirmedBy:e.confirmedBy}:{}};return u.facts.push(m),{save:!0,result:{status:"created",fact:m}}}let y=Date.parse(r.verifiedAt),b=n&&(r.undated||!Number.isFinite(y)||Date.parse(d)>y);return o(r.value)===o(t.value)?!b&&!e.confirmedBy?{save:!1,result:{status:"unchanged",fact:r}}:(Object.assign(r,v,{updatedAt:i},e.confirmedBy?{confirmedBy:e.confirmedBy}:{}),delete r.undated,{save:!0,result:{status:"verified",fact:r}}):!e.confirmedBy&&(!b||r.confirmedBy)?{save:!1,result:{contradiction:r}}:(r.history=[...r.history??[],{value:r.value,source:r.source,verifiedAt:r.verifiedAt,verifiedBy:r.verifiedBy,replacedAt:i}].slice(-10),r.value=t.value.trim(),Object.assign(r,v,{updatedAt:i}),delete r.undated,e.confirmedBy?r.confirmedBy=e.confirmedBy:delete r.confirmedBy,{save:!0,result:{status:"updated",fact:r}})});if("contradiction"in f){let u=q(this.wikiDir,f.contradiction,{...t,verifiedAt:n?d:"undated"});return{status:"contradiction",fact:f.contradiction,questionId:u.id,questionClosed:u.closed}}return f}};function q(a,t,e){let s=new g(a),i={kind:"contradiction",agentId:e.verifiedBy||"unknown",path:"_facts.json",subject:t.subject,field:`${t.attribute}=${o(e.value)}`,tier:"pillar",factId:t.id,proposed:{value:e.value.trim(),source:e.source.trim(),verifiedAt:e.verifiedAt,verifiedBy:e.verifiedBy},question:`${t.subject} \xB7 ${t.attribute}: the wiki says "${t.value}" (${t.source}, checked ${t.verifiedAt.slice(0,10)}), but ${e.verifiedBy} reports "${e.value.trim()}" (${e.source.trim()}, checked ${e.verifiedAt.slice(0,10)}). Which is true?`},c=$(i.kind,i.agentId,i.subject,i.field);s.add([i]);let n=s.list().find(d=>d.id===c);return n?n.status==="answered"||n.status==="dismissed"?{closed:n.status}:{id:c}:{}}function N(a){return new g(a).list("open").filter(t=>t.kind==="contradiction").map(t=>({type:"contradiction",articles:[`_facts.json#${t.factId??"?"}`],message:`[${t.id}] ${t.question}`,confidence:"high"}))}function H(a,t=Date.now()){return a.undated===!0||j(a,t)}function Q(a,t){let e=o(a),s=null;for(let i of t){let c=o(i.subject);if(c.length<3||!e.includes(c))continue;let n=o(i.attribute).split(" ").filter(l=>l.length>2);(e.includes(o(i.value))||i.volatility!=="stable"&&k(a)===i.volatility||n.length>0&&n.every(l=>e.includes(l)))&&(!s||i.subject.length>s.subject.length)&&(s=i)}return s}export{S as a,x as b,N as c,H as d,Q as e};
|
|
2
|
+
//# sourceMappingURL=chunk-5ONH4ITT.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as h}from"./chunk-
|
|
1
|
+
import{a as h}from"./chunk-FRTU3ICQ.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
|
|
2
2
|
`),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
|
|
3
3
|
`),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-6MU3OEII.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var i="(?:5[- ]?h(?:ours?)?|7[- ]?d(?:ays?)?|five[- ]hours?|seven[- ]days?)[- ](?:windows?|limits?|caps?|quotas?|usage|holds?)",o=new RegExp(`\\b(?:claude|anthropic|opus|sonnet|haiku|codex|five_hour|seven_day|${i}|weekly (?:limits?|windows?|caps?)|usage limits?|session limits?|plan windows?)\\b`,"i"),a=[/\b(?:limits?|windows?|quotas?|caps?|allowance)\b[^.\n]{0,60}\bresets?\b/i,/\bresets?\b[^.\n]{0,40}\b(?:limits?|windows?|quotas?)\b/i,/\b(?:limits?|windows?) (?:is |was |has been |got )?(?:reached|hit|exceeded|exhausted|lifted|used up|rejected)\b/i,/\b(?:hit|reached|exceeded) (?:the |its |our |a )?(?:\w+ )?limit\b/i,/\brate[- ]limited\b/i,/\bquotas? (?:is |was )?(?:exceeded|reached|hit|exhausted|used up)\b/i,/\bout of (?:usage|quota|credits)\b/i],n=[/\b(?:plan|provider|claude|quota|usage)[- ]holds?\b/i,/\bdispatch(?:es)? (?:are |is |were )?held\b/i];function d(t){return t.split(`
|
|
2
|
+
`).some(e=>n.some(s=>s.test(e))||o.test(e)&&a.some(s=>s.test(e)))}var r="STALE (limits change hourly; check agentx_node) ",c='- Facts about this machine (OS, version, CPU, memory, disk, installed programs and versions), the Claude account (usage limits, resets, holds) or the work running now: call the agentx_node tool first and answer from it, quoting its check time ("no limit holds work, checked 10:42 UTC"). Never answer these from memory, notes or earlier messages: they go stale within hours.';export{d as a,r as b,c};
|
|
3
|
+
//# sourceMappingURL=chunk-A7JSRDJL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/node-facts.ts"],"sourcesContent":["// --- Facts the node owns: never kept in agent memory (#1531) ---\n//\n// The node reports its own machine, programs, Claude account limits and\n// running work live (GET /api/node, the agentx_node tool). A copy of one\n// of those in memory is how an hour-old \"weekly limit, resets tomorrow\"\n// note was repeated as true after the account had recovered. So:\n// - memory writers refuse usage-limit, reset and hold notes\n// (MemoryStore.addMemory, the rotation memo);\n// - one already stored is rendered with a stale marker that sends the\n// agent to agentx_node;\n// - the prompt rule below tells agents to answer from the tool, with\n// its check time.\n//\n// A line counts only when it is about Claude, this node or its plan:\n// a hold pattern (agentx's own words), or a live-state pattern (limit\n// hit, window resets, rate-limited) on a line that also names a Claude\n// subject. \"nginx rate limit 10r/s\", \"Supabase email limit 4/hour\" or\n// \"extra usage stays off\" are lasting facts about other systems or\n// decisions, and stay in memory.\n\n// A spelled window (\"5h\", \"7-day\", \"five hour\") is a duration unless a\n// window word follows it: \"every 5h\" is a schedule, \"the 5h window\" is\n// Claude's. The API names five_hour and seven_day always count.\nconst WINDOW = \"(?:5[- ]?h(?:ours?)?|7[- ]?d(?:ays?)?|five[- ]hours?|seven[- ]days?)[- ](?:windows?|limits?|caps?|quotas?|usage|holds?)\"\nconst SUBJECT = new RegExp(`\\\\b(?:claude|anthropic|opus|sonnet|haiku|codex|five_hour|seven_day|${WINDOW}|weekly (?:limits?|windows?|caps?)|usage limits?|session limits?|plan windows?)\\\\b`, \"i\")\n\nconst LIVE_STATE: RegExp[] = [\n // \"limit … resets 10-30 17:00\", \"the window resets at 17:00\"\n /\\b(?:limits?|windows?|quotas?|caps?|allowance)\\b[^.\\n]{0,60}\\bresets?\\b/i,\n /\\bresets?\\b[^.\\n]{0,40}\\b(?:limits?|windows?|quotas?)\\b/i,\n // \"limit reached / hit / exceeded / lifted\", \"window rejected\"\n /\\b(?:limits?|windows?) (?:is |was |has been |got )?(?:reached|hit|exceeded|exhausted|lifted|used up|rejected)\\b/i,\n /\\b(?:hit|reached|exceeded) (?:the |its |our |a )?(?:\\w+ )?limit\\b/i,\n // \"rate-limited\", \"quota exceeded\", \"out of usage\"\n /\\brate[- ]limited\\b/i,\n /\\bquotas? (?:is |was )?(?:exceeded|reached|hit|exhausted|used up)\\b/i,\n /\\bout of (?:usage|quota|credits)\\b/i,\n]\n\n// Holds are agentx's own state: \"plan hold\", \"cold dispatches are held\".\nconst HOLDS: RegExp[] = [\n /\\b(?:plan|provider|claude|quota|usage)[- ]holds?\\b/i,\n /\\bdispatch(?:es)? (?:are |is |were )?held\\b/i,\n]\n\n/** True when the text states a Claude usage limit, its reset or a hold. */\nexport function isNodeFact(text: string): boolean {\n return text.split(\"\\n\").some((line) =>\n HOLDS.some((re) => re.test(line)) || (SUBJECT.test(line) && LIVE_STATE.some((re) => re.test(line))))\n}\n\n/** Rendered before a stored note of that kind. */\nexport const NODE_FACT_STALE_TAG = \"STALE (limits change hourly; check agentx_node) \"\n\n/** The prompt rule: answer environment and account facts from the node. */\nexport const NODE_FACTS_RULE =\n \"- Facts about this machine (OS, version, CPU, memory, disk, installed programs and versions), the Claude account \" +\n \"(usage limits, resets, holds) or the work running now: call the agentx_node tool first and answer from it, quoting \" +\n \"its check time (\\\"no limit holds work, checked 10:42 UTC\\\"). Never answer these from memory, notes or earlier messages: they go stale within hours.\"\n"],"mappings":"AAuBA,IAAMA,EAAS,0HACTC,EAAU,IAAI,OAAO,sEAAsED,sFAA4F,GAAG,EAE1LE,EAAuB,CAE3B,2EACA,2DAEA,mHACA,qEAEA,uBACA,uEACA,qCACF,EAGMC,EAAkB,CACtB,sDACA,8CACF,EAGO,SAASC,EAAWC,EAAuB,CAChD,OAAOA,EAAK,MAAM;AAAA,CAAI,EAAE,KAAMC,GAC5BH,EAAM,KAAMI,GAAOA,EAAG,KAAKD,CAAI,CAAC,GAAML,EAAQ,KAAKK,CAAI,GAAKJ,EAAW,KAAMK,GAAOA,EAAG,KAAKD,CAAI,CAAC,CAAE,CACvG,CAGO,IAAME,EAAsB,mDAGtBC,EACX","names":["WINDOW","SUBJECT","LIVE_STATE","HOLDS","isNodeFact","text","line","re","NODE_FACT_STALE_TAG","NODE_FACTS_RULE"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as g}from"./chunk-
|
|
1
|
+
import{e as g}from"./chunk-RQKLUGMS.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
|
|
2
2
|
`)}).join(`
|
|
3
3
|
|
|
4
4
|
---
|
|
@@ -14,4 +14,4 @@ These ${e.length} articles were found by searching the wiki for each entry below
|
|
|
14
14
|
|
|
15
15
|
${i}
|
|
16
16
|
`}var d=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,y=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,w=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,k=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,C=/^\s*\d+[.)]\s/gm;function A(e){let i=[...e.matchAll(d)].map(s=>s[0].replace(/[.,;:!?'"]+$/,"")),r=[...e.matchAll(y)].map(s=>s[1].trim()),n=e.replace(d," ").replace(y," ").replace(C," "),o=[...n.matchAll(w)].map(s=>s[0].toLowerCase()),c=[...n.replace(w," ").matchAll(k)].map(s=>v(s[0]));return{commits:m(o),urls:m(i),wikilinks:m(r),numbers:m(c)}}function R(e,i){let r=A(e),n=A(i),o=i.toLowerCase(),a=[];for(let t of r.commits)!o.includes(t)&&!n.commits.some(l=>l.startsWith(t)||t.startsWith(l))&&a.push(`commit ${t}`);let c=t=>t.toLowerCase().replace(/\/+$/,""),s=new Set(n.urls.map(c));for(let t of r.urls)s.has(c(t))||a.push(`link ${t}`);let f=new Set(n.wikilinks.map(t=>t.toLowerCase()));for(let t of r.wikilinks)f.has(t.toLowerCase())||a.push(`link [[${t}]]`);let h=new Set(n.numbers);for(let t of r.numbers)h.has(t)||a.push(`number ${t}`);return a}function v(e){return/^\d{1,3}(,\d{3})+$/.test(e)?e.replace(/,/g,""):e}function m(e){return[...new Set(e)]}function L(e,i){if(i.some(n=>n.path===e.path))return e.path;let r=b(e.title);return r?i.find(n=>b(n.title)===r)?.path??e.path:e.path}function b(e){return(e||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}export{$ as a,x as b,A as c,R as d,L as e};
|
|
17
|
-
//# sourceMappingURL=chunk-
|
|
17
|
+
//# sourceMappingURL=chunk-AS4NDKUJ.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-SOVWD6TL.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-DCIYOPJF.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}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)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{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 I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(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 t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.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(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.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 i=t.levels.findIndex(s=>s.id===e.level);if(i===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=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)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,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.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),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
1
|
+
import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-3NMBTBNW.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-DCIYOPJF.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}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)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{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 I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(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 t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.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(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.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 i=t.levels.findIndex(s=>s.id===e.level);if(i===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=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)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,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.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),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
2
2
|
`,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
|
|
3
3
|
`).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
|
|
4
4
|
`).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}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 X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(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)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(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 q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=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=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.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,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),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:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).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 i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["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(t,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
5
|
`),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.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)??te(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 u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.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:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(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 H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-BWBTNBPS.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Gb as m,xb as l}from"./chunk-
|
|
1
|
+
import{Gb as m,xb as l}from"./chunk-ZCBTTYQN.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
|
|
2
2
|
`,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
|
|
3
3
|
`,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-CKHLBNMN.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-
|
|
1
|
+
import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-BWBTNBPS.js";import{y as C,z as K}from"./chunk-3NMBTBNW.js";import{c as _,d as x}from"./chunk-AHWWJ7AF.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
|
|
2
2
|
`)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
|
|
3
3
|
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
|
|
4
4
|
`));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
|
|
@@ -102,4 +102,4 @@ We use GitLab for version control.
|
|
|
102
102
|
There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
103
103
|
|
|
104
104
|
${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
|
|
105
|
-
//# sourceMappingURL=chunk-
|
|
105
|
+
//# sourceMappingURL=chunk-FRTU3ICQ.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{B as N,D as k,F as O,I,s as R,v as x}from"./chunk-
|
|
1
|
+
import{B as N,D as k,F as O,I,s as R,v as x}from"./chunk-XJEBJZLX.js";import{a as E}from"./chunk-OSH2PEBH.js";import{Gb as F,xb as j}from"./chunk-ZCBTTYQN.js";F();import{Command as X}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as W,constants as M,existsSync as w,readFileSync as b,readdirSync as C,statSync as B}from"fs";import{join as H,resolve as y}from"path";import{homedir as z}from"os";import{createRequire as G}from"module";var T="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){let n=t.helper===void 0?N():t.helper,e=k({},{platform:t.platform,io:{capture:t.run,helper:n}}).banner;if(!e)return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let i=await e.status();return i==="missing"?{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'}:i==="outdated"?{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}:i==="not-asked"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i==="not-allowed"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:T}:i==="hidden"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:T}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}}async function Z(t={}){let n=[];await Q(n),Y(n);let e=ee(n);return e&&te(n,e),e&&se(n,e),e&&re(n,e),e&&ae(n,e),e&&ie(n,e),e&&ce(n,e),e&&await J(n,e),e&&U(n,e),e&&await K(n,e),e&&V(n,e),t.running!==!1&&e&&await de(n,e),{checks:n,summary:D(n)}}var Ne=new X().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await Z({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
|
|
2
2
|
`):ue(n),process.exit(e.errors>0?1:0)});async function J(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}async function K(t,n,e){let i;try{i=await(e??k(n)).describe()}catch(s){t.push({severity:"warn",group:"Native",title:"Native apps: could not be read",detail:s?.message??String(s)});return}let o=["tasks","notes","banner","sound","focus"].filter(s=>i[s]);t.push({severity:"ok",group:"Native",title:i.os==="none"?"Native apps: none on this machine":`Native apps (${i.os}): ${o.join(", ")||"nothing available"}`,detail:i.problems.join(" ")||void 0})}function V(t,n,e=process.cwd(),i=k(n)){let o=n.native?.mirror;if(!o?.enabled)return;if(!i.tasks){t.push({severity:"warn",group:"Native",title:"Reminders mirror is on, but this machine has no task app",detail:"native.mirror.enabled is set; nothing is mirrored here.",fix:"Turn it on on the machine that holds the owner's cards (the Mac), or set native.mirror.enabled to false here."});return}let s=I(e),a=Object.values(s.items),l=a.filter(g=>g.state==="open").length,u=a.filter(g=>g.state==="failed").length;t.push({severity:s.lastError||u?"warn":"ok",group:"Native",title:`Reminders mirror: ${l} open in "${o.list}"${u?`, ${u} could not be added`:""}`,detail:s.lastError?`Last error ${s.lastError.at}: ${s.lastError.message}`:void 0,fix:s.lastError?"Run remindctl status, and allow Reminders for the app that runs the daemon in System Settings \u203A Privacy & Security \u203A Reminders.":void 0})}function U(t,n,e=process.platform,i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}}){let o=n.reminders;if(!o?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let s=o.command||"remindctl",a=s.includes("/")?i(s)?s:null:x(s,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(o.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${s} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Q(t){let n=E(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return m(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
|
|
3
3
|
`)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let o=e("claude");if(o){let l;try{l=m("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:o})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let s=e("codex");if(s){let l;try{l=m("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=m("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{G(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function Y(t){if(process.platform!=="darwin")return;let n=H(z(),"Library/LaunchAgents"),e=[];try{e=C(n).filter(o=>/agentx\.voice.*\.plist$/.test(o))}catch{return}let i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}};for(let o of e){let s=R(b(H(n,o),"utf-8")),a=x("ffmpeg",s,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${o})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${o} sets PATH to ${s}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function ee(t){let n=y(process.cwd(),"agentx.json");if(!w(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{j(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let o=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");o.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:o.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return s.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function te(t,n){let e=new Set;if(A(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=_(),o=[],s=[];for(let a of e){let l=process.env[a]??i[a];l===void 0?o.push(a):(!l.trim()||/^["']?\s*["']?$/.test(l))&&s.push(a)}o.length===0&&s.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(o.length>0&&t.push({severity:"fail",group:"Secrets",title:`${o.length} env var(s) referenced in agentx.json but missing`,detail:o.join(", "),fix:`Add to .env \u2014 e.g. ${o[0]}=<value>`}),s.length>0&&t.push({severity:"warn",group:"Secrets",title:`${s.length} env var(s) set but empty`,detail:s.join(", ")}))}function _(){let t=y(process.cwd(),".env"),n={};if(w(t))for(let e of b(t,"utf-8").split(/\r?\n/)){let i=e.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);i&&(n[i[1]]=i[2])}return n}function ne(t,n){let e="With a shared token this node cannot tell which peer is calling. For example, closing an approval card forwarded from that peer is refused, and its stop/resume signals are judged as the owner's.",i="Give this pair a token of its own: set the same new value as mesh.peers[].token here and on the peer.",o=[];for(let s of t){let a=(s.token??"").trim();a?n&&a===n&&o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" uses this node's own MESH_TOKEN`,detail:e,fix:i}):o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" has no token; calls to it use the shared MESH_TOKEN`,detail:e,fix:i})}return t.length>0&&o.length===0&&o.push({severity:"ok",group:"Mesh",title:`${t.length} mesh peer(s), each with a token of its own`}),o}function ie(t,n){t.push(...oe(n))}function oe(t,n=process.env,e=_()){let i=a=>(n[a]||e[a]||"").trim(),o=a=>typeof a=="string"?a.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(l,u)=>i(u)):void 0,s=(t.mesh?.peers??[]).filter(a=>typeof a?.name=="string").map(a=>({name:a.name,token:o(a.token)}));return ne(s,i("MESH_TOKEN")||void 0)}function A(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)A(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))A(e,n)}function se(t,n){let e=[];for(let[i,o]of Object.entries(n.agents||{})){if(!o.workspace)continue;let s=o.workspace.startsWith("/")?o.workspace:y(process.cwd(),o.workspace);try{B(s).isDirectory()||e.push(`${i}: ${s} (exists but not a directory)`)}catch{e.push(`${i}: ${s}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
4
4
|
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function re(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[o,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let a=s.workspace.startsWith("/")?s.workspace:y(process.cwd(),s.workspace);for(let l of["settings.json","settings.local.json"]){let u=y(a,".claude",l);if(!w(u))continue;let g;try{g=JSON.parse(b(u,"utf-8"))}catch(c){i.push({severity:"fail",agent:o,msg:`${l}: JSON parse error \u2014 ${c.message}`});continue}let $=g.env||{};for(let[c,h]of Object.entries($)){if(typeof h!="string")continue;let p=h.match(e);p&&i.push({severity:"fail",agent:o,msg:`${l} env.${c} contains unexpanded ${[...new Set(p)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let r=$.PATH;if(typeof r=="string"){let c=r.split(":").filter(Boolean);c.includes("/usr/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),c.includes("/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let d=g.permissions;if(d&&typeof d=="object"&&"allow"in d){let c=d.allow,h=d.deny;Array.isArray(c)&&c.length===0&&Array.isArray(h)&&h.length>0&&i.push({severity:"warn",agent:o,msg:`${l} permissions.allow is explicitly [] with ${h.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let o of i)t.push({severity:o.severity,group:"Workspace settings",title:`${o.agent}: ${o.msg}`,fix:o.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function ae(t,n){let e=n.webhooks??[],i=[],o=y(process.cwd(),n.workflows?.dir||".agentx/workflows"),s=new Set;try{if(w(o))for(let r of C(o))r.endsWith(".json")&&!r.startsWith("_")&&!r.endsWith(".disabled.json")&&s.add(r.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let r of e){if(!r.enabled||!a.has(r.source))continue;!(r.triggers&&Object.keys(r.triggers).length>0)&&!r.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${r.id}" (${r.source} -> ${r.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let r of e)if(!(!r.enabled||!r.triggers)){for(let[d,c]of Object.entries(r.triggers))s.size>0&&!s.has(c)&&i.push({severity:"fail",title:`webhook "${r.id}".triggers["${d}"] -> "${c}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});r.defaultWorkflow&&s.size>0&&!s.has(r.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${r.id}".defaultWorkflow -> "${r.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(w(o)){for(let r of C(o))if(!(!r.endsWith(".json")||r.startsWith("_")||r.endsWith(".disabled.json")))try{let d=JSON.parse(b(y(o,r),"utf-8"));d?.status==="active"&&d?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${d.id??r}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(r=>r.name));for(let r of e)!r.enabled||!r.node||l.has(r.node)||i.push({severity:"fail",title:`webhook "${r.id}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let r of e){if(!r.enabled)continue;let d=`${r.source}:${r.agentId}`,c=u.get(d);c?i.push({severity:"warn",title:`webhook entries "${c}" and "${r.id}" both enabled for ${r.source} -> ${r.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(d,r.id)}let g=new Set(Object.keys(n.agents??{}));for(let r of n.channels?.gitlab?.agentMappings??[])if(r?.agentId){if(r.node){l.has(r.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${r.agentId}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}g.has(r.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${r.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[r,d]of Object.entries(n.channels?.telegram?.accounts??{}))d.agentBinding?g.has(d.agentBinding)||i.push({severity:"fail",title:`telegram account "${r}".agentBinding -> "${d.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${r}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let $=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[r,d]of Object.entries(n.agents??{})){let c=d.integrations??[];if(!c.length)continue;let h=new Set;for(let p of c){let S=`${p.kind}::${p.label}`;h.has(S)&&i.push({severity:"warn",title:`agents.${r}.integrations: duplicate (${p.kind}, ${p.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),h.add(S),$.has(p.kind)||i.push({severity:"warn",title:`agents.${r}.integrations: unknown kind "${p.kind}" on integration "${p.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let L=p.credentials||{};for(let[q,v]of Object.entries(L))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${r}.integrations[${p.kind}/${p.label}].${q} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let r of i)t.push({severity:r.severity,group:"Routing",title:r.title,fix:r.fix})}function le(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function de(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let o=new AbortController,s=setTimeout(()=>o.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:o.signal});if(clearTimeout(s),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=le(l.voice);u&&t.push(u)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function ce(t,n){let e=Object.entries(n.agents||{}).filter(([,o])=>o?.codegraph===!0&&(o.tier==="claude-code"||o.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=m(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
5
|
`)[0]||null}catch{i=null}if(i){let o;try{o=m("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${o||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[o,s]of e){if(!s.workspace||!w(s.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${o}: workspace missing`,detail:`Workspace path ${s.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=y(s.workspace,".codegraph","codegraph.db");w(a)?t.push({severity:"ok",group:"CodeGraph",title:`${o}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${o}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${s.workspace}\` to build it now.`})}}function D(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function ue(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,o]of n){console.log(f.bold(" "+i));for(let s of o){let a=s.severity==="ok"?f.green("\u2713"):s.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${s.title}`),s.detail&&console.log(f.dim(" "+s.detail.replace(/\n/g,`
|
|
6
6
|
`))),s.fix&&console.log(f.dim(" \u2192 "+s.fix))}console.log()}let e=D(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{P as a,Z as b,Ne as c,J as d,K as e,V as f,U as g,ne as h,oe as i,le as j};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-IGLJXEXX.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as d}from"./chunk-A7JSRDJL.js";var u={billing:2,account:2,outage:2,deploy:2,"work-state":2,stable:null};var g=Object.keys(u);function b(e){return typeof e=="string"&&g.includes(e)}var s=e=>new RegExp(e.map(t=>`\\b(?:${t})\\b`).join("|"),"i"),a="is|are|was|were|has been|have been|got|gets|went|goes|go|stays?|still|seems?|now|keeps?",f=[["billing",s(["past[- ]due","overdue","unpaid","outstanding (?:invoice|balance|payment|bill)s?","invoices? (?:is |are |was |were )?(?:due|unpaid|paid|outstanding|overdue)","payments? (?:has |have )?(?:failed|declined|bounced|due|pending|overdue|received)","(?:credit|account|remaining|wallet|prepaid) balance","balance (?:is|was|of) [$\u20AC\xA3]?\\d","credits? (?:left|remaining|exhausted|used up|ran out|run out)","out of credits?","refund(?:ed)?","subscription (?:is |was |has )?(?:active|cancell?ed|expired|lapsed|paused|renew\\w*)","(?:free )?trial (?:ends|ended|expires|expired|period)","on (?:a |the )?(?:free )?trial","billing (?:issue|problem|error|failed|failure|blocked|hold)","(?:plan|tier) (?:was |is |got )?(?:downgraded|upgraded|cancell?ed)","quota (?:is |was )?(?:exceeded|reached|hit|exhausted)","rate[- ]limited"])],["account",s(["(?:account|api key|key|token|license|licence|certificate|cert|domain|seat)s? (?:is |are |was |were |has been |got )?(?:suspended|deactivated|disabled|locked|banned|revoked|expired|inactive|active|closed|frozen|restricted|blocked)","suspended","deactivated","locked out","banned","revoked","expired","expir(?:es|ing) (?:on|in|at|soon)",`(?:${a}) blocked`,"blocked (?:by|on|until|since)","(?:not |un)authori[sz]ed","credentials? (?:expired|invalid|rejected)"])],["outage",s(["outage",`(?:${a}) (?:down|offline)`,"down (?:since|for|again)","offline","unreachable","not (?:responding|reachable|working)",`(?:${a}) (?:broken|failing|crashing|erroring)`,"degraded","5\\d\\d (?:errors?|responses?)",`(?:${a}) (?:back )?(?:up|online|healthy|operational|reachable)`,"(?:up|online|healthy|operational|active) (?:again )?(?:per|via|according to)"])],["deploy",s(["(?:re)?deployed","deploy(?:ment)? (?:failed|succeeded|pending|in progress|rolled back|is (?:done|running|stuck|pending|live))","(?:is|are|now|went|goes) live","live on","rolled (?:out|back)","(?:currently|now) running (?:v|version)","in prod(?:uction)? (?:now|since)"])]];function l(e){for(let[t,n]of f)if(n.test(e))return t;return"stable"}var v=/\b(?:path|target|url|host|owner|name|email|phone|handle|id|role|decision|decided|policy)\b/i,y=[["billing",/\b(?:billing|payment|invoice|plan|subscription|credits?|balance|quota)\b/i],["account",/\b(?:account|access|licen[cs]e|key|token)\b/i],["outage",/\b(?:status|uptime|health|outage|availability)\b/i],["deploy",/\b(?:deploy(?:ment)?|version|release)\b/i]];function A(e,t=""){let n=l(t);if(n!=="stable")return n;if(v.test(e))return"stable";for(let[i,o]of y)if(o.test(e))return i;return"stable"}function h(e){return typeof e.ttlDays=="number"&&e.ttlDays>=0?e.ttlDays:u[e.volatility]}function p(e,t=Date.now()){let n=Date.parse(e??"");return Number.isFinite(n)?Math.max(0,Math.floor((t-n)/864e5)):null}function w(e,t=Date.now()){let n=h(e);if(n===null)return!1;let i=p(e.verifiedAt,t);return i===null||i>=n}function m(e){return b(e.provenance?.volatility)?e.provenance.volatility:e.source.sender==="system:rotation"?"work-state":l(e.content)}function C(e,t=Date.now()){return p(e.provenance?.verifiedAt??e.createdAt,t)}function T(e,t=Date.now()){return e.unverified?!0:w({volatility:m(e),ttlDays:e.provenance?.ttlDays,verifiedAt:e.provenance?.verifiedAt??e.createdAt},t)}var D="[These are notes, not checked facts. Before you state one marked UNVERIFIED to a person or act on it, re-check it against its source (API, CLI, dashboard) and record it with `agentx wiki facts set --checked-at now`. If you can't, say it is unverified and ask the owner.]";function S(e){let t=[],n=[],i=[];for(let o of e.split(`
|
|
2
|
+
`)){let r=o.trim();if(!r)continue;let c=r.replace(/^[-*•]\s*/,"");if(d(c)){i.push(r);continue}(l(c)!=="stable"||k(c)!==null?n:t).push(r)}return{workState:t,claims:n,nodeFacts:i}}function k(e){let t=e.match(/\b(?:per|via|according to|checked (?:with|via|using))\s+([^,;()]+?)(?:,\s*(\d{4}-\d{2}-\d{2}))?\s*(?:[;)]|$)/i);return t?{source:t[1].trim(),...t[2]?{verifiedAt:`${t[2]}T00:00:00.000Z`}:{}}:null}export{g as a,b,l as c,A as d,p as e,w as f,C as g,T as h,D as i,S as j,k};
|
|
3
|
+
//# sourceMappingURL=chunk-JRAG37V5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/fact-freshness.ts"],"sourcesContent":["import { isNodeFact } from \"./node-facts\"\n\n// --- Fact freshness: verify-or-ask (#273) ---\n//\n// The one rule every agent follows about stated facts. A stored fact is a\n// note of what was true when it was checked, not ground truth. Each fact\n// has a volatility class: account, billing, outage and deploy state change\n// on their own and expire after a TTL; names, decisions and paths are\n// stable. Past its TTL, an agent re-checks a fact against its source, or\n// says it is unverified and asks the owner.\n//\n// The class replaces slice 1's single keyword regex, which flagged lasting\n// notes (\"deploy path is …\", \"wrote it down\"). The patterns below match\n// statements of *state* (\"is past due\", \"went down\", \"deployed to\"), not\n// topics. A fact that carries provenance uses its own class and date.\n\nexport type FactClass = \"billing\" | \"account\" | \"outage\" | \"deploy\" | \"work-state\" | \"stable\"\n\n/** Days a fact of each class is trusted without a re-check; null = no expiry. */\nexport const FACT_TTL_DAYS: Record<FactClass, number | null> = {\n billing: 2, account: 2, outage: 2, deploy: 2, \"work-state\": 2, stable: null,\n}\n\n/** Kept for callers of slice 1. */\nexport const VOLATILE_TTL_DAYS = 2\n\nexport const FACT_CLASSES = Object.keys(FACT_TTL_DAYS) as FactClass[]\n\nexport function isFactClass(s: unknown): s is FactClass {\n return typeof s === \"string\" && (FACT_CLASSES as string[]).includes(s)\n}\n\n/** Where a fact came from and when it was last checked. */\nexport interface Provenance {\n /** A system, URL or command, or \"owner said\". */\n source: string\n verifiedAt: string\n /** The agent or person who checked it. */\n verifiedBy: string\n volatility: FactClass\n /** Overrides the class TTL. */\n ttlDays?: number\n}\n\nconst words = (list: string[]) => new RegExp(list.map((w) => `\\\\b(?:${w})\\\\b`).join(\"|\"), \"i\")\n\nconst STATE = \"is|are|was|were|has been|have been|got|gets|went|goes|go|stays?|still|seems?|now|keeps?\"\n\nconst PATTERNS: Array<[FactClass, RegExp]> = [\n [\"billing\", words([\n \"past[- ]due\", \"overdue\", \"unpaid\", \"outstanding (?:invoice|balance|payment|bill)s?\",\n \"invoices? (?:is |are |was |were )?(?:due|unpaid|paid|outstanding|overdue)\",\n \"payments? (?:has |have )?(?:failed|declined|bounced|due|pending|overdue|received)\",\n \"(?:credit|account|remaining|wallet|prepaid) balance\", \"balance (?:is|was|of) [$€£]?\\\\d\",\n \"credits? (?:left|remaining|exhausted|used up|ran out|run out)\", \"out of credits?\", \"refund(?:ed)?\",\n \"subscription (?:is |was |has )?(?:active|cancell?ed|expired|lapsed|paused|renew\\\\w*)\",\n \"(?:free )?trial (?:ends|ended|expires|expired|period)\", \"on (?:a |the )?(?:free )?trial\",\n \"billing (?:issue|problem|error|failed|failure|blocked|hold)\",\n \"(?:plan|tier) (?:was |is |got )?(?:downgraded|upgraded|cancell?ed)\",\n \"quota (?:is |was )?(?:exceeded|reached|hit|exhausted)\", \"rate[- ]limited\",\n ])],\n [\"account\", words([\n \"(?:account|api key|key|token|license|licence|certificate|cert|domain|seat)s? \" +\n \"(?:is |are |was |were |has been |got )?(?:suspended|deactivated|disabled|locked|banned|revoked|expired|inactive|active|closed|frozen|restricted|blocked)\",\n \"suspended\", \"deactivated\", \"locked out\", \"banned\", \"revoked\",\n \"expired\", \"expir(?:es|ing) (?:on|in|at|soon)\",\n `(?:${STATE}) blocked`, \"blocked (?:by|on|until|since)\",\n \"(?:not |un)authori[sz]ed\", \"credentials? (?:expired|invalid|rejected)\",\n ])],\n [\"outage\", words([\n \"outage\", `(?:${STATE}) (?:down|offline)`, \"down (?:since|for|again)\", \"offline\", \"unreachable\",\n \"not (?:responding|reachable|working)\", `(?:${STATE}) (?:broken|failing|crashing|erroring)`,\n \"degraded\", \"5\\\\d\\\\d (?:errors?|responses?)\",\n `(?:${STATE}) (?:back )?(?:up|online|healthy|operational|reachable)`,\n \"(?:up|online|healthy|operational|active) (?:again )?(?:per|via|according to)\",\n ])],\n [\"deploy\", words([\n \"(?:re)?deployed\", \"deploy(?:ment)? (?:failed|succeeded|pending|in progress|rolled back|is (?:done|running|stuck|pending|live))\",\n \"(?:is|are|now|went|goes) live\", \"live on\", \"rolled (?:out|back)\",\n \"(?:currently|now) running (?:v|version)\", \"in prod(?:uction)? (?:now|since)\",\n ])],\n]\n\n/** The class a statement's wording implies. Statements of state, not topics. */\nexport function classifyFact(text: string): FactClass {\n for (const [cls, re] of PATTERNS) if (re.test(text)) return cls\n return \"stable\"\n}\n\nconst STABLE_ATTR = /\\b(?:path|target|url|host|owner|name|email|phone|handle|id|role|decision|decided|policy)\\b/i\nconst ATTR_CLASS: Array<[FactClass, RegExp]> = [\n [\"billing\", /\\b(?:billing|payment|invoice|plan|subscription|credits?|balance|quota)\\b/i],\n [\"account\", /\\b(?:account|access|licen[cs]e|key|token)\\b/i],\n [\"outage\", /\\b(?:status|uptime|health|outage|availability)\\b/i],\n [\"deploy\", /\\b(?:deploy(?:ment)?|version|release)\\b/i],\n]\n\n/** Class for a structured fact: its wording first, then what it is about. */\nexport function classifyAttribute(attribute: string, statement = \"\"): FactClass {\n const worded = classifyFact(statement)\n if (worded !== \"stable\") return worded\n if (STABLE_ATTR.test(attribute)) return \"stable\"\n for (const [cls, re] of ATTR_CLASS) if (re.test(attribute)) return cls\n return \"stable\"\n}\n\nexport function ttlOf(p: { volatility: FactClass; ttlDays?: number }): number | null {\n return typeof p.ttlDays === \"number\" && p.ttlDays >= 0 ? p.ttlDays : FACT_TTL_DAYS[p.volatility]\n}\n\n/** Whole days since `iso`; null when unreadable. */\nexport function daysSince(iso: string | undefined, now = Date.now()): number | null {\n const t = Date.parse(iso ?? \"\")\n return Number.isFinite(t) ? Math.max(0, Math.floor((now - t) / 86_400_000)) : null\n}\n\n/** A checked fact past its TTL, or one whose check date is unreadable. */\nexport function isPastTtl(p: { volatility: FactClass; ttlDays?: number; verifiedAt?: string }, now = Date.now()): boolean {\n const ttl = ttlOf(p)\n if (ttl === null) return false\n const age = daysSince(p.verifiedAt, now)\n return age === null || age >= ttl\n}\n\n// --- Memory-shaped facts ---\n\nexport interface FreshnessFields {\n content: string\n createdAt: string\n source: { sender: string }\n provenance?: Partial<Provenance>\n /** Set by the one-off migration: stated with no source. */\n unverified?: { since: string; reason: string }\n}\n\n/** Session summaries are work state whatever they say. */\nexport function factClassOf(f: FreshnessFields): FactClass {\n if (isFactClass(f.provenance?.volatility)) return f.provenance!.volatility!\n if (f.source.sender === \"system:rotation\") return \"work-state\"\n return classifyFact(f.content)\n}\n\nexport function isVolatile(f: FreshnessFields): boolean {\n return factClassOf(f) !== \"stable\"\n}\n\n/** Days since the fact was last checked (or written, when never checked). */\nexport function ageDays(f: FreshnessFields, now = Date.now()): number | null {\n return daysSince(f.provenance?.verifiedAt ?? f.createdAt, now)\n}\n\nexport function needsRecheck(f: FreshnessFields, now = Date.now()): boolean {\n if (f.unverified) return true\n return isPastTtl({\n volatility: factClassOf(f),\n ttlDays: f.provenance?.ttlDays,\n verifiedAt: f.provenance?.verifiedAt ?? f.createdAt,\n }, now)\n}\n\n/** The rule injected with every memory block that holds a flagged line. */\nexport const VERIFY_OR_ASK_RULE =\n \"[These are notes, not checked facts. Before you state one marked UNVERIFIED to a person or act on it, \" +\n \"re-check it against its source (API, CLI, dashboard) and record it with `agentx wiki facts set --checked-at now`. \" +\n \"If you can't, say it is unverified and ask the owner.]\"\n\n// --- Session summaries ---\n\n/**\n * Split a rotation or continuity memo into work state (what the session\n * was doing) and claims about outside systems. Claims leave the memo for\n * the wiki's proposal queue; only work state is kept as memory.\n */\nexport function splitMemo(memo: string): { workState: string[]; claims: string[]; nodeFacts: string[] } {\n const workState: string[] = []\n const claims: string[] = []\n // Usage limits, resets and holds: the node reports them live (#1531),\n // so they are neither kept nor proposed to the wiki.\n const nodeFacts: string[] = []\n for (const raw of memo.split(\"\\n\")) {\n const line = raw.trim()\n if (!line) continue\n const text = line.replace(/^[-*•]\\s*/, \"\")\n if (isNodeFact(text)) { nodeFacts.push(line); continue }\n // A line citing a check is a claim about an outside system: the memo\n // prompt only lets a summary cite checks for those.\n const claim = classifyFact(text) !== \"stable\" || citedCheck(text) !== null\n ;(claim ? claims : workState).push(line)\n }\n return { workState, claims, nodeFacts }\n}\n\n/** The check a memo line cites, e.g. \"active per GET /v1/user, 2026-09-28\". */\nexport function citedCheck(line: string): { source: string; verifiedAt?: string } | null {\n const m = line.match(/\\b(?:per|via|according to|checked (?:with|via|using))\\s+([^,;()]+?)(?:,\\s*(\\d{4}-\\d{2}-\\d{2}))?\\s*(?:[;)]|$)/i)\n if (!m) return null\n return { source: m[1].trim(), ...(m[2] ? { verifiedAt: `${m[2]}T00:00:00.000Z` } : {}) }\n}\n"],"mappings":"wCAmBO,IAAMA,EAAkD,CAC7D,QAAS,EAAG,QAAS,EAAG,OAAQ,EAAG,OAAQ,EAAG,aAAc,EAAG,OAAQ,IACzE,EAKO,IAAMC,EAAe,OAAO,KAAKC,CAAa,EAE9C,SAASC,EAAYC,EAA4B,CACtD,OAAO,OAAOA,GAAM,UAAaH,EAA0B,SAASG,CAAC,CACvE,CAcA,IAAMC,EAASC,GAAmB,IAAI,OAAOA,EAAK,IAAKC,GAAM,SAASA,OAAO,EAAE,KAAK,GAAG,EAAG,GAAG,EAEvFC,EAAQ,0FAERC,EAAuC,CAC3C,CAAC,UAAWJ,EAAM,CAChB,cAAe,UAAW,SAAU,iDACpC,4EACA,oFACA,sDAAuD,0CACvD,gEAAiE,kBAAmB,gBACpF,uFACA,wDAAyD,iCACzD,8DACA,qEACA,wDAAyD,iBAC3D,CAAC,CAAC,EACF,CAAC,UAAWA,EAAM,CAChB,wOAEA,YAAa,cAAe,aAAc,SAAU,UACpD,UAAW,oCACX,MAAMG,aAAkB,gCACxB,2BAA4B,2CAC9B,CAAC,CAAC,EACF,CAAC,SAAUH,EAAM,CACf,SAAU,MAAMG,sBAA2B,2BAA4B,UAAW,cAClF,uCAAwC,MAAMA,0CAC9C,WAAY,iCACZ,MAAMA,2DACN,8EACF,CAAC,CAAC,EACF,CAAC,SAAUH,EAAM,CACf,kBAAmB,8GACnB,gCAAiC,UAAW,sBAC5C,0CAA2C,kCAC7C,CAAC,CAAC,CACJ,EAGO,SAASK,EAAaC,EAAyB,CACpD,OAAW,CAACC,EAAKC,CAAE,IAAKJ,EAAU,GAAII,EAAG,KAAKF,CAAI,EAAG,OAAOC,EAC5D,MAAO,QACT,CAEA,IAAME,EAAc,8FACdC,EAAyC,CAC7C,CAAC,UAAW,2EAA2E,EACvF,CAAC,UAAW,8CAA8C,EAC1D,CAAC,SAAU,mDAAmD,EAC9D,CAAC,SAAU,0CAA0C,CACvD,EAGO,SAASC,EAAkBC,EAAmBC,EAAY,GAAe,CAC9E,IAAMC,EAAST,EAAaQ,CAAS,EACrC,GAAIC,IAAW,SAAU,OAAOA,EAChC,GAAIL,EAAY,KAAKG,CAAS,EAAG,MAAO,SACxC,OAAW,CAACL,EAAKC,CAAE,IAAKE,EAAY,GAAIF,EAAG,KAAKI,CAAS,EAAG,OAAOL,EACnE,MAAO,QACT,CAEO,SAASQ,EAAMC,EAA+D,CACnF,OAAO,OAAOA,EAAE,SAAY,UAAYA,EAAE,SAAW,EAAIA,EAAE,QAAUnB,EAAcmB,EAAE,UAAU,CACjG,CAGO,SAASC,EAAUC,EAAyBC,EAAM,KAAK,IAAI,EAAkB,CAClF,IAAMC,EAAI,KAAK,MAAMF,GAAO,EAAE,EAC9B,OAAO,OAAO,SAASE,CAAC,EAAI,KAAK,IAAI,EAAG,KAAK,OAAOD,EAAMC,GAAK,KAAU,CAAC,EAAI,IAChF,CAGO,SAASC,EAAUL,EAAqEG,EAAM,KAAK,IAAI,EAAY,CACxH,IAAMG,EAAMP,EAAMC,CAAC,EACnB,GAAIM,IAAQ,KAAM,MAAO,GACzB,IAAMC,EAAMN,EAAUD,EAAE,WAAYG,CAAG,EACvC,OAAOI,IAAQ,MAAQA,GAAOD,CAChC,CAcO,SAASE,EAAYC,EAA+B,CACzD,OAAI3B,EAAY2B,EAAE,YAAY,UAAU,EAAUA,EAAE,WAAY,WAC5DA,EAAE,OAAO,SAAW,kBAA0B,aAC3CpB,EAAaoB,EAAE,OAAO,CAC/B,CAOO,SAASC,EAAQC,EAAoBC,EAAM,KAAK,IAAI,EAAkB,CAC3E,OAAOC,EAAUF,EAAE,YAAY,YAAcA,EAAE,UAAWC,CAAG,CAC/D,CAEO,SAASE,EAAaH,EAAoBC,EAAM,KAAK,IAAI,EAAY,CAC1E,OAAID,EAAE,WAAmB,GAClBI,EAAU,CACf,WAAYC,EAAYL,CAAC,EACzB,QAASA,EAAE,YAAY,QACvB,WAAYA,EAAE,YAAY,YAAcA,EAAE,SAC5C,EAAGC,CAAG,CACR,CAGO,IAAMK,EACX,iRAWK,SAASC,EAAUC,EAA8E,CACtG,IAAMC,EAAsB,CAAC,EACvBC,EAAmB,CAAC,EAGpBC,EAAsB,CAAC,EAC7B,QAAWC,KAAOJ,EAAK,MAAM;AAAA,CAAI,EAAG,CAClC,IAAMK,EAAOD,EAAI,KAAK,EACtB,GAAI,CAACC,EAAM,SACX,IAAMC,EAAOD,EAAK,QAAQ,YAAa,EAAE,EACzC,GAAIE,EAAWD,CAAI,EAAG,CAAEH,EAAU,KAAKE,CAAI,EAAG,UAGhCG,EAAaF,CAAI,IAAM,UAAYG,EAAWH,CAAI,IAAM,KAC5DJ,EAASD,GAAW,KAAKI,CAAI,EAEzC,MAAO,CAAE,UAAAJ,EAAW,OAAAC,EAAQ,UAAAC,CAAU,CACxC,CAGO,SAASM,EAAWJ,EAA8D,CACvF,IAAMK,EAAIL,EAAK,MAAM,+GAA+G,EACpI,OAAKK,EACE,CAAE,OAAQA,EAAE,CAAC,EAAE,KAAK,EAAG,GAAIA,EAAE,CAAC,EAAI,CAAE,WAAY,GAAGA,EAAE,CAAC,iBAAkB,EAAI,CAAC,CAAG,EADxE,IAEjB","names":["FACT_TTL_DAYS","FACT_CLASSES","FACT_TTL_DAYS","isFactClass","s","words","list","w","STATE","PATTERNS","classifyFact","text","cls","re","STABLE_ATTR","ATTR_CLASS","classifyAttribute","attribute","statement","worded","ttlOf","p","daysSince","iso","now","t","isPastTtl","ttl","age","factClassOf","f","ageDays","f","now","daysSince","needsRecheck","isPastTtl","factClassOf","VERIFY_OR_ASK_RULE","splitMemo","memo","workState","claims","nodeFacts","raw","line","text","isNodeFact","classifyFact","citedCheck","m"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Gb as $,fb as y}from"./chunk-
|
|
1
|
+
import{Gb as $,fb as y}from"./chunk-ZCBTTYQN.js";import{randomBytes as x}from"crypto";import{existsSync as b,mkdirSync as k,readdirSync as M,readFileSync as j,renameSync as E,unlinkSync as S,writeFileSync as C}from"fs";import{resolve as u}from"path";function f(t){return u(t,".agentx","email")}function d(t,e){k(u(t,".."),{recursive:!0});let r=`${t}.${process.pid}.tmp`;C(r,JSON.stringify(e,null,2)+`
|
|
2
2
|
`,{mode:384}),E(r,t)}function g(t){try{return JSON.parse(j(t,"utf-8"))}catch{return null}}var D=t=>u(f(t),"threads.json");function w(t){return g(D(t))??{}}function F(t,e){return w(t)[e.toLowerCase()]}function I(t,e){let r=w(t);r[e.to.toLowerCase()]=e,d(D(t),r)}var h=(t,e)=>u(f(t),"cursors",`${e}.json`);function L(t,e){return g(h(t,e))}function z(t,e,r){d(h(t,e),r)}var T=2e4,_=t=>u(f(t),"drafts"),N=t=>/^[a-z0-9-]{8,64}$/.test(t),c=(t,e)=>u(_(t),`${e}.json`);function B(t,e,r=Date.now()){let n=e.text.trim().slice(0,T);if(!n)throw new Error("empty reply");let s={...e,text:n,id:`${r.toString(36)}-${x(4).toString("hex")}`,status:"pending",created_at:new Date(r).toISOString()};return d(c(t,s.id),s),s}function v(t,e){return N(e)?g(c(t,e)):null}function U(t,e){let r=_(t);return b(r)?M(r).filter(n=>n.endsWith(".json")).map(n=>v(t,n.slice(0,-5))).filter(n=>!!n&&(!e||n.status===e)).sort((n,s)=>n.created_at.localeCompare(s.created_at)):[]}async function V(t,e,r,n){let s=v(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no email reply "${e}" is waiting`};let i=`${c(t,e)}.${process.pid}.${x(3).toString("hex")}.claim`;try{E(c(t,e),i)}catch{return{ok:!1,error:`email reply "${e}" is already being decided`}}let a=n.text!==void 0&&n.text.trim()!==""&&n.text.trim()!==s.text,o={...s,...a?{text:n.text.trim().slice(0,T),edited:!0}:{},decided_by:n.by??"operator",decided_at:new Date(n.now??Date.now()).toISOString()};if(r==="no")o.status="rejected";else{let m=await n.send(o).catch(p=>({ok:!1,error:String(p?.message??p)}));if(!m.ok){d(c(t,e),{...s,error:m.error});try{S(i)}catch{}return{ok:!1,error:`not sent: ${m.error}`}}o.status="sent",delete o.error}d(c(t,e),o);try{S(i)}catch{}return{ok:!0,draft:o}}$();function l(t,e){return(t??"").replace(/\$\{(\w+)\}/g,(r,n)=>e[n]??"")}function P(t,e=process.env){let r={host:t.imap.host,port:t.imap.port,secure:t.imap.secure,user:l(t.imap.user,e)||t.address,password:l(t.imap.password,e)},n={host:t.smtp.host,port:t.smtp.port,secure:t.smtp.secure,user:l(t.smtp.user,e)||r.user,password:l(t.smtp.password,e)||r.password};return{imap:r,smtp:n}}async function J(t,e,r,n=process.env){let{smtp:s}=P(t,n);if(!s.password)throw new Error(`no SMTP password for ${t.address}: set it in .env`);let{default:i}=await import("nodemailer"),a=i.createTransport({host:s.host,port:s.port,secure:s.secure,auth:{user:s.user,pass:s.password},connectionTimeout:2e4,greetingTimeout:2e4,socketTimeout:6e4});try{return(await a.sendMail({from:{name:e,address:t.address},to:r.toName?{name:r.toName,address:r.to}:r.to,subject:r.subject,text:r.text,...r.inReplyTo?{inReplyTo:r.inReplyTo}:{},...r.references?{references:r.references}:{},headers:{"Auto-Submitted":"auto-replied"}})).messageId}finally{a.close()}}function q(t,e){return async r=>{let n=t?.channels?.email?.accounts?.[r.account];if(!n)return{ok:!1,error:`no email account "${r.account}" in agentx.json`};let s=y.safeParse(n);if(!s.success)return{ok:!1,error:`email account "${r.account}": ${s.error.issues[0]?.message}`};let i=s.data,a=i.name||t?.agents?.[r.agent]?.name||r.agent;return await J(i,a,{to:r.to,toName:r.to_name,subject:r.subject,inReplyTo:r.in_reply_to,references:r.references,text:r.text},e),{ok:!0}}}export{F as a,I as b,L as c,z as d,B as e,v as f,U as g,V as h,P as i,J as j,q as k};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-KTGTKOLV.js.map
|