agentix-cli 0.201.0 → 0.202.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-UHSMBGRE.js → App-FQRHQT5J.js} +2 -2
- package/dist/{ChatApp-Z6YVST7J.js → ChatApp-WBCGSGJM.js} +2 -2
- package/dist/{absorb-eval-4GDAAYBL.js → absorb-eval-3IU37HZQ.js} +2 -2
- package/dist/{adapter-IITFGDOV.js → adapter-URFSOOFE.js} +2 -2
- package/dist/agent-P7XUCP3A.js +2 -0
- package/dist/{board-dashboard-QXYD62AT.js → board-dashboard-CXFXO5XU.js} +1058 -468
- package/dist/board-dashboard-CXFXO5XU.js.map +1 -0
- package/dist/chunk-36X7D4JA.js +2 -0
- package/dist/chunk-36X7D4JA.js.map +1 -0
- package/dist/{chunk-OD2GONCQ.js → chunk-5VD2J4JN.js} +2 -2
- package/dist/chunk-7NQQIDDI.js +2 -0
- package/dist/chunk-7NQQIDDI.js.map +1 -0
- package/dist/chunk-7QW4RECS.js +2 -0
- package/dist/chunk-7QW4RECS.js.map +1 -0
- package/dist/chunk-BYEL7KKR.js +13 -0
- package/dist/chunk-BYEL7KKR.js.map +1 -0
- package/dist/{chunk-S5A7QZVQ.js → chunk-C2VZHIIX.js} +2 -2
- package/dist/{chunk-EFGAPAYZ.js → chunk-CAYY2IEV.js} +2 -2
- package/dist/{chunk-XDFPXEXU.js → chunk-CJI26AJC.js} +3 -3
- package/dist/{chunk-HUN2UIYB.js → chunk-EMWSFITR.js} +2 -2
- package/dist/{chunk-4LUZO3AP.js → chunk-EQPMQSJE.js} +2 -2
- package/dist/{chunk-ORICHN2H.js → chunk-FCDMB2JA.js} +76 -74
- package/dist/chunk-FCDMB2JA.js.map +1 -0
- package/dist/chunk-FOWRNDMJ.js +2 -0
- package/dist/chunk-FOWRNDMJ.js.map +1 -0
- package/dist/chunk-GDHSJH3T.js +111 -0
- package/dist/chunk-GDHSJH3T.js.map +1 -0
- package/dist/{chunk-MXB47GPG.js → chunk-HX4R7RPR.js} +2 -2
- package/dist/{chunk-TTHY22I4.js → chunk-IAR5F3T5.js} +2 -2
- package/dist/{chunk-2BK25FAQ.js → chunk-JKT5EFXT.js} +2 -2
- package/dist/{chunk-2BK25FAQ.js.map → chunk-JKT5EFXT.js.map} +1 -1
- package/dist/chunk-JLBRNYKY.js +2 -0
- package/dist/chunk-JLBRNYKY.js.map +1 -0
- package/dist/{chunk-2N6LROEF.js → chunk-JUSQMQ7L.js} +2 -2
- package/dist/{chunk-KUAJUHMB.js → chunk-M4VYHPDS.js} +2 -2
- package/dist/{chunk-YHLKEGIC.js → chunk-MAQFWGFT.js} +2 -2
- package/dist/{chunk-VVFJCGX7.js → chunk-N6NZBAWR.js} +2 -2
- package/dist/{chunk-O62HITS4.js → chunk-P65XGEB7.js} +2 -2
- package/dist/{chunk-5TW7QEVK.js → chunk-PSOE356C.js} +25 -25
- package/dist/{chunk-5TW7QEVK.js.map → chunk-PSOE356C.js.map} +1 -1
- package/dist/chunk-Q3A5P373.js +3 -0
- package/dist/chunk-Q3A5P373.js.map +1 -0
- package/dist/{chunk-NDBM7DTN.js → chunk-QOEO27LF.js} +2 -2
- package/dist/{chunk-T4BWPILH.js → chunk-RB7M2NPU.js} +2 -2
- package/dist/chunk-RIBANO2H.js +118 -0
- package/dist/chunk-RIBANO2H.js.map +1 -0
- package/dist/{chunk-BTI3OUFH.js → chunk-RUNCUVAH.js} +2 -2
- package/dist/{chunk-FLSEPYM3.js → chunk-SLX3OHEW.js} +2 -2
- package/dist/chunk-SY7R5N7U.js +7 -0
- package/dist/chunk-SY7R5N7U.js.map +1 -0
- package/dist/{chunk-KAAAB3W3.js → chunk-T7WY5BSJ.js} +85 -85
- package/dist/chunk-T7WY5BSJ.js.map +1 -0
- package/dist/{chunk-XPL6F4HL.js → chunk-TV5BDCQA.js} +2 -2
- package/dist/chunk-U2WAIDSM.js +2 -0
- package/dist/chunk-U2WAIDSM.js.map +1 -0
- package/dist/{chunk-H6FFWHJH.js → chunk-V3FSKTDF.js} +2 -2
- package/dist/{chunk-LCVKEIG2.js → chunk-VGYW3Q7F.js} +2 -2
- package/dist/{chunk-7TO4QLFS.js → chunk-WIGH5WMP.js} +57 -64
- package/dist/chunk-WIGH5WMP.js.map +1 -0
- package/dist/{chunk-EVRLNHIC.js → chunk-WKR2OSCH.js} +2 -2
- package/dist/{chunk-LPSDAS22.js → chunk-Y2D6FQBL.js} +2 -2
- package/dist/{chunk-5OREKHSP.js → chunk-Z6KAK22L.js} +312 -312
- package/dist/chunk-Z6KAK22L.js.map +1 -0
- package/dist/{chunk-QCCVHEKZ.js → chunk-ZPCSPEGO.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/client-EOQLSAUW.js +2 -0
- package/dist/{config-QBTOYJA7.js → config-SZZQFIJF.js} +2 -2
- package/dist/config-mutate-66VDWR46.js +2 -0
- package/dist/config-mutator-OILDQCAJ.js +2 -0
- package/dist/connect-JIWRIGVI.js +2 -0
- package/dist/connect-JIWRIGVI.js.map +1 -0
- package/dist/{contributions-OOPYQSLO.js → contributions-LRQCDZCQ.js} +2 -2
- package/dist/daemon-api-JBXTSPB6.js +2 -0
- package/dist/daemon-api-JBXTSPB6.js.map +1 -0
- package/dist/doctor-QASDCIQ5.js +2 -0
- package/dist/dotenv-DGZD3EDY.js +2 -0
- package/dist/{enrich-MZMIQ3SV.js → enrich-NIUEEGPA.js} +2 -2
- package/dist/{event-levels-PCFARGKL.js → event-levels-D6QSANGF.js} +2 -2
- package/dist/{follow-up-tool-K252F4QA.js → follow-up-tool-QOO2TIQS.js} +2 -2
- package/dist/hub-6TKU6CHO.js +2 -0
- package/dist/index.d.ts +373 -47
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/keyring-EKFUNQAO.js +2 -0
- package/dist/oauth-7J7DJMKN.js +2 -0
- package/dist/open-browser-BTEYT7G4.js +2 -0
- package/dist/{program-3NLSKRKW.js → program-L2ZLEJAO.js} +296 -290
- package/dist/program-L2ZLEJAO.js.map +1 -0
- package/dist/{promote-GWDQR2DT.js → promote-D3KYLUBD.js} +2 -2
- package/dist/providers-P76CWTGQ.js +2 -0
- package/dist/push-bridge-T5HZZRA2.js +1 -1
- package/dist/{query-PYJN4G32.js → query-D2TQ2PUO.js} +2 -2
- package/dist/{query-settings-XFOY343Z.js → query-settings-ILDX3HDF.js} +2 -2
- package/dist/registry-N3BY3HSI.js +2 -0
- package/dist/{request-planner-DP3PIMNQ.js → request-planner-CVCG5XQR.js} +2 -2
- package/dist/resolve-JKXYBZ6R.js +2 -0
- package/dist/{review-candidates-5HRRFPEG.js → review-candidates-CKUN4PSY.js} +2 -2
- package/dist/routing-OCIRGUKK.js +2 -0
- package/dist/{rules-FBOLGE2S.js → rules-A5ES57QT.js} +2 -2
- package/dist/schedule-tool-YFMRYTEO.js +2 -0
- package/dist/schedule-tool-YFMRYTEO.js.map +1 -0
- package/dist/scheduler-D2Z7RSEE.js +2 -0
- package/dist/scheduler-D2Z7RSEE.js.map +1 -0
- package/dist/{seat-2RFBH5N2.js → seat-Z3E2FLDA.js} +2 -2
- package/dist/seat-Z3E2FLDA.js.map +1 -0
- package/dist/{select-MOZ2GNNR.js → select-J4ES7Q67.js} +2 -2
- package/dist/{set-enabled-IFK2TCH5.js → set-enabled-S22TICYC.js} +2 -2
- package/dist/{sprint-tool-WB2M7RHX.js → sprint-tool-NDF47EKV.js} +2 -2
- package/dist/status-PKHYFGZK.js +2 -0
- package/dist/status-PKHYFGZK.js.map +1 -0
- package/dist/{tool-57ZGZ7BD.js → tool-52JRXZVA.js} +2 -2
- package/dist/tool-6NZIUXI7.js +4 -0
- package/dist/tool-6NZIUXI7.js.map +1 -0
- package/dist/{tool-CMHNG2PN.js → tool-RCCMOMEY.js} +2 -2
- package/dist/{tool-SKQNMJP2.js → tool-Z2OVFGWW.js} +2 -2
- package/dist/wiki-HQKFZZSX.js +2 -0
- package/dist/wiki-HQKFZZSX.js.map +1 -0
- package/dist/wiki-enrich-7SZ5W2LF.js +2 -0
- package/dist/wiki-enrich-7SZ5W2LF.js.map +1 -0
- package/dist/workspace-setup-W5UO2WZI.js +2 -0
- package/dist/workspace-setup-W5UO2WZI.js.map +1 -0
- package/package.json +1 -1
- package/dist/agent-T7HRXIBL.js +0 -2
- package/dist/board-dashboard-QXYD62AT.js.map +0 -1
- package/dist/chunk-5OREKHSP.js.map +0 -1
- package/dist/chunk-6YWB3XTT.js +0 -7
- package/dist/chunk-6YWB3XTT.js.map +0 -1
- package/dist/chunk-7TO4QLFS.js.map +0 -1
- package/dist/chunk-AV7T3SYT.js +0 -111
- package/dist/chunk-AV7T3SYT.js.map +0 -1
- package/dist/chunk-KAAAB3W3.js.map +0 -1
- package/dist/chunk-ORICHN2H.js.map +0 -1
- package/dist/chunk-YV2SLQIL.js +0 -118
- package/dist/chunk-YV2SLQIL.js.map +0 -1
- package/dist/client-HJBH2DVH.js +0 -2
- package/dist/config-mutate-G46QCYCR.js +0 -2
- package/dist/config-mutator-3FGEZPF3.js +0 -2
- package/dist/doctor-2KOQNH44.js +0 -2
- package/dist/hub-E56MSG7W.js +0 -2
- package/dist/program-3NLSKRKW.js.map +0 -1
- package/dist/registry-EMB3QRRL.js +0 -2
- package/dist/routing-LX5QYMZW.js +0 -2
- package/dist/schedule-tool-HD72JVUS.js +0 -2
- package/dist/scheduler-UN5ZPEK4.js +0 -2
- package/dist/wiki-K77I5LJP.js +0 -2
- package/dist/wiki-enrich-PK5XQCV3.js +0 -2
- package/dist/workspace-setup-HAV4CQV7.js +0 -2
- /package/dist/{App-UHSMBGRE.js.map → App-FQRHQT5J.js.map} +0 -0
- /package/dist/{ChatApp-Z6YVST7J.js.map → ChatApp-WBCGSGJM.js.map} +0 -0
- /package/dist/{absorb-eval-4GDAAYBL.js.map → absorb-eval-3IU37HZQ.js.map} +0 -0
- /package/dist/{adapter-IITFGDOV.js.map → adapter-URFSOOFE.js.map} +0 -0
- /package/dist/{agent-T7HRXIBL.js.map → agent-P7XUCP3A.js.map} +0 -0
- /package/dist/{chunk-OD2GONCQ.js.map → chunk-5VD2J4JN.js.map} +0 -0
- /package/dist/{chunk-S5A7QZVQ.js.map → chunk-C2VZHIIX.js.map} +0 -0
- /package/dist/{chunk-EFGAPAYZ.js.map → chunk-CAYY2IEV.js.map} +0 -0
- /package/dist/{chunk-XDFPXEXU.js.map → chunk-CJI26AJC.js.map} +0 -0
- /package/dist/{chunk-HUN2UIYB.js.map → chunk-EMWSFITR.js.map} +0 -0
- /package/dist/{chunk-4LUZO3AP.js.map → chunk-EQPMQSJE.js.map} +0 -0
- /package/dist/{chunk-MXB47GPG.js.map → chunk-HX4R7RPR.js.map} +0 -0
- /package/dist/{chunk-TTHY22I4.js.map → chunk-IAR5F3T5.js.map} +0 -0
- /package/dist/{chunk-2N6LROEF.js.map → chunk-JUSQMQ7L.js.map} +0 -0
- /package/dist/{chunk-KUAJUHMB.js.map → chunk-M4VYHPDS.js.map} +0 -0
- /package/dist/{chunk-YHLKEGIC.js.map → chunk-MAQFWGFT.js.map} +0 -0
- /package/dist/{chunk-VVFJCGX7.js.map → chunk-N6NZBAWR.js.map} +0 -0
- /package/dist/{chunk-O62HITS4.js.map → chunk-P65XGEB7.js.map} +0 -0
- /package/dist/{chunk-NDBM7DTN.js.map → chunk-QOEO27LF.js.map} +0 -0
- /package/dist/{chunk-T4BWPILH.js.map → chunk-RB7M2NPU.js.map} +0 -0
- /package/dist/{chunk-BTI3OUFH.js.map → chunk-RUNCUVAH.js.map} +0 -0
- /package/dist/{chunk-FLSEPYM3.js.map → chunk-SLX3OHEW.js.map} +0 -0
- /package/dist/{chunk-XPL6F4HL.js.map → chunk-TV5BDCQA.js.map} +0 -0
- /package/dist/{chunk-H6FFWHJH.js.map → chunk-V3FSKTDF.js.map} +0 -0
- /package/dist/{chunk-LCVKEIG2.js.map → chunk-VGYW3Q7F.js.map} +0 -0
- /package/dist/{chunk-EVRLNHIC.js.map → chunk-WKR2OSCH.js.map} +0 -0
- /package/dist/{chunk-LPSDAS22.js.map → chunk-Y2D6FQBL.js.map} +0 -0
- /package/dist/{chunk-QCCVHEKZ.js.map → chunk-ZPCSPEGO.js.map} +0 -0
- /package/dist/{client-HJBH2DVH.js.map → client-EOQLSAUW.js.map} +0 -0
- /package/dist/{config-QBTOYJA7.js.map → config-SZZQFIJF.js.map} +0 -0
- /package/dist/{config-mutate-G46QCYCR.js.map → config-mutate-66VDWR46.js.map} +0 -0
- /package/dist/{config-mutator-3FGEZPF3.js.map → config-mutator-OILDQCAJ.js.map} +0 -0
- /package/dist/{contributions-OOPYQSLO.js.map → contributions-LRQCDZCQ.js.map} +0 -0
- /package/dist/{doctor-2KOQNH44.js.map → doctor-QASDCIQ5.js.map} +0 -0
- /package/dist/{enrich-MZMIQ3SV.js.map → dotenv-DGZD3EDY.js.map} +0 -0
- /package/dist/{hub-E56MSG7W.js.map → enrich-NIUEEGPA.js.map} +0 -0
- /package/dist/{event-levels-PCFARGKL.js.map → event-levels-D6QSANGF.js.map} +0 -0
- /package/dist/{follow-up-tool-K252F4QA.js.map → follow-up-tool-QOO2TIQS.js.map} +0 -0
- /package/dist/{promote-GWDQR2DT.js.map → hub-6TKU6CHO.js.map} +0 -0
- /package/dist/{query-PYJN4G32.js.map → keyring-EKFUNQAO.js.map} +0 -0
- /package/dist/{registry-EMB3QRRL.js.map → oauth-7J7DJMKN.js.map} +0 -0
- /package/dist/{routing-LX5QYMZW.js.map → open-browser-BTEYT7G4.js.map} +0 -0
- /package/dist/{schedule-tool-HD72JVUS.js.map → promote-D3KYLUBD.js.map} +0 -0
- /package/dist/{scheduler-UN5ZPEK4.js.map → providers-P76CWTGQ.js.map} +0 -0
- /package/dist/{seat-2RFBH5N2.js.map → query-D2TQ2PUO.js.map} +0 -0
- /package/dist/{query-settings-XFOY343Z.js.map → query-settings-ILDX3HDF.js.map} +0 -0
- /package/dist/{wiki-K77I5LJP.js.map → registry-N3BY3HSI.js.map} +0 -0
- /package/dist/{request-planner-DP3PIMNQ.js.map → request-planner-CVCG5XQR.js.map} +0 -0
- /package/dist/{wiki-enrich-PK5XQCV3.js.map → resolve-JKXYBZ6R.js.map} +0 -0
- /package/dist/{review-candidates-5HRRFPEG.js.map → review-candidates-CKUN4PSY.js.map} +0 -0
- /package/dist/{workspace-setup-HAV4CQV7.js.map → routing-OCIRGUKK.js.map} +0 -0
- /package/dist/{rules-FBOLGE2S.js.map → rules-A5ES57QT.js.map} +0 -0
- /package/dist/{select-MOZ2GNNR.js.map → select-J4ES7Q67.js.map} +0 -0
- /package/dist/{set-enabled-IFK2TCH5.js.map → set-enabled-S22TICYC.js.map} +0 -0
- /package/dist/{sprint-tool-WB2M7RHX.js.map → sprint-tool-NDF47EKV.js.map} +0 -0
- /package/dist/{tool-57ZGZ7BD.js.map → tool-52JRXZVA.js.map} +0 -0
- /package/dist/{tool-CMHNG2PN.js.map → tool-RCCMOMEY.js.map} +0 -0
- /package/dist/{tool-SKQNMJP2.js.map → tool-Z2OVFGWW.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function d(e,n=process.env){let t={...e.headers??{}};for(let[r,o]of Object.entries(e.headersEnv??{})){let i=n[o]?.trim();i&&(t[r]=i)}return t}function u(e){let n={...e.headers??{}};for(let[t,r]of Object.entries(e.headersEnv??{}))n[t]=`\${${r}}`;return Object.keys(n).length>0?n:void 0}function a(e){return[...new Set(Object.values(e.headersEnv??{}))]}function l(e){let n=e.split("*").map(t=>t.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${n}$`)}function c(e,n){return e?e.some(t=>t.includes("*")?l(t).test(n):t===n):!0}function g(e,n){if(!n||!e.startsWith("mcp__"))return null;let t=Object.keys(n).sort((r,o)=>o.length-r.length);for(let r of t){let o=`mcp__${r}__`;if(!e.startsWith(o))continue;let i=n[r]?.allowTools;if(!i)return null;let s=e.slice(o.length);return c(i,s)?null:`[agentx-mcp] "${s}" is not on the allowTools list of MCP server "${r}". Allowed: ${i.join(", ")||"(none)"}.`}return null}function f(e){let n=Object.entries(e??{}).filter(([,t])=>Array.isArray(t?.allowTools)).map(([t])=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return n.length===0?null:`mcp__(${n.join("|")})__.*`}export{d as a,u as b,a as c,c as d,g as e,f};
|
|
2
|
+
//# sourceMappingURL=chunk-36X7D4JA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent/mcp-policy.ts"],"sourcesContent":["// --- MCP server policy: secret headers and tool allow lists (#1698) ---\n//\n// Two per-server settings that make a hosted MCP endpoint (a connector\n// service, for instance) safe to declare in agentx.json:\n//\n// headersEnv header name -> NAME of an environment variable. The value\n// is read by the daemon when it connects (orchestrator tier),\n// and written to .mcp.json only as a `${NAME}` placeholder\n// that Claude Code expands at spawn. The secret itself never\n// lands in agentx.json or in a synced file. (`${VAR}` inside\n// plain `headers` is expanded when agentx.json loads, so it\n// would end up in .mcp.json in clear text.)\n//\n// allowTools the only tools of that server an agent may use. Exact\n// names, `*` as a wildcard. The orchestrator tier never lists\n// the others; the claude-code tier's guard hook refuses them.\n//\n// Pure helpers only: no I/O, so mcp-client, agent-mcp, the runtime and the\n// daemon's /guard/check can all share them.\n\n/** An environment variable name as agentx accepts it elsewhere (`tokenEnv`). */\nexport const ENV_NAME_RE = /^[A-Z_][A-Z0-9_]*$/\n\nexport interface McpPolicyFields {\n headers?: Record<string, string>\n headersEnv?: Record<string, string>\n allowTools?: string[]\n}\n\n/** Headers to send on every request: the literal `headers`, then each\n * `headersEnv` entry read from `env`. An unset or empty variable is left\n * out, so the server answers 401 instead of receiving an empty key. */\nexport function resolveHttpHeaders(\n spec: McpPolicyFields,\n env: Record<string, string | undefined> = process.env,\n): Record<string, string> {\n const out: Record<string, string> = { ...(spec.headers ?? {}) }\n for (const [header, name] of Object.entries(spec.headersEnv ?? {})) {\n const value = env[name]?.trim()\n if (value) out[header] = value\n }\n return out\n}\n\n/** Headers as written into a file another program reads (.mcp.json):\n * `headersEnv` entries become `${NAME}` placeholders that program expands\n * from its own environment. The secret value is never looked up here. */\nexport function placeholderHeaders(spec: McpPolicyFields): Record<string, string> | undefined {\n const out: Record<string, string> = { ...(spec.headers ?? {}) }\n for (const [header, name] of Object.entries(spec.headersEnv ?? {})) out[header] = `\\${${name}}`\n return Object.keys(out).length > 0 ? out : undefined\n}\n\n/** Environment variable names a server's `headersEnv` needs. */\nexport function headerEnvNames(spec: McpPolicyFields): string[] {\n return [...new Set(Object.values(spec.headersEnv ?? {}))]\n}\n\nfunction wildcardToRegExp(pattern: string): RegExp {\n const body = pattern.split(\"*\").map((s) => s.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\")).join(\".*\")\n return new RegExp(`^${body}$`)\n}\n\n/** Is `tool` (the server's own tool name, without `mcp__<server>__`) on\n * the list? No list means every tool is allowed; an empty list allows none. */\nexport function toolAllowed(allowTools: string[] | undefined, tool: string): boolean {\n if (!allowTools) return true\n return allowTools.some((p) => (p.includes(\"*\") ? wildcardToRegExp(p).test(tool) : p === tool))\n}\n\n/** Reason to refuse a namespaced `mcp__<server>__<tool>` call, or null.\n * Only servers with an `allowTools` list are checked; a call to any other\n * server, or to a tool that is not an MCP tool, is not this check's call. */\nexport function mcpAllowListDenial(\n toolName: string,\n servers: Record<string, McpPolicyFields> | undefined,\n): string | null {\n if (!servers || !toolName.startsWith(\"mcp__\")) return null\n // Longest server name first, so `a__b` wins over `a` for `mcp__a__b__x`.\n const names = Object.keys(servers).sort((a, b) => b.length - a.length)\n for (const server of names) {\n const prefix = `mcp__${server}__`\n if (!toolName.startsWith(prefix)) continue\n const list = servers[server]?.allowTools\n if (!list) return null\n const tool = toolName.slice(prefix.length)\n if (toolAllowed(list, tool)) return null\n return `[agentx-mcp] \"${tool}\" is not on the allowTools list of MCP server \"${server}\". Allowed: ${list.join(\", \") || \"(none)\"}.`\n }\n return null\n}\n\n/** Hook matcher (a regular expression over tool names) covering every\n * server that has an `allowTools` list, or null when none does. */\nexport function allowListHookMatcher(servers: Record<string, McpPolicyFields> | undefined): string | null {\n const names = Object.entries(servers ?? {})\n .filter(([, s]) => Array.isArray(s?.allowTools))\n .map(([n]) => n.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n if (names.length === 0) return null\n return `mcp__(${names.join(\"|\")})__.*`\n}\n"],"mappings":"AAgCO,SAASA,EACdC,EACAC,EAA0C,QAAQ,IAC1B,CACxB,IAAMC,EAA8B,CAAE,GAAIF,EAAK,SAAW,CAAC,CAAG,EAC9D,OAAW,CAACG,EAAQC,CAAI,IAAK,OAAO,QAAQJ,EAAK,YAAc,CAAC,CAAC,EAAG,CAClE,IAAMK,EAAQJ,EAAIG,CAAI,GAAG,KAAK,EAC1BC,IAAOH,EAAIC,CAAM,EAAIE,GAE3B,OAAOH,CACT,CAKO,SAASI,EAAmBN,EAA2D,CAC5F,IAAME,EAA8B,CAAE,GAAIF,EAAK,SAAW,CAAC,CAAG,EAC9D,OAAW,CAACG,EAAQC,CAAI,IAAK,OAAO,QAAQJ,EAAK,YAAc,CAAC,CAAC,EAAGE,EAAIC,CAAM,EAAI,MAAMC,KACxF,OAAO,OAAO,KAAKF,CAAG,EAAE,OAAS,EAAIA,EAAM,MAC7C,CAGO,SAASK,EAAeP,EAAiC,CAC9D,MAAO,CAAC,GAAG,IAAI,IAAI,OAAO,OAAOA,EAAK,YAAc,CAAC,CAAC,CAAC,CAAC,CAC1D,CAEA,SAASQ,EAAiBC,EAAyB,CACjD,IAAMC,EAAOD,EAAQ,MAAM,GAAG,EAAE,IAAKE,GAAMA,EAAE,QAAQ,qBAAsB,MAAM,CAAC,EAAE,KAAK,IAAI,EAC7F,OAAO,IAAI,OAAO,IAAID,IAAO,CAC/B,CAIO,SAASE,EAAYC,EAAkCC,EAAuB,CACnF,OAAKD,EACEA,EAAW,KAAME,GAAOA,EAAE,SAAS,GAAG,EAAIP,EAAiBO,CAAC,EAAE,KAAKD,CAAI,EAAIC,IAAMD,CAAK,EADrE,EAE1B,CAKO,SAASE,EACdC,EACAC,EACe,CACf,GAAI,CAACA,GAAW,CAACD,EAAS,WAAW,OAAO,EAAG,OAAO,KAEtD,IAAME,EAAQ,OAAO,KAAKD,CAAO,EAAE,KAAK,CAACE,EAAGC,IAAMA,EAAE,OAASD,EAAE,MAAM,EACrE,QAAWE,KAAUH,EAAO,CAC1B,IAAMI,EAAS,QAAQD,MACvB,GAAI,CAACL,EAAS,WAAWM,CAAM,EAAG,SAClC,IAAMC,EAAON,EAAQI,CAAM,GAAG,WAC9B,GAAI,CAACE,EAAM,OAAO,KAClB,IAAMV,EAAOG,EAAS,MAAMM,EAAO,MAAM,EACzC,OAAIX,EAAYY,EAAMV,CAAI,EAAU,KAC7B,iBAAiBA,mDAAsDQ,gBAAqBE,EAAK,KAAK,IAAI,GAAK,YAExH,OAAO,IACT,CAIO,SAASC,EAAqBP,EAAqE,CACxG,IAAMC,EAAQ,OAAO,QAAQD,GAAW,CAAC,CAAC,EACvC,OAAO,CAAC,CAAC,CAAEP,CAAC,IAAM,MAAM,QAAQA,GAAG,UAAU,CAAC,EAC9C,IAAI,CAAC,CAACe,CAAC,IAAMA,EAAE,QAAQ,sBAAuB,MAAM,CAAC,EACxD,OAAIP,EAAM,SAAW,EAAU,KACxB,SAASA,EAAM,KAAK,GAAG,QAChC","names":["resolveHttpHeaders","spec","env","out","header","name","value","placeholderHeaders","headerEnvNames","wildcardToRegExp","pattern","body","s","toolAllowed","allowTools","tool","p","mcpAllowListDenial","toolName","servers","names","a","b","server","prefix","list","allowListHookMatcher","n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as E}from"./chunk-IMLAPB7G.js";import{n as x}from"./chunk-XPZSEDE3.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{
|
|
1
|
+
import{a as E}from"./chunk-IMLAPB7G.js";import{n as x}from"./chunk-XPZSEDE3.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{ia as ne,ja as re,la as oe,ma as ie,sa as I,xa as Je}from"./chunk-RIBANO2H.js";import{accessSync as Qe,closeSync as Ye,constants as Ze,existsSync as pe,openSync as et,readFileSync as tt,readSync as nt,statSync as rt}from"node:fs";import{dirname as T,join as C}from"node:path";import{fileURLToPath as ot}from"node:url";import{homedir as it}from"node:os";import{join as ue,win32 as F}from"path";function $(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var j="agentx-helper.exe";function Ke(e){return F.join(e,"Programs","AgentX",j)}var le="AgentX Helper.app";function B(e){return ue(e,"Applications",le,"Contents/MacOS/agentx-mac-helper")}function ze(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&$(e)==="macos"?r:void 0}function ce(e){let t=ze(e.platform,e.env);if(t)return t;let n=$(e.platform);if(n==="macos"){let r=B(e.home);return e.exists(r)||!e.root?r:ue(e.root,"apps/mac-helper/build",le,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||F.join(e.home,"AppData","Local"),o=Ke(r);return e.exists(o)||!e.root?o:F.join(e.root,"apps","win-helper","build",j)}return null}function Ve(e){let t=$(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${j} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function Xt(e){let t=$(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=Ve(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var X="tn.acme.agentx.voice",Yt="AgentX Desktop.app",Zt="AgentX Helper.app";function en(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function tn(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function U(e){return`'${e.replace(/'/g,"'\\''")}'`}var de="/usr/bin:/bin:/usr/sbin:/sbin";function nn(e,t){return t||[...new Set([...e?[T(e)]:[],...de.split(":")])].join(":")}function O(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function rn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?O(t[1]):de}var on=e=>/agentx\.voice.*\.plist$/.test(e);function sn(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,l)=>s.file<l.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],l=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!l||!O(l).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:O(s)}):n={file:o,label:O(s)})}return{keep:n??{file:C(e,`${X}.plist`),label:X},remove:r}}function me(e,t,n){for(let r of t.split(":"))if(r&&n(C(r,e)))return C(r,e);return null}function an(e){try{if(Qe(e,Ze.X_OK),!rt(e).isFile())return!1;let t=et(e,"r"),n=Buffer.alloc(2);try{nt(t,n,0,2,0)}finally{Ye(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function un(e){let t=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${U(e.cwd)} && ${U(e.node)} ${U(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
3
|
<plist version="1.0"><dict>
|
|
4
4
|
<key>Label</key><string>${t(e.label??X)}</string>
|
|
@@ -35,4 +35,4 @@ function run(argv) {
|
|
|
35
35
|
`),Dt(r,n)}var Ft=5*6e4;function Wr(e,t,n=Date.now()){let r=ee(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=Ft)?!1:r.items[`card:${t}`]?.state!=="failed"}var te=24*36e5;function Ue(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function jt(e,t,n,r){let o=Date.parse(e.expires),i=[w(e.ask,x.ask)];return e.choices?.length&&i.push(...e.choices.map((s,l)=>`${l+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${w(e.recommend,x.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:w(e.title,x.title),notes:i.join(`
|
|
36
36
|
`),due:Ue(r,t,o),priority:Number.isFinite(o)&&o-r<=te?"high":"none"}}function Bt(e,t,n,r){let o=[w(e.question||e.text,x.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:Y(e,x.title).headline,notes:o.join(`
|
|
37
37
|
`),due:Ue(r,t,i),priority:i!==void 0&&i-r<=te?"high":"none"}}async function qr(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),l={created:0,completed:0,dismissed:0,failed:0},a=ee(t);delete a.lastError;let c=u=>{a.lastError={at:s,message:u}},g=new Map;try{if(n.include.includes("card"))for(let u of e.cards())u.status==="pending"&&Date.parse(u.expires)>i&&g.set(`card:${u.id}`,jt(u,n,e.answerUrl,i));if(n.include.includes("request"))for(let u of e.requests())u.state==="waiting_owner"&&g.set(`request:${u.id}`,Bt(u,n,e.answerUrl,i))}catch(u){return o(`[mirror] could not read what is waiting: ${u?.message??u}`),c(String(u?.message??u)),Fe(t,a),l}let D=!0,h=new Map,Xe=async u=>{if(!h.has(u))try{h.set(u,new Set((await r.listOpen(u)).map(p=>p.id)))}catch(p){o(`[mirror] could not read list "${u}": ${p?.message??p}`),c(String(p?.message??p)),h.set(u,null),D=!1}return h.get(u)};for(let[u,p]of Object.entries(a.items)){if(p.state!=="open"||!p.id)continue;let d=await Xe(p.list);if(d)if(g.has(u))d.has(p.id)||(a.items[u]={...p,state:"dismissed",at:s},l.dismissed++,o(`[mirror] ${u}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(p.id))try{await r.complete(p.id)}catch(S){o(`[mirror] ${u}: could not complete its task: ${S?.message??S}`),c(String(S?.message??S));continue}a.items[u]={...p,state:"completed",at:s},l.completed++}}let R=null,W="",q=0,v=[];for(let[u,p]of g){let d=a.items[u];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=Z)continue;if(R===null)try{await r.ensureList(n.list),R=!0}catch(f){o(`[mirror] could not make list "${n.list}": ${f?.message??f}`),W=String(f?.message??f),c(W),R=!1}let S=d?.state==="failed"?d.failures:0;try{if(R===!1)throw new Error(W);let{id:f}=await r.add({list:n.list,title:p.title,notes:p.notes,due:p.due,priority:p.priority});a.items[u]={id:f,list:n.list,state:"open",at:s,createdAt:s,failures:0},l.created++}catch(f){let P=String(f?.message??f);u.startsWith("card:")&&q++;let H=S+1;a.items[u]={list:n.list,state:"failed",at:s,failures:H,lastError:P},c(P),l.failed++,o(`[mirror] ${u}: could not add to Reminders (${H}/${Z}): ${P}`),H===Z&&v.push({title:p.title,message:P})}}q&&o(`[mirror] ${q} card(s) could not be added to Reminders; the Mac popup shows them instead`);let Ge=a.failureToldAt?Date.parse(a.failureToldAt):NaN;if(v.length&&!(i-Ge<te)){let u=v[0],p=v.length>1?` (and ${v.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${u.title}${p}: ${w(u.message,200)}. Still on the Desk.`),a.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}D&&(a.checkedAt=s,a.cards=n.include.includes("card"));for(let[u,p]of Object.entries(a.items))p.state!=="open"&&!g.has(u)&&i-Date.parse(p.at)>Ht&&delete a.items[u];return Fe(t,a),l}var je=5*6e4;function Hr(e,t,n,r,o=Date.now()){let i=ee(e),s=a=>{let c=a?Date.parse(a):NaN;return c>=n&&c<r},l={from:new Date(n).toISOString(),to:new Date(r).toISOString(),raised:0,created:{cards:0,requests:0},missed:[],closedFast:0,tooNew:0};for(let[a,c]of Object.entries(i.items))!c.id||!s(c.createdAt)||(a.startsWith("card:")?l.created.cards++:l.created.requests++);for(let a of t){if(!s(a.created_at))continue;l.raised++;let c=i.items[`card:${a.id}`];if(c?.id)continue;let g=Date.parse(a.created_at);if((a.status==="pending"?NaN:Date.parse(a.decided_at??""))-g<=je){l.closedFast++;continue}if(a.status==="pending"&&o-g<=je){l.tooNew++;continue}let h=c?.state==="failed"?`could not be added (${c.failures}x): ${c.lastError??"unknown error"}`:"no pass reached it";l.missed.push({id:a.id,title:a.title,reason:h})}return l}function Fr(e){let t=[e.closedFast?`closed within 5 min: ${e.closedFast}`:"",e.tooNew?`raised in the last 5 min: ${e.tooNew}`:""].filter(Boolean);return`cards raised ${e.raised} / Reminders created ${e.created.cards+e.created.requests} (${e.created.cards} cards, ${e.created.requests} requests) / missed ${e.missed.length}${t.length?` \xB7 ${t.join(" \xB7 ")}`:""}`}export{Nr as a,Me as b,V as c,Q as d,Ar as e,br as f,Tt as g,vr as h,kr as i,Rr as j,Y as k,w as l,Ct as m,Or as n,$ as o,ce as p,Ve as q,Xt as r,Yt as s,Zt as t,en as u,tn as v,nn as w,rn as x,on as y,sn as z,me as A,an as B,un as C,ln as D,cn as E,st as F,k as G,Se as H,z as I,Le as J,fr as K,gr as L,yr as M,ee as N,Wr as O,qr as P,Hr as Q,Fr as R};
|
|
38
|
-
//# sourceMappingURL=chunk-
|
|
38
|
+
//# sourceMappingURL=chunk-5VD2J4JN.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{spawn as t}from"child_process";import i from"chalk";function s(r=process.platform){return r==="darwin"?"open":r==="win32"?"start":"xdg-open"}function d(r,e=s()){let o=()=>console.log(i.dim(` Couldn't open a browser. Visit ${r}`));try{let n=t(e,[r],{stdio:"ignore",detached:!0});n.once("error",o),n.unref()}catch{o()}}export{s as a,d as b};
|
|
2
|
+
//# sourceMappingURL=chunk-7NQQIDDI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/open-browser.ts"],"sourcesContent":["import { spawn } from \"child_process\"\nimport chalk from \"chalk\"\n\nexport function browserOpener(platform: string = process.platform): string {\n return platform === \"darwin\" ? \"open\" : platform === \"win32\" ? \"start\" : \"xdg-open\"\n}\n\n// A missing opener (a server has no xdg-open) arrives as an \"error\" event on\n// the child, not as a throw. Unhandled, that event ends the process.\nexport function openBrowser(url: string, opener: string = browserOpener()): void {\n const failed = () => console.log(chalk.dim(` Couldn't open a browser. Visit ${url}`))\n try {\n const child = spawn(opener, [url], { stdio: \"ignore\", detached: true })\n child.once(\"error\", failed)\n child.unref()\n } catch {\n failed()\n }\n}\n"],"mappings":"AAAA,OAAS,SAAAA,MAAa,gBACtB,OAAOC,MAAW,QAEX,SAASC,EAAcC,EAAmB,QAAQ,SAAkB,CACzE,OAAOA,IAAa,SAAW,OAASA,IAAa,QAAU,QAAU,UAC3E,CAIO,SAASC,EAAYC,EAAaC,EAAiBJ,EAAc,EAAS,CAC/E,IAAMK,EAAS,IAAM,QAAQ,IAAIN,EAAM,IAAI,oCAAoCI,GAAK,CAAC,EACrF,GAAI,CACF,IAAMG,EAAQR,EAAMM,EAAQ,CAACD,CAAG,EAAG,CAAE,MAAO,SAAU,SAAU,EAAK,CAAC,EACtEG,EAAM,KAAK,QAASD,CAAM,EAC1BC,EAAM,MAAM,CACd,MAAE,CACAD,EAAO,CACT,CACF","names":["spawn","chalk","browserOpener","platform","openBrowser","url","opener","failed","child"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as A}from"./chunk-BYEL7KKR.js";import{b as y,c as h}from"./chunk-Q3A5P373.js";import{e as m}from"./chunk-JLBRNYKY.js";import{resolve as I}from"path";function w(t,e,r,n){let s=t.agents?.[e];if(!s)return null;let a=s.integrations;if(!Array.isArray(a))return null;let o=a.find(u=>u.enabled!==!1&&u.kind===r&&(!n||u.label===n));return o?{agentId:e,integration:o}:null}function R(t,e){let r=[];for(let[n,s]of Object.entries(t.agents??{})){let a=s.integrations;if(Array.isArray(a))for(let o of a)o.enabled!==!1&&o.kind===e&&r.push({agentId:n,integration:o})}return r}function C(t,e){let n=(t.credentials??{})[e];if(!n)return{status:"no-credential",reason:`integration "${t.label}" has no ${String(e)} configured`};if(e==="auth"&&n==="keyring")return{status:"ok"};if(typeof n=="string"&&/^[A-Z][A-Z0-9_]*$/.test(n)){let s=process.env[n];return s?{status:"ok",value:s,envVar:n}:{status:"env-unset",envVar:n,reason:`env var ${n} is unset (declared by integration "${t.label}")`}}return typeof n=="string"?{status:"ok",value:n}:{status:"no-credential",reason:`unrecognized credential ref shape for ${String(e)}`}}function J(t,e,r,n,s){let a=w(t,e,r,s);return a?C(a.integration,n):{status:"kind-not-found",reason:`agent "${e}" has no integration of kind "${r}"${s?` with label "${s}"`:""}`}}var x=6e4;function p(t,e){return`agentx agent integrations connect ${t} ${e.kind}${e.label!==e.kind?` --label "${e.label}"`:""}`}var $=(t,e)=>{let r=Number(t.metadata?.[e]);return Number.isFinite(r)&&r>0?r:void 0};function b(t){let e=t.metadata?.oauthScopes;return typeof e=="string"?e.split(/\s+/).filter(Boolean):[]}function D(t,e,r={}){let n=e.credentials??{},s=r.env??process.env,a=$(e,"oauthConnectedAt")??0;if(n.auth==="keyring"){let o=r.keyring??h(),u=o.available()?o.get(y(t,e.kind,e.label)):null;if(!u)return{ok:!1,status:"not-connected",reason:`no token in the OS keyring for ${e.kind} "${e.label}": run ${p(t,e)}`};try{let l=JSON.parse(u);if(typeof l?.accessToken!="string")throw new Error("bad shape");return{ok:!0,source:"keyring",grant:{...l,scopes:Array.isArray(l.scopes)?l.scopes:[]}}}catch{return{ok:!1,status:"not-connected",reason:`the keyring entry for ${e.kind} "${e.label}" is unreadable: connect again`}}}if(n.refreshTokenEnv){let o=s[n.refreshTokenEnv];return o?{ok:!0,source:"refresh-env",grant:{accessToken:"",refreshToken:o,scopes:b(e),connectedAt:a}}:{ok:!1,status:"env-unset",reason:`env var ${n.refreshTokenEnv} is unset (declared by integration "${e.label}")`}}if(n.tokenEnv){let o=s[n.tokenEnv];return o?{ok:!0,source:"token-env",grant:{accessToken:o,expiresAt:$(e,"oauthExpiresAt"),scopes:b(e),connectedAt:a}}:{ok:!1,status:"env-unset",reason:`env var ${n.tokenEnv} is unset (declared by integration "${e.label}")`}}return{ok:!1,status:"not-connected",reason:`integration "${e.label}" has no token: run ${p(t,e)}`}}function G(t,e=process.env){let r=t.credentials??{};if(!r.clientIdEnv||!r.clientSecretEnv)return{ok:!1,reason:`integration "${t.label}" needs credentials.clientIdEnv and credentials.clientSecretEnv (the app's client id and secret)`};let n=e[r.clientIdEnv],s=e[r.clientSecretEnv];return n?s?{ok:!0,clientId:n,clientSecret:s}:{ok:!1,reason:`env var ${r.clientSecretEnv} is unset (the app's client secret)`}:{ok:!1,reason:`env var ${r.clientIdEnv} is unset (the app's client id)`}}var k=new Map,v=new Map;function M(){k.clear(),v.clear()}async function V(t,e,r,n={}){let s=(n.now??Date.now)(),a=[t,e.kind,e.label,String(e.metadata?.oauthConnectedAt??"")].join("\0"),o=k.get(a);if(o&&(!o.expiresAt||o.expiresAt-x>s))return{status:"ok",...o};let u=v.get(a);if(u)return u;let l=(async()=>{let f=D(t,e,n);if(!f.ok)return{status:f.status,reason:f.reason};let c=f.grant;if(c.accessToken&&(!c.expiresAt||c.expiresAt-x>s))return k.set(a,{token:c.accessToken,expiresAt:c.expiresAt}),{status:"ok",token:c.accessToken,expiresAt:c.expiresAt};if(!c.refreshToken||r.oauth.refresh==="none")return{status:"expired",reason:`the ${r.title} token for "${e.label}" has expired: run ${p(t,e)}`};let g=G(e,n.env??process.env);if(!g.ok)return{status:"no-client",reason:g.reason};try{let i=await m(r,c,{fetch:n.fetch??fetch,clientId:g.clientId,clientSecret:g.clientSecret,now:s});if(f.source==="keyring"){let d=n.keyring??h();try{d.set(y(t,e.kind,e.label),JSON.stringify(i))}catch{}}else if(f.source==="refresh-env"&&e.credentials?.refreshTokenEnv&&i.refreshToken&&i.refreshToken!==c.refreshToken){let d=e.credentials.refreshTokenEnv;(n.env??process.env)[d]=i.refreshToken;let T=n.writeEnv??((S,E)=>A(I(process.cwd(),".env"),S,E));try{T(d,i.refreshToken)}catch{}}return k.set(a,{token:i.accessToken,expiresAt:i.expiresAt}),{status:"ok",token:i.accessToken,expiresAt:i.expiresAt}}catch(i){return{status:"refresh-failed",reason:`${i?.message??i}. If it keeps failing, connect again: ${p(t,e)}`}}})();v.set(a,l);try{return await l}finally{v.delete(a)}}export{w as a,R as b,C as c,J as d,p as e,b as f,D as g,G as h,M as i,V as j};
|
|
2
|
+
//# sourceMappingURL=chunk-7QW4RECS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/integrations/resolve.ts"],"sourcesContent":["// --- Per-agent integration credential resolver ---\n//\n// Given an agent's `integrations[]` registration in agentx.json, resolve the\n// concrete credential (env-var lookup, keyring read, etc.) at use-time.\n// Skills, channel adapters, and the action layer call into this instead of\n// hard-coding env-var names.\n//\n// Secrets never live in the config; only references do. This module is the\n// single chokepoint where references become values, so audit / redact /\n// rotate logic can land here later without touching call sites.\n\nimport type { DaemonConfig } from \"@/daemon/config\"\nimport type { Integration } from \"@/daemon/config\"\nimport type { KeyringStore } from \"./keyring\"\nimport { integrationAccount, systemKeyring } from \"./keyring\"\nimport { refreshGrant } from \"./oauth\"\nimport { setDotenvKey } from \"@/utils/dotenv\"\nimport { resolve } from \"path\"\nimport type { OAuthGrant, ProviderSpec } from \"./providers/types\"\n\nexport type ResolvedStatus = \"ok\" | \"env-unset\" | \"no-credential\" | \"kind-not-found\" | \"agent-not-found\"\n\nexport interface ResolvedCredential {\n status: ResolvedStatus\n value?: string\n envVar?: string\n /** Surfaced in error logs; safe to log (never the secret itself). */\n reason?: string\n}\n\n/**\n * Look up an integration on an agent by `kind` (or `kind` + `label`). When\n * multiple integrations of the same kind exist, the caller should pass a\n * label to disambiguate; otherwise the first matching enabled entry wins.\n */\nexport function getIntegration(\n config: DaemonConfig,\n agentId: string,\n kind: string,\n label?: string,\n): { agentId: string; integration: Integration } | null {\n const agent = config.agents?.[agentId]\n if (!agent) return null\n const list = (agent as any).integrations as Integration[] | undefined\n if (!Array.isArray(list)) return null\n const match = list.find(\n (i) => i.enabled !== false && i.kind === kind && (!label || i.label === label),\n )\n return match ? { agentId, integration: match } : null\n}\n\n/**\n * List every integration of a given kind across all agents. Useful for\n * webhook-routing UI (\"which agents have hubspot?\") and for skill loaders.\n */\nexport function findIntegrationsByKind(\n config: DaemonConfig,\n kind: string,\n): Array<{ agentId: string; integration: Integration }> {\n const out: Array<{ agentId: string; integration: Integration }> = []\n for (const [agentId, agent] of Object.entries(config.agents ?? {})) {\n const list = (agent as any).integrations as Integration[] | undefined\n if (!Array.isArray(list)) continue\n for (const integration of list) {\n if (integration.enabled === false) continue\n if (integration.kind === kind) out.push({ agentId, integration })\n }\n }\n return out\n}\n\n/**\n * Resolve a specific credential field on an integration. The `key` is one\n * of the optional fields on credentialsSchema (`tokenEnv`, `apiKeyEnv`,\n * `privateAppTokenEnv`, etc.) OR `auth` for keyring directive.\n *\n * Resolution rules:\n * - `*Env` keys → look up process.env[<value>]\n * - `auth: \"keyring\"` → returns `{ status: \"ok\", value: undefined }` —\n * skills are responsible for the actual keyring read (uses agentId+kind\n * as the canonical entry name).\n * - missing field → `{ status: \"no-credential\" }`\n */\nexport function resolveCredential(\n integration: Integration,\n key: keyof Integration[\"credentials\"],\n): ResolvedCredential {\n const creds = integration.credentials ?? {}\n const ref = (creds as any)[key]\n if (!ref) {\n return { status: \"no-credential\", reason: `integration \"${integration.label}\" has no ${String(key)} configured` }\n }\n // Keyring directive — caller (the skill) does the actual read.\n if (key === \"auth\" && ref === \"keyring\") {\n return { status: \"ok\" }\n }\n // Env-var ref.\n if (typeof ref === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(ref)) {\n const value = process.env[ref]\n if (!value) {\n return {\n status: \"env-unset\",\n envVar: ref,\n reason: `env var ${ref} is unset (declared by integration \"${integration.label}\")`,\n }\n }\n return { status: \"ok\", value, envVar: ref }\n }\n // Anything else is a literal string field (e.g. sessionDir for whatsapp).\n if (typeof ref === \"string\") {\n return { status: \"ok\", value: ref }\n }\n return { status: \"no-credential\", reason: `unrecognized credential ref shape for ${String(key)}` }\n}\n\n/**\n * Convenience: resolve the agent + kind in one call.\n */\nexport function resolveAgentCredential(\n config: DaemonConfig,\n agentId: string,\n kind: string,\n key: keyof Integration[\"credentials\"],\n label?: string,\n): ResolvedCredential {\n const found = getIntegration(config, agentId, kind, label)\n if (!found) {\n return {\n status: \"kind-not-found\",\n reason: `agent \"${agentId}\" has no integration of kind \"${kind}\"${label ? ` with label \"${label}\"` : \"\"}`,\n }\n }\n return resolveCredential(found.integration, key)\n}\n\n// --- OAuth access tokens for provider-backed integrations (#1696) ---\n//\n// Where an integration's grant lives, in order:\n// - `auth: \"keyring\"`: the OS keyring entry for (agent, kind, label),\n// holding the whole grant (access + refresh token, expiry, scopes).\n// - `refreshTokenEnv`: a refresh token in the environment (.env); access\n// tokens are fetched with it and kept in memory only. A rotated refresh\n// token is written back to .env (and the process env).\n// - `tokenEnv`: a static access token (no refresh).\n// Access tokens are refreshed here, at use time, a minute before they\n// expire. Nothing in this section returns or logs a refresh token.\n\nexport interface TokenDeps {\n keyring?: KeyringStore\n fetch?: typeof fetch\n env?: NodeJS.ProcessEnv\n now?: () => number\n /** Persist a rotated refresh token for a `refreshTokenEnv` integration.\n * Default: the .env in the folder AgentX runs in. */\n writeEnv?: (key: string, value: string) => void\n}\n\nexport type StoredGrant =\n | { ok: true; source: \"keyring\" | \"refresh-env\" | \"token-env\"; grant: OAuthGrant }\n | { ok: false; status: \"not-connected\" | \"env-unset\"; reason: string }\n\nexport type AccessToken =\n | { status: \"ok\"; token: string; expiresAt?: number }\n | { status: \"not-connected\" | \"env-unset\" | \"expired\" | \"no-client\" | \"refresh-failed\"; reason: string }\n\nconst EARLY_MS = 60_000\n\n/** The command that (re)connects an integration. */\nexport function connectCommand(agentId: string, i: Integration): string {\n return `agentx agent integrations connect ${agentId} ${i.kind}${i.label !== i.kind ? ` --label \"${i.label}\"` : \"\"}`\n}\n\nconst metaNum = (i: Integration, k: string): number | undefined => {\n const v = Number(i.metadata?.[k])\n return Number.isFinite(v) && v > 0 ? v : undefined\n}\n\n/** Scopes recorded at connect time (metadata.oauthScopes, space-separated). */\nexport function recordedScopes(i: Integration): string[] {\n const v = i.metadata?.oauthScopes\n return typeof v === \"string\" ? v.split(/\\s+/).filter(Boolean) : []\n}\n\n/** Read the stored grant for an integration. The result holds secrets: pass\n * it on to the token logic only, never to a response or a log line. */\nexport function readStoredGrant(agentId: string, i: Integration, deps: TokenDeps = {}): StoredGrant {\n const creds = i.credentials ?? {}\n const env = deps.env ?? process.env\n const connectedAt = metaNum(i, \"oauthConnectedAt\") ?? 0\n if (creds.auth === \"keyring\") {\n const keyring = deps.keyring ?? systemKeyring()\n const raw = keyring.available() ? keyring.get(integrationAccount(agentId, i.kind, i.label)) : null\n if (!raw) return { ok: false, status: \"not-connected\", reason: `no token in the OS keyring for ${i.kind} \"${i.label}\": run ${connectCommand(agentId, i)}` }\n try {\n const grant = JSON.parse(raw) as OAuthGrant\n if (typeof grant?.accessToken !== \"string\") throw new Error(\"bad shape\")\n return { ok: true, source: \"keyring\", grant: { ...grant, scopes: Array.isArray(grant.scopes) ? grant.scopes : [] } }\n } catch {\n return { ok: false, status: \"not-connected\", reason: `the keyring entry for ${i.kind} \"${i.label}\" is unreadable: connect again` }\n }\n }\n if (creds.refreshTokenEnv) {\n const v = env[creds.refreshTokenEnv]\n if (!v) return { ok: false, status: \"env-unset\", reason: `env var ${creds.refreshTokenEnv} is unset (declared by integration \"${i.label}\")` }\n return { ok: true, source: \"refresh-env\", grant: { accessToken: \"\", refreshToken: v, scopes: recordedScopes(i), connectedAt } }\n }\n if (creds.tokenEnv) {\n const v = env[creds.tokenEnv]\n if (!v) return { ok: false, status: \"env-unset\", reason: `env var ${creds.tokenEnv} is unset (declared by integration \"${i.label}\")` }\n return { ok: true, source: \"token-env\", grant: { accessToken: v, expiresAt: metaNum(i, \"oauthExpiresAt\"), scopes: recordedScopes(i), connectedAt } }\n }\n return { ok: false, status: \"not-connected\", reason: `integration \"${i.label}\" has no token: run ${connectCommand(agentId, i)}` }\n}\n\n/** The OAuth client of an integration (clientIdEnv / clientSecretEnv). */\nexport function resolveClient(i: Integration, env: NodeJS.ProcessEnv = process.env):\n { ok: true; clientId: string; clientSecret: string } | { ok: false; reason: string } {\n const c = i.credentials ?? {}\n if (!c.clientIdEnv || !c.clientSecretEnv) return { ok: false, reason: `integration \"${i.label}\" needs credentials.clientIdEnv and credentials.clientSecretEnv (the app's client id and secret)` }\n const clientId = env[c.clientIdEnv]\n const clientSecret = env[c.clientSecretEnv]\n if (!clientId) return { ok: false, reason: `env var ${c.clientIdEnv} is unset (the app's client id)` }\n if (!clientSecret) return { ok: false, reason: `env var ${c.clientSecretEnv} is unset (the app's client secret)` }\n return { ok: true, clientId, clientSecret }\n}\n\nconst tokenCache = new Map<string, { token: string; expiresAt?: number }>()\nconst inflight = new Map<string, Promise<AccessToken>>()\n\n/** Forget cached access tokens (tests, disconnect). */\nexport function clearTokenCache(): void { tokenCache.clear(); inflight.clear() }\n\n/** A usable access token for a provider-backed integration, refreshed when\n * it is about to expire. */\nexport async function resolveAccessToken(\n agentId: string,\n i: Integration,\n spec: ProviderSpec,\n deps: TokenDeps = {},\n): Promise<AccessToken> {\n const now = (deps.now ?? Date.now)()\n // A reconnect changes oauthConnectedAt, which drops the old cache entry.\n const key = [agentId, i.kind, i.label, String(i.metadata?.oauthConnectedAt ?? \"\")].join(\"\\u0000\")\n const cached = tokenCache.get(key)\n if (cached && (!cached.expiresAt || cached.expiresAt - EARLY_MS > now)) return { status: \"ok\", ...cached }\n const running = inflight.get(key)\n if (running) return running\n const p = (async (): Promise<AccessToken> => {\n const stored = readStoredGrant(agentId, i, deps)\n if (!stored.ok) return { status: stored.status, reason: stored.reason }\n const g = stored.grant\n if (g.accessToken && (!g.expiresAt || g.expiresAt - EARLY_MS > now)) {\n tokenCache.set(key, { token: g.accessToken, expiresAt: g.expiresAt })\n return { status: \"ok\", token: g.accessToken, expiresAt: g.expiresAt }\n }\n if (!g.refreshToken || spec.oauth.refresh === \"none\") {\n return { status: \"expired\", reason: `the ${spec.title} token for \"${i.label}\" has expired: run ${connectCommand(agentId, i)}` }\n }\n const client = resolveClient(i, deps.env ?? process.env)\n if (!client.ok) return { status: \"no-client\", reason: client.reason }\n try {\n const next = await refreshGrant(spec, g, { fetch: deps.fetch ?? fetch, clientId: client.clientId, clientSecret: client.clientSecret, now })\n if (stored.source === \"keyring\") {\n const keyring = deps.keyring ?? systemKeyring()\n try { keyring.set(integrationAccount(agentId, i.kind, i.label), JSON.stringify(next)) } catch { /* the new token still works for this process */ }\n } else if (stored.source === \"refresh-env\" && i.credentials?.refreshTokenEnv && next.refreshToken && next.refreshToken !== g.refreshToken) {\n const envKey = i.credentials.refreshTokenEnv\n ;(deps.env ?? process.env)[envKey] = next.refreshToken\n const writeEnv = deps.writeEnv ?? ((k: string, v: string) => setDotenvKey(resolve(process.cwd(), \".env\"), k, v))\n try { writeEnv(envKey, next.refreshToken) } catch { /* the new token still works until a restart */ }\n }\n tokenCache.set(key, { token: next.accessToken, expiresAt: next.expiresAt })\n return { status: \"ok\", token: next.accessToken, expiresAt: next.expiresAt }\n } catch (e: any) {\n return { status: \"refresh-failed\", reason: `${e?.message ?? e}. If it keeps failing, connect again: ${connectCommand(agentId, i)}` }\n }\n })()\n inflight.set(key, p)\n try { return await p } finally { inflight.delete(key) }\n}\n"],"mappings":"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","names":["resolve","getIntegration","config","agentId","kind","label","agent","list","match","i","findIntegrationsByKind","out","integration","resolveCredential","key","ref","value","resolveAgentCredential","found","EARLY_MS","connectCommand","metaNum","k","v","recordedScopes","readStoredGrant","deps","creds","env","connectedAt","keyring","systemKeyring","raw","integrationAccount","grant","resolveClient","c","clientId","clientSecret","tokenCache","inflight","clearTokenCache","resolveAccessToken","spec","now","cached","running","p","stored","g","client","next","refreshGrant","envKey","writeEnv","setDotenvKey","e"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{a as c}from"./chunk-QUFIUXMQ.js";import{appendFileSync as $,chmodSync as f,existsSync as i,readFileSync as s,writeFileSync as m}from"fs";function l(n){return i(n)?Object.fromEntries(c(s(n,"utf-8"))):{}}function u(n,t,e){if(!/^[A-Z_][A-Z0-9_]*$/.test(t))throw new Error(`not an environment variable name: ${t}`);if(!e||/[\r\n]/.test(e))throw new Error("the value must be one non-empty line");if(l(n)[t])return!1;if(!i(n))return m(n,`# AgentX environment variables
|
|
2
|
+
# (Never commit this file: it contains secrets.)
|
|
3
|
+
|
|
4
|
+
${t}=${e}
|
|
5
|
+
`,{mode:384}),!0;try{f(n,384)}catch{}let o=s(n,"utf-8"),r=o===""||o.endsWith(`
|
|
6
|
+
`)?"":`
|
|
7
|
+
`;return $(n,`${r}${t}=${e}
|
|
8
|
+
`),!0}function v(n,t,e){if(!/^[A-Z_][A-Z0-9_]*$/.test(t))throw new Error(`not an environment variable name: ${t}`);if(!e||/[\r\n]/.test(e))throw new Error("the value must be one non-empty line");if(!i(n)){u(n,t,e);return}try{f(n,384)}catch{}let o=new RegExp(`^\\s*(?:export\\s+)?${t}\\s*=`),r=s(n,"utf-8").split(`
|
|
9
|
+
`).filter(g=>!o.test(g));for(;r.length&&r[r.length-1]==="";)r.pop();m(n,`${r.join(`
|
|
10
|
+
`)}${r.length?`
|
|
11
|
+
`:""}${t}=${e}
|
|
12
|
+
`,{mode:384})}export{l as a,u as b,v as c};
|
|
13
|
+
//# sourceMappingURL=chunk-BYEL7KKR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/dotenv.ts"],"sourcesContent":["import { appendFileSync, chmodSync, existsSync, readFileSync, writeFileSync } from \"fs\"\nimport { parseDotEnv } from \"@/utils/workspace-env\"\n\n// --- .env in the folder AgentX runs in: read it, add one key ---\n//\n// The daemon loads .env itself in loadDaemonConfig, which also runs on\n// POST /reload, so a key added here is picked up without a restart (#1163).\n\n/** The KEY=VALUE pairs of a .env file. Missing file: empty. */\nexport function readDotenv(path: string): Record<string, string> {\n if (!existsSync(path)) return {}\n return Object.fromEntries(parseDotEnv(readFileSync(path, \"utf-8\")))\n}\n\n/** Add KEY=value to .env, creating it (mode 600) if needed; an existing file\n * is tightened to 600 before the key is written. Never replaces\n * a key that already has a value: returns false and leaves the file alone. */\nexport function addDotenvKey(path: string, key: string, value: string): boolean {\n if (!/^[A-Z_][A-Z0-9_]*$/.test(key)) throw new Error(`not an environment variable name: ${key}`)\n if (!value || /[\\r\\n]/.test(value)) throw new Error(\"the value must be one non-empty line\")\n if (readDotenv(path)[key]) return false\n if (!existsSync(path)) {\n writeFileSync(path, `# AgentX environment variables\\n# (Never commit this file: it contains secrets.)\\n\\n${key}=${value}\\n`, { mode: 0o600 })\n return true\n }\n // Best effort: a file we can write but do not own cannot be chmod-ed.\n try { chmodSync(path, 0o600) } catch {}\n const existing = readFileSync(path, \"utf-8\")\n const sep = existing === \"\" || existing.endsWith(\"\\n\") ? \"\" : \"\\n\"\n appendFileSync(path, `${sep}${key}=${value}\\n`)\n return true\n}\n\n/** Set KEY=value in .env, replacing every earlier line for KEY. Same file\n * rules as addDotenvKey (created or tightened to mode 600). */\nexport function setDotenvKey(path: string, key: string, value: string): void {\n if (!/^[A-Z_][A-Z0-9_]*$/.test(key)) throw new Error(`not an environment variable name: ${key}`)\n if (!value || /[\\r\\n]/.test(value)) throw new Error(\"the value must be one non-empty line\")\n if (!existsSync(path)) { addDotenvKey(path, key, value); return }\n try { chmodSync(path, 0o600) } catch {}\n const isKey = new RegExp(`^\\\\s*(?:export\\\\s+)?${key}\\\\s*=`)\n const kept = readFileSync(path, \"utf-8\").split(\"\\n\").filter((line) => !isKey.test(line))\n while (kept.length && kept[kept.length - 1] === \"\") kept.pop()\n writeFileSync(path, `${kept.join(\"\\n\")}${kept.length ? \"\\n\" : \"\"}${key}=${value}\\n`, { mode: 0o600 })\n}\n"],"mappings":"wCAAA,OAAS,kBAAAA,EAAgB,aAAAC,EAAW,cAAAC,EAAY,gBAAAC,EAAc,iBAAAC,MAAqB,KAS5E,SAASC,EAAWC,EAAsC,CAC/D,OAAKC,EAAWD,CAAI,EACb,OAAO,YAAYE,EAAYC,EAAaH,EAAM,OAAO,CAAC,CAAC,EADpC,CAAC,CAEjC,CAKO,SAASI,EAAaJ,EAAcK,EAAaC,EAAwB,CAC9E,GAAI,CAAC,qBAAqB,KAAKD,CAAG,EAAG,MAAM,IAAI,MAAM,qCAAqCA,GAAK,EAC/F,GAAI,CAACC,GAAS,SAAS,KAAKA,CAAK,EAAG,MAAM,IAAI,MAAM,sCAAsC,EAC1F,GAAIP,EAAWC,CAAI,EAAEK,CAAG,EAAG,MAAO,GAClC,GAAI,CAACJ,EAAWD,CAAI,EAClB,OAAAO,EAAcP,EAAM;AAAA;AAAA;AAAA,EAAuFK,KAAOC;AAAA,EAAW,CAAE,KAAM,GAAM,CAAC,EACrI,GAGT,GAAI,CAAEE,EAAUR,EAAM,GAAK,CAAE,MAAE,CAAO,CACtC,IAAMS,EAAWN,EAAaH,EAAM,OAAO,EACrCU,EAAMD,IAAa,IAAMA,EAAS,SAAS;AAAA,CAAI,EAAI,GAAK;AAAA,EAC9D,OAAAE,EAAeX,EAAM,GAAGU,IAAML,KAAOC;AAAA,CAAS,EACvC,EACT,CAIO,SAASM,EAAaZ,EAAcK,EAAaC,EAAqB,CAC3E,GAAI,CAAC,qBAAqB,KAAKD,CAAG,EAAG,MAAM,IAAI,MAAM,qCAAqCA,GAAK,EAC/F,GAAI,CAACC,GAAS,SAAS,KAAKA,CAAK,EAAG,MAAM,IAAI,MAAM,sCAAsC,EAC1F,GAAI,CAACL,EAAWD,CAAI,EAAG,CAAEI,EAAaJ,EAAMK,EAAKC,CAAK,EAAG,OACzD,GAAI,CAAEE,EAAUR,EAAM,GAAK,CAAE,MAAE,CAAO,CACtC,IAAMa,EAAQ,IAAI,OAAO,uBAAuBR,QAAU,EACpDS,EAAOX,EAAaH,EAAM,OAAO,EAAE,MAAM;AAAA,CAAI,EAAE,OAAQe,GAAS,CAACF,EAAM,KAAKE,CAAI,CAAC,EACvF,KAAOD,EAAK,QAAUA,EAAKA,EAAK,OAAS,CAAC,IAAM,IAAIA,EAAK,IAAI,EAC7DP,EAAcP,EAAM,GAAGc,EAAK,KAAK;AAAA,CAAI,IAAIA,EAAK,OAAS;AAAA,EAAO,KAAKT,KAAOC;AAAA,EAAW,CAAE,KAAM,GAAM,CAAC,CACtG","names":["appendFileSync","chmodSync","existsSync","readFileSync","writeFileSync","readDotenv","path","existsSync","parseDotEnv","readFileSync","addDotenvKey","key","value","writeFileSync","chmodSync","existing","sep","appendFileSync","setDotenvKey","isKey","kept","line"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as _,k as O,l as M,m as D}from"./chunk-
|
|
1
|
+
import{a as _,k as O,l as M,m as D}from"./chunk-CAYY2IEV.js";import{f as N,g as Y}from"./chunk-DODL5POT.js";import{f as v}from"./chunk-QAWKN2N4.js";import{c as G}from"./chunk-OWNQ2FD4.js";import{b as C}from"./chunk-KEXBEUSU.js";import{createHash as J}from"crypto";import{existsSync as B,mkdirSync as V,readFileSync as q,writeFileSync as K}from"fs";import{resolve as P}from"path";var H="wiki-enrich",$e=["person","organization","project","place","device","server","app","domain","account"],Q=new Set(["person","organization","project","place"]),F=3500,X=700;function Z(e,n){let s=e.ontology.types.find(r=>r.id===n)?.lens??[],t=new Map;for(let r of s)if(Y(r)==="statements")for(let i of N(r)){if(i==="related"||t.has(i))continue;let l=e.ontology.properties.find(u=>u.id===i);l?.domain&&!l.domain.includes(n)||t.set(i,l?.label??i.replace(/_/g," "))}return t}function T(e,n,s){let t=v(n.title);return t.length<4?[]:[...e.entities.values()].filter(r=>r.type===s&&r.id!==n.id&&` ${v(r.title)} `.includes(` ${t} `))}function L(e){return e.access==="public"?null:new Set([e.owner,...e.access==="shared"?e.sharedWith??[]:[]])}function ee(e,n){let s=L(e);if(!s)return!0;let t=L(n);return!!t&&[...t].every(r=>s.has(r))}function te(e,n,s,t){let r=a=>!t||ee(a.article.meta,t.article.meta),i=a=>a.pages.some(r),l=n.pages.filter(r),u=t?[...new Set(l.flatMap(a=>a.article.meta.sources??[]))]:n.sources,p=_(e,n,null).filter(i),f=a=>[...new Map(a.map(g=>[g.id,g])).values()],E=f([...p.filter(a=>a.type==="event"),...T(e,n,"event").filter(i)]).sort((a,g)=>(g.date||"").localeCompare(a.date||"")).slice(0,30),o=f([...p.filter(a=>a.type==="project"),...T(e,n,"project").filter(i)]).slice(0,12),d=p.filter(a=>a.type!=="event"&&a.type!=="project").filter(i).filter(a=>n.type!=="person"||Q.has(a.type)).slice(0,40),w=s(u).sort((a,g)=>g.date.localeCompare(a.date)).slice(0,14),c=Z(e,n.type),m=new Map;for(let a of c.keys()){let g=e.ontology.properties.find(h=>h.id===a)?.range;g?.length&&m.set(a,g)}return{entity:n,pages:l,properties:c,ranges:m,neighbours:d,events:E,projects:o,entries:w,sources:u,mentions:ne(e,n,12,r)}}function ne(e,n,s=12,t=()=>!0){let r=[n.title,...n.pages.flatMap(p=>p.article.meta.aliases??[])].filter(p=>p.trim().length>=3);if(r.length===0)return[];let i=r.map(p=>p.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),l=new RegExp(`(^|[^\\p{L}\\p{N}])(${i.join("|")})(?=$|[^\\p{L}\\p{N}])`,"iu"),u=[];for(let p of e.entities.values())if(!(p.id===n.id||p.type==="event"))for(let f of p.pages){if(!t(f))continue;let E=O(f.article.content),o=l.exec(E);if(!o)continue;let d=Math.max(0,o.index-250);u.push({page:f,excerpt:E.slice(d,o.index+450).replace(/\s+/g," ").trim(),at:f.article.meta.lastUpdated||""});break}return u.sort((p,f)=>f.at.localeCompare(p.at)).slice(0,s).map(({page:p,excerpt:f})=>({page:p,excerpt:f}))}function ie(e){let n=[...e.pages.map(s=>`${s.agentId}/${s.article.path}`),...e.sources,...e.events.map(s=>s.id),...e.projects.map(s=>s.id),...e.mentions.map(s=>`${s.page.agentId}/${s.page.article.path}`)].sort();return J("sha1").update(n.join(`
|
|
2
2
|
`)).digest("hex").slice(0,16)}var x=(e,n)=>e.length>n?`${e.slice(0,n)}\u2026`:e;function se(e,n,s){let t=e.entity,r=[`You are bringing one wiki page up to date. Today is ${s}.`,`Subject: "${t.title}" (${n}).`,"","## What the agents' pages say"];for(let i of e.pages)r.push(`### page ${i.agentId}/${i.article.path} (updated ${i.article.meta.lastUpdated||"?"})`,x(O(i.article.content),F),"");if(e.mentions.length){r.push("## Other pages that name the subject");for(let i of e.mentions)r.push(`### page ${i.page.agentId}/${i.page.article.path}: "${i.page.article.meta.title}"`,i.excerpt,"")}r.push("## Source entries (newest first)");for(let i of e.entries)r.push(`### entry ${i.id} (${i.date}, ${i.agentId}, ${i.source})`,x(i.content.trim(),X),"");return r.push("## Event pages",...e.events.map(i=>`- ${i.date||"?"} \xB7 ${i.title}`),""),r.push("## Project pages",...e.projects.map(i=>`- ${i.title}`),""),r.push("## Other pages it may name",...e.neighbours.map(i=>`- ${i.title} (${i.type})`),""),r.push(`## Properties you may use (the subject is always ${t.title})`,...[...e.properties].map(([i,l])=>`- ${i}: "${t.title} ${l} <value>"${e.ranges.get(i)?`, value is a ${e.ranges.get(i).join(" or ")}`:""}`),""),r.push("## Task","Return one JSON object and nothing else:",'{"overview": "\u2026", "statements": [{"property": "\u2026", "value": "\u2026", "role": "\u2026", "since": "YYYY-MM-DD", "until": "YYYY-MM-DD", "source": "\u2026"}], "history": ["event page title"], "projects": ["project page title"]}',"","Rules:",`- overview: 3 to 6 full sentences telling the story of the relationship: who ${t.title} is to us, how it started, what changed, and where it stands now, with dates. Plain prose. Link pages as [[Exact Title]] only when the title is listed above. Never stop mid-sentence.`,"- statements: only facts the pages or entries state. Use only the listed properties. value is a listed page title when it names one, else a short literal. role, since and until only when stated.","- source: the entry id, the page (agent/path) or the event title the fact comes from. A statement without one of these is dropped.","- Do not list an AI agent or bot as a person's relation.","- history: titles of the listed event pages that are about the subject. projects: listed project titles it takes part in.","- Leave out anything you could not verify. Do not write 'unknown' or 'not captured' as a fact.","- Write in the language the pages are written in."),r.join(`
|
|
3
3
|
`)}function re(e){let n=e.match(/```(?:json)?\s*\n([\s\S]*?)\n```/),s=n?n[1]:e.slice(e.indexOf("{"),e.lastIndexOf("}")+1);try{let t=JSON.parse(s);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}var z=/^\d{4}-\d{2}(-\d{2})?$/,b=e=>typeof e=="string"?e.trim():"";function oe(e,n,s){let t=[],r=n.entity,i=b(e.overview);if(i&&!/[.!?؟)»"']$/.test(i)){let o=Math.max(i.lastIndexOf(". "),i.lastIndexOf("? "),i.lastIndexOf("! "));i=o>0?i.slice(0,o+1):"",t.push("overview: unfinished last sentence removed")}let l=[...n.entries.map(o=>o.id),...n.pages.map(o=>`${o.agentId}/${o.article.path}`),...n.pages.map(o=>o.article.path),...n.mentions.map(o=>`${o.page.agentId}/${o.page.article.path}`),...n.mentions.map(o=>o.page.article.path),...n.events.map(o=>o.title)],u=[],p=new Set;for(let o of Array.isArray(e.statements)?e.statements:[]){let d=o??{},w=b(d.property),c=b(d.value),m=b(d.source),a=`${w} ${c}`;if(!n.properties.has(w)){t.push(`${a}: property not allowed`);continue}if(!c||/^(unknown|not (given|known|captured|recorded))\b/i.test(c)){t.push(`${a}: no value`);continue}if(!m||!l.some(k=>m.includes(k))){t.push(`${a}: source not among those given`);continue}let g=s.names.get(v(c)),h=g?s.entities.get(g):void 0;if(h?.id===r.id){t.push(`${a}: points at itself`);continue}if(r.type==="person"&&h?.type==="agent"){t.push(`${a}: an agent is not a person's relation`);continue}let j=n.ranges.get(w);if(j&&h&&!j.includes(h.type)){t.push(`${a}: value is a ${h.type}, expected ${j.join(" or ")}`);continue}let A=`${w}
|
|
4
4
|
${v(c)}`;if(p.has(A))continue;p.add(A);let $={property:w,value:h?.title??c,source:x(m,200)},W=b(d.role);W&&($.role=x(W,80)),z.test(b(d.since))&&($.since=b(d.since)),z.test(b(d.until))&&($.until=b(d.until)),u.push($)}let f=new Map([...n.events,...n.projects].map(o=>[v(o.title),o.title])),E=[];for(let o of[...Array.isArray(e.history)?e.history:[],...Array.isArray(e.projects)?e.projects:[]]){let d=f.get(v(b(o).replace(/^\d{4}-\d{2}-\d{2}\s*·\s*/,"")));d&&!E.includes(d)?E.push(d):!d&&b(o)&&t.push(`link ${b(o)}: no such page`)}return{overview:i,statements:u,links:E,dropped:t}}function ae(e,n){let s=`## Overview
|
|
@@ -13,4 +13,4 @@ ${e.trim()}
|
|
|
13
13
|
`}function ce(e,n,s){let t=p=>`${p.property}
|
|
14
14
|
${v(p.value)}`,r=(e.statements??[]).filter(p=>p.by!==H),i=new Set(r.map(t)),l=[...r,...n.statements.filter(p=>!i.has(t(p))).map(p=>({...p,checked_at:s,by:H}))],u=[...new Set([...e.related??[],...n.links])];return{...e,statements:l.length?l:void 0,related:u.length?u:void 0,lastUpdated:s}}function pe(e,n){return n.pages.filter(s=>!e.syncedFrom(s.agentId)).sort((s,t)=>(t.article.meta.sources?.length??0)-(s.article.meta.sources?.length??0)||t.article.content.length-s.article.content.length)[0]}var le={person:"people",organization:"organizations",project:"projects",place:"places"};function Ee(e,n,s,t,r){let i=n.replace(/\s+/g," ").trim(),l=e.getAgentWiki(t);if(l.listAllArticles().some(E=>v(E.meta.title)===v(i)))return null;let u=`${le[s]??`${s}s`}/${v(i).replace(/ /g,"-").slice(0,80)||"page"}.md`,p=C(s)?s:void 0,f={title:i,type:p,class:s,tags:[],owner:t,access:"shared",created:r,lastUpdated:r,sources:[]};return l.writeArticle(u,f,`${i}.
|
|
15
15
|
`,t)?u:null}function ke(e){let n=P(e,"_enrich","state.json");if(!B(n))return{entities:{}};try{let s=JSON.parse(q(n,"utf-8"));return s&&typeof s.entities=="object"?s:{entities:{}}}catch{return{entities:{}}}}function be(e,n){V(P(e,"_enrich"),{recursive:!0}),K(P(e,"_enrich","state.json"),JSON.stringify(n,null,2))}async function Se(e,n,s,t,r){let i=new Set(t.types),l=new Set(t.only.map(v)),u=c=>c.sources.length+c.pages.length,p=c=>r.entities[c.id]?.failures??0,f=[...n.entities.values()].filter(c=>i.has(c.type)).filter(c=>l.size===0||l.has(v(c.id))||l.has(v(c.title))).sort((c,m)=>p(c)-p(m)||u(m)-u(c)),E=c=>e.getSharedStore().readEntries(c),o={outcomes:[],costUsd:0,capped:!1},d=0,w=(c,m,a,g=!1)=>{if(t.dryRun)return;let h=r.entities[c];r.entities[c]=g?{fingerprint:h?.fingerprint??"",at:new Date().toISOString(),costUsd:a,failures:(h?.failures??0)+1}:{fingerprint:m,at:new Date().toISOString(),costUsd:a},t.save?.(r)};for(let c of f){if(d>=t.max)break;let m={entity:c.id,title:c.title,statements:0,links:0,overview:!1,costUsd:0,dropped:[]},a=pe(e,c);if(!a){o.outcomes.push({...m,status:"no-page"});continue}let g=te(n,c,E,a),h=ie(g);if(!t.force&&r.entities[c.id]?.fingerprint===h){l.size&&o.outcomes.push({...m,status:"unchanged"});continue}if(o.costUsd>=t.maxCostUsd){o.capped=!0;break}d++;let j=n.ontology.types.find(y=>y.id===c.type)?.label??c.type,A=`${a.agentId}/${a.article.path}`,$;try{$=await s(se(g,j,t.today))}catch(y){o.outcomes.push({...m,page:A,status:"failed",dropped:[y.message.slice(0,200)]}),w(c.id,h,0,!0);continue}o.costUsd+=$.costUsd;let W=re($.text),k={...m,page:A,status:"no-reply",costUsd:$.costUsd};if(!W){o.outcomes.push(k),w(c.id,h,$.costUsd);continue}let S=oe(W,g,n);if(Object.assign(k,{statements:S.statements.length,links:S.links.length,overview:!!S.overview,dropped:S.dropped}),!S.overview&&S.statements.length===0&&S.links.length===0){k.status="nothing-new",o.outcomes.push(k),w(c.id,h,$.costUsd);continue}let U=y=>S.overview?ae(y.content,S.overview):y.content;if(t.dryRun){o.outcomes.push({...k,status:"dry-run",preview:U(a.article),facts:S.statements});continue}let R=e.getAgentWiki(a.agentId),I;try{I=R.withArticleLock(a.article.path,()=>{let y=R.readArticle(a.article.path);return y?R.writeArticle(a.article.path,ce(y.meta,S,t.today),U(y),y.meta.owner||a.agentId)?void 0:"write refused":"the page was moved or removed during the run"})}catch(y){if(!(y instanceof G))throw y;I="the page was busy; run again"}if(I){k.status="failed",k.dropped.push(I),o.outcomes.push(k),w(c.id,h,$.costUsd,!0);continue}R.rebuildIndex(),w(c.id,h,$.costUsd),k.status="written",o.outcomes.push(k)}return o}export{H as a,$e as b,Z as c,ee as d,te as e,ne as f,ie as g,se as h,re as i,oe as j,ae as k,ce as l,pe as m,Ee as n,ke as o,be as p,Se as q};
|
|
16
|
-
//# sourceMappingURL=chunk-
|
|
16
|
+
//# sourceMappingURL=chunk-C2VZHIIX.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as
|
|
1
|
+
import{f as j,g}from"./chunk-DODL5POT.js";import{f as h}from"./chunk-QAWKN2N4.js";import{a as z}from"./chunk-IMLAPB7G.js";function E(o,t){return o.ontology.types.find(e=>e.id===t)?.lens??[{panel:"notes",source:"notes",show:1}]}function v(o,t,e){let a=o.ontology.properties.find(n=>n.id===t);return a?e?a.inverse??a.label:a.label:t.replace(/_/g," ")}function G(o,t){let e=o.until??o.date??o.since??"",a=t.until??t.date??t.since??"";return e!==a?a.localeCompare(e):o.label.localeCompare(t.label)}function R(o,t,e,a,n){let r=a?n:e.target?o.entities.get(e.target):void 0,i=[v(o,e.property,a)];return e.role&&i.unshift(e.role.length>40?`${e.role.slice(0,39)}\u2026`:e.role),{label:r?.title??e.value,entityId:r?.id,type:r?.type,chips:i,since:e.since,until:e.until,status:e.status,private:e.access==="private",statement:a?void 0:t.statements.indexOf(e),sub:e.note}}function H(o,t,e){let a=new Set(j(e)),n=e.types?new Set(e.types):null,r=[],i=new Set,s=x=>!n||!!x&&n.has(x.type);for(let x of t.statements){if(!a.has(x.property))continue;let d=x.target?o.entities.get(x.target):void 0;s(d)&&(r.push(R(o,t,x,!1)),d&&i.add(d.id))}for(let x of o.incoming.get(t.id)??[]){if(!a.has(x.property))continue;let d=o.entities.get(x.from);!d||!s(d)||(x.statement?r.push(R(o,t,x.statement,!0,d)):i.has(d.id)||r.push({label:d.title,entityId:d.id,type:d.type,chips:[v(o,"related",!0)],date:d.updated}),i.add(d.id))}if(a.has("related"))for(let x of o.outgoing.get(t.id)??[]){if(x.property!=="related"||i.has(x.to))continue;let d=o.entities.get(x.to);!d||!s(d)||(r.push({label:d.title,entityId:d.id,type:d.type,chips:[v(o,"related",!1)],date:d.updated}),i.add(d.id))}let c=r.filter(x=>!x.chips.includes(v(o,"related",!1))),p=r.filter(x=>x.chips.includes(v(o,"related",!1)));return[...c.sort(G),...p.sort(G)]}function I(o,t,e){let a=new Set;for(let r of o.outgoing.get(t.id)??[])a.add(r.to);for(let r of o.incoming.get(t.id)??[])a.add(r.from);let n=[];for(let r of a){let i=o.entities.get(r);i&&(!e||e.has(i.type))&&n.push(i)}return n.sort((r,i)=>(i.date||i.updated).localeCompare(r.date||r.updated))}function M(o){return{label:o.title,entityId:o.id,type:o.type,chips:[],date:o.date,importance:o.importance}}function T(o,t,e){let a=I(o,t,new Set(["event"])).map(M),n=new Set(e.importance??["major","normal","minor"]),r=a.filter(p=>n.has(p.importance??o.ontology.importance.default)),i=e.fold?a.filter(p=>p.importance===e.fold):[],s=[],c=e.rollup??o.ontology.importance.rollup;if(i.length>=c.min&&i[0].date){let p=Date.parse(i[0].date),x=i.filter(d=>d.date&&p-Date.parse(d.date)<=c.days*864e5);x.length>=c.min&&s.push(`${x.length} minor events in ${c.days} days up to ${i[0].date}`)}return{shown:r,folded:i,rollups:s}}function V(o,t){let e=o.statements.map((r,i)=>({st:r,i})).filter(({st:r})=>r.property==="reading"||!!r.metric).sort((r,i)=>(i.st.at??"").localeCompare(r.st.at??"")),a=new Set,n=[];for(let{st:r,i}of e){let s=r.metric??"reading";t&&a.has(s)||(a.add(s),n.push({label:`${s.replace(/_/g," ")}: ${r.value}`,chips:[],date:r.at,statement:i,private:r.access==="private"}))}return n}function B(o,t){return t(o.sources).sort((e,a)=>a.date.localeCompare(e.date)).map(e=>{let a=e.content.split(`
|
|
2
2
|
`).map(n=>n.trim()).find(Boolean)??"";return{label:a.length>120?`${a.slice(0,117)}\u2026`:a,chips:[],date:e.date,sub:`${e.date} \xB7 ${e.agentId} \xB7 ${e.source}`}})}function P(o,t,e,a){let n=g(e),r=[],i=[],s=[];if(n==="statements")r=H(o,t,e);else if(n==="linked")r=I(o,t,e.types?new Set(e.types):null).map(M);else if(n==="readings")r=V(t,!a.full&&e.latest!==!1);else if(n==="discussed")r=B(t,a.readEntries);else if(n==="history"){let p=T(o,t,e);r=a.full?I(o,t,new Set(["event"])).map(M):p.shown,i=a.full?[]:p.folded,s=p.rollups}let c=r.length;if(a.full){let p=a.pageSize??50,x=Math.max(1,a.page??1);r=r.slice((x-1)*p,x*p)}else r=r.slice(0,e.show??5);return{def:e,title:e.title??e.panel.replace(/_/g," "),items:r,total:c,folded:i,rollups:s,ownerOnly:e.access==="owner"}}function l(o){return String(o??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var O={home:'<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/>',person:'<circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-6 8-6s8 2 8 6"/>',org:'<rect x="4" y="3" width="16" height="18" rx="2"/><path d="M9 7h2M13 7h2M9 11h2M13 11h2M9 15h2M13 15h2"/>',pin:'<path d="M12 21s-7-6.2-7-11a7 7 0 0 1 14 0c0 4.8-7 11-7 11z"/><circle cx="12" cy="10" r="2.5"/>',server:'<rect x="3" y="4" width="18" height="7" rx="2"/><rect x="3" y="13" width="18" height="7" rx="2"/><path d="M7 7.5h.01M7 16.5h.01"/>',device:'<rect x="4" y="5" width="16" height="11" rx="1.5"/><path d="M2 19h20"/>',app:'<rect x="4" y="4" width="16" height="16" rx="3"/><path d="M9 12h6M12 9v6"/>',globe:'<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3.5 3 14.5 0 18M12 3c-3 3.5-3 14.5 0 18"/>',key:'<circle cx="8" cy="15" r="4"/><path d="M11 12l9-9M17 6l3 3"/>',agent:'<rect x="5" y="8" width="14" height="11" rx="3"/><path d="M12 4v4M9 13h.01M15 13h.01"/>',project:'<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9z"/><path d="M4 7.5l8 4.5 8-4.5M12 12v9"/>',contract:'<path d="M7 3h7l5 5v13H7z"/><path d="M14 3v5h5M10 13h6M10 17h4"/>',law:'<path d="M12 3v18M5 21h14M6 7h12M6 7l-3 7a3 3 0 0 0 6 0zM18 7l-3 7a3 3 0 0 0 6 0z"/>',calendar:'<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4"/>',decision:'<path d="M12 3v18M12 8H6l-2 2 2 2h6M12 12h6l2 2-2 2h-6"/>',steps:'<path d="M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2M4 12l1 1 2-2M4 18l1 1 2-2"/>',topic:'<path d="M4 7h16M4 12h10M4 17h7"/>',chat:'<path d="M4 5h16v11H9l-5 4z"/>',lock:'<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/>',arrow:'<path d="M5 12h14M13 6l6 6-6 6"/>',search:'<circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/>',merge:'<circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="12" r="2"/><path d="M6 8v8M8 6c6 0 8 2 8 6"/>'};function m(o){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${O[o??""]??O.topic}</svg>`}function u(o,t){return m(o.types.find(e=>e.id===t)?.icon)}function b(o,t){return o.types.find(e=>e.id===t)?.label??t??""}function f(o){return`/e/${encodeURIComponent(o)}`}function L(o){return`<nav class="ox-crumbs" aria-label="Breadcrumb">${[{label:"Wiki",href:"/"},...o].map((e,a,n)=>a===n.length-1||!e.href?`<b>${l(e.label)}</b>`:`<a href="${e.href}">${l(e.label)}</a>`).join('<span aria-hidden="true">/</span>')}</nav>`}function y(o){let t=["","Pillar","Overview","Panel","Statement"];return`<div class="ox-zoom" title="Zoom level">${[1,2,3,4].map(a=>`<span class="${a===o?"on":""}">Z${a}${a===o?` ${t[a]}`:""}</span>`).join("")}</div>`}function w(o,t){let e=o.ontology,a=`<a class="ox-nav${t.home?" on":""}" href="/">${m("home")}<span>Home</span></a>`,n=e.sidebar.pins.slice(0,e.sidebar.pins_max);if(n.length){a+='<div class="ox-side-h">Pinned</div>';for(let r of n){let i=o.names.get(h(r)),s=i?o.entities.get(i):void 0;s&&(a+=`<a class="ox-nav pin${t.entity===s.id?" on":""}" href="${f(s.id)}">${u(e,s.type)}<span>${l(s.title)}</span></a>`)}}a+='<div class="ox-side-h">Pillars</div>';for(let r of e.pillars)r.sidebar!==!1&&(a+=`<a class="ox-nav${t.pillar===r.id?" on":""}" href="/p/${encodeURIComponent(r.id)}">${m(r.icon)}<span>${l(r.label)}</span></a>`);return a+='<div class="ox-side-foot">Types, topics and agent wikis are one level down, on Home and the pillar pages.</div>',a}function $(o,t,e,a="",n=""){return`<!DOCTYPE html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
@@ -149,4 +149,4 @@ body>a[href="/admin"]+.ox-app .ox-top{padding-right:130px}
|
|
|
149
149
|
`;var F=()=>new Date().toISOString().slice(0,10);function q(o){return o?`<span class="ox-st ${l(o)}">${l(o)}</span>`:""}function K(o){return o.private?`<span class="l"><span class="ox-mask">\u2022\u2022\u2022\u2022</span> ${m("lock")}</span>`:o.entityId?`<a href="${f(o.entityId)}">${l(o.label)}</a>`:`<span class="l">${l(o.label)}</span>`}function J(o,t){if(t.sub)return t.sub;let e=[];return t.type&&e.push(b(o.ontology,t.type).toLowerCase()),t.since||t.until?e.push(`${t.since??"\u2026"} \u2192 ${t.until??"now"}`):t.date&&e.push(t.date),e.join(" \xB7 ")}function Y(o,t,e){let a=J(o,e),n=e.chips.map(i=>`<span class="ox-chip">${l(i)}</span>`).join(""),r=e.statement!==void 0&&e.statement>=0?`<a class="ox-sub" href="${f(t.id)}/s/${e.statement}" title="Where this comes from (Z4)">Z4</a>`:"";return`<div class="ox-row"><span class="ox-ic">${e.type?u(o.ontology,e.type):m(e.private?"lock":"topic")}</span><div class="t">${K(e)}${a?`<div class="ox-sub">${l(a)}</div>`:""}</div><div class="r">${n}${q(e.status)}${r}</div></div>`}function U(o){let t=o.importance??"normal";return`<div class="ox-ev"><span class="d">${l(o.date??"")}</span><span class="ox-st ${t}">${t}</span><span>${o.entityId?`<a href="${f(o.entityId)}">${l(o.label)}</a>`:l(o.label)}</span></div>`}function Q(o){let t=o.flatMap(s=>[s.since,s.until]).filter(s=>!!s).map(s=>Number(s.slice(0,4))).filter(Boolean),e=Number(F().slice(0,4)),a=Math.min(...t,e-1),n=Math.max(1,e+1-a),r=(s,c)=>{if(!s)return c?100:0;let[p,x]=[Number(s.slice(0,4)),Number(s.slice(5,7))||(c?12:1)];return Math.min(100,Math.max(0,(p-a+(x-1)/12)/n*100))},i=`<div class="ox-tl-axis"><span></span><span class="yrs"><span>${a}</span><span>${e}</span></span></div>`;for(let s of o){let c=r(s.since,!1),p=r(s.until,!0),x=`${s.since??"\u2026"} \u2192 ${s.until??"now"}`;i+=`<div class="ox-tl-row"><div class="who">${s.chips.map(l).join(", ")}<small>${s.entityId?`<a href="${f(s.entityId)}">${l(s.label)}</a>`:l(s.label)}</small></div><div class="ox-track"><i class="${s.until?"past":""}" style="left:${c.toFixed(1)}%;width:${Math.max(4,p-c).toFixed(1)}%" title="${l(x)}">${l(x)}</i></div></div>`}return i}function S(o,t,e,a,n=""){let r=!a&&(e.total>e.items.length||e.def.source==="notes"||e.folded.length)?`<a class="zin" href="${f(t.id)}/${encodeURIComponent(e.def.panel)}">all ${e.total||""} (Z3) \u2192</a>`:"",s=e.def.source==="notes"||e.def.panel==="notes"?`${t.pages.length} page${t.pages.length===1?"":"s"}`:`${e.total} ${e.total===1?"item":"items"}`,c=`<span class="note">${e.ownerOnly?`${m("lock")} private to the owner \xB7 `:""}${s}</span>`,p="";e.def.source==="notes"||e.def.panel==="notes"?p=n||'<div class="ox-empty">No notes.</div>':e.items.length===0?p='<div class="ox-empty">Nothing recorded yet.</div>':e.def.display==="timeline"&&e.items.some(d=>d.since)?p=Q(e.items):e.def.source==="history"||e.items.every(d=>d.type==="event")?p=e.items.map(U).join(""):p=e.items.map(d=>Y(o,t,d)).join("");for(let d of e.rollups)p+=`<div class="ox-fold">\u21BB Recurring: ${l(d)}</div>`;return e.folded.length&&(p+=`<details class="ox-fold"><summary>+ ${e.folded.length} minor event${e.folded.length===1?"":"s"}</summary>${e.folded.slice(0,20).map(U).join("")}</details>`),`<section class="ox-card${e.def.display==="timeline"||e.def.source==="notes"||e.def.panel==="notes"?" wide":""}"><div class="ox-card-h"><h2>${l(e.title)}</h2>${c}${r}</div>${p}</section>`}function C(o,t){return z(t.replace(/<!--\s*tags?:[^>]*-->\s*\n?/gi,"").replace(/<!-- \/overview -->\s*\n?/g,""),{wikilink:(e,a)=>{let n=o.names.get(h(e));return n?`<a href="${f(n)}" class="wikilink">${a}</a>`:`<a href="/find?q=${encodeURIComponent(e)}" class="wikilink broken" title="No page yet">${a}</a>`}})}function k(o){return o.replace(/^---\n[\s\S]*?\n---\n?/,"").trim()}var X=/^##[ \t]+Overview[ \t]*$/im,N="<!-- /overview -->";function D(o){let t=X.exec(o);if(!t)return;let e=t.index+t[0].length,a=o.slice(e),n=a.indexOf(N),r=a.search(/^#{1,2}[ \t]/m),i=[n,r].filter(p=>p>=0),s=e+(i.length?Math.min(...i):a.length),c=n>=0&&e+n===s?s+N.length:s;return{start:t.index,textStart:e,end:s,after:c}}function ee(o){let t=k(o),e=D(t);return(e?t.slice(e.textStart,e.end).trim():"")||void 0}function te(o){let t=[...o.pages].sort((e,a)=>(a.article.meta.lastUpdated||"").localeCompare(e.article.meta.lastUpdated||""));for(let e of t){let a=ee(e.article.content);if(a)return a}}function oe(o,t){if(o.length<=t)return o;let e=o.slice(0,t),a=Math.max(...[". ","! ","? ","\u061F ","\u3002"].map(n=>e.lastIndexOf(n)));return a>t/3?e.slice(0,a+1):`${e.replace(/\s+\S*$/,"")}\u2026`}function ne(o,t=360){let n=(k(o.pages[0]?.article.content??"").split(/\n\s*\n/).map(r=>r.trim()).find(r=>r&&!r.startsWith("#")&&!r.startsWith("|")&&!r.startsWith("```"))??"").replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g,(r,i,s)=>s??i).replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/^[-*]\s+/gm,"").replace(/[*_`]/g,"").replace(/\s+/g," ").trim();return oe(n,t)}function ae(o,t){return o.ontology.pillars.find(e=>e.id===t.pillar)}function W(o,t,e=[]){let a=ae(o,t);return L([{label:a?.label??t.pillar,href:`/p/${encodeURIComponent(t.pillar)}`},{label:b(o.ontology,t.type),href:`/p/${encodeURIComponent(t.pillar)}?kind=${encodeURIComponent(t.type)}`},{label:t.title,href:e.length?f(t.id):void 0},...e])}function _(o,t,e){if(!e){let a=t.pages[0];if(!a)return"";let n=k(a.article.content),r=D(n),i=(r?n.slice(0,r.start)+n.slice(r.after):n).trim(),s=i.length>1600?`${i.slice(0,1600).replace(/\n[^\n]*$/,"")}
|
|
150
150
|
|
|
151
151
|
\u2026`:i;return`<div class="ox-prose">${C(o,s)}</div>`}return t.pages.map(a=>`<div class="ox-sub">from ${l(a.agentId)} \xB7 ${l(a.article.path)} \xB7 updated ${l(a.article.meta.lastUpdated||"\u2014")}</div><div class="ox-prose">${C(o,k(a.article.content))}</div>`).join('<hr style="border:0;border-top:1px solid var(--edge);margin:16px 0">')}function re(o,t,e){let a=o.ontology.types.find(i=>i.id===t.type),n=`<span class="ox-lbl">Lens for this type</span><div class="ox-annot"><b>${l(a?.label??t.type)}</b> opens with:<ol>`;n+=e.map(i=>`<li>${l(i.title??i.panel)}</li>`).join(""),n+=`</ol><span class="ox-sub">from ontology.yaml \xB7 types.${l(t.type)}.lens</span></div>`,n+='<span class="ox-lbl" style="margin-top:20px">Zoom in</span>';for(let i of e)n+=`<div class="ox-row"><span class="ox-ic">${m(g(i)==="history"?"calendar":g(i)==="discussed"?"chat":"arrow")}</span><div class="t"><a href="${f(t.id)}/${encodeURIComponent(i.panel)}">${l(i.title??i.panel)}</a><div class="ox-sub">Z3 \xB7 in full</div></div></div>`;n+='<span class="ox-lbl" style="margin-top:20px">Provenance</span>';let r=new Map;for(let i of t.pages)r.set(i.agentId,(r.get(i.agentId)??0)+1);for(let[i,s]of r){let c=t.pages.find(p=>p.agentId===i);n+=`<div class="ox-row"><span class="ox-ic">${m("agent")}</span><div class="t"><a href="/agent/${encodeURIComponent(i)}/article/${encodeURIComponent(c.article.path)}">${l(i)}</a><div class="ox-sub">${s} page${s===1?"":"s"} \xB7 ${t.statements.filter(p=>p.page.agentId===i).length} statements</div></div></div>`}return t.pages.length>1&&(n+=`<div class="ox-row"><span class="ox-ic">${m("merge")}</span><div class="t"><span class="l">${t.pages.length} pages merged</span><div class="ox-sub">same name, one entity</div></div></div>`),n}function ve(o,t){let{g:e}=o,a=E(e,t.type),n=e.ontology.types.find(p=>p.id===t.type),r=e.ontology.sidebar.pins.some(p=>e.names.get(h(p))===t.id),i=`<div class="ox-bar">${W(e,t)}${y(2)}</div>`;i+=`<div class="ox-head"><div class="ox-avatar">${u(e.ontology,t.type)}</div><div><h1>${l(t.title)}</h1><div class="ox-chips">`,i+=`<span class="ox-chip type">${u(e.ontology,t.type)}${l(n?.label??t.type)}</span>`,n?.schema&&(i+=`<span class="ox-chip mono">${l(n.schema.includes(" ")||n.schema.includes(":")?n.schema:`schema.org/${n.schema}`)}</span>`),t.type==="event"&&(i+=`<span class="ox-st ${t.importance}">${t.importance}</span>`),r&&(i+='<span class="ox-chip">pinned</span>'),t.pages.length>1&&(i+=`<span class="ox-chip">${m("merge")}merged from ${t.pages.length} pages</span>`),i+="</div></div></div>",t.review&&(i+=`<div class="ox-card ox-sub" style="border-color:var(--warn,#d97706)">Check the type: ${l(t.review)}</div>`);let s=te(t),c=s?"":ne(t);if((s||c)&&a[0]?.panel!=="notes"){let p=s?`<div class="ox-summary ox-prose">${C(e,s)}</div>`:`<p class="ox-summary">${l(c)}</p>`;i+=`<section class="ox-card">${p}<div class="ox-meta"><span>updated ${l(t.updated||"\u2014")}</span><span>sources: ${t.sources.length}</span><span>${t.statements.length} statements</span></div></section>`}i+='<div class="ox-grid2">';for(let p of a){let x=P(e,t,p,{full:!1,readEntries:o.readEntries}),d=g(p)==="notes";i+=S(e,t,x,!1,d?_(e,t,!1):"")}return i+="</div>",$(t.title,w(e,{pillar:t.pillar,entity:t.id}),i,re(e,t,a))}function be(o,t,e,a){let{g:n}=o,r=E(n,t.type).find(d=>d.panel===e);if(!r)return null;let i=P(n,t,r,{full:!0,page:a,pageSize:50,readEntries:o.readEntries}),s=r.title??r.panel,c=`<div class="ox-bar">${W(n,t,[{label:s}])}${y(3)}</div>`;c+=`<div class="ox-head"><div class="ox-avatar">${u(n.ontology,t.type)}</div><div><h1>${l(s)}</h1><p>${l(t.title)} \xB7 ${i.total} item${i.total===1?"":"s"}</p></div></div>`;let p=g(r)==="notes";c+=S(n,t,i,!0,p?_(n,t,!0):"");let x=Math.ceil(i.total/50);if(x>1){let d=`${f(t.id)}/${encodeURIComponent(e)}`;c+=`<div class="ox-pager">${a>1?`<a href="${d}?page=${a-1}">\u2190 newer</a>`:""}<span>page ${a} of ${x}</span>${a<x?`<a href="${d}?page=${a+1}">older \u2192</a>`:""}</div>`}return $(`${s} \xB7 ${t.title}`,w(n,{pillar:t.pillar,entity:t.id}),c)}function ye(o,t,e){let{g:a}=o,n=t.statements[e];if(!n)return null;let r=a.ontology.properties.find(d=>d.id===n.property),i=n.target?a.entities.get(n.target):void 0,s=n.page.article.meta,c=[["Subject",`<a href="${f(t.id)}">${l(t.title)}</a>`],["Property",`${l(r?.label??n.property)}${r?.wikidata?` <span class="ox-sub">wikidata ${l(r.wikidata)}</span>`:""}`],["Value",i?`<a href="${f(i.id)}">${l(i.title)}</a>`:l(n.value)]];n.role&&c.push(["Role",l(n.role)]),n.metric&&c.push(["Metric",l(n.metric)]),(n.since||n.until)&&c.push(["True",`${l(n.since??"\u2026")} \u2192 ${l(n.until??"now")}`]),n.at&&c.push(["Measured",l(n.at)]),c.push(["Recorded",l(s.lastUpdated||s.created||"\u2014")]),c.push(["Source",l(n.source??(s.sources.length?`${s.sources.length} conversation entries`:"not given"))]),c.push(["Written by",`${l(n.page.agentId)} \xB7 <a href="/agent/${encodeURIComponent(n.page.agentId)}/article/${encodeURIComponent(n.page.article.path)}">${l(n.page.article.path)}</a>`]),c.push(["Status",n.status?`<span class="ox-st ${l(n.status)}">${l(n.status)}</span>`:"not set"]),n.confirmed_by&&c.push(["Confirmed by",l(n.confirmed_by)]),n.checked_at&&c.push(["Checked",l(n.checked_at)]),c.push(["Access",l(n.access??s.access)]),n.note&&c.push(["Note",l(n.note)]);let p=o.versions(n.page.agentId,n.page.article.path);c.push(["Past versions",p.length?p.slice(0,8).map(d=>l(d.timestamp)).join("<br>"):"none saved"]);let x=`<div class="ox-bar">${W(a,t,[{label:r?.label??n.property}])}${y(4)}</div>`;return x+=`<div class="ox-head"><div class="ox-avatar">${m("key")}</div><div><h1>${l(r?.label??n.property)}</h1><p>${l(t.title)} \u2192 ${l(i?.title??n.value)}</p></div></div>`,x+=`<section class="ox-card">${c.map(([d,A])=>`<div class="ox-kv"><span class="k">${d}</span><span>${A}</span></div>`).join("")}</section>`,$(`${r?.label??n.property} \xB7 ${t.title}`,w(a,{pillar:t.pillar,entity:t.id}),x)}export{I as a,l as b,m as c,u as d,b as e,f,L as g,y as h,w as i,$ as j,k,N as l,D as m,ne as n,ve as o,be as p,ye as q};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-CAYY2IEV.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-
|
|
1
|
+
import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-QOEO27LF.js";import{a as H}from"./chunk-LUOW2YHY.js";import{y as N,z as ot}from"./chunk-WKR2OSCH.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
|
|
2
2
|
|
|
3
3
|
## Shared wiki (other agents' articles)
|
|
4
4
|
|
|
@@ -51,5 +51,5 @@ ${o}
|
|
|
51
51
|
|
|
52
52
|
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
53
53
|
|
|
54
|
-
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-
|
|
55
|
-
//# sourceMappingURL=chunk-
|
|
54
|
+
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-SZZQFIJF.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
|
|
55
|
+
//# sourceMappingURL=chunk-CJI26AJC.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as g}from"./chunk-
|
|
1
|
+
import{e as g}from"./chunk-CJI26AJC.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-EMWSFITR.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{s as p}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{s as p}from"./chunk-IAR5F3T5.js";import{b as i,c as u,d as l,e as c}from"./chunk-P65XGEB7.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,g=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',m=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function x(e){return m.test(e)}function w(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function S(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function $(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??g,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.report==="exceptions"&&(t.report="exceptions"),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){return e.deliverResult===!1?"(failures only)":e.report==="exceptions"?"(exceptions and failures)":"(results and failures)"}function T(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function A(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function D(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function y(e){return e?.approval?.action==="create"}async function R(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&y(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,x as c,w as d,S as e,$ as f,P as g,T as h,A as i,D as j,y as k,R as l,I as m,O as n};
|
|
2
|
+
//# sourceMappingURL=chunk-EQPMQSJE.js.map
|