agentix-cli 0.119.0 → 0.120.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-E6W5VBYH.js → agent-63RXZRL2.js} +2 -2
- package/dist/{board-dashboard-WDO6Z24C.js → board-dashboard-XQEZBQL5.js} +2 -2
- package/dist/{chunk-PVQPXZHE.js → chunk-247SOQLP.js} +4 -4
- package/dist/chunk-56KNKUFF.js +3 -0
- package/dist/chunk-56KNKUFF.js.map +1 -0
- package/dist/chunk-6FVFD5WU.js +4 -0
- package/dist/chunk-6FVFD5WU.js.map +1 -0
- package/dist/{chunk-IVCFXLAR.js → chunk-6JJJ5MUU.js} +5 -5
- package/dist/chunk-6JJJ5MUU.js.map +1 -0
- package/dist/{chunk-TJ7IUHC7.js → chunk-7ZABMMSW.js} +2 -2
- package/dist/{chunk-GJKYOEDE.js → chunk-AXFE34OV.js} +2 -2
- package/dist/{chunk-ZDWE47LM.js → chunk-KQX3U3H2.js} +2 -2
- package/dist/{chunk-JMFP35EU.js → chunk-PCOXSCYT.js} +180 -180
- package/dist/{chunk-JMFP35EU.js.map → chunk-PCOXSCYT.js.map} +1 -1
- package/dist/{chunk-5PR6DZYW.js → chunk-S6NQB7VV.js} +2 -2
- package/dist/{chunk-5UFIHT66.js → chunk-UAPWOE2W.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{grants-V2ZNLWSJ.js → grants-ZMHSJMYE.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{program-SOKOBCYN.js → program-E3NTPNCZ.js} +217 -206
- package/dist/program-E3NTPNCZ.js.map +1 -0
- package/dist/{query-NAU7J34H.js → query-R6YELRQN.js} +2 -2
- package/dist/{registry-I5PXGCO6.js → registry-HIZIFAVH.js} +2 -2
- package/dist/{review-candidates-HAP7P6SH.js → review-candidates-6YIBOEEG.js} +2 -2
- package/dist/{rotation-memo-5MTSJ4FH.js → rotation-memo-6UW6DTBQ.js} +2 -2
- package/dist/{rotation-memo-5MTSJ4FH.js.map → rotation-memo-6UW6DTBQ.js.map} +1 -1
- package/dist/{wiki-PPX3HYXW.js → wiki-R4MNLBXE.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-2GIDVZ4H.js +0 -3
- package/dist/chunk-2GIDVZ4H.js.map +0 -1
- package/dist/chunk-BDJWN3PL.js +0 -4
- package/dist/chunk-BDJWN3PL.js.map +0 -1
- package/dist/chunk-IVCFXLAR.js.map +0 -1
- package/dist/program-SOKOBCYN.js.map +0 -1
- /package/dist/{agent-E6W5VBYH.js.map → agent-63RXZRL2.js.map} +0 -0
- /package/dist/{board-dashboard-WDO6Z24C.js.map → board-dashboard-XQEZBQL5.js.map} +0 -0
- /package/dist/{chunk-PVQPXZHE.js.map → chunk-247SOQLP.js.map} +0 -0
- /package/dist/{chunk-TJ7IUHC7.js.map → chunk-7ZABMMSW.js.map} +0 -0
- /package/dist/{chunk-GJKYOEDE.js.map → chunk-AXFE34OV.js.map} +0 -0
- /package/dist/{chunk-ZDWE47LM.js.map → chunk-KQX3U3H2.js.map} +0 -0
- /package/dist/{chunk-5PR6DZYW.js.map → chunk-S6NQB7VV.js.map} +0 -0
- /package/dist/{chunk-5UFIHT66.js.map → chunk-UAPWOE2W.js.map} +0 -0
- /package/dist/{grants-V2ZNLWSJ.js.map → grants-ZMHSJMYE.js.map} +0 -0
- /package/dist/{query-NAU7J34H.js.map → query-R6YELRQN.js.map} +0 -0
- /package/dist/{registry-I5PXGCO6.js.map → registry-HIZIFAVH.js.map} +0 -0
- /package/dist/{review-candidates-HAP7P6SH.js.map → review-candidates-6YIBOEEG.js.map} +0 -0
- /package/dist/{wiki-PPX3HYXW.js.map → wiki-R4MNLBXE.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=query-
|
|
1
|
+
import{a,b,c}from"./chunk-6JJJ5MUU.js";import"./chunk-FTZCNID3.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import"./chunk-NDPU6AX2.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-IMLLHT7U.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_GRAPH_WEIGHT,a as agenticQuery,c as rankCatalogPool};
|
|
2
|
+
//# sourceMappingURL=query-R6YELRQN.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$ as j,S as a,T as b,U as c,V as d,W as e,X as f,Y as g,Z as h,_ as i,aa as k,ba as l,ca as m,da as n}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=registry-
|
|
1
|
+
import{$ as j,S as a,T as b,U as c,V as d,W as e,X as f,Y as g,Z as h,_ as i,aa as k,ba as l,ca as m,da as n}from"./chunk-247SOQLP.js";import"./chunk-RJBRYUKU.js";import"./chunk-GLQLCBJS.js";import"./chunk-6W74CHNW.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-B6OXEIOF.js";import"./chunk-4PQREYBU.js";import"./chunk-VWTBHLMX.js";import"./chunk-23SQSUBI.js";import"./chunk-HK7TU5NX.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GSX4NK2N.js";import"./chunk-2G227TF3.js";import"./chunk-MYVHVJWZ.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-6JJJ5MUU.js";import"./chunk-FTZCNID3.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import"./chunk-NDPU6AX2.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-IMLLHT7U.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{m as AgentRegistry,a as EDIT_TOOL_INSTRUCTION,h as TRACE_STEP_SUMMARY_BYTES,e as buildEntryMeta,f as buildEventDigest,g as buildWikiContext,i as clipForTrace,b as codingInstructions,l as emitTraceStepsFromStreamEvent,k as firstMissingRequiredTool,d as getGlobalRegistry,n as richReplyPrompt,c as setGlobalRegistry,j as tallyToolUses};
|
|
2
|
+
//# sourceMappingURL=registry-HIZIFAVH.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as I}from"./chunk-
|
|
1
|
+
import{b as I}from"./chunk-KQX3U3H2.js";import"./chunk-GLQLCBJS.js";import"./chunk-56KNKUFF.js";import"./chunk-NDPU6AX2.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-IMLLHT7U.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as E}from"crypto";var v="review:",b={decisions:"project",warnings:"feedback",friction:"feedback",context:"reference"};function A(t,n,r){let s=E("sha1").update(r.trim().toLowerCase()).digest("hex").slice(0,10);return`${v}${t}/${n}@${s}`}function F(t){if(!t.startsWith(v))return null;let n=t.slice(v.length),r=n.lastIndexOf("@"),s=n.lastIndexOf("/",r===-1?void 0:r);return r===-1||s===-1?null:{reviewId:n.slice(0,s),kind:n.slice(s+1,r),digest:n.slice(r+1)}}var C=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,48)||"finding",L=5;function T(t,n){return`${t}|${I(n)}`}function K(t,n={}){let r=n.kinds??Object.keys(b),s=n.minLength??24,h=[],d=new Map,u=new Map,f=new Map,x=new Map;for(let e of t){let i;try{i=JSON.parse(e.result)}catch{continue}let o=e.updated_at?new Date(e.updated_at).toISOString():new Date().toISOString();for(let c of r){let l=b[c];if(!l)continue;let R=i[c];if(Array.isArray(R))for(let $ of R){let a=String($?.text??"").trim();if(a.length<s)continue;let g=A(e.id,c,a),_=g.slice(g.lastIndexOf("@")),w=`${c}${_}`,y=T(c,a),S=f.get(y)??new Set;if(S.add(e.session_id??e.id),f.set(y,S),d.has(w))continue;let O=String($?.evidence??"").trim(),k={occurrences:1,agentId:e.agent,key:`${e.agent}/${l}_${C(a)}`,stamp:g,memory:{name:C(a),type:l,description:a.slice(0,200),body:"",createdAt:o,updatedAt:o}};x.set(g,{text:a,evidence:O,agent:e.agent,source:e.source}),d.set(w,k),u.set(w,y),h.push(k)}}}for(let[e,i]of d){let o=f.get(u.get(e)??"");i.occurrences=o?.size??1,i.sessions=[...o??[]].slice(0,L);let c=x.get(i.stamp);i.memory.body=D(c,i.occurrences)}let m=new Map;for(let[e,i]of d){let o=u.get(e)??e,c=m.get(o)??[];c.push(i),m.set(o,c)}let M=[...m.values()].sort((e,i)=>i[0].occurrences-e[0].occurrences),p=[];for(let e=0;p.length<h.length;e++){let i=!1;for(let o of M)e<o.length&&(p.push(o[e]),i=!0);if(!i)break}return p}function D(t,n){let r=`${t.agent}${t.source?` via ${t.source}`:""}`,s=[];return n>1?(s.push(`Observed in ${n} separate sessions. Most recently stated as:`),s.push(`> ${t.text}`),s.push(`Recurring across ${n} sessions is what makes this worth recording \u2014 any single occurrence is session state, the repetition is the finding.`)):s.push(t.text),t.evidence&&s.push(`**Evidence:** ${t.evidence}`),s.push(`_From ${n>1?"session reviews":"a session review"} of ${r}._`),s.join(`
|
|
2
2
|
|
|
3
3
|
`)}export{L as MAX_EVIDENCE_SESSIONS,b as PROMOTABLE_KINDS,v as REVIEW_STAMP_PREFIX,F as parseReviewStamp,A as reviewStamp,K as reviewsToCandidates};
|
|
4
|
-
//# sourceMappingURL=review-candidates-
|
|
4
|
+
//# sourceMappingURL=review-candidates-6YIBOEEG.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as u,c}from"./chunk-
|
|
1
|
+
import{a as u,d as c}from"./chunk-56KNKUFF.js";import"./chunk-QIJLFPWE.js";import{execFile as f}from"child_process";var g=3e4,w="haiku",y=`You are about to lose this working session due to context-size rotation. Before that happens, write a compact memo of what you should carry forward to your next session on the same conversation.
|
|
2
2
|
|
|
3
3
|
Include only durable facts a future turn would otherwise have to rediscover:
|
|
4
4
|
- Names, handles, agent ids, telegram/whatsapp/gitlab usernames
|
|
@@ -12,4 +12,4 @@ Do not restate the state of an outside system (billing, account, plan, outage, d
|
|
|
12
12
|
Format: 3-12 short bullet points. Each \u2264120 chars. No prose, no preamble, no header. If the session was uninformative or just casual chat, reply with exactly the literal text "(no memo)".
|
|
13
13
|
|
|
14
14
|
Begin the memo now.`;async function E(n,r){let m=Date.now();if(!r)return{memo:null,reason:"no-resume",durationMs:0};let i=["-p",y,"--output-format","json","--resume",r,"--model",w];n.permissionMode==="bypassPermissions"&&i.push("--dangerously-skip-permissions");let d=c(u(n.workspace),n.billing);return new Promise(p=>{let a=!1,e=(t,s)=>{a||(a=!0,p({memo:t,reason:s,durationMs:Date.now()-m}))};f("claude",i,{cwd:n.workspace,env:d,timeout:g,maxBuffer:1024*1024},(t,s,b)=>{if(t)return t.killed?e(null,"timeout"):e(null,`error:${t.message.slice(0,80)}`);try{let l=JSON.parse(s||"{}"),o=typeof l.result=="string"?l.result.trim():"";if(!o||o==="(no memo)")return e(null,"empty");let h=o.length>4096?o.slice(0,4096)+"\u2026":o;return e(h,"ok")}catch{return e(null,"parse-error")}}).on("error",()=>e(null,"spawn-error"))})}export{E as extractRotationMemo};
|
|
15
|
-
//# sourceMappingURL=rotation-memo-
|
|
15
|
+
//# sourceMappingURL=rotation-memo-6UW6DTBQ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agents/rotation-memo.ts"],"sourcesContent":["import { execFile } from \"child_process\"\nimport type { AgentDef } from \"@/daemon/config\"\nimport { buildAgentEnv, claudeBillingEnv } from \"@/utils/workspace-env\"\n\n// --- Pre-rotation memo extraction ---\n//\n// Just before agentx clears `claudeSessionId` (tier-2 / max-turns / stale\n// rotation), we ask the dying Claude session to dump the facts and\n// decisions it should carry forward. The agent has full working-memory\n// of its tool-use history at this moment — the only chance to capture\n// it before --resume is dropped and the next turn starts with a blank\n// session.\n//\n// The memo persists into MemoryStore, where the existing findRelevant\n// path injects it into future turns naturally. No new wiring on the\n// read side; one-shot LLM call on the write side.\n//\n// Hard rule: never block rotation. Timeout, errors, empty memos all\n// mean \"skip this round of memo capture\". Memory continuity is a\n// best-effort enhancement, not a correctness requirement.\n\nconst MEMO_TIMEOUT_MS = 30_000\nconst MEMO_MODEL = \"haiku\" // cheapest fast model — memo is summarisation, not reasoning\n\nconst MEMO_PROMPT =\n \"You are about to lose this working session due to context-size rotation. \" +\n \"Before that happens, write a compact memo of what you should carry forward \" +\n \"to your next session on the same conversation.\\n\\n\" +\n \"Include only durable facts a future turn would otherwise have to rediscover:\\n\" +\n \"- Names, handles, agent ids, telegram/whatsapp/gitlab usernames\\n\" +\n \"- File paths, URLs, project namespaces, ssh hosts, ports\\n\" +\n \"- Decisions made and their reasoning\\n\" +\n \"- Open tasks or commitments to follow up on\\n\" +\n \"- Identifiers (issue numbers, PR numbers, ticket ids) the user referred to\\n\\n\" +\n \"Do not restate the state of an outside system (billing, account, plan, outage, \" +\n \"deploy) unless you checked it in this session; then say how and when you checked \" +\n \"(e.g. \\\"active per GET /v1/user, 2026-09-28\\\").\\n\\n\" +\n \"Format: 3-12 short bullet points. Each ≤120 chars. No prose, no preamble, \" +\n \"no header. If the session was uninformative or just casual chat, reply with \" +\n \"exactly the literal text \\\"(no memo)\\\".\\n\\n\" +\n \"Begin the memo now.\"\n\nexport interface RotationMemoResult {\n /** The extracted memo text, or null when extraction failed/skipped. */\n memo: string | null\n /** Why we skipped or what happened — \"ok\", \"timeout\", \"error\", \"empty\", \"no-resume\". */\n reason: string\n /** Wall-clock time spent in the extractor. */\n durationMs: number\n}\n\n/** Ask the dying Claude session for a carry-forward memo. Spawns one\n * short claude CLI call with --resume on the about-to-be-dropped\n * session id, asks for a compact memo, returns the text. Never throws\n * — every failure mode resolves with `memo=null` so the caller can\n * proceed with the rotation regardless. */\nexport async function extractRotationMemo(\n agent: AgentDef,\n resumeSessionId: string | undefined,\n): Promise<RotationMemoResult> {\n const start = Date.now()\n if (!resumeSessionId) {\n return { memo: null, reason: \"no-resume\", durationMs: 0 }\n }\n\n const args: string[] = [\n \"-p\", MEMO_PROMPT,\n \"--output-format\", \"json\",\n \"--resume\", resumeSessionId,\n \"--model\", MEMO_MODEL,\n ]\n if (agent.permissionMode === \"bypassPermissions\") {\n args.push(\"--dangerously-skip-permissions\")\n }\n\n const env = claudeBillingEnv(buildAgentEnv(agent.workspace), agent.billing)\n\n return new Promise<RotationMemoResult>((resolve) => {\n let settled = false\n const finish = (memo: string | null, reason: string) => {\n if (settled) return\n settled = true\n resolve({ memo, reason, durationMs: Date.now() - start })\n }\n\n const child = execFile(\n \"claude\",\n args,\n {\n cwd: agent.workspace,\n env,\n timeout: MEMO_TIMEOUT_MS,\n maxBuffer: 1024 * 1024, // 1 MB; the memo itself is tiny\n },\n (err, stdout, _stderr) => {\n if (err) {\n // execFile signals timeout via signal SIGTERM + err.killed\n if ((err as NodeJS.ErrnoException & { killed?: boolean }).killed) {\n return finish(null, \"timeout\")\n }\n return finish(null, `error:${err.message.slice(0, 80)}`)\n }\n try {\n const data = JSON.parse(stdout || \"{}\")\n // claude -p --output-format json yields { result, ... }\n const text = typeof data.result === \"string\" ? data.result.trim() : \"\"\n if (!text || text === \"(no memo)\") return finish(null, \"empty\")\n // Defensive cap: memos > 4 KB are almost certainly the LLM\n // ignoring instructions and dumping prose. Truncate.\n const capped = text.length > 4096 ? text.slice(0, 4096) + \"…\" : text\n return finish(capped, \"ok\")\n } catch {\n return finish(null, \"parse-error\")\n }\n },\n )\n child.on(\"error\", () => finish(null, \"spawn-error\"))\n })\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/agents/rotation-memo.ts"],"sourcesContent":["import { execFile } from \"child_process\"\nimport type { AgentDef } from \"@/daemon/config\"\nimport { buildAgentEnv, claudeBillingEnv } from \"@/utils/workspace-env\"\n\n// --- Pre-rotation memo extraction ---\n//\n// Just before agentx clears `claudeSessionId` (tier-2 / max-turns / stale\n// rotation), we ask the dying Claude session to dump the facts and\n// decisions it should carry forward. The agent has full working-memory\n// of its tool-use history at this moment — the only chance to capture\n// it before --resume is dropped and the next turn starts with a blank\n// session.\n//\n// The memo persists into MemoryStore, where the existing findRelevant\n// path injects it into future turns naturally. No new wiring on the\n// read side; one-shot LLM call on the write side.\n//\n// Hard rule: never block rotation. Timeout, errors, empty memos all\n// mean \"skip this round of memo capture\". Memory continuity is a\n// best-effort enhancement, not a correctness requirement.\n\nconst MEMO_TIMEOUT_MS = 30_000\nconst MEMO_MODEL = \"haiku\" // cheapest fast model — memo is summarisation, not reasoning\n\nconst MEMO_PROMPT =\n \"You are about to lose this working session due to context-size rotation. \" +\n \"Before that happens, write a compact memo of what you should carry forward \" +\n \"to your next session on the same conversation.\\n\\n\" +\n \"Include only durable facts a future turn would otherwise have to rediscover:\\n\" +\n \"- Names, handles, agent ids, telegram/whatsapp/gitlab usernames\\n\" +\n \"- File paths, URLs, project namespaces, ssh hosts, ports\\n\" +\n \"- Decisions made and their reasoning\\n\" +\n \"- Open tasks or commitments to follow up on\\n\" +\n \"- Identifiers (issue numbers, PR numbers, ticket ids) the user referred to\\n\\n\" +\n \"Do not restate the state of an outside system (billing, account, plan, outage, \" +\n \"deploy) unless you checked it in this session; then say how and when you checked \" +\n \"(e.g. \\\"active per GET /v1/user, 2026-09-28\\\").\\n\\n\" +\n \"Format: 3-12 short bullet points. Each ≤120 chars. No prose, no preamble, \" +\n \"no header. If the session was uninformative or just casual chat, reply with \" +\n \"exactly the literal text \\\"(no memo)\\\".\\n\\n\" +\n \"Begin the memo now.\"\n\nexport interface RotationMemoResult {\n /** The extracted memo text, or null when extraction failed/skipped. */\n memo: string | null\n /** Why we skipped or what happened — \"ok\", \"timeout\", \"error\", \"empty\", \"no-resume\". */\n reason: string\n /** Wall-clock time spent in the extractor. */\n durationMs: number\n}\n\n/** Ask the dying Claude session for a carry-forward memo. Spawns one\n * short claude CLI call with --resume on the about-to-be-dropped\n * session id, asks for a compact memo, returns the text. Never throws\n * — every failure mode resolves with `memo=null` so the caller can\n * proceed with the rotation regardless. */\nexport async function extractRotationMemo(\n agent: AgentDef,\n resumeSessionId: string | undefined,\n): Promise<RotationMemoResult> {\n const start = Date.now()\n if (!resumeSessionId) {\n return { memo: null, reason: \"no-resume\", durationMs: 0 }\n }\n\n const args: string[] = [\n \"-p\", MEMO_PROMPT,\n \"--output-format\", \"json\",\n \"--resume\", resumeSessionId,\n \"--model\", MEMO_MODEL,\n ]\n if (agent.permissionMode === \"bypassPermissions\") {\n args.push(\"--dangerously-skip-permissions\")\n }\n\n const env = claudeBillingEnv(buildAgentEnv(agent.workspace), agent.billing)\n\n return new Promise<RotationMemoResult>((resolve) => {\n let settled = false\n const finish = (memo: string | null, reason: string) => {\n if (settled) return\n settled = true\n resolve({ memo, reason, durationMs: Date.now() - start })\n }\n\n const child = execFile(\n \"claude\",\n args,\n {\n cwd: agent.workspace,\n env,\n timeout: MEMO_TIMEOUT_MS,\n maxBuffer: 1024 * 1024, // 1 MB; the memo itself is tiny\n },\n (err, stdout, _stderr) => {\n if (err) {\n // execFile signals timeout via signal SIGTERM + err.killed\n if ((err as NodeJS.ErrnoException & { killed?: boolean }).killed) {\n return finish(null, \"timeout\")\n }\n return finish(null, `error:${err.message.slice(0, 80)}`)\n }\n try {\n const data = JSON.parse(stdout || \"{}\")\n // claude -p --output-format json yields { result, ... }\n const text = typeof data.result === \"string\" ? data.result.trim() : \"\"\n if (!text || text === \"(no memo)\") return finish(null, \"empty\")\n // Defensive cap: memos > 4 KB are almost certainly the LLM\n // ignoring instructions and dumping prose. Truncate.\n const capped = text.length > 4096 ? text.slice(0, 4096) + \"…\" : text\n return finish(capped, \"ok\")\n } catch {\n return finish(null, \"parse-error\")\n }\n },\n )\n child.on(\"error\", () => finish(null, \"spawn-error\"))\n })\n}\n"],"mappings":"2EAAA,OAAS,YAAAA,MAAgB,gBAqBzB,IAAMC,EAAkB,IAClBC,EAAa,QAEbC,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBA+BF,eAAsBC,EACpBC,EACAC,EAC6B,CAC7B,IAAMC,EAAQ,KAAK,IAAI,EACvB,GAAI,CAACD,EACH,MAAO,CAAE,KAAM,KAAM,OAAQ,YAAa,WAAY,CAAE,EAG1D,IAAME,EAAiB,CACrB,KAAML,EACN,kBAAmB,OACnB,WAAYG,EACZ,UAAWJ,CACb,EACIG,EAAM,iBAAmB,qBAC3BG,EAAK,KAAK,gCAAgC,EAG5C,IAAMC,EAAMC,EAAiBC,EAAcN,EAAM,SAAS,EAAGA,EAAM,OAAO,EAE1E,OAAO,IAAI,QAA6BO,GAAY,CAClD,IAAIC,EAAU,GACRC,EAAS,CAACC,EAAqBC,IAAmB,CAClDH,IACJA,EAAU,GACVD,EAAQ,CAAE,KAAAG,EAAM,OAAAC,EAAQ,WAAY,KAAK,IAAI,EAAIT,CAAM,CAAC,EAC1D,EAEcU,EACZ,SACAT,EACA,CACE,IAAKH,EAAM,UACX,IAAAI,EACA,QAASR,EACT,UAAW,KAAO,IACpB,EACA,CAACiB,EAAKC,EAAQC,IAAY,CACxB,GAAIF,EAEF,OAAKA,EAAqD,OACjDJ,EAAO,KAAM,SAAS,EAExBA,EAAO,KAAM,SAASI,EAAI,QAAQ,MAAM,EAAG,EAAE,GAAG,EAEzD,GAAI,CACF,IAAMG,EAAO,KAAK,MAAMF,GAAU,IAAI,EAEhCG,EAAO,OAAOD,EAAK,QAAW,SAAWA,EAAK,OAAO,KAAK,EAAI,GACpE,GAAI,CAACC,GAAQA,IAAS,YAAa,OAAOR,EAAO,KAAM,OAAO,EAG9D,IAAMS,EAASD,EAAK,OAAS,KAAOA,EAAK,MAAM,EAAG,IAAI,EAAI,SAAMA,EAChE,OAAOR,EAAOS,EAAQ,IAAI,CAC5B,MAAE,CACA,OAAOT,EAAO,KAAM,aAAa,CACnC,CACF,CACF,EACM,GAAG,QAAS,IAAMA,EAAO,KAAM,aAAa,CAAC,CACrD,CAAC,CACH","names":["execFile","MEMO_TIMEOUT_MS","MEMO_MODEL","MEMO_PROMPT","extractRotationMemo","agent","resumeSessionId","start","args","env","claudeBillingEnv","buildAgentEnv","resolve","settled","finish","memo","reason","execFile","err","stdout","_stderr","data","text","capped"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./chunk-VWTBHLMX.js";import{a as b}from"./chunk-23SQSUBI.js";import{a}from"./chunk-HK7TU5NX.js";import"./chunk-CECHWYJ2.js";import{a as c}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=wiki-
|
|
1
|
+
import"./chunk-VWTBHLMX.js";import{a as b}from"./chunk-23SQSUBI.js";import{a}from"./chunk-HK7TU5NX.js";import"./chunk-CECHWYJ2.js";import{a as c}from"./chunk-6JJJ5MUU.js";import"./chunk-FTZCNID3.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import"./chunk-NDPU6AX2.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-IMLLHT7U.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as WikiHub,a as WikiStore,c as agenticQuery};
|
|
2
|
+
//# sourceMappingURL=wiki-R4MNLBXE.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentix-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.120.0",
|
|
4
4
|
"description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
package/dist/chunk-2GIDVZ4H.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{readFileSync as f,existsSync as l}from"fs";import{resolve as p}from"path";function a(e){let n=[];for(let r of e.split(`
|
|
2
|
-
`)){let t=r.trim();if(!t||t.startsWith("#"))continue;let o=t.startsWith("export ")?t.slice(7).trim():t,i=o.indexOf("=");if(i===-1)continue;let c=o.slice(0,i).trim(),s=o.slice(i+1).trim();s.length>=2&&(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),c&&n.push([c,s])}return n}function u(e){let n={};for(let r of[".env",".env.gitlab"]){let t=p(e,r);if(l(t))try{for(let[o,i]of a(f(t,"utf-8")))n[o]=i}catch{}}return n}var d=new Map;function g(e=process.cwd()){let n=d.get(e);if(n)return n;let r=p(e,".env"),t;if(!l(r))t=new Set;else try{t=new Set(a(f(r,"utf-8")).map(([o])=>o))}catch{t=new Set}return d.set(e,t),t}function P(e,n=process.env,r=process.cwd()){let t=u(e),o=g(r),i={...n};for(let c of o)c in t||delete i[c];for(let[c,s]of Object.entries(t))i[c]=s;return i}function E(e){return delete e.ANTHROPIC_API_KEY,delete e.ANTHROPIC_API_KEY_OLD,e}function A(e,n="subscription"){if(n!=="api")return E(e);if(!e.ANTHROPIC_API_KEY)throw new Error(`billing "api" needs ANTHROPIC_API_KEY in the agent's environment`);return delete e.ANTHROPIC_API_KEY_OLD,delete e.CLAUDE_CODE_OAUTH_TOKEN,e}function m(e){if(l(e))for(let[n,r]of a(f(e,"utf-8")))process.env[n]===void 0&&(process.env[n]=r)}export{P as a,E as b,A as c,m as d};
|
|
3
|
-
//# sourceMappingURL=chunk-2GIDVZ4H.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/workspace-env.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// Loads per-agent secrets from the agent's workspace and tells the runtime\n// which keys the daemon's own .env injected, so we can strip those before\n// spawning the agent's claude process. Without this, every agent inherits\n// the daemon's GITLAB_TOKEN regardless of whether their workspace has its\n// own .env.gitlab — defeating per-agent identity boundaries (each agent\n// should commit/push as itself, not as the daemon's account).\n\n/**\n * Parse a dotenv-style file. Tolerates the `export KEY=VALUE` form used by\n * shell-sourced files like .env.gitlab on peer-server.\n */\nfunction parseDotEnv(content: string): Array<[string, string]> {\n const out: Array<[string, string]> = []\n for (const raw of content.split(\"\\n\")) {\n const trimmed = raw.trim()\n if (!trimmed || trimmed.startsWith(\"#\")) continue\n const stripped = trimmed.startsWith(\"export \") ? trimmed.slice(7).trim() : trimmed\n const eq = stripped.indexOf(\"=\")\n if (eq === -1) continue\n const key = stripped.slice(0, eq).trim()\n let value = stripped.slice(eq + 1).trim()\n if (value.length >= 2 && ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\")))) {\n value = value.slice(1, -1)\n }\n if (key) out.push([key, value])\n }\n return out\n}\n\n/**\n * Read .env then .env.gitlab from a workspace and return their merged keys.\n * .env.gitlab wins on collision — it's the more specific per-channel file.\n */\nexport function loadWorkspaceEnv(workspace: string): Record<string, string> {\n const merged: Record<string, string> = {}\n for (const fname of [\".env\", \".env.gitlab\"]) {\n const path = resolve(workspace, fname)\n if (!existsSync(path)) continue\n try {\n for (const [k, v] of parseDotEnv(readFileSync(path, \"utf-8\"))) {\n merged[k] = v\n }\n } catch { /* best-effort */ }\n }\n return merged\n}\n\n/**\n * Keys defined in the daemon's own .env file, cached per daemonCwd. The\n * runtime uses this to strip those keys from the child env before adding\n * the workspace overrides — so a daemon-level GITLAB_TOKEN never leaks to\n * an agent that hasn't put one in its own workspace.\n */\nconst daemonEnvKeysCache = new Map<string, Set<string>>()\n\nexport function getDaemonEnvKeys(daemonCwd: string = process.cwd()): Set<string> {\n const cached = daemonEnvKeysCache.get(daemonCwd)\n if (cached) return cached\n const path = resolve(daemonCwd, \".env\")\n let keys: Set<string>\n if (!existsSync(path)) {\n keys = new Set()\n } else {\n try {\n keys = new Set(parseDotEnv(readFileSync(path, \"utf-8\")).map(([k]) => k))\n } catch {\n keys = new Set()\n }\n }\n daemonEnvKeysCache.set(daemonCwd, keys)\n return keys\n}\n\n/** Test-only: clear the cache so a different daemonCwd is re-read. */\nexport function _resetDaemonEnvKeysCache(): void {\n daemonEnvKeysCache.clear()\n}\n\n/**\n * Build the env object passed to a spawned agent process. Starts from\n * parentEnv (default process.env), removes any keys that came from the\n * daemon's own .env (so daemon-level secrets don't leak), then layers in\n * workspace .env / .env.gitlab.\n *\n * - System env (PATH, HOME, USER, …) survives untouched.\n * - Daemon-level secrets (e.g. GITLAB_TOKEN in /home/peer/agentx/.env) are\n * stripped UNLESS the workspace provides its own value for that key.\n * - Workspace env (per-agent .env / .env.gitlab) wins on the final merge.\n */\nexport function buildAgentEnv(\n workspace: string,\n parentEnv: NodeJS.ProcessEnv = process.env,\n daemonCwd: string = process.cwd(),\n): NodeJS.ProcessEnv {\n const workspaceEnv = loadWorkspaceEnv(workspace)\n const daemonOwnedKeys = getDaemonEnvKeys(daemonCwd)\n const child: NodeJS.ProcessEnv = { ...parentEnv }\n for (const k of daemonOwnedKeys) {\n if (!(k in workspaceEnv)) delete child[k]\n }\n for (const [k, v] of Object.entries(workspaceEnv)) {\n child[k] = v\n }\n return child\n}\n\n// Force the `claude` CLI to use OAuth/subscription billing. When\n// ANTHROPIC_API_KEY is present (env, systemd EnvironmentFile, daemon .env not\n// stripped because the workspace also defines it), the CLI silently switches\n// to the API-key path and any usage caps on that key surface as\n// \"You have reached your specified API usage limits...\". This caused\n// claude-code-tier agents to bypass the user's subscription. The same\n// stripping pattern lives in src/agent/providers/claude-code.ts for the\n// in-process provider — keep them in sync.\nexport function stripAnthropicApiKey(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_API_KEY_OLD\n return env\n}\n\n/** How an agent's `claude` CLI is billed. \"subscription\" (the default) is\n * the OAuth login shared by the fleet. \"api\" bills ANTHROPIC_API_KEY\n * instead, for agents that must not draw on that shared quota, such as\n * benchmark runs. */\nexport type ClaudeBilling = \"subscription\" | \"api\"\n\n/** Shape a `claude` spawn env for the agent's billing. Each mode removes the\n * other's credential, because the CLI silently uses whichever it finds. An\n * \"api\" agent with no key throws rather than falling back to the\n * subscription. */\nexport function claudeBillingEnv(\n env: NodeJS.ProcessEnv,\n billing: ClaudeBilling = \"subscription\",\n): NodeJS.ProcessEnv {\n if (billing !== \"api\") return stripAnthropicApiKey(env)\n if (!env.ANTHROPIC_API_KEY) {\n throw new Error('billing \"api\" needs ANTHROPIC_API_KEY in the agent\\'s environment')\n }\n delete env.ANTHROPIC_API_KEY_OLD\n delete env.CLAUDE_CODE_OAUTH_TOKEN\n return env\n}\n\n/**\n * Load a dotenv file into process.env for the CURRENT process. Variables\n * already present win, so a systemd/launchd override always beats the file.\n *\n * `agentx daemon start` has always done this; `agentx board serve` did not,\n * so `${MESH_TOKEN}` in agentx.json expanded to \"\" inside the dashboard and\n * every proxied mesh call went out with an empty Bearer (401 from peers).\n */\nexport function loadEnvFileIntoProcess(path: string): void {\n if (!existsSync(path)) return\n for (const [key, value] of parseDotEnv(readFileSync(path, \"utf-8\"))) {\n if (process.env[key] === undefined) process.env[key] = value\n }\n}\n"],"mappings":"AAAA,OAAS,gBAAAA,EAAc,cAAAC,MAAkB,KACzC,OAAS,WAAAC,MAAe,OAaxB,SAASC,EAAYC,EAA0C,CAC7D,IAAMC,EAA+B,CAAC,EACtC,QAAWC,KAAOF,EAAQ,MAAM;AAAA,CAAI,EAAG,CACrC,IAAMG,EAAUD,EAAI,KAAK,EACzB,GAAI,CAACC,GAAWA,EAAQ,WAAW,GAAG,EAAG,SACzC,IAAMC,EAAWD,EAAQ,WAAW,SAAS,EAAIA,EAAQ,MAAM,CAAC,EAAE,KAAK,EAAIA,EACrEE,EAAKD,EAAS,QAAQ,GAAG,EAC/B,GAAIC,IAAO,GAAI,SACf,IAAMC,EAAMF,EAAS,MAAM,EAAGC,CAAE,EAAE,KAAK,EACnCE,EAAQH,EAAS,MAAMC,EAAK,CAAC,EAAE,KAAK,EACpCE,EAAM,QAAU,IAAOA,EAAM,WAAW,GAAG,GAAKA,EAAM,SAAS,GAAG,GAAOA,EAAM,WAAW,GAAG,GAAKA,EAAM,SAAS,GAAG,KACtHA,EAAQA,EAAM,MAAM,EAAG,EAAE,GAEvBD,GAAKL,EAAI,KAAK,CAACK,EAAKC,CAAK,CAAC,EAEhC,OAAON,CACT,CAMO,SAASO,EAAiBC,EAA2C,CAC1E,IAAMC,EAAiC,CAAC,EACxC,QAAWC,IAAS,CAAC,OAAQ,aAAa,EAAG,CAC3C,IAAMC,EAAOd,EAAQW,EAAWE,CAAK,EACrC,GAAKd,EAAWe,CAAI,EACpB,GAAI,CACF,OAAW,CAACC,EAAGC,CAAC,IAAKf,EAAYH,EAAagB,EAAM,OAAO,CAAC,EAC1DF,EAAOG,CAAC,EAAIC,CAEhB,MAAE,CAA0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,CAAG,IAAM,SAAW,QAAQ,IAAIA,CAAG,EAAIC,EAE3D","names":["readFileSync","existsSync","resolve","parseDotEnv","content","out","raw","trimmed","stripped","eq","key","value","loadWorkspaceEnv","workspace","merged","fname","path","k","v","daemonEnvKeysCache","getDaemonEnvKeys","daemonCwd","cached","keys","buildAgentEnv","workspace","parentEnv","daemonCwd","workspaceEnv","loadWorkspaceEnv","daemonOwnedKeys","getDaemonEnvKeys","child","k","v","stripAnthropicApiKey","env","claudeBillingEnv","billing","loadEnvFileIntoProcess","path","existsSync","key","value","parseDotEnv","readFileSync"]}
|
package/dist/chunk-BDJWN3PL.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{c as b,d as D,e as $,f as I}from"./chunk-Y4CYQV7G.js";import{existsSync as A,mkdirSync as L,readdirSync as q,readFileSync as F,renameSync as j,writeFileSync as z}from"fs";import{resolve as R}from"path";function m(e){return e.status==="decided"&&e.verdict==="yes"&&!!e.choice&&e.choice!==k}function O(e,r,n){let t=[`This was a retro card about run ${e.taskId} (\`agentx trace show ${e.taskId}\`).`];if(!m(r))return t.push("Change nothing. Do not propose these fixes again on your own."),t;t.push(`The operator picked this fix: ${r.choice}`);let i=e.specs?.[(r.choices??[]).indexOf(r.choice)];return i&&t.push("Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):",i),n&&t.push("The operator's note on the fix:",n),t.push("Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.","Do not apply it to a live system directly. Tag what you add with `retro:"+e.taskId+"` so it can be found and removed later."),t}var k="None of these";function v(e,r){let n=e.list?` in the "${e.list}" list`:"",t=[`This card came from the operator's reminder "${e.title}"${n} (id ${e.id}).`];return t.push(r?`Do what the operator chose, then tick the reminder off: remindctl complete ${e.id}`:"Leave the reminder open; it will come back at a later check-in."),t}var T=["discard","keep","pause"];function x(e){return e==="approve"?"keep":T.includes(e)?e:null}var d={title:120,ask:300,recommend:300,source:500,note:500,pendingPerAgent:25},B={defaultExpiryDays:3,maxExpiryDays:30};function y(e){return R(e,".agentx","approvals")}var V=/^[a-z0-9][a-z0-9-]{0,80}$/;function E(e){return V.test(e)}function N(e,r){if(!E(r))throw new Error(`invalid card id: ${r}`);return R(y(e),`${r}.json`)}function M(e,r){let n=new Date(e).toISOString().slice(0,10),t=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${n}-${t||"card"}-${Math.random().toString(36).slice(2,6)}`}function f(e,r){L(y(e),{recursive:!0});let n=N(e,r.id),t=`${n}.${process.pid}.tmp`;z(t,JSON.stringify(r,null,2)+`
|
|
2
|
-
`),j(t,n)}function w(e,r){if(!E(r))return null;try{let n=JSON.parse(F(N(e,r),"utf-8")),t=n.if_silent==="approve"||n.outcome==="approve";return{...n,if_silent:x(n.if_silent)??"keep",...n.outcome?{outcome:x(n.outcome)??"keep"}:{},...t?{if_silent_asked:"approve"}:{}}}catch{return null}}function _(e,r){let n=y(e);if(!A(n))return[];let t=[];for(let i of q(n).filter(o=>o.endsWith(".json")&&!o.startsWith("_")).sort()){let o=w(e,i.slice(0,-5));o&&(!r||o.status===r)&&t.push(o)}return t}function c(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function Y(e,r,n){let t=r+n.maxExpiryDays*864e5,i,o=c(e);if(!o)i=r+n.defaultExpiryDays*864e5;else{let s=/^(\d+)\s*([hd])$/i.exec(o);if(s)i=r+Number(s[1])*(s[2].toLowerCase()==="d"?864e5:36e5);else if(i=Date.parse(o),Number.isNaN(i))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${o}")`}}return i<=r?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(i,t)).toISOString()}}function J(e,r={}){let n=r.now??Date.now(),t=r.settings??B,i=c(e.title),o=c(e.ask),s=c(e.recommend),a=c(e.raised_by);if(!i)return{ok:!1,error:"title is required"};if(!o)return{ok:!1,error:"ask is required: the yes/no question"};if(!s)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!a)return{ok:!1,error:"raised_by is required: the agent id"};if(i.length>d.title)return{ok:!1,error:`title is longer than ${d.title} characters`};if(o.length>d.ask)return{ok:!1,error:`ask is longer than ${d.ask} characters`};if(s.length>d.recommend)return{ok:!1,error:`recommend is longer than ${d.recommend} characters`};let C=c(e.if_silent).toLowerCase(),S=x(C);if(!S)return{ok:!1,error:`if_silent must be one of ${T.join(", ")}`};let p=Y(e.expires,n,t);if(!p.ok)return p;let l=c(e.source);if(l.length>d.source)return{ok:!1,error:`source is longer than ${d.source} characters`};if(l&&/^[a-z][a-z0-9+.-]*:/i.test(l)&&!/^https?:\/\//i.test(l))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let g=b(e);if(!g.ok)return g;let h,u=e.reply;return u&&typeof u=="object"&&c(u.channel)&&c(u.chatId)&&(h={channel:c(u.channel),chatId:c(u.chatId),...c(u.accountId)?{accountId:c(u.accountId)}:{}}),{ok:!0,card:{id:M(n,i),title:i,ask:o,recommend:s,if_silent:S,...C==="approve"?{if_silent_asked:"approve"}:{},expires:p.at,...l?{source:l}:{},raised_by:a,...r.node?{node:r.node}:{},created_at:new Date(n).toISOString(),...h?{reply:h}:{},...g.value,...r.origin?{origin:r.origin}:{},status:"pending"}}}function H(e,r,n={}){let t=J(r,n);if(!t.ok)return t;let i=a=>a.origin?.kind==="retro",o=i(t.card),s=_(e,"pending").filter(a=>a.raised_by===t.card.raised_by&&i(a)===o).length;if(s>=d.pendingPerAgent){let a=o?"retro cards":"cards";return{ok:!1,error:`${t.card.raised_by} already has ${s} ${a} waiting; wait for decisions before raising more`}}return f(e,t.card),t}function K(e,r,n,t={}){let i=w(e,r);if(!i)return{ok:!1,error:`no card "${r}"`};if(i.status!=="pending")return{ok:!1,error:`card "${r}" is already ${i.status}`};let o=$(i,n,t);if(!o.ok)return o;let s=c(t.note).slice(0,d.note),a={...i,status:"decided",verdict:n,decided_by:t.by??"operator",decided_at:new Date(t.now??Date.now()).toISOString(),...s?{note:s}:{},...o.choice?{choice:o.choice}:{},...o.text?{text:o.text}:{}};return f(e,a),{ok:!0,card:a}}function X(e,r=Date.now()){let n=[];for(let t of _(e,"pending")){if(Date.parse(t.expires)>r)continue;let i={...t,status:"expired",outcome:t.if_silent,decided_by:"expiry",decided_at:new Date(r).toISOString()};f(e,i),n.push(i)}return n}function Z(e){return _(e).filter(r=>r.status!=="pending"&&!r.agent_notified_at)}function ee(e,r,n=Date.now()){let t=w(e,r);!t||t.agent_notified_at||f(e,{...t,agent_notified_at:new Date(n).toISOString()})}function te(e){let r=e.origin?.kind==="retro"?e.origin:void 0,n=e.status==="decided"?e.verdict==="yes"?r&&!m(e)?`The operator picked "${k}", which counts as NO.`:"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${e.outcome??e.if_silent}.`,t=[`[Approval result] Your decision card "${e.title}" (${e.id}) is closed.`,`Question: ${e.ask}`,n];if(e.status==="decided"&&e.verdict==="yes"&&!r&&t.push(...I(e)),e.note&&t.push(`Operator note: ${e.note}`),e.source&&t.push(`Source: ${e.source}`),e.origin?.kind==="reminder"&&t.push(...v(e.origin,e.status==="decided"&&e.verdict==="yes")),r){let i=a=>a.replace(/\s+/g," ").trim(),o=D(e.draft,e.choice),s=e.text&&i(e.text)!==i(o)?e.text:void 0;t.push(...O(r,e,s))}return e.reply&&t.push(`You raised it from ${e.reply.channel} chat ${e.reply.chatId}; reply there if the requester should know.`),e.node&&t.push(`The operator answered it on another machine; the card was forwarded from ${e.node}.`),t.push("Act on this result now. Do not raise the same card again."),t.join(`
|
|
3
|
-
`)}export{k as a,T as b,d as c,y as d,E as e,w as f,_ as g,H as h,K as i,X as j,Z as k,ee as l,te as m};
|
|
4
|
-
//# sourceMappingURL=chunk-BDJWN3PL.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/approvals/cards.ts","../src/approvals/origin.ts"],"sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { answerLines, buildChoices, draftFor, resolveAnswer, type CardChoices } from \"./choices\"\nimport { originLines, RETRO_NONE, retroApproved, retroLines, type CardOrigin } from \"./origin\"\n\n// --- Decision cards: what an agent asks the operator ---\n//\n// An agent that needs a yes/no from the operator writes a card instead of\n// asking in chat. A card says what it is, the question, what the agent\n// recommends, and what happens if nobody answers by `expires`. Nothing\n// waits forever: past `expires` the daemon applies `if_silent` (sweep.ts).\n//\n// Storage: one JSON file per card under `.agentx/approvals/`, written\n// atomically, like wiki proposals. The CLI, the dashboard and the daemon\n// are separate processes and all read the same files.\n//\n// Field names match the API (`if_silent`, `raised_by`), so a stored card is\n// exactly what `POST /approvals` accepted.\n\n// No card approves itself (#741): only the operator says yes. \"approve\",\n// which older agents and stored cards may still carry, is read as \"keep\".\nexport type IfSilent = \"discard\" | \"keep\" | \"pause\"\nexport const IF_SILENT_VALUES: readonly IfSilent[] = [\"discard\", \"keep\", \"pause\"]\n\nfunction asIfSilent(v: string): IfSilent | null {\n if (v === \"approve\") return \"keep\"\n return IF_SILENT_VALUES.includes(v as IfSilent) ? (v as IfSilent) : null\n}\n\nexport type CardStatus = \"pending\" | \"decided\" | \"expired\"\nexport type Verdict = \"yes\" | \"no\"\n\n/** Where the agent was asked, so the verdict can be taken back there. */\nexport interface ReplyTarget {\n channel: string\n chatId: string\n accountId?: string\n}\n\nexport interface DecisionCard extends CardChoices {\n id: string\n title: string\n ask: string\n recommend: string\n if_silent: IfSilent\n /** ISO time the default applies. Always set. */\n expires: string\n /** Link to the draft, PR or issue. */\n source?: string\n raised_by: string\n /** The mesh node the raising agent is on, when the card was forwarded\n * here from there (forward.ts, #668). Unset: this node. */\n node?: string\n created_at: string\n reply?: ReplyTarget\n status: CardStatus\n /** The operator's answer (status \"decided\"). */\n verdict?: Verdict\n /** What applied on expiry (status \"expired\"). */\n outcome?: IfSilent\n /** Set when the agent, or a card stored before #741, asked for\n * \"approve\" on expiry; `if_silent` then holds \"keep\". Kept so the\n * record still shows what was originally asked. */\n if_silent_asked?: \"approve\"\n decided_by?: string\n decided_at?: string\n note?: string\n /** The option the operator picked, when the card offered choices. */\n choice?: string\n /** The message the operator approved, after any edit. */\n text?: string\n /** Set once the raising agent has been told the result. */\n agent_notified_at?: string\n /** What the card is about, when the daemon raised it (origin.ts). */\n origin?: CardOrigin\n}\n\nexport const CARD_LIMITS = {\n title: 120,\n ask: 300,\n recommend: 300,\n source: 500,\n note: 500,\n /** Pending cards one agent may have open at a time. */\n pendingPerAgent: 25,\n} as const\n\nexport interface CardSettings {\n defaultExpiryDays: number\n maxExpiryDays: number\n}\n\nexport const DEFAULT_CARD_SETTINGS: CardSettings = { defaultExpiryDays: 3, maxExpiryDays: 30 }\n\nexport function approvalsDir(root: string): string {\n return resolve(root, \".agentx\", \"approvals\")\n}\n\nconst CARD_ID_RE = /^[a-z0-9][a-z0-9-]{0,80}$/\n\nexport function isValidCardId(id: string): boolean {\n return CARD_ID_RE.test(id)\n}\n\nfunction fileFor(root: string, id: string): string {\n if (!isValidCardId(id)) throw new Error(`invalid card id: ${id}`)\n return resolve(approvalsDir(root), `${id}.json`)\n}\n\nexport function newCardId(now: number, title: string): string {\n const day = new Date(now).toISOString().slice(0, 10)\n const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40)\n return `${day}-${slug || \"card\"}-${Math.random().toString(36).slice(2, 6)}`\n}\n\nexport function saveCard(root: string, card: DecisionCard): void {\n mkdirSync(approvalsDir(root), { recursive: true })\n const path = fileFor(root, card.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(card, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\nexport function readCard(root: string, id: string): DecisionCard | null {\n if (!isValidCardId(id)) return null\n try {\n const card = JSON.parse(readFileSync(fileFor(root, id), \"utf-8\")) as DecisionCard\n // A card that expired as \"approve\" before #741 is read as \"keep\" too, so\n // an agent not yet told never hears \"default applied: approve\".\n const legacy = (card.if_silent as string) === \"approve\" || (card.outcome as string) === \"approve\"\n return {\n ...card,\n if_silent: asIfSilent(card.if_silent) ?? \"keep\",\n ...(card.outcome ? { outcome: asIfSilent(card.outcome) ?? \"keep\" } : {}),\n ...(legacy ? { if_silent_asked: \"approve\" as const } : {}),\n }\n } catch {\n return null\n }\n}\n\n/** Cards, oldest first; only `status` ones when given. */\nexport function listCards(root: string, status?: CardStatus): DecisionCard[] {\n const dir = approvalsDir(root)\n if (!existsSync(dir)) return []\n const out: DecisionCard[] = []\n for (const f of readdirSync(dir).filter((f) => f.endsWith(\".json\") && !f.startsWith(\"_\")).sort()) {\n const c = readCard(root, f.slice(0, -5))\n if (c && (!status || c.status === status)) out.push(c)\n }\n return out\n}\n\nfunction oneLine(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\"\n}\n\n/**\n * `expires` as given by an agent: an ISO date or time, or a relative\n * \"12h\" / \"3d\". Unset: the default. Always capped at maxExpiryDays, so a\n * card can't be parked for a year.\n */\nexport function resolveExpiry(input: unknown, now: number, settings: CardSettings): { ok: true; at: string } | { ok: false; error: string } {\n const max = now + settings.maxExpiryDays * 86_400_000\n let at: number\n const raw = oneLine(input)\n if (!raw) {\n at = now + settings.defaultExpiryDays * 86_400_000\n } else {\n const rel = /^(\\d+)\\s*([hd])$/i.exec(raw)\n if (rel) {\n at = now + Number(rel[1]) * (rel[2].toLowerCase() === \"d\" ? 86_400_000 : 3_600_000)\n } else {\n at = Date.parse(raw)\n if (Number.isNaN(at)) return { ok: false, error: `expires must be an ISO date or time, or like \"12h\" / \"3d\" (got \"${raw}\")` }\n }\n }\n if (at <= now) return { ok: false, error: \"expires must be in the future\" }\n return { ok: true, at: new Date(Math.min(at, max)).toISOString() }\n}\n\nexport interface CardInput {\n title?: unknown\n ask?: unknown\n recommend?: unknown\n if_silent?: unknown\n expires?: unknown\n source?: unknown\n raised_by?: unknown\n reply?: unknown\n choices?: unknown\n draft?: unknown\n say?: unknown\n context?: unknown\n}\n\n/** Validate what an agent sent and build a pending card. Never saves. */\nexport interface BuildCardOptions {\n now?: number\n settings?: CardSettings\n origin?: CardOrigin\n /** The peer the card was forwarded from. The daemon sets it after\n * checking the name against its mesh peers; never taken as sent. */\n node?: string\n}\n\nexport function buildCard(\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const now = opts.now ?? Date.now()\n const settings = opts.settings ?? DEFAULT_CARD_SETTINGS\n const title = oneLine(input.title)\n const ask = oneLine(input.ask)\n const recommend = oneLine(input.recommend)\n const raisedBy = oneLine(input.raised_by)\n if (!title) return { ok: false, error: \"title is required\" }\n if (!ask) return { ok: false, error: \"ask is required: the yes/no question\" }\n if (!recommend) return { ok: false, error: \"recommend is required: your advice and why, in one line\" }\n if (!raisedBy) return { ok: false, error: \"raised_by is required: the agent id\" }\n if (title.length > CARD_LIMITS.title) return { ok: false, error: `title is longer than ${CARD_LIMITS.title} characters` }\n if (ask.length > CARD_LIMITS.ask) return { ok: false, error: `ask is longer than ${CARD_LIMITS.ask} characters` }\n if (recommend.length > CARD_LIMITS.recommend) return { ok: false, error: `recommend is longer than ${CARD_LIMITS.recommend} characters` }\n const ifSilentRaw = oneLine(input.if_silent).toLowerCase()\n const ifSilent = asIfSilent(ifSilentRaw)\n if (!ifSilent) {\n return { ok: false, error: `if_silent must be one of ${IF_SILENT_VALUES.join(\", \")}` }\n }\n const expiry = resolveExpiry(input.expires, now, settings)\n if (!expiry.ok) return expiry\n const source = oneLine(input.source)\n if (source.length > CARD_LIMITS.source) return { ok: false, error: `source is longer than ${CARD_LIMITS.source} characters` }\n if (source && /^[a-z][a-z0-9+.-]*:/i.test(source) && !/^https?:\\/\\//i.test(source)) {\n return { ok: false, error: \"source must be an http(s) link or a plain reference\" }\n }\n const extras = buildChoices(input)\n if (!extras.ok) return extras\n let reply: ReplyTarget | undefined\n const r = input.reply as Record<string, unknown> | undefined\n if (r && typeof r === \"object\" && oneLine(r.channel) && oneLine(r.chatId)) {\n reply = { channel: oneLine(r.channel), chatId: oneLine(r.chatId), ...(oneLine(r.accountId) ? { accountId: oneLine(r.accountId) } : {}) }\n }\n return {\n ok: true,\n card: {\n id: newCardId(now, title),\n title,\n ask,\n recommend,\n if_silent: ifSilent,\n ...(ifSilentRaw === \"approve\" ? { if_silent_asked: \"approve\" as const } : {}),\n expires: expiry.at,\n ...(source ? { source } : {}),\n raised_by: raisedBy,\n ...(opts.node ? { node: opts.node } : {}),\n created_at: new Date(now).toISOString(),\n ...(reply ? { reply } : {}),\n ...extras.value,\n // Set by the daemon only (check-ins), never from what an agent sent.\n ...(opts.origin ? { origin: opts.origin } : {}),\n status: \"pending\",\n },\n }\n}\n\n/** Validate, enforce the per-agent cap, and save. */\nexport function createCard(\n root: string,\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const built = buildCard(input, opts)\n if (!built.ok) return built\n // Retro cards are raised for an agent, not by it: they get their own\n // count, so they never use up the agent's room for its own cards.\n const isRetro = (c: { origin?: CardOrigin }) => c.origin?.kind === \"retro\"\n const retro = isRetro(built.card)\n const open = listCards(root, \"pending\").filter((c) => c.raised_by === built.card.raised_by && isRetro(c) === retro).length\n if (open >= CARD_LIMITS.pendingPerAgent) {\n const what = retro ? \"retro cards\" : \"cards\"\n return { ok: false, error: `${built.card.raised_by} already has ${open} ${what} waiting; wait for decisions before raising more` }\n }\n saveCard(root, built.card)\n return built\n}\n\n/** Record the operator's answer. Refuses anything no longer pending. */\nexport function decideCard(\n root: string,\n id: string,\n verdict: Verdict,\n opts: { by?: string; note?: string; now?: number; choice?: string | number; text?: string } = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, error: `no card \"${id}\"` }\n if (card.status !== \"pending\") return { ok: false, error: `card \"${id}\" is already ${card.status}` }\n const answer = resolveAnswer(card, verdict, opts)\n if (!answer.ok) return answer\n const note = oneLine(opts.note).slice(0, CARD_LIMITS.note)\n const decided: DecisionCard = {\n ...card,\n status: \"decided\",\n verdict,\n decided_by: opts.by ?? \"operator\",\n decided_at: new Date(opts.now ?? Date.now()).toISOString(),\n ...(note ? { note } : {}),\n ...(answer.choice ? { choice: answer.choice } : {}),\n ...(answer.text ? { text: answer.text } : {}),\n }\n saveCard(root, decided)\n return { ok: true, card: decided }\n}\n\n/** Apply `if_silent` to every pending card past its expiry. */\nexport function expireCards(root: string, now: number = Date.now()): DecisionCard[] {\n const out: DecisionCard[] = []\n for (const card of listCards(root, \"pending\")) {\n if (Date.parse(card.expires) > now) continue\n const expired: DecisionCard = {\n ...card,\n status: \"expired\",\n outcome: card.if_silent,\n decided_by: \"expiry\",\n decided_at: new Date(now).toISOString(),\n }\n saveCard(root, expired)\n out.push(expired)\n }\n return out\n}\n\n/** Decided or expired cards whose agent hasn't been told yet. */\nexport function cardsAwaitingAgentNotice(root: string): DecisionCard[] {\n return listCards(root).filter((c) => c.status !== \"pending\" && !c.agent_notified_at)\n}\n\nexport function markAgentNotified(root: string, id: string, now: number = Date.now()): void {\n const card = readCard(root, id)\n if (!card || card.agent_notified_at) return\n saveCard(root, { ...card, agent_notified_at: new Date(now).toISOString() })\n}\n\n/** What the raising agent is told. Plain text, one short message. */\nexport function verdictMessage(card: DecisionCard): string {\n const retro = card.origin?.kind === \"retro\" ? card.origin : undefined\n const result = card.status === \"decided\"\n ? (card.verdict === \"yes\"\n ? (retro && !retroApproved(card) ? `The operator picked \"${RETRO_NONE}\", which counts as NO.` : \"The operator said YES.\")\n : \"The operator said NO.\")\n : `Nobody answered before it expired, so the default applied: ${card.outcome ?? card.if_silent}.`\n const lines = [\n `[Approval result] Your decision card \"${card.title}\" (${card.id}) is closed.`,\n `Question: ${card.ask}`,\n result,\n ]\n // A retro card's pick and spec go through retroLines, labelled as the\n // reviewer's proposal: never \"Approved text (send exactly this)\".\n if (card.status === \"decided\" && card.verdict === \"yes\" && !retro) lines.push(...answerLines(card))\n if (card.note) lines.push(`Operator note: ${card.note}`)\n if (card.source) lines.push(`Source: ${card.source}`)\n if (card.origin?.kind === \"reminder\") lines.push(...originLines(card.origin, card.status === \"decided\" && card.verdict === \"yes\"))\n if (retro) {\n // Compare ignoring whitespace so a dashboard that only reflows the draft\n // does not resend the whole draft as the operator's note.\n const squash = (s: string) => s.replace(/\\s+/g, \" \").trim()\n const draft = draftFor(card.draft, card.choice)\n const edited = card.text && squash(card.text) !== squash(draft) ? card.text : undefined\n lines.push(...retroLines(retro, card, edited))\n }\n if (card.reply) lines.push(`You raised it from ${card.reply.channel} chat ${card.reply.chatId}; reply there if the requester should know.`)\n if (card.node) lines.push(`The operator answered it on another machine; the card was forwarded from ${card.node}.`)\n lines.push(\"Act on this result now. Do not raise the same card again.\")\n return lines.join(\"\\n\")\n}\n","// --- Where a card came from, when the daemon raised it ---\n//\n// Agents raise most cards themselves. A check-in (checkin.ts) raises one on\n// an agent's behalf for an open Apple Reminder, and records the reminder\n// here so the agent that gets the answer knows what to act on and what to\n// tick off. Only the daemon sets it: POST /approvals and the agent tool\n// never pass it through.\n\nexport interface ReminderOrigin {\n kind: \"reminder\"\n /** The reminder's full id, as remindctl prints it. */\n id: string\n title: string\n list?: string\n}\n\n/** An open request that needs attention, shown as a card on the Mac\n * (popup-runner.ts). Never stored: the request is the record. */\nexport interface RequestOrigin {\n kind: \"request\"\n id: string\n}\n\n/** A retro card (src/retro): fixes to the agents' environment proposed\n * from one run that struggled. The answer goes back to the agent that ran\n * it, which builds the picked fix for a second review. */\nexport interface RetroOrigin {\n kind: \"retro\"\n /** The run the retro read. */\n taskId: string\n /** Failure signature (wiki/failure-candidates.ts), for one card per signature. */\n signature: string\n /** The reviewer's spec for each fix, in the order of the card's choices\n * (without \"None of these\"). Only the picked one reaches the agent. */\n specs?: string[]\n}\n\nexport type CardOrigin = ReminderOrigin | RequestOrigin | RetroOrigin\n\n/** True when the operator answered a retro card with something to build:\n * YES and a fix picked. YES on \"None of these\" counts as NO. */\nexport function retroApproved(card: { status: string; verdict?: string; choice?: string }): boolean {\n return card.status === \"decided\" && card.verdict === \"yes\" && !!card.choice && card.choice !== RETRO_NONE\n}\n\n/** Lines for the agent told the result of a retro card. Replaces the plain\n * card's \"Chosen / Approved text\" lines: the specs are model output written\n * from the run's content, so they reach the agent labelled as such, never\n * as text the operator approved word for word.\n * `edited` is the operator's text when they changed the suggested one. */\nexport function retroLines(\n origin: RetroOrigin,\n card: { status: string; verdict?: string; choice?: string; choices?: string[] },\n edited?: string,\n): string[] {\n const lines = [`This was a retro card about run ${origin.taskId} (\\`agentx trace show ${origin.taskId}\\`).`]\n if (!retroApproved(card)) {\n lines.push(\"Change nothing. Do not propose these fixes again on your own.\")\n return lines\n }\n lines.push(`The operator picked this fix: ${card.choice}`)\n const spec = origin.specs?.[(card.choices ?? []).indexOf(card.choice!)]\n if (spec) {\n lines.push(\n \"Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):\",\n spec,\n )\n }\n if (edited) lines.push(\"The operator's note on the fix:\", edited)\n lines.push(\n \"Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.\",\n \"Do not apply it to a live system directly. Tag what you add with `retro:\" + origin.taskId + \"` so it can be found and removed later.\",\n )\n return lines\n}\n\n/** The last choice on every retro card. */\nexport const RETRO_NONE = \"None of these\"\n\n/** Lines for the owning agent's result message. */\nexport function originLines(origin: ReminderOrigin, approved: boolean): string[] {\n const where = origin.list ? ` in the \"${origin.list}\" list` : \"\"\n const lines = [`This card came from the operator's reminder \"${origin.title}\"${where} (id ${origin.id}).`]\n lines.push(approved\n ? `Do what the operator chose, then tick the reminder off: remindctl complete ${origin.id}`\n : \"Leave the reminder open; it will come back at a later check-in.\")\n return lines\n}\n"],"mappings":"6DAAA,OAAS,cAAAA,EAAY,aAAAC,EAAW,eAAAC,EAAa,gBAAAC,EAAc,cAAAC,EAAY,iBAAAC,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D,EAAK,OAAQA,EAAK,SAAW,WAAaA,EAAK,UAAY,KAAK,CAAC,EAC7HyC,EAAO,CAGT,IAAMoB,EAAUC,GAAcA,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EACpDC,EAAQC,EAAShE,EAAK,MAAOA,EAAK,MAAM,EACxCiE,EAASjE,EAAK,MAAQ6D,EAAO7D,EAAK,IAAI,IAAM6D,EAAOE,CAAK,EAAI/D,EAAK,KAAO,OAC9E0D,EAAM,KAAK,GAAGQ,EAAWzB,EAAOzC,EAAMiE,CAAM,CAAC,EAE/C,OAAIjE,EAAK,OAAO0D,EAAM,KAAK,sBAAsB1D,EAAK,MAAM,gBAAgBA,EAAK,MAAM,mDAAmD,EACtIA,EAAK,MAAM0D,EAAM,KAAK,4EAA4E1D,EAAK,OAAO,EAClH0D,EAAM,KAAK,2DAA2D,EAC/DA,EAAM,KAAK;AAAA,CAAI,CACxB","names":["existsSync","mkdirSync","readdirSync","readFileSync","renameSync","writeFileSync","resolve","retroApproved","card","RETRO_NONE","retroLines","origin","edited","lines","spec","originLines","approved","where","IF_SILENT_VALUES","asIfSilent","v","CARD_LIMITS","DEFAULT_CARD_SETTINGS","approvalsDir","root","resolve","CARD_ID_RE","isValidCardId","id","fileFor","newCardId","now","title","day","slug","saveCard","card","mkdirSync","path","tmp","writeFileSync","renameSync","readCard","readFileSync","legacy","listCards","status","dir","existsSync","out","f","readdirSync","c","oneLine","resolveExpiry","input","settings","max","at","raw","rel","buildCard","opts","ask","recommend","raisedBy","ifSilentRaw","ifSilent","expiry","source","extras","buildChoices","reply","r","createCard","built","isRetro","retro","open","what","decideCard","verdict","answer","resolveAnswer","note","decided","expireCards","expired","cardsAwaitingAgentNotice","markAgentNotified","verdictMessage","result","retroApproved","RETRO_NONE","lines","answerLines","originLines","squash","s","draft","draftFor","edited","retroLines"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/wiki/query.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { buildIndex, scoreAll } from \"@/memory/bm25\"\nimport { askSeat } from \"@/decisions/seat\"\nimport { ancestryScore } from \"@/graph\"\nimport {\n DEFAULT_SHORTLIST,\n WIKI_RERANK_SEAT,\n rerankQuestions,\n rerankState,\n toRanking,\n type RerankCandidate,\n} from \"@/decisions/seats/wiki-rerank\"\nimport { stripAnthropicApiKey } from \"@/utils/workspace-env\"\nimport { resolve } from \"path\"\nimport { execSync } from \"child_process\"\nimport type { WikiArticle } from \"./types\"\nimport type { WikiStore } from \"./store\"\n\n/**\n * Agentic wiki query — the \"Farzapedia-faithful\" retrieval path.\n *\n * Two LLM calls + a deterministic graph walk:\n * 1. Selector (cheap): read `_index.md` + question → pick up to `maxCandidates`\n * candidate articles by title + type.\n * 2. Walk (pure code): starting from candidates, follow `related` wikilinks\n * up to `maxHops`, capped at `maxArticles` total.\n * 3. Synthesis (main): answer the question from the walked subgraph.\n *\n * Returns an answer with citations and a trace of which articles were walked,\n * so callers can audit the retrieval path.\n */\n\nexport interface AgenticQueryOptions {\n /** Candidate-selection model (cheap). Defaults to \"haiku\". */\n selectorModel?: string\n /** Synthesis model (main). Defaults to \"sonnet\". */\n synthModel?: string\n /** Number of candidates the selector is asked to return. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from candidates. Default 2. */\n maxHops?: number\n /** Hard cap on total articles walked. Default 8. */\n maxArticles?: number\n /** Timeout per LLM call, ms. Default 60_000. */\n timeoutMs?: number\n /** Logger — defaults to console.error. */\n log?: (...args: unknown[]) => void\n /** Intent-graph path the question's request was classified under.\n * Articles on the same branch rank higher in candidate selection. */\n messagePath?: string[]\n /** Weight of the branch match against the text match, 0–1. Default 0.6\n * (`graph.retrievalWeights.graph`). */\n graphWeight?: number\n}\n\nexport interface AgenticQueryResult {\n answer: string\n citations: Array<{ title: string; path: string; type?: string }>\n /** Titles/paths the selector picked. */\n candidates: Array<{ title: string; path: string }>\n /** Full article subgraph the walk produced. */\n walked: Array<{ title: string; path: string; type?: string; hop: number }>\n /** \"no-catalog\" | \"no-candidates\" | \"ok\" */\n status: \"ok\" | \"no-catalog\" | \"no-candidates\" | \"error\"\n /** For operator debugging only. */\n trace?: {\n selectorMs: number\n synthesisMs: number\n selectorOutput?: string\n }\n error?: string\n}\n\n/**\n * Run an agentic query against a specific agent's WikiStore.\n *\n * `requesterId` is used for permission checks — only articles the requester\n * can read will be included in the synthesis input.\n */\nexport async function agenticQuery(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: AgenticQueryOptions = {},\n): Promise<AgenticQueryResult> {\n const selectorModel = opts.selectorModel ?? \"haiku\"\n const synthModel = opts.synthModel ?? \"sonnet\"\n const maxCandidates = opts.maxCandidates ?? 3\n const maxHops = opts.maxHops ?? 2\n const maxArticles = opts.maxArticles ?? 8\n const timeoutMs = opts.timeoutMs ?? 60_000\n const log = opts.log ?? console.error.bind(console, \"[wiki-query]\")\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n\n // --- Step 1: Load the catalog ---\n const catalogPath = resolve(store.baseDir, \"_index.md\")\n if (!existsSync(catalogPath)) {\n return emptyResult(\"no-catalog\", question, \"No _index.md found — run `agentx wiki status` to rebuild.\")\n }\n const catalog = readFileSync(catalogPath, \"utf-8\")\n\n // --- Step 2: Selector — pick candidates ---\n const selectorStart = Date.now()\n let candidates: Array<{ title: string; path: string }> = []\n let selectorOutput = \"\"\n try {\n const viaSeat = await selectCandidatesViaSeat(question, store, requesterId, maxCandidates, messagePath, graphWeight)\n if (viaSeat) {\n candidates = viaSeat\n selectorOutput = `[wiki-rerank seat] ${viaSeat.map((c) => c.title).join(\" | \")}`\n } else {\n selectorOutput = await runClaude(\n buildSelectorPrompt(question, catalog, maxCandidates, messagePath),\n selectorModel,\n timeoutMs,\n )\n candidates = parseCandidates(selectorOutput)\n }\n } catch (e: any) {\n log(\"selector failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Selector: ${e?.message || \"unknown\"}`), trace: { selectorMs: Date.now() - selectorStart, synthesisMs: 0, selectorOutput } }\n }\n const selectorMs = Date.now() - selectorStart\n\n if (candidates.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Selector returned no candidates.\"), trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 3: Walk the subgraph via `related` wikilinks ---\n const walked = walkSubgraph(candidates, store, requesterId, maxHops, maxArticles)\n\n if (walked.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Candidates did not resolve to readable articles.\"), candidates, trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 4: Synthesize the answer ---\n const synthStart = Date.now()\n let answer = \"\"\n try {\n answer = await runClaude(\n buildSynthesisPrompt(question, walked),\n synthModel,\n timeoutMs * 2,\n )\n } catch (e: any) {\n log(\"synthesis failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Synthesis: ${e?.message || \"unknown\"}`), candidates, walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })), trace: { selectorMs, synthesisMs: Date.now() - synthStart, selectorOutput } }\n }\n const synthesisMs = Date.now() - synthStart\n\n return {\n answer: answer.trim(),\n citations: walked.map(a => ({ title: a.meta.title, path: a.path, type: a.meta.type })),\n candidates,\n walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })),\n status: \"ok\",\n trace: { selectorMs, synthesisMs, selectorOutput },\n }\n}\n\n// --- Helpers ---\n\nfunction emptyResult(\n status: AgenticQueryResult[\"status\"],\n _question: string,\n error?: string,\n): AgenticQueryResult {\n return {\n answer: \"\",\n citations: [],\n candidates: [],\n walked: [],\n status,\n error,\n }\n}\n\nfunction walkSubgraph(\n candidates: Array<{ title: string; path: string }>,\n store: WikiStore,\n requesterId: string | undefined,\n maxHops: number,\n maxArticles: number,\n): Array<WikiArticle & { hop: number }> {\n // Build a title → path index from the store so wikilinks resolve.\n const titleIndex = new Map<string, string>()\n for (const article of store.listArticles(requesterId || \"\")) {\n titleIndex.set(article.meta.title.toLowerCase(), article.path)\n }\n\n const opened = new Map<string, WikiArticle & { hop: number }>()\n let frontier: Array<{ path: string; hop: number }> = []\n\n for (const c of candidates) {\n if (!opened.has(c.path)) frontier.push({ path: c.path, hop: 0 })\n }\n\n while (frontier.length && opened.size < maxArticles) {\n const next = frontier.shift()!\n if (opened.has(next.path)) continue\n if (next.hop > maxHops) continue\n\n const article = requesterId\n ? store.readArticleAs(next.path, requesterId)\n : store.readArticle(next.path)\n if (!article) continue\n\n opened.set(next.path, { ...article, hop: next.hop })\n if (next.hop >= maxHops) continue\n\n for (const target of article.meta.related || []) {\n const path = titleIndex.get(target.toLowerCase())\n if (path && !opened.has(path)) {\n frontier.push({ path, hop: next.hop + 1 })\n }\n }\n }\n\n return Array.from(opened.values())\n}\n\n// --- Prompts ---\n\n/**\n * Pick candidates with the wiki-rerank seat instead of a Claude CLI call.\n *\n * The selector is 56% of a wiki query — 14.1s of a 25s total, measured —\n * and its whole job is \"pick 3 articles from this catalog\", which is a\n * Choice with per-option probabilities. Jev answers that in about a\n * second. Synthesis stays on Sonnet; it writes prose, which Jev cannot.\n *\n * BM25 shortlists first because the shared catalog carries 971 entries,\n * past the 255-option cap. Same two-stage shape as findRelevantReranked,\n * and it reuses that seat rather than introducing a second one.\n *\n * Returns null whenever the seat is off, errors, or has nothing to rank,\n * and the caller falls back to the CLI selector — so this is strictly an\n * accelerator, never a new way to fail.\n */\nasync function selectCandidatesViaSeat(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n maxCandidates: number,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): Promise<Array<{ title: string; path: string }> | null> {\n try {\n const index = store.rebuildIndex()\n const pool = (index.articles ?? []).filter((a) => a.path && !a.path.includes(\"/_versions/\"))\n if (pool.length < 2) return null\n\n const shortlist = rankCatalogPool(question, pool, messagePath, graphWeight).slice(0, DEFAULT_SHORTLIST)\n\n const candidates: RerankCandidate[] = shortlist.map((i) => ({\n id: `k${i}`,\n title: pool[i].title || pool[i].path,\n tags: pool[i].tags,\n // The catalog has no body — a title, its type, its wikilinks and its\n // branch of the intent graph are what the selector chooses on.\n excerpt: [\n pool[i].type ? `type: ${pool[i].type}` : \"\",\n (pool[i].related ?? []).length ? `related: ${(pool[i].related ?? []).join(\", \")}` : \"\",\n (pool[i].graphPath ?? []).length ? `graph: ${(pool[i].graphPath ?? []).join(\" › \")}` : \"\",\n ].filter(Boolean).join(\" · \"),\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query: question, candidates, excerptChars: 300 }),\n rerankQuestions(candidates),\n { features: { agent: requesterId ?? \"unknown\", stage: \"catalog-selector\" } },\n )\n if (!result || result.mode !== \"active\") return null\n\n const ranking = toRanking(result.answers as never, candidates)\n const picked = ranking.ranked\n .slice(0, maxCandidates)\n .map((id) => pool[Number(id.slice(1))])\n .filter(Boolean)\n .map((a) => ({ title: a.title, path: a.path }))\n return picked.length > 0 ? picked : null\n } catch {\n return null\n }\n}\n\n/** Weight of the intent-graph branch match against the text match when\n * shortlisting catalog candidates. Mirrors `graph.retrievalWeights.graph`. */\nexport const DEFAULT_GRAPH_WEIGHT = 0.6\n\n/**\n * Order the catalog pool for a question. Three bands, never mixed:\n *\n * 1. articles the text match scored, ordered by `text * (1 + w * branch)`\n * when the request was classified: the branch reorders text matches\n * but cannot lift an unrelated article above one;\n * 2. articles on the request's branch that the text never matched, by\n * how much of the path they share;\n * 3. the rest, in catalog order.\n *\n * Band 1 comes first in full because the shortlist the reranker sees is\n * finite (DEFAULT_SHORTLIST): a busy category holds more same-branch\n * articles than that, and a blended score let them push the article that\n * actually answers the question out of the list.\n *\n * Exported for tests; the seat and the CLI selector both consume the order.\n */\nexport function rankCatalogPool(\n question: string,\n pool: Array<{ title: string; tags?: string[]; related?: string[]; graphPath?: string[] }>,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): number[] {\n const docs = pool.map((a) =>\n [a.title, (a.tags ?? []).join(\" \"), (a.related ?? []).join(\" \")].join(\" \"),\n )\n const bm25 = scoreAll(question, buildIndex(docs))\n const maxBm25 = bm25.reduce((m, r) => Math.max(m, r.score), 0)\n const text = new Map(bm25.map((r) => [r.docIndex, maxBm25 > 0 ? r.score / maxBm25 : 0]))\n const useGraph = !!messagePath?.length\n const branch = (a: { graphPath?: string[] }) =>\n useGraph && a.graphPath?.length ? ancestryScore(messagePath!, a.graphPath) : 0\n\n const byScore = (x: { i: number; score: number }, y: { i: number; score: number }) => y.score - x.score || x.i - y.i\n const matched = pool\n .map((a, i) => ({ i, score: (text.get(i) ?? 0) * (1 + graphWeight * branch(a)) }))\n .filter((c) => text.has(c.i))\n .sort(byScore)\n const branchOnly = pool\n .map((a, i) => ({ i, score: branch(a) }))\n .filter((c) => !text.has(c.i) && c.score > 0)\n .sort(byScore)\n const ranked = [...matched, ...branchOnly].map((c) => c.i)\n for (let i = 0; i < pool.length; i++) if (!ranked.includes(i)) ranked.push(i)\n return ranked\n}\n\nfunction buildSelectorPrompt(question: string, catalog: string, maxCandidates: number, messagePath?: string[]): string {\n const branch = messagePath?.length\n ? `\\n## Intent\\n\\nThe request was classified under the intent-graph path \"${messagePath.join(\" › \")}\". Prefer articles filed under the same branch when their titles are equally plausible.\\n`\n : \"\"\n return `You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.\n\n## Question\n\n${question}\n${branch}\n## Catalog (_index.md — articles grouped by type, with wikilink previews)\n\n${catalog}\n\n## Your task\n\nPick up to ${maxCandidates} articles from the catalog that are most likely to answer the question. Prefer:\n- Articles whose title directly names a subject in the question.\n- Articles of the right type (e.g. a \"who owns X\" question → person or project; a \"what happened on DATE\" → event).\n- Articles whose wikilinks suggest they sit at the center of a relevant subgraph.\n\nReturn ONLY valid JSON, no markdown fencing, no prose:\n\n[\n {\"title\": \"Exact Article Title\", \"path\": \"path/from/catalog.md\"},\n ...\n]\n\nIf none of the articles match, return [].`\n}\n\nfunction buildSynthesisPrompt(\n question: string,\n articles: Array<WikiArticle & { hop: number }>,\n): string {\n const articlesBlock = articles\n .map(a => {\n const header = `### ${a.meta.title} — ${a.meta.type || \"untyped\"} (${a.path}) [hop ${a.hop}]`\n const related = a.meta.related?.length ? `Related: ${a.meta.related.join(\", \")}` : \"\"\n return [header, related, \"\", a.content].filter(Boolean).join(\"\\n\")\n })\n .join(\"\\n\\n---\\n\\n\")\n\n return `You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.\n\n## Question\n\n${question}\n\n## Articles (${articles.length} walked from the catalog)\n\n${articlesBlock}\n\n## Your task\n\nAnswer the question in 2–6 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.\n\nOutput ONLY the answer — no preamble, no \"here is my answer:\", no markdown fencing.`\n}\n\nfunction parseCandidates(raw: string): Array<{ title: string; path: string }> {\n const match = raw.match(/\\[[\\s\\S]*?\\]/)\n if (!match) return []\n try {\n const parsed = JSON.parse(match[0])\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter((x: any) => x && typeof x.title === \"string\" && typeof x.path === \"string\")\n .map((x: any) => ({ title: x.title, path: x.path }))\n } catch {\n return []\n }\n}\n\nasync function runClaude(prompt: string, model: string, timeoutMs: number): Promise<string> {\n // Use stdin via a temp-file pipe to avoid shell-escaping a huge prompt.\n // Prompts can exceed the `-E` arg buffer on macOS, so we always pipe.\n const { writeFileSync, mkdirSync, rmSync } = await import(\"fs\")\n const { tmpdir } = await import(\"os\")\n const dir = resolve(tmpdir(), `agentx-wiki-query-${process.pid}`)\n mkdirSync(dir, { recursive: true })\n const promptPath = resolve(dir, `prompt-${Date.now()}.txt`)\n writeFileSync(promptPath, prompt)\n try {\n const cmd = `cat '${promptPath}' | claude -p - --output-format json --max-turns 1 --model ${model} --disallowedTools \"Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit\"`\n const raw = execSync(cmd, { env: stripAnthropicApiKey({ ...process.env }), encoding: \"utf-8\", timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 })\n try {\n const envelope = JSON.parse(raw)\n return String(envelope.result || envelope.content || \"\")\n } catch {\n return raw\n }\n } finally {\n try { rmSync(promptPath, { force: true }) } catch {}\n }\n}\n"],"mappings":"iNAAA,OAAS,gBAAAA,EAAc,cAAAC,MAAkB,KAEzCC,IAWA,OAAS,WAAAC,MAAe,OACxB,OAAS,YAAAC,MAAgB,gBAiEzB,eAAsBC,GACpBC,EACAC,EACAC,EACAC,EAA4B,CAAC,EACA,CAC7B,IAAMC,EAAgBD,EAAK,eAAiB,QACtCE,EAAaF,EAAK,YAAc,SAChCG,EAAgBH,EAAK,eAAiB,EACtCI,EAAUJ,EAAK,SAAW,EAC1BK,EAAcL,EAAK,aAAe,EAClCM,EAAYN,EAAK,WAAa,IAC9BO,EAAMP,EAAK,KAAO,QAAQ,MAAM,KAAK,QAAS,cAAc,EAC5DQ,EAAcR,EAAK,aAAa,OAASA,EAAK,YAAc,OAC5DS,EAAcT,EAAK,aAAeU,EAGlCC,EAAcjB,EAAQI,EAAM,QAAS,WAAW,EACtD,GAAI,CAACc,EAAWD,CAAW,EACzB,OAAOE,EAAY,aAAchB,EAAU,gEAA2D,EAExG,IAAMiB,EAAUC,EAAaJ,EAAa,OAAO,EAG3CK,EAAgB,KAAK,IAAI,EAC3BC,EAAqD,CAAC,EACtDC,EAAiB,GACrB,GAAI,CACF,IAAMC,EAAU,MAAMC,EAAwBvB,EAAUC,EAAOC,EAAaI,EAAeK,EAAaC,CAAW,EAC/GU,GACFF,EAAaE,EACbD,EAAiB,sBAAsBC,EAAQ,IAAKE,GAAMA,EAAE,KAAK,EAAE,KAAK,KAAK,MAE7EH,EAAiB,MAAMI,EACrBC,EAAoB1B,EAAUiB,EAASX,EAAeK,CAAW,EACjEP,EACAK,CACF,EACAW,EA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,CACF,QAAE,CACA,GAAI,CAAEO,EAAOG,EAAY,CAAE,MAAO,EAAK,CAAC,CAAE,MAAE,CAAO,CACrD,CACF","names":["readFileSync","existsSync","init_seat","resolve","execSync","agenticQuery","question","store","requesterId","opts","selectorModel","synthModel","maxCandidates","maxHops","maxArticles","timeoutMs","log","messagePath","graphWeight","DEFAULT_GRAPH_WEIGHT","catalogPath","existsSync","emptyResult","catalog","readFileSync","selectorStart","candidates","selectorOutput","viaSeat","selectCandidatesViaSeat","c","runClaude","buildSelectorPrompt","parseCandidates","e","selectorMs","walked","walkSubgraph","synthStart","answer","buildSynthesisPrompt","w","synthesisMs","a","status","_question","error","titleIndex","article","opened","frontier","next","target","path","pool","rankCatalogPool","DEFAULT_SHORTLIST","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","picked","toRanking","id","docs","bm25","scoreAll","buildIndex","maxBm25","m","r","text","useGraph","branch","ancestryScore","byScore","x","y","matched","i","branchOnly","ranked","articles","articlesBlock","header","related","raw","match","parsed","prompt","model","writeFileSync","mkdirSync","rmSync","tmpdir","dir","promptPath","cmd","stripAnthropicApiKey","envelope"]}
|