agentix-cli 0.26.0 → 0.28.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/README.md +67 -118
- package/apps/mac-helper/Sources/AgentXHelper/AXTree.swift +159 -0
- package/apps/mac-helper/Sources/AgentXHelper/Brand.swift +63 -0
- package/apps/mac-helper/Sources/AgentXHelper/Focus.swift +97 -0
- package/apps/mac-helper/Sources/AgentXHelper/HUD.swift +179 -0
- package/apps/mac-helper/Sources/AgentXHelper/OCR.swift +117 -0
- package/apps/mac-helper/Sources/AgentXHelper/Pointer.swift +309 -0
- package/apps/mac-helper/Sources/AgentXHelper/Screens.swift +67 -0
- package/apps/mac-helper/Sources/AgentXHelper/Typer.swift +185 -0
- package/apps/mac-helper/Sources/AgentXHelper/Vision.swift +201 -0
- package/apps/mac-helper/Sources/AgentXHelper/main.swift +265 -0
- package/apps/mac-helper/build.sh +39 -0
- package/apps/mac-voice/Resources/Info.plist +18 -0
- package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +108 -0
- package/apps/mac-voice/Sources/AgentXVoice/Brand.swift +123 -0
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +68 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hold.swift +74 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hotkey.swift +76 -0
- package/apps/mac-voice/Sources/AgentXVoice/Markdown.swift +140 -0
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +275 -0
- package/apps/mac-voice/Sources/AgentXVoice/Progress.swift +147 -0
- package/apps/mac-voice/Sources/AgentXVoice/Recorder.swift +139 -0
- package/apps/mac-voice/Sources/AgentXVoice/ResultCard.swift +162 -0
- package/apps/mac-voice/Sources/AgentXVoice/SmartPaste.swift +72 -0
- package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +192 -0
- package/apps/mac-voice/Sources/AgentXVoice/StepLabel.swift +159 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +380 -0
- package/apps/mac-voice/build.sh +32 -0
- package/dist/{App-BPNHIGUX.js → App-CKPH3HHF.js} +2 -2
- package/dist/{ChatApp-6XSSZB4U.js → ChatApp-MX7IG4K2.js} +2 -2
- package/dist/agent-2U574KBZ.js +2 -0
- package/dist/article-fields-L4D2BOGY.js +2 -0
- package/dist/article-quality-44ONVGLN.js +3 -0
- package/dist/article-quality-44ONVGLN.js.map +1 -0
- package/dist/{audit-JU3HWISB.js → audit-4245CX6P.js} +2 -2
- package/dist/backfill-MTD2B62I.js +6 -0
- package/dist/backfill-MTD2B62I.js.map +1 -0
- package/dist/{board-dashboard-M3372FLO.js → board-dashboard-QR7CVTKA.js} +1411 -453
- package/dist/board-dashboard-QR7CVTKA.js.map +1 -0
- package/dist/{builtin-FRKAQMFS.js → builtin-B67DMJ3M.js} +2 -2
- package/dist/calibration-ILS5OI44.js +2 -0
- package/dist/{chunk-V3U4OF7L.js → chunk-3LYM22IV.js} +46 -48
- package/dist/chunk-3LYM22IV.js.map +1 -0
- package/dist/chunk-3SCPRYJB.js +5 -0
- package/dist/chunk-3SCPRYJB.js.map +1 -0
- package/dist/chunk-4BR7D2OU.js +36 -0
- package/dist/chunk-4BR7D2OU.js.map +1 -0
- package/dist/{chunk-P4VWIVKN.js → chunk-52ZPELD2.js} +403 -29
- package/dist/chunk-52ZPELD2.js.map +1 -0
- package/dist/chunk-5IA2CYHN.js +5 -0
- package/dist/{chunk-O6YPEOQF.js.map → chunk-5IA2CYHN.js.map} +1 -1
- package/dist/chunk-64CAIB3C.js +9 -0
- package/dist/chunk-64CAIB3C.js.map +1 -0
- package/dist/{chunk-5U35WAZF.js → chunk-77OV7346.js} +6 -6
- package/dist/chunk-77OV7346.js.map +1 -0
- package/dist/chunk-AJ5RMU7X.js +2 -0
- package/dist/chunk-AJ5RMU7X.js.map +1 -0
- package/dist/chunk-AJONZWLT.js +2 -0
- package/dist/chunk-AJONZWLT.js.map +1 -0
- package/dist/chunk-BH3GTCZ6.js +2 -0
- package/dist/chunk-BH3GTCZ6.js.map +1 -0
- package/dist/chunk-E3UJHQGN.js +1189 -0
- package/dist/chunk-E3UJHQGN.js.map +1 -0
- package/dist/chunk-EVWEG3VD.js +3 -0
- package/dist/chunk-EVWEG3VD.js.map +1 -0
- package/dist/chunk-F4HZTZHW.js +2 -0
- package/dist/chunk-F4HZTZHW.js.map +1 -0
- package/dist/chunk-F6CNF7V3.js +25 -0
- package/dist/chunk-F6CNF7V3.js.map +1 -0
- package/dist/chunk-FIOB3MEX.js +2 -0
- package/dist/{chunk-H5D7ATXS.js → chunk-FKBGJYWQ.js} +5 -5
- package/dist/chunk-FKBGJYWQ.js.map +1 -0
- package/dist/{chunk-BVGJSPW4.js → chunk-G2HMRDUQ.js} +7 -7
- package/dist/chunk-G2HMRDUQ.js.map +1 -0
- package/dist/chunk-H2QQU2XV.js +109 -0
- package/dist/chunk-H2QQU2XV.js.map +1 -0
- package/dist/{chunk-LDHPMJ7M.js → chunk-IWMW5432.js} +3 -3
- package/dist/chunk-IWMW5432.js.map +1 -0
- package/dist/chunk-K33GIBSE.js +2 -0
- package/dist/chunk-K33GIBSE.js.map +1 -0
- package/dist/chunk-L2WSPY6S.js +2 -0
- package/dist/chunk-L2WSPY6S.js.map +1 -0
- package/dist/chunk-LCIREYTD.js +54 -0
- package/dist/chunk-LCIREYTD.js.map +1 -0
- package/dist/chunk-MHIMGM4G.js +126 -0
- package/dist/chunk-MHIMGM4G.js.map +1 -0
- package/dist/chunk-P5ZBBEPL.js +13 -0
- package/dist/chunk-P5ZBBEPL.js.map +1 -0
- package/dist/{chunk-JTJIPNXY.js → chunk-PNWNVOEZ.js} +1 -1
- package/dist/chunk-PNWNVOEZ.js.map +1 -0
- package/dist/chunk-QHTQPBHU.js +45 -0
- package/dist/chunk-QHTQPBHU.js.map +1 -0
- package/dist/chunk-S2MNL5V6.js +2 -0
- package/dist/chunk-S2MNL5V6.js.map +1 -0
- package/dist/chunk-SCTIUFL4.js +5 -0
- package/dist/{chunk-K2CAPYES.js.map → chunk-SCTIUFL4.js.map} +1 -1
- package/dist/chunk-ULLAE6LE.js +157 -0
- package/dist/chunk-ULLAE6LE.js.map +1 -0
- package/dist/{chunk-DJEZ2HVU.js → chunk-VDMYBPYB.js} +1 -1
- package/dist/chunk-VDMYBPYB.js.map +1 -0
- package/dist/chunk-VIH7ARPF.js +547 -0
- package/dist/chunk-VIH7ARPF.js.map +1 -0
- package/dist/chunk-W5C2GDNC.js +32 -0
- package/dist/{chunk-JP5IEXR7.js.map → chunk-W5C2GDNC.js.map} +1 -1
- package/dist/chunk-WPMX3VGI.js +3 -0
- package/dist/chunk-WPMX3VGI.js.map +1 -0
- package/dist/chunk-YLBERT7N.js +24 -0
- package/dist/chunk-YLBERT7N.js.map +1 -0
- package/dist/chunk-YLGIZRHV.js +114 -0
- package/dist/chunk-YLGIZRHV.js.map +1 -0
- package/dist/chunk-ZMYGXHPT.js +121 -0
- package/dist/chunk-ZMYGXHPT.js.map +1 -0
- package/dist/chunk-ZTEU5JVQ.js +2 -0
- package/dist/chunk-ZTEU5JVQ.js.map +1 -0
- package/dist/{chunk-2WVX3LEC.js → chunk-ZVP6GB4G.js} +1 -1
- package/dist/chunk-ZVP6GB4G.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-ZLSXGPTV.js +2 -0
- package/dist/{compaction-NWEMOSHA.js → compaction-FD4R23HZ.js} +4 -4
- package/dist/config-HMW3EBZL.js +2 -0
- package/dist/config-mutator-4SZ5YEVD.js +2 -0
- package/dist/{conflict-detector-D7VIYPDI.js → conflict-detector-ZPOT3M2C.js} +2 -2
- package/dist/conflict-detector-ZPOT3M2C.js.map +1 -0
- package/dist/context-planner-AQHJMVY2.js +17 -0
- package/dist/context-planner-AQHJMVY2.js.map +1 -0
- package/dist/debug-3MEUO2P2.js +2 -0
- package/dist/{discover-XJXQXXIO.js → discover-D4VVRNAI.js} +2 -2
- package/dist/discover-D4VVRNAI.js.map +1 -0
- package/dist/doctor-LRYV3QLK.js +2 -0
- package/dist/editor-chat-OB7IQOB5.js +137 -0
- package/dist/editor-chat-OB7IQOB5.js.map +1 -0
- package/dist/entry-triage-LK34TSQD.js +2 -0
- package/dist/entry-triage-LK34TSQD.js.map +1 -0
- package/dist/facts-YVEJOM7O.js +22 -0
- package/dist/facts-YVEJOM7O.js.map +1 -0
- package/dist/heal-FVLBHYP7.js +2 -0
- package/dist/index.d.ts +1040 -64
- package/dist/index.js +12 -19
- package/dist/index.js.map +1 -1
- package/dist/{ingest-whatsapp-LZE62INA.js → ingest-whatsapp-NS4OWDOU.js} +2 -2
- package/dist/loader-4ZGTK7LD.js +2 -0
- package/dist/loader-BOKE5M5S.js +2 -0
- package/dist/memory-extract-F5ZHWY5E.js +2 -0
- package/dist/{migrate-v2-QO7SLKIM.js → migrate-v2-V4WN2VVM.js} +2 -2
- package/dist/ntfy-X7EPB3TG.js +4 -0
- package/dist/ntfy-X7EPB3TG.js.map +1 -0
- package/dist/processes-WU23U2OJ.js +2 -0
- package/dist/program-GSZ5AYAM.js +2 -0
- package/dist/{projects-api-KRME2YKZ.js → projects-api-QE6L65SK.js} +2 -2
- package/dist/{projects-mutate-3NHVG437.js → projects-mutate-MY7JTLSZ.js} +2 -2
- package/dist/providers-KO2DODIO.js +2 -0
- package/dist/query-SQDHE4HV.js +2 -0
- package/dist/questions-4B4KSPXG.js +3 -0
- package/dist/questions-4B4KSPXG.js.map +1 -0
- package/dist/recipes-7S4MC5OJ.js +2 -0
- package/dist/registry-LE6FWYZC.js +2 -0
- package/dist/review-candidates-RQU5KNZM.js +4 -0
- package/dist/review-candidates-RQU5KNZM.js.map +1 -0
- package/dist/review-store-B4YE3EFK.js +4 -0
- package/dist/review-store-B4YE3EFK.js.map +1 -0
- package/dist/{rotation-memo-B3EXXSEH.js → rotation-memo-7T75BLEX.js} +2 -2
- package/dist/routing-ILERJXB6.js +2 -0
- package/dist/runner-YRBVNYTY.js +2 -0
- package/dist/scheduler-BFM3EINS.js +2 -0
- package/dist/seat-7WM7II2B.js +2 -0
- package/dist/select-X4KVMOP5.js +2 -0
- package/dist/select-X4KVMOP5.js.map +1 -0
- package/dist/store-MCOA6N4F.js +2 -0
- package/dist/{subagent-WV7QKQ3L.js → subagent-2SJHSSJS.js} +2 -2
- package/dist/{surface-usage-PRL6Z4U3.js → surface-usage-NS74AXSE.js} +2 -2
- package/dist/timers-PCB4ZIBD.js +2 -0
- package/dist/triage-backtest-JNO7RKX7.js +2 -0
- package/dist/triage-backtest-JNO7RKX7.js.map +1 -0
- package/dist/types-H5ENIUIT.js +2 -0
- package/dist/types-OIFU3KSQ.js +2 -0
- package/dist/types-OIFU3KSQ.js.map +1 -0
- package/dist/web/workflow-editor.global.js +1542 -0
- package/dist/web/workflow-editor.global.js.map +1 -0
- package/dist/{whatsapp-state-XMTCSRXU.js → whatsapp-state-6D6FHHD2.js} +2 -2
- package/dist/wiki-2AUFSIKO.js +2 -0
- package/dist/wiki-2AUFSIKO.js.map +1 -0
- package/dist/workflows/templates/branching.yaml +1 -1
- package/dist/{workspace-setup-TBQAHYHJ.js → workspace-setup-B3F3TUDE.js} +2 -2
- package/dist/workspace-setup-B3F3TUDE.js.map +1 -0
- package/package.json +14 -3
- package/scripts/postinstall.mjs +80 -0
- package/dist/agent-5QMITZT6.js +0 -2
- package/dist/architect-SEPWMWS4.js +0 -2
- package/dist/board-dashboard-M3372FLO.js.map +0 -1
- package/dist/chunk-2WVX3LEC.js.map +0 -1
- package/dist/chunk-3WQFCIB6.js +0 -24
- package/dist/chunk-3WQFCIB6.js.map +0 -1
- package/dist/chunk-4YCH6IZV.js +0 -2
- package/dist/chunk-53NRX2NA.js +0 -2
- package/dist/chunk-53NRX2NA.js.map +0 -1
- package/dist/chunk-5U35WAZF.js.map +0 -1
- package/dist/chunk-BFXONUUN.js +0 -108
- package/dist/chunk-BFXONUUN.js.map +0 -1
- package/dist/chunk-BFZUG66X.js +0 -45
- package/dist/chunk-BFZUG66X.js.map +0 -1
- package/dist/chunk-BTHHSY7D.js +0 -13
- package/dist/chunk-BTHHSY7D.js.map +0 -1
- package/dist/chunk-BVGJSPW4.js.map +0 -1
- package/dist/chunk-D46VZ7K7.js +0 -116
- package/dist/chunk-D46VZ7K7.js.map +0 -1
- package/dist/chunk-DJEZ2HVU.js.map +0 -1
- package/dist/chunk-E5CXCI33.js +0 -155
- package/dist/chunk-E5CXCI33.js.map +0 -1
- package/dist/chunk-FDWOECJY.js +0 -54
- package/dist/chunk-FDWOECJY.js.map +0 -1
- package/dist/chunk-H5D7ATXS.js.map +0 -1
- package/dist/chunk-HR4JSRZS.js +0 -3
- package/dist/chunk-HR4JSRZS.js.map +0 -1
- package/dist/chunk-ISEBLHWX.js +0 -118
- package/dist/chunk-ISEBLHWX.js.map +0 -1
- package/dist/chunk-JP5IEXR7.js +0 -32
- package/dist/chunk-JTJIPNXY.js.map +0 -1
- package/dist/chunk-K2CAPYES.js +0 -5
- package/dist/chunk-LDHPMJ7M.js.map +0 -1
- package/dist/chunk-METYYZKQ.js +0 -1115
- package/dist/chunk-METYYZKQ.js.map +0 -1
- package/dist/chunk-MTAPOCGA.js +0 -47
- package/dist/chunk-MTAPOCGA.js.map +0 -1
- package/dist/chunk-O6YPEOQF.js +0 -5
- package/dist/chunk-P4VWIVKN.js.map +0 -1
- package/dist/chunk-SR3X25TN.js +0 -3
- package/dist/chunk-SR3X25TN.js.map +0 -1
- package/dist/chunk-UHE5FCPB.js +0 -431
- package/dist/chunk-UHE5FCPB.js.map +0 -1
- package/dist/chunk-V3U4OF7L.js.map +0 -1
- package/dist/chunk-VJUTQAPJ.js +0 -2
- package/dist/chunk-VJUTQAPJ.js.map +0 -1
- package/dist/chunk-VT5XYFDD.js +0 -126
- package/dist/chunk-VT5XYFDD.js.map +0 -1
- package/dist/client-HGKAC6VP.js +0 -2
- package/dist/config-A4RWEJHV.js +0 -2
- package/dist/config-mutator-MNSFUN7D.js +0 -2
- package/dist/conflict-detector-D7VIYPDI.js.map +0 -1
- package/dist/context-planner-45GEWKGL.js +0 -17
- package/dist/context-planner-45GEWKGL.js.map +0 -1
- package/dist/debug-N3B5NVJU.js +0 -2
- package/dist/discover-XJXQXXIO.js.map +0 -1
- package/dist/doctor-3Q36ZFE6.js +0 -2
- package/dist/heal-HZ3EQD52.js +0 -2
- package/dist/loader-5CA3O5GM.js +0 -2
- package/dist/loader-6IHUCPVO.js +0 -2
- package/dist/memory-extract-AENFVVO5.js +0 -2
- package/dist/processes-UIC4XXA6.js +0 -2
- package/dist/program-SAUNRCCD.js +0 -2
- package/dist/providers-L27BJ5A6.js +0 -2
- package/dist/query-HZYYRCLU.js +0 -2
- package/dist/recipes-EPLE2SNT.js +0 -2
- package/dist/registry-HK3WQ7BS.js +0 -2
- package/dist/runner-BFYDWPUO.js +0 -2
- package/dist/scheduler-6T2SU5ST.js +0 -2
- package/dist/store-I3HEWVLQ.js +0 -2
- package/dist/timers-5LPZN55J.js +0 -2
- package/dist/types-VECTMYTO.js +0 -2
- package/dist/types-Y6ZCZ52Z.js +0 -2
- package/dist/wiki-M6YNRFC4.js +0 -2
- /package/dist/{App-BPNHIGUX.js.map → App-CKPH3HHF.js.map} +0 -0
- /package/dist/{ChatApp-6XSSZB4U.js.map → ChatApp-MX7IG4K2.js.map} +0 -0
- /package/dist/{agent-5QMITZT6.js.map → agent-2U574KBZ.js.map} +0 -0
- /package/dist/{architect-SEPWMWS4.js.map → article-fields-L4D2BOGY.js.map} +0 -0
- /package/dist/{audit-JU3HWISB.js.map → audit-4245CX6P.js.map} +0 -0
- /package/dist/{builtin-FRKAQMFS.js.map → builtin-B67DMJ3M.js.map} +0 -0
- /package/dist/{chunk-4YCH6IZV.js.map → calibration-ILS5OI44.js.map} +0 -0
- /package/dist/{client-HGKAC6VP.js.map → chunk-FIOB3MEX.js.map} +0 -0
- /package/dist/{config-A4RWEJHV.js.map → client-ZLSXGPTV.js.map} +0 -0
- /package/dist/{compaction-NWEMOSHA.js.map → compaction-FD4R23HZ.js.map} +0 -0
- /package/dist/{config-mutator-MNSFUN7D.js.map → config-HMW3EBZL.js.map} +0 -0
- /package/dist/{debug-N3B5NVJU.js.map → config-mutator-4SZ5YEVD.js.map} +0 -0
- /package/dist/{doctor-3Q36ZFE6.js.map → debug-3MEUO2P2.js.map} +0 -0
- /package/dist/{heal-HZ3EQD52.js.map → doctor-LRYV3QLK.js.map} +0 -0
- /package/dist/{loader-5CA3O5GM.js.map → heal-FVLBHYP7.js.map} +0 -0
- /package/dist/{ingest-whatsapp-LZE62INA.js.map → ingest-whatsapp-NS4OWDOU.js.map} +0 -0
- /package/dist/{loader-6IHUCPVO.js.map → loader-4ZGTK7LD.js.map} +0 -0
- /package/dist/{memory-extract-AENFVVO5.js.map → loader-BOKE5M5S.js.map} +0 -0
- /package/dist/{processes-UIC4XXA6.js.map → memory-extract-F5ZHWY5E.js.map} +0 -0
- /package/dist/{migrate-v2-QO7SLKIM.js.map → migrate-v2-V4WN2VVM.js.map} +0 -0
- /package/dist/{program-SAUNRCCD.js.map → processes-WU23U2OJ.js.map} +0 -0
- /package/dist/{providers-L27BJ5A6.js.map → program-GSZ5AYAM.js.map} +0 -0
- /package/dist/{projects-api-KRME2YKZ.js.map → projects-api-QE6L65SK.js.map} +0 -0
- /package/dist/{projects-mutate-3NHVG437.js.map → projects-mutate-MY7JTLSZ.js.map} +0 -0
- /package/dist/{query-HZYYRCLU.js.map → providers-KO2DODIO.js.map} +0 -0
- /package/dist/{recipes-EPLE2SNT.js.map → query-SQDHE4HV.js.map} +0 -0
- /package/dist/{registry-HK3WQ7BS.js.map → recipes-7S4MC5OJ.js.map} +0 -0
- /package/dist/{runner-BFYDWPUO.js.map → registry-LE6FWYZC.js.map} +0 -0
- /package/dist/{rotation-memo-B3EXXSEH.js.map → rotation-memo-7T75BLEX.js.map} +0 -0
- /package/dist/{scheduler-6T2SU5ST.js.map → routing-ILERJXB6.js.map} +0 -0
- /package/dist/{store-I3HEWVLQ.js.map → runner-YRBVNYTY.js.map} +0 -0
- /package/dist/{surface-usage-PRL6Z4U3.js.map → scheduler-BFM3EINS.js.map} +0 -0
- /package/dist/{timers-5LPZN55J.js.map → seat-7WM7II2B.js.map} +0 -0
- /package/dist/{types-VECTMYTO.js.map → store-MCOA6N4F.js.map} +0 -0
- /package/dist/{subagent-WV7QKQ3L.js.map → subagent-2SJHSSJS.js.map} +0 -0
- /package/dist/{types-Y6ZCZ52Z.js.map → surface-usage-NS74AXSE.js.map} +0 -0
- /package/dist/{wiki-M6YNRFC4.js.map → timers-PCB4ZIBD.js.map} +0 -0
- /package/dist/{workspace-setup-TBQAHYHJ.js.map → types-H5ENIUIT.js.map} +0 -0
- /package/dist/{whatsapp-state-XMTCSRXU.js.map → whatsapp-state-6D6FHHD2.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/references/discover.ts"],"sourcesContent":["import type { Skill } from \"@/agent/skills/types\"\nimport type { ReferenceCard, ReferenceKind } from \"./types\"\n\n// --- References discovery ---\n//\n// Pure extractor: given a namespace and a bag of source skills, walk their\n// markdown bodies and pull out structured facts (SSH hosts, GitLab project\n// IDs, filesystem paths, contacts) as ReferenceCard[]. Deterministic regex —\n// no LLM in the loop. Operator reviews the output and edits before flipping\n// `contextReferences: true` on the agents.\n\nconst SSH_LINE_RE = /\\bssh\\s+(?:-i\\s+(\\S+)\\s+)?([a-z_][a-z0-9_-]*)@([a-z0-9][a-z0-9.-]+|\\d{1,3}(?:\\.\\d{1,3}){3})/gi\nconst IP_RE = /\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b/g\nconst EMAIL_RE = /\\b([a-z0-9][a-z0-9._-]*)@([a-z0-9][a-z0-9.-]+\\.[a-z]{2,})\\b/gi\nconst GITLAB_PROJECT_LINE_RE = /([a-z0-9][a-z0-9._-]+)\\/([a-z0-9][a-z0-9._-]+)[^\\n|]*\\(?\\s*ID:?\\s*(\\d+)\\s*\\)?/gi\nconst GITLAB_GROUP_RE = /groups\\/([a-z0-9][a-z0-9._-]+)[^\\n|]*\\(?\\s*ID:?\\s*(\\d+)\\s*\\)?/gi\nconst PATH_RE = /(\\/Users\\/[^\\s)`'\"\\]]+|\\/home\\/[^\\s)`'\"\\]]+|\\/var\\/www\\/[^\\s)`'\"\\]]+|\\/etc\\/[^\\s)`'\"\\]]+)/g\nconst PHONE_RE = /(\\+\\d{1,3}[\\s.-]?(?:\\(\\d+\\)[\\s.-]?)?\\d[\\s.\\d-]{6,}\\d)/g\nconst PRIVATE_IP_RE = /^(?:127\\.|10\\.|192\\.168\\.|172\\.(?:1[6-9]|2\\d|3[01])\\.)/\n\nexport interface DiscoveryResult {\n /** Cards keyed by kind (ssh, gitlab, path, contact). */\n byKind: Record<string, ReferenceCard[]>\n /** Skills that were scanned. */\n scannedSkills: string[]\n /** Per-source diagnostics — what was found in which skill. */\n diagnostics: Array<{ skill: string; kind: string; id: string }>\n}\n\nexport interface DiscoveryOptions {\n /** Namespace prefix applied to every generated card id. */\n namespace: string\n /** Include only skills whose name OR tags contain any of these substrings.\n * Empty = scan every skill. */\n filter?: string[]\n /** Optional GitLab host to validate project URLs against (e.g.\n * https://gitlab.example.com). When set, project URLs from other hosts are\n * ignored — keeps stray GitHub mentions out of a self-hosted registry. */\n gitlabHost?: string\n}\n\nexport function discoverFromSkills(skills: Skill[], opts: DiscoveryOptions): DiscoveryResult {\n const result: DiscoveryResult = {\n byKind: { ssh: [], gitlab: [], path: [], contact: [] },\n scannedSkills: [],\n diagnostics: [],\n }\n const seen = new Set<string>() // id de-dup across skills\n\n for (const skill of skills) {\n const fm = skill.frontmatter\n const body = skill.instructions ?? \"\"\n if (opts.filter?.length) {\n const hay = [\n fm.name,\n fm.description,\n ...(fm.tags ?? []),\n (fm as any).category ?? \"\",\n skill.path ?? \"\",\n body.slice(0, 500), // first ~125 tokens of body, enough for a \"Globex Odoo Server\" header\n ].join(\" \").toLowerCase()\n const hit = opts.filter.some(f => hay.includes(f.toLowerCase()))\n if (!hit) continue\n }\n result.scannedSkills.push(fm.name)\n\n const ownerHint = fm.name\n\n for (const card of extractSshCards(body, opts.namespace, ownerHint)) {\n if (push(result, card, \"ssh\", seen)) result.diagnostics.push({ skill: fm.name, kind: \"ssh\", id: card.id })\n }\n for (const card of extractGitlabCards(body, opts.namespace, opts.gitlabHost)) {\n if (push(result, card, \"gitlab\", seen)) result.diagnostics.push({ skill: fm.name, kind: \"gitlab\", id: card.id })\n }\n for (const card of extractPathCards(body, opts.namespace)) {\n if (push(result, card, \"path\", seen)) result.diagnostics.push({ skill: fm.name, kind: \"path\", id: card.id })\n }\n for (const card of extractContactCards(body, opts.namespace)) {\n if (push(result, card, \"contact\", seen)) result.diagnostics.push({ skill: fm.name, kind: \"contact\", id: card.id })\n }\n }\n\n return result\n}\n\nfunction push(\n result: DiscoveryResult,\n card: ReferenceCard,\n kind: ReferenceKind,\n seen: Set<string>,\n): boolean {\n if (seen.has(card.id)) return false\n seen.add(card.id)\n result.byKind[kind].push(card)\n return true\n}\n\n// ---- Extractors ----\n\nfunction extractSshCards(body: string, ns: string, owner: string): ReferenceCard[] {\n const cards: ReferenceCard[] = []\n for (const m of body.matchAll(SSH_LINE_RE)) {\n const [, key, user, host] = m\n if (!user || !host) continue\n const slug = slugify(`${user}-${host.replace(/[^a-z0-9-]/gi, \"-\")}`)\n cards.push({\n id: `${ns}.ssh.${slug}`,\n kind: \"ssh\",\n summary: `SSH ${user}@${host}`,\n fields: cleanFields({ user, host, key }),\n tags: [\"discovered\"],\n ownerAgent: owner,\n })\n }\n // Catch IPs not already paired with a user\n const claimed = new Set(cards.flatMap(c => Object.values(c.fields)))\n for (const m of body.matchAll(IP_RE)) {\n const ip = m[0]\n if (claimed.has(ip)) continue\n if (PRIVATE_IP_RE.test(ip)) continue\n const slug = slugify(`host-${ip.replace(/\\./g, \"-\")}`)\n cards.push({\n id: `${ns}.ssh.${slug}`,\n kind: \"ssh\",\n summary: `Host ${ip} (user not detected — fill in)`,\n fields: { host: ip },\n tags: [\"discovered\", \"needs-review\"],\n ownerAgent: owner,\n })\n claimed.add(ip)\n }\n return cards\n}\n\nconst PROJECT_LINE_RE = /\\b([a-z0-9][a-z0-9._-]{1,40})\\/([a-z0-9][a-z0-9._-]{1,40})\\b/i\nconst ID_NUM_RE = /\\b(\\d{1,8})\\b/g\n\nfunction extractGitlabCards(body: string, ns: string, gitlabHost?: string): ReferenceCard[] {\n const cards: ReferenceCard[] = []\n if (gitlabHost && !body.includes(gitlabHost.replace(/^https?:\\/\\//, \"\"))) return cards\n // Group lines anywhere\n for (const m of body.matchAll(GITLAB_GROUP_RE)) {\n const [, slug, id] = m\n if (!slug || !id) continue\n cards.push({\n id: `${ns}.gitlab.group.${slugify(slug)}`,\n kind: \"gitlab\",\n summary: `GitLab group ${slug}`,\n fields: { groupId: Number(id), path: slug },\n tags: [\"discovered\"],\n })\n }\n // Project lines: walk line-by-line so table rows (\"| g/p | 269 |\") are\n // handled the same way as prose (\"g/p (ID: 269)\"). For each line that\n // mentions <group>/<project>, take the rightmost plausible numeric ID.\n const projectGlobalRe = new RegExp(PROJECT_LINE_RE.source, \"gi\")\n for (const line of body.split(/\\r?\\n/)) {\n // Skip lines that look like prose mentioning a path, not a GitLab project.\n // Real GitLab callouts almost always include \"ID:\" or a gitlab.* hostname\n // in the same line, or appear inside a markdown table row. Without one of\n // those, the noise rate is too high.\n const isTableRow = /^\\s*\\|.+\\|/.test(line)\n if (!isTableRow && !/\\bID[:\\s]/i.test(line) && !/gitlab/i.test(line)) continue\n // Two-pass: prefer a GitLab URL (https://gitlab.<host>/<group>/<repo>)\n // when present on the line, otherwise fall back to the rightmost\n // <group>/<repo> token that doesn't have a hostname-shaped group.\n let group: string | undefined\n let repo: string | undefined\n const urlMatch = line.match(/https?:\\/\\/[^\\s)]*gitlab[^\\s)]*?\\/([a-z0-9][a-z0-9._-]+)\\/([a-z0-9][a-z0-9._-]+)/i)\n if (urlMatch && urlMatch[1] && urlMatch[2]) {\n group = urlMatch[1]\n repo = urlMatch[2].replace(/[).,;:]+$/, \"\")\n } else {\n // Walk every <a>/<b> on the line and keep the last one that looks like\n // a real group/repo (no dots in group, not a wp-content path, not a file).\n for (const m of line.matchAll(projectGlobalRe)) {\n const g = m[1]\n const r = m[2]\n if (!g || !r) continue\n if (g === \"wp-content\" || r === \"wp-content\") continue\n if (g.includes(\".\")) continue\n if (looksLikeFile(r)) continue\n group = g\n repo = r\n }\n }\n if (!group || !repo) continue\n const ids = [...line.matchAll(ID_NUM_RE)].map(m => Number(m[1]))\n const id = ids.find(n => n >= 10 && n <= 9_999_999)\n if (!id) continue\n cards.push({\n id: `${ns}.gitlab.project.${slugify(repo)}`,\n kind: \"gitlab\",\n summary: `GitLab project ${group}/${repo}`,\n fields: { projectId: id, path: `${group}/${repo}` },\n tags: [\"discovered\"],\n })\n }\n return cards\n}\n\nfunction looksLikeFile(s: string): boolean {\n return /\\.(md|ya?ml|json|ts|tsx|js|jsx|py|sh|conf|env)$/i.test(s)\n}\n\nfunction extractPathCards(body: string, ns: string): ReferenceCard[] {\n const cards: ReferenceCard[] = []\n for (const m of body.matchAll(PATH_RE)) {\n let p = m[1].replace(/[.,;:)]+$/, \"\") // strip trailing punctuation\n if (p.length < 4) continue\n const slug = slugify(p.replace(/^\\//, \"\").replace(/[/.]/g, \"-\"))\n cards.push({\n id: `${ns}.paths.${slug}`,\n kind: \"path\",\n summary: p,\n fields: { path: p },\n tags: [\"discovered\"],\n })\n }\n return cards\n}\n\nfunction extractContactCards(body: string, ns: string): ReferenceCard[] {\n const cards: ReferenceCard[] = []\n for (const m of body.matchAll(EMAIL_RE)) {\n const [, local, domain] = m\n if (domain.endsWith(\".png\") || domain.endsWith(\".jpg\")) continue // junk filter\n const slug = slugify(local)\n cards.push({\n id: `${ns}.contacts.${slug}`,\n kind: \"contact\",\n summary: `${local}@${domain}`,\n fields: { email: `${local}@${domain}` },\n tags: [\"discovered\"],\n })\n }\n // Best-effort: if a phone appears on the same line as a known contact email\n // we already picked, attach it. Otherwise drop a standalone phone card.\n const phones = [...body.matchAll(PHONE_RE)].map(m => m[1].trim())\n for (const phone of phones) {\n const slug = slugify(`phone-${phone.replace(/\\D+/g, \"\")}`)\n cards.push({\n id: `${ns}.contacts.${slug}`,\n kind: \"contact\",\n summary: `Phone ${phone}`,\n fields: { mobile: phone },\n tags: [\"discovered\", \"needs-review\"],\n })\n }\n return cards\n}\n\n// ---- Helpers ----\n\nfunction cleanFields(fields: Record<string, string | number | boolean | undefined>): Record<string, string | number | boolean> {\n const out: Record<string, string | number | boolean> = {}\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined || v === \"\") continue\n out[k] = v\n }\n return out\n}\n\nfunction slugify(input: string): string {\n return input\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 60) || \"x\"\n}\n\n/**\n * Render a discovery result as YAML-ready file contents, one per kind.\n * Output is a complete `ReferenceFile`-shaped payload, ready to write to\n * `.agentx/references/<ns>/{ssh,gitlab,paths,contacts}.yaml`.\n */\nexport function renderDiscovery(result: DiscoveryResult, namespace: string): Record<string, string> {\n const out: Record<string, string> = {}\n const fileMap: Record<string, string> = {\n ssh: \"ssh.yaml\",\n gitlab: \"gitlab.yaml\",\n path: \"paths.yaml\",\n contact: \"contacts.yaml\",\n }\n for (const [kind, cards] of Object.entries(result.byKind)) {\n if (cards.length === 0) continue\n const ns = `${namespace}.${kind === \"path\" ? \"paths\" : kind === \"contact\" ? \"contacts\" : kind}`\n const lines = [\n `# Discovered automatically by 'agentx references discover'.`,\n `# Review every card — flagged ones (tags include \"needs-review\") are`,\n `# best-effort guesses. Set lastVerified once you've confirmed.`,\n `namespace: ${ns}`,\n `cards:`,\n ]\n for (const card of cards) {\n // Strip the namespace from the id so the file's `namespace:` doesn't\n // double-apply it on load.\n const localId = card.id.startsWith(`${ns}.`) ? card.id.slice(ns.length + 1) : card.id\n lines.push(` - id: ${localId}`)\n lines.push(` kind: ${card.kind}`)\n lines.push(` summary: ${quote(card.summary)}`)\n lines.push(` fields:`)\n for (const [k, v] of Object.entries(card.fields)) {\n lines.push(` ${k}: ${typeof v === \"number\" || typeof v === \"boolean\" ? v : quote(String(v))}`)\n }\n lines.push(` tags: [${card.tags.join(\", \")}]`)\n if (card.ownerAgent) lines.push(` ownerAgent: ${card.ownerAgent}`)\n }\n out[fileMap[kind]] = lines.join(\"\\n\") + \"\\n\"\n }\n return out\n}\n\nfunction quote(s: string): string {\n if (/^[A-Za-z0-9_./@+:-]+$/.test(s) && !/^\\d/.test(s)) return s\n return `\"${s.replace(/\"/g, '\\\\\"')}\"`\n}\n"],"mappings":"4BAWA,IAAMA,EAAc,gGACdC,EAAQ,+BACRC,EAAW,gEAEjB,IAAMC,EAAkB,kEAClBC,EAAU,6FACVC,EAAW,yDACXC,EAAgB,yDAuBf,SAASC,EAAmBC,EAAiBC,EAAyC,CAC3F,IAAMC,EAA0B,CAC9B,OAAQ,CAAE,IAAK,CAAC,EAAG,OAAQ,CAAC,EAAG,KAAM,CAAC,EAAG,QAAS,CAAC,CAAE,EACrD,cAAe,CAAC,EAChB,YAAa,CAAC,CAChB,EACMC,EAAO,IAAI,IAEjB,QAAWC,KAASJ,EAAQ,CAC1B,IAAMK,EAAKD,EAAM,YACXE,EAAOF,EAAM,cAAgB,GACnC,GAAIH,EAAK,QAAQ,OAAQ,CACvB,IAAMM,EAAM,CACVF,EAAG,KACHA,EAAG,YACH,GAAIA,EAAG,MAAQ,CAAC,EACfA,EAAW,UAAY,GACxBD,EAAM,MAAQ,GACdE,EAAK,MAAM,EAAG,GAAG,CACnB,EAAE,KAAK,GAAG,EAAE,YAAY,EAExB,GAAI,CADQL,EAAK,OAAO,KAAKO,GAAKD,EAAI,SAASC,EAAE,YAAY,CAAC,CAAC,EACrD,SAEZN,EAAO,cAAc,KAAKG,EAAG,IAAI,EAEjC,IAAMI,EAAYJ,EAAG,KAErB,QAAWK,KAAQC,EAAgBL,EAAML,EAAK,UAAWQ,CAAS,EAC5DG,EAAK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KA,CAAC,GAAK,CAAC,MAAM,KAAKA,CAAC,EAAUA,EACvD,IAAIA,EAAE,QAAQ,KAAM,KAAK,IAClC","names":["SSH_LINE_RE","IP_RE","EMAIL_RE","GITLAB_GROUP_RE","PATH_RE","PHONE_RE","PRIVATE_IP_RE","discoverFromSkills","skills","opts","result","seen","skill","fm","body","hay","f","ownerHint","card","extractSshCards","push","extractGitlabCards","extractPathCards","extractContactCards","kind","ns","owner","cards","m","SSH_LINE_RE","key","user","host","slug","slugify","cleanFields","claimed","c","IP_RE","ip","PROJECT_LINE_RE","ID_NUM_RE","gitlabHost","id","projectGlobalRe","line","group","repo","urlMatch","g","r","looksLikeFile","n","s","p","EMAIL_RE","local","domain","phones","phone","fields","out","k","v","input","renderDiscovery","namespace","fileMap","lines","localId","quote"]}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import"./chunk-FIOB3MEX.js";function c(o){let s=o.store.list().map(t=>({id:t.id,title:t.title})),e=[];if(e.push(r),e.push(""),e.push(i),e.push(""),e.push("# Environment \u2014 only reference values that exist"),e.push(""),e.push("## Available agents (for `agent` nodes)"),o.availableAgents.length===0)e.push(" (none registered \u2014 the user must add an agent first for `agent` nodes to work)");else for(let t of o.availableAgents)e.push(` - \`${t.id}\`${t.description?` \u2014 ${t.description}`:""}`);if(e.push(""),e.push("## Assignees (for `userTask.assignTo`)"),e.push(" Any agent id above, or a plain string naming the person responsible."),e.push(""),e.push("## Available roles (for `userTask.assignTo`)"),e.push(""),e.push("## Available channels (for `action.*` and `trigger.channel`)"),e.push(` ${o.availableChannels.length?o.availableChannels.map(t=>`\`${t}\``).join(", "):"(none live on this node)"}`),e.push(""),e.push("## Existing workflows (for `subProcess.workflowId`)"),s.length===0)e.push(" (no other workflows defined)");else for(let t of s)e.push(` - \`${t.id}\` \u2014 ${t.title}`);e.push(""),o.currentWorkflow&&(e.push("# Current workflow on canvas"),e.push(""),e.push("The user is editing this workflow. Build on it \u2014 do NOT replace it unless they explicitly ask."),e.push(""),e.push("```json"),e.push(JSON.stringify(o.currentWorkflow,null,2)),e.push("```"),e.push("")),e.push("# Conversation"),e.push("");for(let t of o.messages){let a=t.role==="user"?"USER":"ASSISTANT";e.push(`${a}: ${t.content}`),e.push("")}return e.push(l),e.join(`
|
|
2
|
+
`)}function u(o){let s=/```(?:json)?\s*\n([\s\S]*?)```/.exec(o),e=[];s&&e.push(s[1]);let t=o.match(/\{[\s\S]*\}/);t&&e.push(t[0]);for(let a of e)try{let n=JSON.parse(a);if(n&&typeof n=="object"&&"id"in n&&"nodes"in n)return n}catch{}return null}var r=`You are AgentX's workflow author. The user describes a business process in
|
|
3
|
+
plain language; you return a valid V2 workflow JSON that implements it.
|
|
4
|
+
|
|
5
|
+
Read the node catalog below. Prefer the BPM primitives (userTask,
|
|
6
|
+
subProcess, signal.emit/wait, timer.boundary, gateway.parallel, rule)
|
|
7
|
+
when modelling processes with humans, deadlines, parallel streams, or
|
|
8
|
+
nested activities. Prefer the bot primitives (agent, branch, action.*)
|
|
9
|
+
for simple message-in \u2192 reply-out automations.`,i=`# V2 Node catalog
|
|
10
|
+
|
|
11
|
+
## Triggers (exactly one per workflow)
|
|
12
|
+
- \`trigger.channel\` \u2014 inbound channel event.
|
|
13
|
+
config: { "source": "whatsapp-message" | "telegram-message" | "slack-message" | "discord-message" | "gitlab-issue" | "gitlab-pipeline", "filter": { "chat"?: "*", "project"?: "acme/web", "labels"?: ["x"] } }
|
|
14
|
+
- \`trigger.cron\` \u2014 scheduled. config: { "spec": "0 9 * * *", "timezone": "Africa/Tunis" }
|
|
15
|
+
- \`trigger.hook\` \u2014 subscribes to any on:* hook event. config: { "event": "on:gitlab-issue" }
|
|
16
|
+
- \`trigger.manual\` \u2014 kicked off by CLI or API. config: {}
|
|
17
|
+
- \`trigger.form\` \u2014 human fills a form to start. config: { "form": FormSchema, "startableBy": "role:public" }
|
|
18
|
+
|
|
19
|
+
## Compute
|
|
20
|
+
- \`agent\` \u2014 run an agent with a templated prompt. Output: { reply, result (parsed RESULT: token), json?, durationMs }.
|
|
21
|
+
config: { "agentId": "<id>", "prompt": "Classify {{trigger.text}} \u2014 reply on one line: RESULT: a|b|c", "resultParser": "acme-result-token" | "json", "timeoutMinutes": 2 }
|
|
22
|
+
- \`transform\` \u2014 reshape upstream context.
|
|
23
|
+
config: { "path": "trigger.contact.phone" } OR { "template": { "key": "{{trigger.text}}" } }
|
|
24
|
+
|
|
25
|
+
## Control flow
|
|
26
|
+
- \`branch\` \u2014 N-way switch (first match wins).
|
|
27
|
+
config: { "cases": [{ "when": { "kind": "equals"|"contains"|"matches"|"exists", "params": { "path": "classify.result", "value": "ok" } }, "to": "port1" }], "default": "fallbackPort" }
|
|
28
|
+
Wire with edges: { "from": "branchId", "fromPort": "port1", "to": "nextNode" }
|
|
29
|
+
- \`gateway.parallel\` \u2014 fan-out (one \u2192 many) or join (many \u2192 one).
|
|
30
|
+
config: { "mode": "fanOut" } \u2014 splits to every outgoing edge
|
|
31
|
+
config: { "mode": "join" } \u2014 waits until every incoming edge arrives, then fires once
|
|
32
|
+
- \`rule\` \u2014 DMN decision table, first matching row wins.
|
|
33
|
+
config: {
|
|
34
|
+
"inputs": ["{{trigger.tier}}", "{{trigger.amount}}"],
|
|
35
|
+
"rules": [
|
|
36
|
+
{ "when": ["gold", ">100"], "to": "vip", "output": { "route": "vip" } },
|
|
37
|
+
{ "when": ["*", ">50"], "to": "high", "output": { "route": "high" } }
|
|
38
|
+
],
|
|
39
|
+
"default": { "to": "low", "output": { "route": "low" } }
|
|
40
|
+
}
|
|
41
|
+
Cell syntax: "*" wildcard, exact "value", ">N" "<N" ">=N" "<=N", "!=x", "/regex/".
|
|
42
|
+
- \`checkpoint\` \u2014 pause until a matching event.
|
|
43
|
+
config: { "name": "await-x", "waitFor": { "source": "manual" }, "resumeMatch": {} }
|
|
44
|
+
|
|
45
|
+
## BPM
|
|
46
|
+
- \`userTask\` \u2014 assign a form to an actor or role; pauses until submission.
|
|
47
|
+
config: {
|
|
48
|
+
"assignTo": "actor:alice" | "role:reviewers",
|
|
49
|
+
"title": "Review expense {{trigger.values.amount}}",
|
|
50
|
+
"description": "\u2026",
|
|
51
|
+
"dueIn": "P2D" | "PT2H" | { "minutes": 60 },
|
|
52
|
+
"form": FormSchema
|
|
53
|
+
}
|
|
54
|
+
Output: { submittedBy, submittedAt, values: { fieldKey: value }, action: "primary" | "secondary" }
|
|
55
|
+
- \`subProcess\` \u2014 spawn a child workflow; parent pauses until child reaches end.
|
|
56
|
+
config: {
|
|
57
|
+
"workflowId": "<other workflow id>",
|
|
58
|
+
"inputMap": { "trigger": { "grantee": "{{trigger.values.name}}" } } (or "*" for full inherit),
|
|
59
|
+
"awaitCompletion": true
|
|
60
|
+
}
|
|
61
|
+
Output: { childRunId, status, output: <child's last bundle> }
|
|
62
|
+
- \`signal.emit\` \u2014 publish an event. config: { "name": "approved", "scope": "workflow"|"global", "payload": {} }
|
|
63
|
+
- \`signal.wait\` \u2014 pause until matching signal arrives. config: { "name": "approved", "scope": "workflow", "match": { "grantId": "{{trigger.id}}" } }
|
|
64
|
+
- \`timer.boundary\` \u2014 pause for a duration. config: { "after": "PT2H" | "P1D" | 60 (minutes) }
|
|
65
|
+
|
|
66
|
+
## Actions \u2014 side-effect sinks
|
|
67
|
+
- \`action.send\` \u2014 post a message to any channel. config: { "channel": "telegram"|"whatsapp"|\u2026, "chatId": "{{trigger.chatId}}", "text": "Hi {{classify.reply}}", "accountId"?: "\u2026" }
|
|
68
|
+
- \`action.createIssue\` \u2014 open a GitLab issue. config: { "channel": "gitlab", "project": "acme/web", "title": "\u2026", "description": "\u2026", "labels": ["x"], "assignees": ["user"] }
|
|
69
|
+
- \`action.setLabel\` / \`action.readLabel\` / \`action.react\` / \`action.editMessage\` / \`action.logTime\` \u2014 self-explanatory; each maps 1:1 to a channel adapter method.
|
|
70
|
+
- \`action.callHTTP\` \u2014 outbound HTTP. config: { "method": "POST"|"GET"|\u2026, "url": "https://\u2026", "headers": {}, "body": {}, "timeoutMs": 30000 }
|
|
71
|
+
|
|
72
|
+
## Terminal
|
|
73
|
+
- \`end\` \u2014 completes the run. config: { "status": "completed" | "failed" | "canceled" }
|
|
74
|
+
|
|
75
|
+
## FormSchema (used by userTask + trigger.form)
|
|
76
|
+
{
|
|
77
|
+
"title": "Review application",
|
|
78
|
+
"description": "\u2026",
|
|
79
|
+
"fields": [
|
|
80
|
+
{ "key": "score", "label": "Score", "type": "number", "required": true, "validate": { "min": 1, "max": 10 } },
|
|
81
|
+
{ "key": "verdict", "label": "Verdict", "type": "select", "required": true, "options": ["approve", "reject"] },
|
|
82
|
+
{ "key": "notes", "label": "Notes", "type": "long-text" }
|
|
83
|
+
],
|
|
84
|
+
"submitLabel": "Approve",
|
|
85
|
+
"secondaryAction": { "key": "reject", "label": "Reject" }
|
|
86
|
+
}
|
|
87
|
+
Field types: text, long-text, number, boolean, date, select, multi-select, file.
|
|
88
|
+
A form with a \`secondaryAction\` and no required-unfilled fields renders as one-tap Approve/Reject buttons in chat.
|
|
89
|
+
|
|
90
|
+
## Templates
|
|
91
|
+
Every prompt + config value can reference \`{{nodeId.path}}\` against the run context. Examples:
|
|
92
|
+
{{trigger.values.amount}} \u2014 field from the start form
|
|
93
|
+
{{classify.result}} \u2014 parsed RESULT: token from an agent node
|
|
94
|
+
{{review.values.score}} \u2014 submitted userTask field
|
|
95
|
+
{{env.GITLAB_TOKEN}} \u2014 env var (must be listed in workflow.envAllow)
|
|
96
|
+
|
|
97
|
+
## Edges
|
|
98
|
+
[{ "from": "nodeId", "to": "nodeId" }, { "from": "branchId", "fromPort": "case-label", "to": "nodeId" }]
|
|
99
|
+
Every edge's from/to must reference an existing node. Branch + rule nodes MUST have outgoing edges whose fromPort matches a declared case/rule/default.
|
|
100
|
+
|
|
101
|
+
## Workflow shell
|
|
102
|
+
{
|
|
103
|
+
"id": "lower-kebab-id",
|
|
104
|
+
"version": 2,
|
|
105
|
+
"title": "Human readable",
|
|
106
|
+
"description": "optional",
|
|
107
|
+
"priority": 0,
|
|
108
|
+
"fanOut": false,
|
|
109
|
+
"envAllow": [],
|
|
110
|
+
"maxChildDepth": 5,
|
|
111
|
+
"retention": { "maxRuns": 500, "maxDays": 90 },
|
|
112
|
+
"nodes": [...],
|
|
113
|
+
"edges": [...]
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
## Lint rules (all enforced on save)
|
|
117
|
+
- exactly one trigger.* node
|
|
118
|
+
- every edge references an existing node
|
|
119
|
+
- every node is reachable from the trigger
|
|
120
|
+
- at least one end/checkpoint/userTask/subProcess/signal.wait/timer.boundary is reachable
|
|
121
|
+
- branch + rule outgoing fromPort values match declared cases (or default)
|
|
122
|
+
- cycles are only allowed when the cycle crosses an agent/checkpoint/userTask/subProcess/signal.wait/timer.boundary`,l=`# Your reply
|
|
123
|
+
|
|
124
|
+
Respond in ONE of two ways:
|
|
125
|
+
|
|
126
|
+
1. **Clarification**: if the user's request is ambiguous, ask exactly ONE short follow-up question. No JSON.
|
|
127
|
+
|
|
128
|
+
2. **Workflow**: if you have enough to produce a workflow, reply with:
|
|
129
|
+
- 1\u20133 short lines explaining what you built
|
|
130
|
+
- a \`\`\`json code block containing the complete, valid V2 workflow
|
|
131
|
+
- (no prose after the JSON block)
|
|
132
|
+
|
|
133
|
+
Only reference agent ids, actor ids, role ids, and channel names that
|
|
134
|
+
appear in the Environment section above. If the user asks for an agent
|
|
135
|
+
that doesn't exist, tell them which agent to register first. Never
|
|
136
|
+
invent workflowIds for subProcess that aren't in the existing list.`;export{c as buildWorkflowAuthorPrompt,u as extractWorkflowJson};
|
|
137
|
+
//# sourceMappingURL=editor-chat-OB7IQOB5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/workflows/editor-chat.ts"],"sourcesContent":["import type { Workflow } from \"./types\"\nimport type { WorkflowStore } from \"./store\"\n\n// --- Workflow-builder chat context ---\n//\n// Produces the plain-text prompt the authoring agent reads. Packs\n// *everything* the agent needs to generate a valid V2 workflow JSON on\n// its first try: node catalog with config examples, available agent\n// ids, actor + role ids, channel adapter names, the user's existing\n// workflow list (for subProcess targets), and — when the author is\n// editing — the current workflow JSON as a starting point.\n//\n// The output is deliberately text, not JSON. Agents (LLMs) produce\n// better structured output when the schema is described as prose +\n// examples rather than as raw JSON Schema. The explicit \"reply with a\n// ```json block```\" instruction at the tail is what the API endpoint\n// parses back.\n\nexport interface ChatMessage {\n role: \"user\" | \"assistant\"\n content: string\n}\n\nexport interface BuildContextArgs {\n messages: ChatMessage[]\n store: WorkflowStore\n /** Full list of agent ids + optional descriptions. */\n availableAgents: Array<{ id: string; description?: string; tags?: string[] }>\n /** Adapter names the daemon has live (telegram, whatsapp, gitlab, ...). */\n availableChannels: string[]\n /** The workflow the user is currently editing (if any). */\n currentWorkflow?: Workflow\n}\n\n/** Build the single-string prompt the agent executes. */\nexport function buildWorkflowAuthorPrompt(args: BuildContextArgs): string {\n const workflows = args.store.list().map((w) => ({ id: w.id, title: w.title }))\n\n const parts: string[] = []\n\n parts.push(SYSTEM_HEADER)\n parts.push(\"\")\n parts.push(NODE_CATALOG)\n parts.push(\"\")\n parts.push(\"# Environment — only reference values that exist\")\n parts.push(\"\")\n parts.push(`## Available agents (for \\`agent\\` nodes)`)\n if (args.availableAgents.length === 0) {\n parts.push(\" (none registered — the user must add an agent first for `agent` nodes to work)\")\n } else {\n for (const a of args.availableAgents) {\n parts.push(` - \\`${a.id}\\`${a.description ? ` — ${a.description}` : \"\"}`)\n }\n }\n parts.push(\"\")\n parts.push(\"## Assignees (for `userTask.assignTo`)\")\n parts.push(\" Any agent id above, or a plain string naming the person responsible.\")\n parts.push(\"\")\n parts.push(\"## Available roles (for `userTask.assignTo`)\")\n parts.push(\"\")\n parts.push(\"## Available channels (for `action.*` and `trigger.channel`)\")\n parts.push(` ${args.availableChannels.length ? args.availableChannels.map((c) => `\\`${c}\\``).join(\", \") : \"(none live on this node)\"}`)\n parts.push(\"\")\n parts.push(\"## Existing workflows (for `subProcess.workflowId`)\")\n if (workflows.length === 0) parts.push(\" (no other workflows defined)\")\n else for (const w of workflows) parts.push(` - \\`${w.id}\\` — ${w.title}`)\n parts.push(\"\")\n\n if (args.currentWorkflow) {\n parts.push(\"# Current workflow on canvas\")\n parts.push(\"\")\n parts.push(\"The user is editing this workflow. Build on it — do NOT replace it unless they explicitly ask.\")\n parts.push(\"\")\n parts.push(\"```json\")\n parts.push(JSON.stringify(args.currentWorkflow, null, 2))\n parts.push(\"```\")\n parts.push(\"\")\n }\n\n parts.push(\"# Conversation\")\n parts.push(\"\")\n for (const m of args.messages) {\n const tag = m.role === \"user\" ? \"USER\" : \"ASSISTANT\"\n parts.push(`${tag}: ${m.content}`)\n parts.push(\"\")\n }\n\n parts.push(RESPONSE_RULES)\n return parts.join(\"\\n\")\n}\n\n/** Try to extract a workflow-shaped JSON block from an agent reply. Returns\n * null if no JSON block is present OR the JSON doesn't have the minimum\n * workflow fields (id, nodes). The caller still runs full zod validation\n * before writing. */\nexport function extractWorkflowJson(reply: string): Record<string, unknown> | null {\n // Prefer fenced ```json blocks; fall back to the largest {...} block.\n const fenced = /```(?:json)?\\s*\\n([\\s\\S]*?)```/.exec(reply)\n const candidates: string[] = []\n if (fenced) candidates.push(fenced[1])\n const braceMatch = reply.match(/\\{[\\s\\S]*\\}/)\n if (braceMatch) candidates.push(braceMatch[0])\n\n for (const raw of candidates) {\n try {\n const parsed = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && \"id\" in parsed && \"nodes\" in parsed) {\n return parsed as Record<string, unknown>\n }\n } catch { /* try next */ }\n }\n return null\n}\n\nconst SYSTEM_HEADER = `You are AgentX's workflow author. The user describes a business process in\nplain language; you return a valid V2 workflow JSON that implements it.\n\nRead the node catalog below. Prefer the BPM primitives (userTask,\nsubProcess, signal.emit/wait, timer.boundary, gateway.parallel, rule)\nwhen modelling processes with humans, deadlines, parallel streams, or\nnested activities. Prefer the bot primitives (agent, branch, action.*)\nfor simple message-in → reply-out automations.`\n\nconst NODE_CATALOG = `# V2 Node catalog\n\n## Triggers (exactly one per workflow)\n- \\`trigger.channel\\` — inbound channel event.\n config: { \"source\": \"whatsapp-message\" | \"telegram-message\" | \"slack-message\" | \"discord-message\" | \"gitlab-issue\" | \"gitlab-pipeline\", \"filter\": { \"chat\"?: \"*\", \"project\"?: \"acme/web\", \"labels\"?: [\"x\"] } }\n- \\`trigger.cron\\` — scheduled. config: { \"spec\": \"0 9 * * *\", \"timezone\": \"Africa/Tunis\" }\n- \\`trigger.hook\\` — subscribes to any on:* hook event. config: { \"event\": \"on:gitlab-issue\" }\n- \\`trigger.manual\\` — kicked off by CLI or API. config: {}\n- \\`trigger.form\\` — human fills a form to start. config: { \"form\": FormSchema, \"startableBy\": \"role:public\" }\n\n## Compute\n- \\`agent\\` — run an agent with a templated prompt. Output: { reply, result (parsed RESULT: token), json?, durationMs }.\n config: { \"agentId\": \"<id>\", \"prompt\": \"Classify {{trigger.text}} — reply on one line: RESULT: a|b|c\", \"resultParser\": \"acme-result-token\" | \"json\", \"timeoutMinutes\": 2 }\n- \\`transform\\` — reshape upstream context.\n config: { \"path\": \"trigger.contact.phone\" } OR { \"template\": { \"key\": \"{{trigger.text}}\" } }\n\n## Control flow\n- \\`branch\\` — N-way switch (first match wins).\n config: { \"cases\": [{ \"when\": { \"kind\": \"equals\"|\"contains\"|\"matches\"|\"exists\", \"params\": { \"path\": \"classify.result\", \"value\": \"ok\" } }, \"to\": \"port1\" }], \"default\": \"fallbackPort\" }\n Wire with edges: { \"from\": \"branchId\", \"fromPort\": \"port1\", \"to\": \"nextNode\" }\n- \\`gateway.parallel\\` — fan-out (one → many) or join (many → one).\n config: { \"mode\": \"fanOut\" } — splits to every outgoing edge\n config: { \"mode\": \"join\" } — waits until every incoming edge arrives, then fires once\n- \\`rule\\` — DMN decision table, first matching row wins.\n config: {\n \"inputs\": [\"{{trigger.tier}}\", \"{{trigger.amount}}\"],\n \"rules\": [\n { \"when\": [\"gold\", \">100\"], \"to\": \"vip\", \"output\": { \"route\": \"vip\" } },\n { \"when\": [\"*\", \">50\"], \"to\": \"high\", \"output\": { \"route\": \"high\" } }\n ],\n \"default\": { \"to\": \"low\", \"output\": { \"route\": \"low\" } }\n }\n Cell syntax: \"*\" wildcard, exact \"value\", \">N\" \"<N\" \">=N\" \"<=N\", \"!=x\", \"/regex/\".\n- \\`checkpoint\\` — pause until a matching event.\n config: { \"name\": \"await-x\", \"waitFor\": { \"source\": \"manual\" }, \"resumeMatch\": {} }\n\n## BPM\n- \\`userTask\\` — assign a form to an actor or role; pauses until submission.\n config: {\n \"assignTo\": \"actor:alice\" | \"role:reviewers\",\n \"title\": \"Review expense {{trigger.values.amount}}\",\n \"description\": \"…\",\n \"dueIn\": \"P2D\" | \"PT2H\" | { \"minutes\": 60 },\n \"form\": FormSchema\n }\n Output: { submittedBy, submittedAt, values: { fieldKey: value }, action: \"primary\" | \"secondary\" }\n- \\`subProcess\\` — spawn a child workflow; parent pauses until child reaches end.\n config: {\n \"workflowId\": \"<other workflow id>\",\n \"inputMap\": { \"trigger\": { \"grantee\": \"{{trigger.values.name}}\" } } (or \"*\" for full inherit),\n \"awaitCompletion\": true\n }\n Output: { childRunId, status, output: <child's last bundle> }\n- \\`signal.emit\\` — publish an event. config: { \"name\": \"approved\", \"scope\": \"workflow\"|\"global\", \"payload\": {} }\n- \\`signal.wait\\` — pause until matching signal arrives. config: { \"name\": \"approved\", \"scope\": \"workflow\", \"match\": { \"grantId\": \"{{trigger.id}}\" } }\n- \\`timer.boundary\\` — pause for a duration. config: { \"after\": \"PT2H\" | \"P1D\" | 60 (minutes) }\n\n## Actions — side-effect sinks\n- \\`action.send\\` — post a message to any channel. config: { \"channel\": \"telegram\"|\"whatsapp\"|…, \"chatId\": \"{{trigger.chatId}}\", \"text\": \"Hi {{classify.reply}}\", \"accountId\"?: \"…\" }\n- \\`action.createIssue\\` — open a GitLab issue. config: { \"channel\": \"gitlab\", \"project\": \"acme/web\", \"title\": \"…\", \"description\": \"…\", \"labels\": [\"x\"], \"assignees\": [\"user\"] }\n- \\`action.setLabel\\` / \\`action.readLabel\\` / \\`action.react\\` / \\`action.editMessage\\` / \\`action.logTime\\` — self-explanatory; each maps 1:1 to a channel adapter method.\n- \\`action.callHTTP\\` — outbound HTTP. config: { \"method\": \"POST\"|\"GET\"|…, \"url\": \"https://…\", \"headers\": {}, \"body\": {}, \"timeoutMs\": 30000 }\n\n## Terminal\n- \\`end\\` — completes the run. config: { \"status\": \"completed\" | \"failed\" | \"canceled\" }\n\n## FormSchema (used by userTask + trigger.form)\n{\n \"title\": \"Review application\",\n \"description\": \"…\",\n \"fields\": [\n { \"key\": \"score\", \"label\": \"Score\", \"type\": \"number\", \"required\": true, \"validate\": { \"min\": 1, \"max\": 10 } },\n { \"key\": \"verdict\", \"label\": \"Verdict\", \"type\": \"select\", \"required\": true, \"options\": [\"approve\", \"reject\"] },\n { \"key\": \"notes\", \"label\": \"Notes\", \"type\": \"long-text\" }\n ],\n \"submitLabel\": \"Approve\",\n \"secondaryAction\": { \"key\": \"reject\", \"label\": \"Reject\" }\n}\nField types: text, long-text, number, boolean, date, select, multi-select, file.\nA form with a \\`secondaryAction\\` and no required-unfilled fields renders as one-tap Approve/Reject buttons in chat.\n\n## Templates\nEvery prompt + config value can reference \\`{{nodeId.path}}\\` against the run context. Examples:\n {{trigger.values.amount}} — field from the start form\n {{classify.result}} — parsed RESULT: token from an agent node\n {{review.values.score}} — submitted userTask field\n {{env.GITLAB_TOKEN}} — env var (must be listed in workflow.envAllow)\n\n## Edges\n[{ \"from\": \"nodeId\", \"to\": \"nodeId\" }, { \"from\": \"branchId\", \"fromPort\": \"case-label\", \"to\": \"nodeId\" }]\nEvery edge's from/to must reference an existing node. Branch + rule nodes MUST have outgoing edges whose fromPort matches a declared case/rule/default.\n\n## Workflow shell\n{\n \"id\": \"lower-kebab-id\",\n \"version\": 2,\n \"title\": \"Human readable\",\n \"description\": \"optional\",\n \"priority\": 0,\n \"fanOut\": false,\n \"envAllow\": [],\n \"maxChildDepth\": 5,\n \"retention\": { \"maxRuns\": 500, \"maxDays\": 90 },\n \"nodes\": [...],\n \"edges\": [...]\n}\n\n## Lint rules (all enforced on save)\n- exactly one trigger.* node\n- every edge references an existing node\n- every node is reachable from the trigger\n- at least one end/checkpoint/userTask/subProcess/signal.wait/timer.boundary is reachable\n- branch + rule outgoing fromPort values match declared cases (or default)\n- cycles are only allowed when the cycle crosses an agent/checkpoint/userTask/subProcess/signal.wait/timer.boundary`\n\nconst RESPONSE_RULES = `# Your reply\n\nRespond in ONE of two ways:\n\n1. **Clarification**: if the user's request is ambiguous, ask exactly ONE short follow-up question. No JSON.\n\n2. **Workflow**: if you have enough to produce a workflow, reply with:\n - 1–3 short lines explaining what you built\n - a \\`\\`\\`json code block containing the complete, valid V2 workflow\n - (no prose after the JSON block)\n\nOnly reference agent ids, actor ids, role ids, and channel names that\nappear in the Environment section above. If the user asks for an agent\nthat doesn't exist, tell them which agent to register first. Never\ninvent workflowIds for subProcess that aren't in the existing list.`"],"mappings":"4BAmCO,SAASA,EAA0BC,EAAgC,CACxE,IAAMC,EAAYD,EAAK,MAAM,KAAK,EAAE,IAAKE,IAAO,CAAE,GAAIA,EAAE,GAAI,MAAOA,EAAE,KAAM,EAAE,EAEvEC,EAAkB,CAAC,EASzB,GAPAA,EAAM,KAAKC,CAAa,EACxBD,EAAM,KAAK,EAAE,EACbA,EAAM,KAAKE,CAAY,EACvBF,EAAM,KAAK,EAAE,EACbA,EAAM,KAAK,uDAAkD,EAC7DA,EAAM,KAAK,EAAE,EACbA,EAAM,KAAK,yCAA2C,EAClDH,EAAK,gBAAgB,SAAW,EAClCG,EAAM,KAAK,uFAAkF,MAE7F,SAAWG,KAAKN,EAAK,gBACnBG,EAAM,KAAK,SAASG,EAAE,OAAOA,EAAE,YAAc,WAAMA,EAAE,cAAgB,IAAI,EAa7E,GAVAH,EAAM,KAAK,EAAE,EACbA,EAAM,KAAK,wCAAwC,EACnDA,EAAM,KAAK,wEAAwE,EACnFA,E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G,EAC7B,GAAIC,GAAU,OAAOA,GAAW,UAAY,OAAQA,GAAU,UAAWA,EACvE,OAAOA,CAEX,MAAE,CAAuB,CAE3B,OAAO,IACT,CAEA,IAAMb,EAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qDAShBC,EAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qHAmHfK,EAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;","names":["buildWorkflowAuthorPrompt","args","workflows","w","parts","SYSTEM_HEADER","NODE_CATALOG","a","c","m","tag","RESPONSE_RULES","extractWorkflowJson","reply","fenced","candidates","braceMatch","raw","parsed"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as r,b as c,c as u,f as g}from"./chunk-F4HZTZHW.js";import"./chunk-FIOB3MEX.js";g();var w="entry-triage",f={person:"A named human, team, or agent",project:"A named piece of work with a lifecycle",place:"A server, environment, repository, or system",concept:"A durable idea, term, or explanation",event:"Something that happened at a time \u2014 an incident, deploy, meeting",decision:"A choice made, and why",pattern:"A recurring way of doing or seeing something",none:"Nothing that fits a wiki article \u2014 chatter, a transient status, a duplicate, or noise"},T={citeWorthy:r("Would a curated wiki cite this entry for anything at all \u2014 a fact, a date, a name, a decision \u2014 even a single sentence inside an article about something else?"),type:c(f,"What kind of wiki article, if any, does this entry belong in?"),worthKeeping:r("Would this entry still be useful to someone in six months?"),procedure:r("Does this entry describe how to do something, step by step?"),durability:u(["True only in the moment it was written","True for days \u2014 a status, a run, a transient state","True for months \u2014 a project, a person's role, a current setup","True indefinitely \u2014 a decision, an incident that happened, a rule"],"How long will what this entry says remain true?")};function A(e,t=2e3){let n=String(e.content??"").replace(/\s+/g," ").trim();return{date:e.date??null,source:e.source??null,context:e.sourceContext?l(e.sourceContext,200):null,content:l(n,t)}}function x(e,t={}){let n=e.type,o=e.worthKeeping.noul,p=e.procedure.noul,i=e.durability.score,y=t.minTypeConfidence??.5,d=t.minWorth??.5,m=t.minDurability??1.5,h=n.choice!=="none"&&n.confidence>=y,a=o>=d,s=i>=m;return{type:n.choice,typeConfidence:n.confidence,worthKeeping:o,procedure:p,durability:i,absorb:h&&a&&s,rememberOnly:!s&&a}}function l(e,t){return e.length>t?e.slice(0,t):e}export{w as ENTRY_TRIAGE_SEAT,f as ENTRY_TYPES,T as entryTriageQuestions,x as triage,A as triageState};
|
|
2
|
+
//# sourceMappingURL=entry-triage-LK34TSQD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/decisions/seats/entry-triage.ts"],"sourcesContent":["import { choice, noul, score } from \"../questions\"\nimport type { AnswersFor, ChoiceAnswer, NoulAnswer, ScoreAnswer, StateValue } from \"../types\"\n\n// Triaging raw wiki entries before anything expensive reads them.\n//\n// The numbers that motivate this: 10,185 unabsorbed raw entries have so\n// far produced 257 articles. Absorb pays Sonnet to read every entry and\n// write articles for the few that deserve one, at --max 5 per agent —\n// 136 nightly runs to clear the backlog, four and a half months.\n//\n// Most of that spend is reading noise. Deciding whether an entry is worth\n// keeping is a classification, not a composition, so it does not need a\n// model that can write. The wiki's own absorb prompt already says as much:\n//\n// \"Choose the type BEFORE writing; if you can't pick one, the article\n// probably isn't needed.\"\n//\n// That is a Choice with a none option, stated in prose and handed to a\n// writing model. Asked directly it costs about $0.00003 an entry, which\n// puts the whole backlog around thirty cents.\n//\n// What this does NOT do is write the article. Jev cannot generate text.\n// The output is a gate and a label; Sonnet still composes whatever\n// survives. The saving is in what never reaches it.\n//\n// ---------------------------------------------------------------------\n// MEASURED, AND IT DOES NOT WORK. Do not wire this in active mode.\n//\n// `agentx wiki triage-backtest` grades the gate against absorb's own\n// verdicts — 815 entries absorb cited, 4,811 it passed over, free labels\n// already on disk. On a balanced sample of 200:\n//\n// default policy recall 25%, filtering 72%\n// every threshold 0 recall 45% (the type gate alone costs 55%)\n// type gate off too recall 95% buys 4% filtering — nothing\n//\n// So the thresholds were never the problem. A rewritten question aimed\n// straight at the label — \"would a wiki cite this at all, even one\n// sentence inside an article about something else?\" — came out\n// ANTI-correlated: mean 0.245 on entries absorb kept versus 0.323 on\n// entries it discarded. Worse than a coin toss.\n//\n// Two readings, and they are not exclusive. Absorb merges: whether an\n// entry gets cited depends on what else was in its batch of five and\n// whether a related article already existed, so the label carries a lot\n// of lottery. And whatever the model is judging when asked \"is this\n// worth keeping\", it is not the thing absorb responds to.\n//\n// The honest state: this seat is unvalidated, the harness that would\n// validate it exists, and the evidence so far says no. Left in the tree\n// because the backtest is the useful artifact and because a future\n// question may do better — but nothing should route through it until a\n// run of `wiki triage-backtest --sweep` says otherwise.\n// ---------------------------------------------------------------------\n\nexport const ENTRY_TRIAGE_SEAT = \"entry-triage\"\n\n/** The wiki's own enum, plus the escape hatch its prompt describes. */\nexport const ENTRY_TYPES = {\n person: \"A named human, team, or agent\",\n project: \"A named piece of work with a lifecycle\",\n place: \"A server, environment, repository, or system\",\n concept: \"A durable idea, term, or explanation\",\n event: \"Something that happened at a time — an incident, deploy, meeting\",\n decision: \"A choice made, and why\",\n pattern: \"A recurring way of doing or seeing something\",\n none: \"Nothing that fits a wiki article — chatter, a transient status, a duplicate, or noise\",\n} as const\n\nexport const entryTriageQuestions = {\n // The question that matches how absorb actually behaves.\n //\n // The three below ask whether an entry DESERVES AN ARTICLE. Measured\n // against absorb's own verdicts they filtered 4% of the corpus at 95%\n // recall — useless — because absorb mostly MERGES an entry into an\n // article that already exists. An entry can supply one sentence to a\n // person's page without being a person article itself, so \"what type\n // is this?\" and \"is this worth reading?\" are different questions and\n // only the second is the one the gate needs answered.\n citeWorthy: noul(\n \"Would a curated wiki cite this entry for anything at all — a fact, a date, a name, a decision — even a single sentence inside an article about something else?\",\n ),\n type: choice(ENTRY_TYPES, \"What kind of wiki article, if any, does this entry belong in?\"),\n worthKeeping: noul(\"Would this entry still be useful to someone in six months?\"),\n procedure: noul(\"Does this entry describe how to do something, step by step?\"),\n // Ordered low to high, so the expected score is directly comparable\n // across entries and thresholdable in code.\n durability: score(\n [\n \"True only in the moment it was written\",\n \"True for days — a status, a run, a transient state\",\n \"True for months — a project, a person's role, a current setup\",\n \"True indefinitely — a decision, an incident that happened, a rule\",\n ],\n \"How long will what this entry says remain true?\",\n ),\n}\n\nexport type EntryTriageAnswers = AnswersFor<typeof entryTriageQuestions>\n\nexport interface TriageEntry {\n id: string\n date?: string\n source?: string\n sourceContext?: string\n content: string\n}\n\n/** Entries are already short; 2k is generous and keeps a batch cheap. */\nexport function triageState(entry: TriageEntry, maxChars = 2000): StateValue {\n const text = String(entry.content ?? \"\").replace(/\\s+/g, \" \").trim()\n return {\n date: entry.date ?? null,\n source: entry.source ?? null,\n context: entry.sourceContext ? clip(entry.sourceContext, 200) : null,\n content: clip(text, maxChars),\n }\n}\n\nexport interface TriageVerdict {\n type: keyof typeof ENTRY_TYPES\n typeConfidence: number\n worthKeeping: number\n procedure: number\n durability: number\n /** Should this entry reach the writing model at all? */\n absorb: boolean\n /** Worth remembering but not worth an article — a candidate for the\n * memory store rather than the wiki. */\n rememberOnly: boolean\n}\n\nexport interface TriagePolicy {\n /** Minimum confidence in a non-none type before absorbing. */\n minTypeConfidence?: number\n /** Minimum P(useful in six months). */\n minWorth?: number\n /** Minimum expected durability, on the 0-3 rubric above. */\n minDurability?: number\n}\n\n/**\n * Three independent signals, because they fail differently.\n *\n * `type` can be confidently wrong about WHICH article an entry belongs in\n * while being right that it belongs in one. `worthKeeping` catches the\n * entry that fits a type but says nothing anyone needs. `durability`\n * catches the one that is genuinely useful today and meaningless next\n * week — the status ping, the \"deploy started\" line — which is most of\n * what a chat-sourced corpus contains.\n *\n * An entry that clears worth but not durability is not discarded: it is\n * flagged rememberOnly, because \"useful but short-lived\" describes a\n * memory, not an encyclopaedia article.\n */\nexport function triage(answers: EntryTriageAnswers, policy: TriagePolicy = {}): TriageVerdict {\n const type = answers.type as ChoiceAnswer\n const worth = (answers.worthKeeping as NoulAnswer).noul\n const procedure = (answers.procedure as NoulAnswer).noul\n const durability = (answers.durability as ScoreAnswer).score\n\n const minType = policy.minTypeConfidence ?? 0.5\n const minWorth = policy.minWorth ?? 0.5\n const minDurability = policy.minDurability ?? 1.5\n\n const typed = type.choice !== \"none\" && type.confidence >= minType\n const useful = worth >= minWorth\n const durable = durability >= minDurability\n\n return {\n type: type.choice as keyof typeof ENTRY_TYPES,\n typeConfidence: type.confidence,\n worthKeeping: worth,\n procedure,\n durability,\n absorb: typed && useful && durable,\n rememberOnly: !durable && useful,\n }\n}\n\nfunction clip(text: string, max: number): string {\n return text.length > max ? text.slice(0, max) : text\n}\n"],"mappings":"yFAAAA,IAuDO,IAAMC,EAAoB,eAGpBC,EAAc,CACzB,OAAQ,gCACR,QAAS,yCACT,MAAO,+CACP,QAAS,uCACT,MAAO,wEACP,SAAU,yBACV,QAAS,+CACT,KAAM,4FACR,EAEaC,EAAuB,CAUlC,WAAYC,EACV,0KACF,EACA,KAAMC,EAAOH,EAAa,+DAA+D,EACzF,aAAcE,EAAK,4DAA4D,EAC/E,UAAWA,EAAK,6DAA6D,EAG7E,WAAYE,EACV,CACE,yCACA,0DACA,qEACA,wEACF,EACA,iDACF,CACF,EAaO,SAASC,EAAYC,EAAoBC,EAAW,IAAkB,CAC3E,IAAMC,EAAO,OAAOF,EAAM,SAAW,EAAE,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EACnE,MAAO,CACL,KAAMA,EAAM,MAAQ,KACpB,OAAQA,EAAM,QAAU,KACxB,QAASA,EAAM,cAAgBG,EAAKH,EAAM,cAAe,GAAG,EAAI,KAChE,QAASG,EAAKD,EAAMD,CAAQ,CAC9B,CACF,CAsCO,SAASG,EAAOC,EAA6BC,EAAuB,CAAC,EAAkB,CAC5F,IAAMC,EAAOF,EAAQ,KACfG,EAASH,EAAQ,aAA4B,KAC7CI,EAAaJ,EAAQ,UAAyB,KAC9CK,EAAcL,EAAQ,WAA2B,MAEjDM,EAAUL,EAAO,mBAAqB,GACtCM,EAAWN,EAAO,UAAY,GAC9BO,EAAgBP,EAAO,eAAiB,IAExCQ,EAAQP,EAAK,SAAW,QAAUA,EAAK,YAAcI,EACrDI,EAASP,GAASI,EAClBI,EAAUN,GAAcG,EAE9B,MAAO,CACL,KAAMN,EAAK,OACX,eAAgBA,EAAK,WACrB,aAAcC,EACd,UAAAC,EACA,WAAAC,EACA,OAAQI,GAASC,GAAUC,EAC3B,aAAc,CAACA,GAAWD,CAC5B,CACF,CAEA,SAASZ,EAAKD,EAAce,EAAqB,CAC/C,OAAOf,EAAK,OAASe,EAAMf,EAAK,MAAM,EAAGe,CAAG,EAAIf,CAClD","names":["init_questions","ENTRY_TRIAGE_SEAT","ENTRY_TYPES","entryTriageQuestions","noul","choice","score","triageState","entry","maxChars","text","clip","triage","answers","policy","type","worth","procedure","durability","minType","minWorth","minDurability","typed","useful","durable","max"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import"./chunk-FIOB3MEX.js";import{existsSync as E,readFileSync as T}from"fs";import{resolve as j}from"path";import{execFile as N}from"child_process";function p(e,t,o={}){return new Promise(n=>{N(e,t,{timeout:o.timeoutMs??15e3,signal:o.signal,maxBuffer:4*1024*1024,env:{...process.env,PATH:[process.env.PATH??"","/opt/homebrew/bin","/usr/local/bin",`${process.env.HOME??""}/.local/bin`].filter(Boolean).join(":")}},(r,a,i)=>{let s=r&&typeof r.code=="number"?r.code:r?1:0;n({stdout:String(a??""),stderr:String(i??""),code:s})})})}async function y(e){let{code:t}=await p("command",["-v",e],{timeoutMs:3e3}).catch(()=>({code:1}));if(t===0)return!0;let{code:o}=await p("/usr/bin/which",[e],{timeoutMs:3e3});return o===0}var G=[["216","Tunisia"],["966","Saudi Arabia"],["971","UAE"],["974","Qatar"],["965","Kuwait"],["973","Bahrain"],["968","Oman"],["962","Jordan"],["961","Lebanon"],["212","Morocco"],["213","Algeria"],["218","Libya"],["249","Sudan"],["20","Egypt"],["90","Turkey"],["33","France"],["49","Germany"],["39","Italy"],["34","Spain"],["44","United Kingdom"],["31","Netherlands"],["32","Belgium"],["41","Switzerland"],["1","US/Canada"]];function m(e){let t=e.replace(/\D/g,""),o,n=0;for(let[r,a]of G)t.startsWith(r)&&r.length>n&&(o=a,n=r.length);return o}function F(e){let t=[];for(let o of e.split(`
|
|
2
|
+
`)){let n=o.trim();if(!n||n.startsWith("ALIAS"))continue;let r=n.split(/\s{2,}/).filter(Boolean);if(r.length<2)continue;let a=r[r.length-1];if(!a.includes("@"))continue;let i=r[r.length-2],s=r.length>=3?r[r.length-3]:"";if(!s||!/\d/.test(i))continue;let l=m(i);t.push({name:s,source:"wacli",fields:{phone:`+${i.replace(/\D/g,"")}`,whatsapp:a,...l?{country:l}:{}}})}return t}function w(){return{name:"wacli",provides:["contact value","country"],async available(){if(!await y("wacli"))return{kind:"not-installed",hint:"brew install wacli \u2014 see https://wacli.sh"};let{stdout:e,stderr:t,code:o}=await p("wacli",["contacts","search","__agentx_probe__"],{timeoutMs:1e4});return o!==0&&/auth|not logged in|no session|login/i.test(e+t)?{kind:"not-configured",hint:"wacli auth \u2014 scan the QR to link the account"}:null},async lookup(e,t){let o=[],n=new Set;for(let r of e)for(let a of P(r.name)){let{stdout:i,code:s}=await p("wacli",["contacts","search",a],{signal:t,timeoutMs:15e3});if(s!==0)continue;let l=F(i).filter(u=>A(u.name,r.name));if(l.length!==0){for(let u of l){let c=u.fields.whatsapp;n.has(c)||(n.add(c),o.push({...u,fuzzy:!I(u.name,r.name)}))}break}}return o}}}var h=e=>e.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9 ]/g,"").trim(),I=(e,t)=>h(e)===h(t);function P(e){let t=h(e).split(/\s+/).filter(o=>o.length>2);return t.length>1?[e,t[t.length-1]]:[e]}function A(e,t){let o=h(e).split(/\s+/).filter(Boolean),n=h(t).split(/\s+/).filter(Boolean);if(o.length===0||n.length===0)return!1;let[r,a]=o.length<=n.length?[o,n]:[n,o];return r.every(i=>a.includes(i))}var M={whatsapp:"whatsapp",telegram:"telegram",gitlab:"gitlab",github:"github",email:"email",phone:"phone",slack:"slack",discord:"discord"};function D(e=".agentx"){return j(process.cwd(),e,"contacts.json")}function S(e){if(!E(e))return[];try{let t=JSON.parse(T(e,"utf-8"));return Array.isArray(t?.contacts)?t.contacts:[]}catch{return[]}}var b=e=>e.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9 ]/g,"").trim();function C(e){return[e.name,e.id,...e.aliases??[]].filter(t=>!!(t&&t.trim())).map(b)}function _(e){let t={};for(let[o,n]of Object.entries(e.channels??{})){let r=String(n??"").trim();if(!r)continue;let a=M[o.toLowerCase()]??o.toLowerCase();if(a==="whatsapp"){let i=r.split("@")[0].replace(/\D/g,"");if(t.whatsapp=r.includes("@")?r:`${i}@s.whatsapp.net`,i){t.phone??=`+${i}`;let s=m(i);s&&(t.country??=s)}continue}if(a==="phone"){let i=r.replace(/\D/g,"");t.phone=r.startsWith("+")?r:`+${i}`;let s=m(i);s&&(t.country??=s);continue}if(a==="telegram"&&/^\d+$/.test(r)){t.telegramId=r;continue}t[a]=a==="gitlab"||a==="github"?r.startsWith("@")?r:`@${r}`:r}return t}function k(e={}){let t=e.path??D();return{name:"contacts",provides:["contact value","handles","country"],async available(){return E(t)?S(t).length>0?null:{kind:"not-configured",hint:`${t} has no contacts`}:{kind:"not-configured",hint:`no ${t} \u2014 add {"contacts":[{"name":"\u2026","aliases":[],"channels":{"whatsapp":"\u2026"}}]}`}},async lookup(o){let n=S(t);if(n.length===0)return[];let r=new Map;for(let s of n)for(let l of C(s))l&&r.set(l,s);let a=[],i=new Set;for(let s of o){let l=r.get(b(s.name));if(!l||i.has(l))continue;i.add(l);let u=_(l);Object.keys(u).length!==0&&a.push({name:l.name??s.name,source:"contacts",fields:u,fuzzy:b(l.name??"")!==b(s.name)})}return a}}}function v(e={}){let t=(e.baseUrl??process.env.GITLAB_URL??"").replace(/\/+$/,""),o=e.token??process.env.GITLAB_ADMIN_TOKEN??process.env.GITLAB_TOKEN;return{name:"gitlab",provides:["email","handle","profile URL"],async available(){if(!t)return{kind:"not-configured",hint:"export GITLAB_URL=https://<your-gitlab-host>"};if(!o)return{kind:"not-configured",hint:"export GITLAB_ADMIN_TOKEN=<PAT> (read_api scope is enough)"};try{let n=await fetch(`${t}/api/v4/user`,{headers:{"PRIVATE-TOKEN":o}});if(n.status===401||n.status===403)return{kind:"not-configured",hint:`GitLab rejected the token (${n.status}) \u2014 set a valid GITLAB_ADMIN_TOKEN`};if(!n.ok)return{kind:"failed",hint:`GitLab returned ${n.status} for the auth probe`}}catch(n){return{kind:"failed",hint:`cannot reach ${t}: ${String(n?.message??n)}`}}return null},async lookup(n,r){if(!o||!t)return[];let a=[],i=new Set;for(let s of n){let l=`${t}/api/v4/users?search=${encodeURIComponent(s.name)}&per_page=5`,u;try{let c=await fetch(l,{headers:{"PRIVATE-TOKEN":o},signal:r});if(!c.ok)continue;u=await c.json()}catch{continue}if(Array.isArray(u))for(let c of u){let d=c.username??c.web_url??"";if(!d||i.has(d))continue;i.add(d);let f={},g=c.email||c.public_email;g&&(f.email=g),c.username&&(f.gitlab=`@${c.username}`),c.web_url&&(f.profile=c.web_url),c.organization&&(f.organisation=c.organization),c.job_title&&(f.role=c.job_title),c.state&&c.state!=="active"&&(f.accountState=c.state),Object.keys(f).length!==0&&a.push({name:c.name??s.name,source:"gitlab",fields:f,fuzzy:(c.name??"").toLowerCase()!==s.name.toLowerCase()})}}return a}}}function x(){return{name:"gog",provides:["contact value","email","organisation","role","country"],async available(){if(!await y("gog"))return{kind:"not-installed",hint:"brew install gog \u2014 Google CLI"};let{stdout:e,stderr:t}=await p("gog",["contacts","list","-j"],{timeoutMs:2e4}),o=e+t;return/unknown flag|Run with --help/i.test(o)?{kind:"failed",hint:`gog rejected the probe: ${o.split(`
|
|
3
|
+
`)[0]}`}:/accessNotConfigured|has not been used in project/i.test(o)?{kind:"not-configured",hint:"enable the People API on the gog OAuth project, then retry (console.developers.google.com \u2192 APIs \u2192 People API)"}:/invalid_grant|PERMISSION_DENIED|unauthenticated/i.test(o)?{kind:"not-configured",hint:"gog auth login \u2014 the stored token is expired or lacks contacts scope"}:null},async lookup(e,t){let o=[];for(let n of e){let{stdout:r,code:a}=await p("gog",["contacts","search",n.name,"-j","--results-only"],{signal:t,timeoutMs:2e4});if(a!==0)continue;let i;try{i=JSON.parse(r)}catch{continue}let s=Array.isArray(i)?i:i?.results??i?.people??[];for(let l of s){let u={},c=l.phoneNumbers?.[0]?.value,d=l.emailAddresses?.[0]?.value,f=l.organizations?.[0];c&&(u.phone=c),d&&(u.email=d),f?.name&&(u.organisation=f.name),f?.title&&(u.role=f.title);let g=l.addresses?.[0]?.country;g&&(u.country=g),Object.keys(u).length!==0&&o.push({name:l.names?.[0]?.displayName??n.name,source:"gog",fields:u})}}return o}}}var R=e=>typeof e=="string"&&e.trim()?e.trim():void 0;function L(e){return String(e??"").split("@")[0].split(":")[0].toLowerCase()}function z(e){let t=new Map;for(let o of e){let n=R(o.meta?.sender);if(!n)continue;let r=R(o.meta?.senderId),a=R(o.meta?.senderUsername),i=L(o.source),s={};if(r&&/@s\.whatsapp\.net$/.test(r)){let c=r.split("@")[0].replace(/\D/g,"");if(c){s.phone=`+${c}`,s.whatsapp=r;let d=m(c);d&&(s.country=d)}}else if(i==="whatsapp"&&r&&/^\d{6,}$/.test(r)){s.phone=`+${r}`,s.whatsapp=`${r}@s.whatsapp.net`;let c=m(r);c&&(s.country=c)}if(a){let c=a.startsWith("@")?a:`@${a}`;i==="gitlab"?s.gitlab=c:i==="github"?s.github=c:i==="telegram"?s.telegram=c:s.handle=c}if(r&&!s.phone&&!a&&(s[`${i||"platform"}Id`]=r),Object.keys(s).length===0)continue;let l=n.toLowerCase(),u=t.get(l);if(!u){t.set(l,{name:n,source:"entries",fields:s});continue}for(let[c,d]of Object.entries(s))u.fields[c]??=d}return Array.from(t.values())}function H(e){let t;return{...e,available:()=>t??=e.available(),lookup:(o,n)=>e.lookup(o,n)}}function O(){return[k(),w(),v(),x()].map(H)}function ct(e,t={}){let o=t.max??25,n=new Map;for(let a of e){let i=(a.sender??"").trim();i&&$(i)&&n.set(i.toLowerCase(),{name:i,origin:"sender",type:"person"})}for(let a of e){let i=(a.context??"").trim();if(!$(i))continue;let s=i.toLowerCase();n.has(s)||n.set(s,{name:i,origin:"context"})}let r=(t.known??[]).filter(a=>a.trim().length>2);if(r.length>0){let a=e.map(i=>i.content??"").join(`
|
|
4
|
+
`).toLowerCase();for(let i of r){let s=i.toLowerCase().trim();n.has(s)||a.includes(s)&&n.set(s,{name:i,origin:"body",type:"person"})}}return Array.from(n.values()).slice(0,o)}var U=new Set(["me","user","system","cron","unknown","anonymous","bot","agent","self","test","admin","none","null","n/a"]),B=new Set(["group","team","chat","channel","squad","crew","room","family","project","board","committee","club","staff","office","dept","department","support","sales","ops","admins","everyone","all"]);function $(e){let t=e.trim();if(!t||t.length>48||U.has(t.toLowerCase())||/[\d@/\\#:|_]/.test(t))return!1;let o=t.split(/\s+/);return o.length<2||o.length>4||o.some(n=>B.has(n.toLowerCase()))?!1:o.every(n=>/^[\p{Lu}][\p{L}'’.-]*$/u.test(n))}async function lt(e,t={}){let o=t.sources??O(),n=e.slice(0,t.maxEntities??25);if(n.length===0)return{records:[],results:[]};let r=new AbortController,a=setTimeout(()=>r.abort(),t.timeoutMs??12e4);try{let i=await Promise.all(o.map(async s=>{let l=Date.now();try{let u=await s.available();if(u)return{source:s.name,records:[],unavailable:u,ms:Date.now()-l};let c=await s.lookup(n,r.signal);return{source:s.name,records:c,ms:Date.now()-l}}catch(u){return{source:s.name,records:[],unavailable:{kind:"failed",hint:String(u?.message??u)},ms:Date.now()-l}}}));for(let s of i)t.onResult?.(s);return{records:i.flatMap(s=>s.records),results:i}}finally{clearTimeout(a)}}function ut(e,t=O()){let o=new Map(t.map(n=>[n.name,n.provides]));return e.filter(n=>n.unavailable&&n.unavailable.kind!=="failed").map(n=>({source:n.source,kind:n.unavailable.kind,hint:n.unavailable.hint,provides:o.get(n.source)??[]}))}function ft(e){let t=new Map;for(let o of e){let n=o.name.toLowerCase().trim(),r=t.get(n);r||(r={name:o.name,fields:{}},t.set(n,r));for(let[a,i]of Object.entries(o.fields)){if(!i?.trim())continue;let s=r.fields[a];if(!s){r.fields[a]={value:i,source:o.source};continue}s.value!==i&&(r.fields[`${a} (${o.source})`]??={value:i,source:o.source})}}return Array.from(t.values())}function dt(e){if(e.length===0)return"";let t=e.filter(o=>Object.keys(o.fields).length>0).map(o=>{let n=Object.entries(o.fields).map(([r,a])=>` - ${r}: \`${a.value}\` _(${a.source})_`).join(`
|
|
5
|
+
`);return`- **${o.name}**
|
|
6
|
+
${n}`});return t.length===0?"":`
|
|
7
|
+
## Verified facts
|
|
8
|
+
|
|
9
|
+
These were read from systems of record \u2014 WhatsApp, GitLab, Google, the
|
|
10
|
+
ERP \u2014 not from the entries. They are more reliable than anything the
|
|
11
|
+
conversation implies, and they are the identity fields articles are
|
|
12
|
+
graded on.
|
|
13
|
+
|
|
14
|
+
Copy every value that belongs to an article you write, **verbatim**, into
|
|
15
|
+
its Identity section. Do not paraphrase an identifier, reformat it, or
|
|
16
|
+
replace it with the name of the channel it belongs to. Where a fact here
|
|
17
|
+
contradicts the entries, this wins and the entry is stale.
|
|
18
|
+
|
|
19
|
+
${t.join(`
|
|
20
|
+
`)}
|
|
21
|
+
`}export{m as countryFromPhone,k as createContactsSource,v as createGitlabSource,x as createGogSource,w as createWacliSource,O as defaultSources,ct as extractHints,_ as factsFrom,ut as installPrompts,$ as isPersonName,S as loadContacts,H as memoizeAvailability,ft as mergeRecords,C as namesOf,F as parseContactsTable,L as platformOf,A as plausible,z as recordsFromEntries,dt as renderFactsBlock,lt as resolveFacts};
|
|
22
|
+
//# sourceMappingURL=facts-YVEJOM7O.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/facts/sources/contacts.ts","../src/wiki/facts/exec.ts","../src/wiki/facts/sources/wacli.ts","../src/wiki/facts/sources/gitlab.ts","../src/wiki/facts/sources/gog.ts","../src/wiki/facts/sources/entries.ts","../src/wiki/facts/index.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport type { EntityHint, FactRecord, FactSource } from \"../types\"\nimport { countryFromPhone } from \"./wacli\"\n\n// The contact registry an operator maintains by hand.\n//\n// `.agentx/contacts.json` already existed and nothing in the wiki layer\n// read it, which meant the one place a person had deliberately written\n// down \"this human is these accounts\" was invisible to the pipeline\n// asking that exact question.\n//\n// It ranks above every other source. wacli knows what WhatsApp knows,\n// GitLab knows what GitLab knows, and the entries know who sent a\n// message; this is the only source where someone decided that a name,\n// an alias and a set of handles all refer to one person. Where it\n// disagrees with a directory, the deliberate answer wins — and the\n// disagreement is kept and rendered rather than resolved silently.\n//\n// It is also the only source that resolves aliases, which is what makes\n// a single registry entry cover a given name, a \"first.last\" handle and\n// the display name a phone happens to be saved under.\n\nexport interface ContactRecord {\n id?: string\n name?: string\n aliases?: string[]\n channels?: Record<string, string>\n}\n\n/** Channel key → the fact field it supplies. */\nconst CHANNEL_FIELDS: Record<string, string> = {\n whatsapp: \"whatsapp\",\n telegram: \"telegram\",\n gitlab: \"gitlab\",\n github: \"github\",\n email: \"email\",\n phone: \"phone\",\n slack: \"slack\",\n discord: \"discord\",\n}\n\nexport function contactsPath(agentxDir = \".agentx\"): string {\n return resolve(process.cwd(), agentxDir, \"contacts.json\")\n}\n\nexport function loadContacts(path: string): ContactRecord[] {\n if (!existsSync(path)) return []\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf-8\")) as { contacts?: unknown }\n return Array.isArray(parsed?.contacts) ? (parsed.contacts as ContactRecord[]) : []\n } catch {\n return []\n }\n}\n\nconst norm = (s: string) =>\n s.toLowerCase().normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").replace(/[^a-z0-9 ]/g, \"\").trim()\n\n/** Every spelling this registry entry answers to. */\nexport function namesOf(c: ContactRecord): string[] {\n return [c.name, c.id, ...(c.aliases ?? [])]\n .filter((x): x is string => Boolean(x && x.trim()))\n .map(norm)\n}\n\n/**\n * Turn one registry entry's channels into fact fields.\n *\n * A WhatsApp JID is also a number and a country, so it expands rather\n * than being copied across verbatim — the same unpacking the entries\n * source does, because a reader wants the number, not the routing\n * address it happens to be embedded in.\n */\nexport function factsFrom(c: ContactRecord): Record<string, string> {\n const fields: Record<string, string> = {}\n for (const [key, raw] of Object.entries(c.channels ?? {})) {\n const value = String(raw ?? \"\").trim()\n if (!value) continue\n const field = CHANNEL_FIELDS[key.toLowerCase()] ?? key.toLowerCase()\n\n if (field === \"whatsapp\") {\n const digits = value.split(\"@\")[0].replace(/\\D/g, \"\")\n fields.whatsapp = value.includes(\"@\") ? value : `${digits}@s.whatsapp.net`\n if (digits) {\n fields.phone ??= `+${digits}`\n const country = countryFromPhone(digits)\n if (country) fields.country ??= country\n }\n continue\n }\n if (field === \"phone\") {\n const digits = value.replace(/\\D/g, \"\")\n fields.phone = value.startsWith(\"+\") ? value : `+${digits}`\n const country = countryFromPhone(digits)\n if (country) fields.country ??= country\n continue\n }\n // A bare numeric Telegram id is an account, not a way to reach\n // someone — same rule the entries source applies.\n if (field === \"telegram\" && /^\\d+$/.test(value)) {\n fields.telegramId = value\n continue\n }\n fields[field] = field === \"gitlab\" || field === \"github\"\n ? (value.startsWith(\"@\") ? value : `@${value}`)\n : value\n }\n return fields\n}\n\nexport function createContactsSource(opts: { path?: string } = {}): FactSource {\n const path = opts.path ?? contactsPath()\n\n return {\n name: \"contacts\",\n provides: [\"contact value\", \"handles\", \"country\"],\n async available() {\n if (!existsSync(path)) {\n return {\n kind: \"not-configured\",\n hint: `no ${path} — add {\"contacts\":[{\"name\":\"…\",\"aliases\":[],\"channels\":{\"whatsapp\":\"…\"}}]}`,\n }\n }\n return loadContacts(path).length > 0\n ? null\n : { kind: \"not-configured\", hint: `${path} has no contacts` }\n },\n async lookup(hints: EntityHint[]) {\n const contacts = loadContacts(path)\n if (contacts.length === 0) return []\n\n const index = new Map<string, ContactRecord>()\n for (const c of contacts) for (const n of namesOf(c)) if (n) index.set(n, c)\n\n const out: FactRecord[] = []\n const seen = new Set<ContactRecord>()\n for (const h of hints) {\n const c = index.get(norm(h.name))\n if (!c || seen.has(c)) continue\n seen.add(c)\n const fields = factsFrom(c)\n if (Object.keys(fields).length === 0) continue\n out.push({\n name: c.name ?? h.name,\n source: \"contacts\",\n fields,\n // Matched on an alias rather than the registry's own name.\n fuzzy: norm(c.name ?? \"\") !== norm(h.name),\n })\n }\n return out\n },\n }\n}\n","import { execFile } from \"child_process\"\n\n/**\n * execFile, not exec — an entity name is untrusted input that reaches\n * this from chat messages and GitLab issue titles. Through a shell,\n * a contact called `; rm -rf ~` is a command. execFile passes argv\n * directly and never opens one.\n */\nexport function run(\n cmd: string,\n args: string[],\n opts: { timeoutMs?: number; signal?: AbortSignal } = {},\n): Promise<{ stdout: string; stderr: string; code: number }> {\n return new Promise((resolve) => {\n execFile(\n cmd,\n args,\n {\n timeout: opts.timeoutMs ?? 15_000,\n signal: opts.signal,\n maxBuffer: 4 * 1024 * 1024,\n // The daemon's PATH is not a login shell's. wacli and gog live in\n // Homebrew, and ~/.local/bin is where the fleet's own tools land.\n env: {\n ...process.env,\n PATH: [\n process.env.PATH ?? \"\",\n \"/opt/homebrew/bin\",\n \"/usr/local/bin\",\n `${process.env.HOME ?? \"\"}/.local/bin`,\n ].filter(Boolean).join(\":\"),\n },\n },\n (err, stdout, stderr) => {\n const code = err && typeof (err as { code?: unknown }).code === \"number\"\n ? ((err as { code: number }).code)\n : err ? 1 : 0\n resolve({ stdout: String(stdout ?? \"\"), stderr: String(stderr ?? \"\"), code })\n },\n )\n })\n}\n\nexport async function binaryExists(cmd: string): Promise<boolean> {\n const { code } = await run(\"command\", [\"-v\", cmd], { timeoutMs: 3000 }).catch(() => ({ code: 1 }) as never)\n if (code === 0) return true\n // `command` is a shell builtin, so the above fails on most systems.\n const { code: which } = await run(\"/usr/bin/which\", [cmd], { timeoutMs: 3000 })\n return which === 0\n}\n","import { binaryExists, run } from \"../exec\"\nimport type { EntityHint, FactRecord, FactSource } from \"../types\"\n\n// Phone numbers, from the WhatsApp contact store.\n//\n// This is the source that closes the gap the grader found. It also\n// answers country for free: a JID is an E.164 number, so the dialling\n// prefix identifies the country without a second lookup.\n\nconst CC: Array<[string, string]> = [\n [\"216\", \"Tunisia\"], [\"966\", \"Saudi Arabia\"], [\"971\", \"UAE\"], [\"974\", \"Qatar\"],\n [\"965\", \"Kuwait\"], [\"973\", \"Bahrain\"], [\"968\", \"Oman\"], [\"962\", \"Jordan\"],\n [\"961\", \"Lebanon\"], [\"212\", \"Morocco\"], [\"213\", \"Algeria\"], [\"218\", \"Libya\"],\n [\"249\", \"Sudan\"], [\"20\", \"Egypt\"], [\"90\", \"Turkey\"], [\"33\", \"France\"],\n [\"49\", \"Germany\"], [\"39\", \"Italy\"], [\"34\", \"Spain\"], [\"44\", \"United Kingdom\"],\n [\"31\", \"Netherlands\"], [\"32\", \"Belgium\"], [\"41\", \"Switzerland\"], [\"1\", \"US/Canada\"],\n]\n\n/** Longest prefix wins, or \"1\" would claim every +1xx number. */\nexport function countryFromPhone(phone: string): string | undefined {\n const d = phone.replace(/\\D/g, \"\")\n let best: string | undefined\n let bestLen = 0\n for (const [code, name] of CC) {\n if (d.startsWith(code) && code.length > bestLen) { best = name; bestLen = code.length }\n }\n return best\n}\n\n/**\n * `wacli contacts search` prints a fixed-width table, not JSON:\n *\n * ALIAS NAME PHONE JID\n * Sample Person <e164> <e164>@s.whatsapp.net\n *\n * Parsed from the right, because ALIAS is frequently empty and NAME\n * contains spaces — splitting from the left mis-assigns both.\n */\nexport function parseContactsTable(stdout: string): FactRecord[] {\n const out: FactRecord[] = []\n for (const line of stdout.split(\"\\n\")) {\n const t = line.trim()\n if (!t || t.startsWith(\"ALIAS\")) continue\n const cols = t.split(/\\s{2,}/).filter(Boolean)\n if (cols.length < 2) continue\n const jid = cols[cols.length - 1]\n if (!jid.includes(\"@\")) continue\n const phone = cols[cols.length - 2]\n const name = cols.length >= 3 ? cols[cols.length - 3] : \"\"\n if (!name || !/\\d/.test(phone)) continue\n const country = countryFromPhone(phone)\n out.push({\n name,\n source: \"wacli\",\n fields: {\n phone: `+${phone.replace(/\\D/g, \"\")}`,\n whatsapp: jid,\n ...(country ? { country } : {}),\n },\n })\n }\n return out\n}\n\nexport function createWacliSource(): FactSource {\n return {\n name: \"wacli\",\n provides: [\"contact value\", \"country\"],\n async available() {\n if (!(await binaryExists(\"wacli\"))) {\n return { kind: \"not-installed\", hint: \"brew install wacli — see https://wacli.sh\" }\n }\n // Installed but never authenticated returns an empty store for\n // every query, which looks identical to \"this person is not a\n // contact\" and would quietly teach us the corpus has no numbers.\n const { stdout, stderr, code } = await run(\"wacli\", [\"contacts\", \"search\", \"__agentx_probe__\"], { timeoutMs: 10_000 })\n if (code !== 0 && /auth|not logged in|no session|login/i.test(stdout + stderr)) {\n return { kind: \"not-configured\", hint: \"wacli auth — scan the QR to link the account\" }\n }\n return null\n },\n async lookup(hints: EntityHint[], signal?: AbortSignal) {\n const records: FactRecord[] = []\n const seen = new Set<string>()\n for (const h of hints) {\n // Search the surname alone when the full name misses; the\n // contact store often holds a shorter form than the wiki does.\n for (const q of queriesFor(h.name)) {\n const { stdout, code } = await run(\"wacli\", [\"contacts\", \"search\", q], { signal, timeoutMs: 15_000 })\n if (code !== 0) continue\n const hit = parseContactsTable(stdout).filter((r) => plausible(r.name, h.name))\n if (hit.length === 0) continue\n for (const r of hit) {\n const key = r.fields.whatsapp\n if (seen.has(key)) continue\n seen.add(key)\n records.push({ ...r, fuzzy: !sameName(r.name, h.name) })\n }\n break\n }\n }\n return records\n },\n }\n}\n\nconst norm = (s: string) => s.toLowerCase().normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").replace(/[^a-z0-9 ]/g, \"\").trim()\nconst sameName = (a: string, b: string) => norm(a) === norm(b)\n\nfunction queriesFor(name: string): string[] {\n const parts = norm(name).split(/\\s+/).filter((p) => p.length > 2)\n return parts.length > 1 ? [name, parts[parts.length - 1]] : [name]\n}\n\n/**\n * A surname search returns everyone who shares it. Requiring every token\n * of the shorter name to appear in the longer one keeps a two-word wiki\n * name matching a contact stored under just the first name, while\n * rejecting an unrelated person who shares the surname.\n */\nexport function plausible(candidate: string, wanted: string): boolean {\n const a = norm(candidate).split(/\\s+/).filter(Boolean)\n const b = norm(wanted).split(/\\s+/).filter(Boolean)\n if (a.length === 0 || b.length === 0) return false\n const [short, long] = a.length <= b.length ? [a, b] : [b, a]\n return short.every((t) => long.includes(t))\n}\n","import type { EntityHint, FactRecord, FactSource } from \"../types\"\n\n// Emails, handles and profile URLs, from the GitLab instance.\n//\n// Where most of a fleet's entries arrive through GitLab, this is the\n// system that knows who the people in them are. The user search returns\n// `organization` and `job_title` too, but both are optional and often\n// blank — the source reports what it has and stays quiet about the\n// rest, so a blank job title never reaches the prompt as a fact.\n//\n// Host and token come from the environment. There is no default host:\n// guessing one would send entity names from a private corpus to\n// whatever answers at that address.\n\nexport interface GitlabSourceOptions {\n baseUrl?: string\n token?: string\n}\n\ninterface GitlabUser {\n username?: string\n name?: string\n email?: string\n public_email?: string\n organization?: string\n job_title?: string\n web_url?: string\n state?: string\n}\n\nexport function createGitlabSource(opts: GitlabSourceOptions = {}): FactSource {\n const baseUrl = (opts.baseUrl ?? process.env.GITLAB_URL ?? \"\").replace(/\\/+$/, \"\")\n const token = opts.token ?? process.env.GITLAB_ADMIN_TOKEN ?? process.env.GITLAB_TOKEN\n\n return {\n name: \"gitlab\",\n provides: [\"email\", \"handle\", \"profile URL\"],\n async available() {\n if (!baseUrl) {\n return { kind: \"not-configured\", hint: \"export GITLAB_URL=https://<your-gitlab-host>\" }\n }\n if (!token) {\n return { kind: \"not-configured\", hint: \"export GITLAB_ADMIN_TOKEN=<PAT> (read_api scope is enough)\" }\n }\n // A present-but-rejected token is the dangerous case: every lookup\n // returns nothing, which is indistinguishable from \"this person is\n // not in GitLab\", and the corpus quietly grows a hole while the\n // source reports itself healthy. One authenticated call turns that\n // into a prompt.\n try {\n const res = await fetch(`${baseUrl}/api/v4/user`, { headers: { \"PRIVATE-TOKEN\": token } })\n if (res.status === 401 || res.status === 403) {\n return { kind: \"not-configured\", hint: `GitLab rejected the token (${res.status}) — set a valid GITLAB_ADMIN_TOKEN` }\n }\n if (!res.ok) {\n return { kind: \"failed\", hint: `GitLab returned ${res.status} for the auth probe` }\n }\n } catch (err) {\n return { kind: \"failed\", hint: `cannot reach ${baseUrl}: ${String((err as Error)?.message ?? err)}` }\n }\n return null\n },\n async lookup(hints: EntityHint[], signal?: AbortSignal) {\n if (!token || !baseUrl) return []\n const records: FactRecord[] = []\n const seen = new Set<string>()\n for (const h of hints) {\n const url = `${baseUrl}/api/v4/users?search=${encodeURIComponent(h.name)}&per_page=5`\n let users: GitlabUser[]\n try {\n const res = await fetch(url, { headers: { \"PRIVATE-TOKEN\": token }, signal })\n if (!res.ok) continue\n users = (await res.json()) as GitlabUser[]\n } catch {\n continue\n }\n if (!Array.isArray(users)) continue\n for (const u of users) {\n const key = u.username ?? u.web_url ?? \"\"\n if (!key || seen.has(key)) continue\n seen.add(key)\n const fields: Record<string, string> = {}\n const email = u.email || u.public_email\n if (email) fields.email = email\n if (u.username) fields.gitlab = `@${u.username}`\n if (u.web_url) fields.profile = u.web_url\n // Blank strings are the instance's default, not a stated fact.\n if (u.organization) fields.organisation = u.organization\n if (u.job_title) fields.role = u.job_title\n if (u.state && u.state !== \"active\") fields.accountState = u.state\n if (Object.keys(fields).length === 0) continue\n records.push({\n name: u.name ?? h.name,\n source: \"gitlab\",\n fields,\n fuzzy: (u.name ?? \"\").toLowerCase() !== h.name.toLowerCase(),\n })\n }\n }\n return records\n },\n }\n}\n","import { binaryExists, run } from \"../exec\"\nimport type { EntityHint, FactRecord, FactSource } from \"../types\"\n\n// Contact cards, from Google Contacts via `gog`.\n//\n// On this install the People API is not enabled on the OAuth project and\n// every call returns 403 accessNotConfigured. That is the normal case\n// for a source, not an exception: `available()` reports false, the\n// resolver drops it, and the absorb runs with one fewer input. Enabling\n// the API turns it on with no code change.\n\ninterface GogContact {\n names?: Array<{ displayName?: string }>\n emailAddresses?: Array<{ value?: string }>\n phoneNumbers?: Array<{ value?: string }>\n organizations?: Array<{ name?: string; title?: string }>\n addresses?: Array<{ formattedValue?: string; country?: string }>\n}\n\nexport function createGogSource(): FactSource {\n return {\n name: \"gog\",\n provides: [\"contact value\", \"email\", \"organisation\", \"role\", \"country\"],\n async available() {\n if (!(await binaryExists(\"gog\"))) {\n return { kind: \"not-installed\", hint: \"brew install gog — Google CLI\" }\n }\n // A 403 for a disabled API is reported on stdout with exit 0, so\n // the exit code alone would call this source healthy. The probe\n // takes no flags beyond -j: an unknown flag makes gog print a\n // usage error instead of calling the API, and the probe then\n // passes while every real lookup fails.\n const { stdout, stderr } = await run(\"gog\", [\"contacts\", \"list\", \"-j\"], { timeoutMs: 20_000 })\n const out = stdout + stderr\n if (/unknown flag|Run with --help/i.test(out)) {\n return { kind: \"failed\", hint: `gog rejected the probe: ${out.split(\"\\n\")[0]}` }\n }\n if (/accessNotConfigured|has not been used in project/i.test(out)) {\n return {\n kind: \"not-configured\",\n hint: \"enable the People API on the gog OAuth project, then retry (console.developers.google.com → APIs → People API)\",\n }\n }\n if (/invalid_grant|PERMISSION_DENIED|unauthenticated/i.test(out)) {\n return { kind: \"not-configured\", hint: \"gog auth login — the stored token is expired or lacks contacts scope\" }\n }\n return null\n },\n async lookup(hints: EntityHint[], signal?: AbortSignal) {\n const records: FactRecord[] = []\n for (const h of hints) {\n const { stdout, code } = await run(\"gog\", [\"contacts\", \"search\", h.name, \"-j\", \"--results-only\"], { signal, timeoutMs: 20_000 })\n if (code !== 0) continue\n let parsed: unknown\n try { parsed = JSON.parse(stdout) } catch { continue }\n const list: GogContact[] = Array.isArray(parsed)\n ? (parsed as GogContact[])\n : ((parsed as { results?: unknown[]; people?: unknown[] })?.results as GogContact[])\n ?? ((parsed as { people?: unknown[] })?.people as GogContact[])\n ?? []\n for (const c of list) {\n const fields: Record<string, string> = {}\n const phone = c.phoneNumbers?.[0]?.value\n const email = c.emailAddresses?.[0]?.value\n const org = c.organizations?.[0]\n if (phone) fields.phone = phone\n if (email) fields.email = email\n if (org?.name) fields.organisation = org.name\n if (org?.title) fields.role = org.title\n const country = c.addresses?.[0]?.country\n if (country) fields.country = country\n if (Object.keys(fields).length === 0) continue\n records.push({ name: c.names?.[0]?.displayName ?? h.name, source: \"gog\", fields })\n }\n }\n return records\n },\n }\n}\n","import type { FactRecord } from \"../types\"\nimport { countryFromPhone } from \"./wacli\"\n\n// Identifiers the entries already carry.\n//\n// Every other source in this directory asks an outside system who\n// someone is. This one asks the batch, because since senders are\n// stamped at capture the platform's own identifier travels with the\n// message: a WhatsApp JID is the number, a GitLab sender is the handle.\n//\n// That makes it the best source available, not a fallback. It needs no\n// tool installed, no token, and no network — it works on a server with\n// none of the CLIs — and it cannot mismatch, because there is no name\n// resolution step to get wrong. `wacli` answers \"who is called Alex\n// Rivera\"; this answers \"who sent this message\", and only the second\n// question has one right answer.\n\nexport interface SenderStampedEntry {\n source?: string\n meta?: Record<string, unknown> | undefined\n}\n\nconst str = (v: unknown): string | undefined =>\n typeof v === \"string\" && v.trim() ? v.trim() : undefined\n\n/** \"whatsapp@peer-server\" and \"gitlab\" both normalise to their platform. */\nexport function platformOf(source?: string): string {\n return String(source ?? \"\").split(\"@\")[0].split(\":\")[0].toLowerCase()\n}\n\n/**\n * Turn stamped sender metadata into fact records.\n *\n * Deliberately conservative about what counts as a contact value. A\n * Telegram numeric user id identifies an account but cannot be dialled,\n * messaged by a human, or pasted anywhere useful, so it is recorded as\n * an account id and never as a way to reach someone — writing it into\n * an article's contact line would satisfy the grader while helping\n * nobody, which is the exact failure this whole layer exists to undo.\n */\nexport function recordsFromEntries(entries: SenderStampedEntry[]): FactRecord[] {\n const byName = new Map<string, FactRecord>()\n\n for (const e of entries) {\n const name = str(e.meta?.sender)\n if (!name) continue\n const id = str(e.meta?.senderId)\n const username = str(e.meta?.senderUsername)\n const platform = platformOf(e.source)\n\n const fields: Record<string, string> = {}\n\n if (id && /@s\\.whatsapp\\.net$/.test(id)) {\n const digits = id.split(\"@\")[0].replace(/\\D/g, \"\")\n if (digits) {\n fields.phone = `+${digits}`\n fields.whatsapp = id\n const country = countryFromPhone(digits)\n if (country) fields.country = country\n }\n } else if (platform === \"whatsapp\" && id && /^\\d{6,}$/.test(id)) {\n fields.phone = `+${id}`\n fields.whatsapp = `${id}@s.whatsapp.net`\n const country = countryFromPhone(id)\n if (country) fields.country = country\n }\n\n if (username) {\n const handle = username.startsWith(\"@\") ? username : `@${username}`\n if (platform === \"gitlab\") fields.gitlab = handle\n else if (platform === \"github\") fields.github = handle\n else if (platform === \"telegram\") fields.telegram = handle\n else fields.handle = handle\n }\n\n // An account id is provenance, not a contact value.\n if (id && !fields.phone && !username) fields[`${platform || \"platform\"}Id`] = id\n\n if (Object.keys(fields).length === 0) continue\n\n const key = name.toLowerCase()\n const existing = byName.get(key)\n if (!existing) {\n byName.set(key, { name, source: \"entries\", fields })\n continue\n }\n // Same person across several entries — union the identifiers rather\n // than letting the last message win.\n for (const [k, v] of Object.entries(fields)) existing.fields[k] ??= v\n }\n\n return Array.from(byName.values())\n}\n","import { createContactsSource } from \"./sources/contacts\"\nimport { createGitlabSource } from \"./sources/gitlab\"\nimport { createGogSource } from \"./sources/gog\"\nimport { createWacliSource } from \"./sources/wacli\"\nimport type { EntityHint, FactRecord, FactSource, FactSourceResult, Unavailable } from \"./types\"\n\nexport * from \"./types\"\nexport { countryFromPhone, parseContactsTable, plausible } from \"./sources/wacli\"\nexport { createGitlabSource } from \"./sources/gitlab\"\nexport { createGogSource } from \"./sources/gog\"\nexport { createWacliSource } from \"./sources/wacli\"\nexport { platformOf, recordsFromEntries } from \"./sources/entries\"\nexport { createContactsSource, factsFrom, loadContacts, namesOf } from \"./sources/contacts\"\nexport type { ContactRecord } from \"./sources/contacts\"\nexport type { SenderStampedEntry } from \"./sources/entries\"\n\nexport interface ResolveOptions {\n sources?: FactSource[]\n /** Whole-resolve budget. A slow address book must not stall an absorb. */\n timeoutMs?: number\n /** Cap on entities looked up per batch — each one is N network calls. */\n maxEntities?: number\n onResult?: (r: FactSourceResult) => void\n}\n\n/**\n * Probe each source once per process, not once per lookup.\n *\n * Availability does not change mid-run, but the probes are real work —\n * gog's costs about 1.4s because it has to make an API call to\n * distinguish \"installed\" from \"installed but the API is disabled\".\n * Backfilling 50 articles re-ran every probe 50 times and spent longer\n * asking whether the sources worked than using them.\n *\n * The promise is cached, not the result, so concurrent callers share one\n * probe rather than racing.\n */\nexport function memoizeAvailability(source: FactSource): FactSource {\n let probe: Promise<Unavailable | null> | undefined\n return {\n ...source,\n available: () => (probe ??= source.available()),\n lookup: (hints, signal) => source.lookup(hints, signal),\n }\n}\n\n/**\n * Ordered by authority, because mergeRecords lets the first source to\n * state a field win.\n *\n * The hand-maintained registry comes first: it is the only source where\n * a person decided that a name, its aliases and a set of handles all\n * refer to one human. Directories only know their own corner, and they\n * cannot resolve an alias at all.\n */\nexport function defaultSources(): FactSource[] {\n return [\n createContactsSource(),\n createWacliSource(),\n createGitlabSource(),\n createGogSource(),\n ].map(memoizeAvailability)\n}\n\n/**\n * Names worth a lookup, taken from the batch.\n *\n * Only entities the batch already mentions are ever queried. That is a\n * deliberate limit and not just an efficiency one: exporting the address\n * book into a prompt would put identifiers for people who have nothing\n * to do with the work into a model's context. A lookup is justified by\n * the entry that names the person.\n */\nexport function extractHints(\n entries: Array<{ context?: string; content?: string; sender?: string }>,\n opts: { max?: number; known?: string[] } = {},\n): EntityHint[] {\n const max = opts.max ?? 25\n const byName = new Map<string, EntityHint>()\n\n // The stamped sender first: it is the platform's own record of who\n // spoke, so it beats both a heuristic over `context` and a substring\n // scan of the body. Entries captured before senders were recorded\n // simply have none, and fall through to the other two.\n for (const e of entries) {\n const s = (e.sender ?? \"\").trim()\n if (s && isPersonName(s)) byName.set(s.toLowerCase(), { name: s, origin: \"sender\", type: \"person\" })\n }\n\n for (const e of entries) {\n const ctx = (e.context ?? \"\").trim()\n if (!isPersonName(ctx)) continue\n const key = ctx.toLowerCase()\n if (byName.has(key)) continue\n byName.set(key, { name: ctx, origin: \"context\" })\n }\n\n // `context` only names a person for one-to-one channels. On a GitLab\n // entry it is the issue title, and in a group chat it is the group —\n // so the people who talk in groups, which is most of them, were never\n // looked up at all. The first article written with this layer live\n // said \"Contact identifiers: unknown … no number is recorded\" about\n // someone the contact store knew perfectly well.\n //\n // The bodies do name them, but harvesting capitalised word pairs out\n // of free text would spend lookups on noise and, worse, resolve\n // strangers. So the corpus is its own dictionary: a name is a hint\n // only if the wiki already has a person article for it. That is\n // precise by construction, and it targets exactly the articles a\n // second pass is going to rewrite.\n const known = (opts.known ?? []).filter((n) => n.trim().length > 2)\n if (known.length > 0) {\n const haystack = entries.map((e) => e.content ?? \"\").join(\"\\n\").toLowerCase()\n for (const name of known) {\n const key = name.toLowerCase().trim()\n if (byName.has(key)) continue\n if (haystack.includes(key)) byName.set(key, { name, origin: \"body\", type: \"person\" })\n }\n }\n\n return Array.from(byName.values()).slice(0, max)\n}\n\nconst NOT_A_PERSON = new Set([\n \"me\", \"user\", \"system\", \"cron\", \"unknown\", \"anonymous\", \"bot\", \"agent\",\n \"self\", \"test\", \"admin\", \"none\", \"null\", \"n/a\",\n])\n\n/**\n * Words that make a capitalised phrase a collection rather than a person.\n *\n * A group chat's `context` is its name, and plenty of group names are\n * shaped exactly like a person's — \"Team Group\", \"Acme Family\". Shape\n * alone cannot separate them, and treating one as a person spends a\n * lookup and risks matching a real contact with a similar name.\n */\nconst COLLECTION_NOUNS = new Set([\n \"group\", \"team\", \"chat\", \"channel\", \"squad\", \"crew\", \"room\", \"family\",\n \"project\", \"board\", \"committee\", \"club\", \"staff\", \"office\", \"dept\",\n \"department\", \"support\", \"sales\", \"ops\", \"admins\", \"everyone\", \"all\",\n])\n\n/**\n * Two to four capitalised words, no digits, not a known placeholder.\n *\n * `context` holds a person's name for chat sources and an issue title\n * for GitLab ones, and issue titles are long and full of punctuation.\n * The bar is deliberately high: a false positive costs a wasted lookup\n * and, worse, risks putting an unrelated person's identifiers into the\n * prompt, so a missed name is the cheaper error.\n */\nexport function isPersonName(s: string): boolean {\n const t = s.trim()\n if (!t || t.length > 48) return false\n if (NOT_A_PERSON.has(t.toLowerCase())) return false\n if (/[\\d@/\\\\#:|_]/.test(t)) return false\n const words = t.split(/\\s+/)\n if (words.length < 2 || words.length > 4) return false\n if (words.some((w) => COLLECTION_NOUNS.has(w.toLowerCase()))) return false\n return words.every((w) => /^[\\p{Lu}][\\p{L}'’.-]*$/u.test(w))\n}\n\nexport async function resolveFacts(\n hints: EntityHint[],\n opts: ResolveOptions = {},\n): Promise<{ records: FactRecord[]; results: FactSourceResult[] }> {\n const sources = opts.sources ?? defaultSources()\n const picked = hints.slice(0, opts.maxEntities ?? 25)\n if (picked.length === 0) return { records: [], results: [] }\n\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? 120_000)\n try {\n const results = await Promise.all(sources.map(async (s): Promise<FactSourceResult> => {\n const t0 = Date.now()\n try {\n const why = await s.available()\n if (why) return { source: s.name, records: [], unavailable: why, ms: Date.now() - t0 }\n const records = await s.lookup(picked, ac.signal)\n return { source: s.name, records, ms: Date.now() - t0 }\n } catch (err) {\n // A source that throws contributes nothing and blocks nothing.\n return {\n source: s.name,\n records: [],\n unavailable: { kind: \"failed\", hint: String((err as Error)?.message ?? err) },\n ms: Date.now() - t0,\n }\n }\n }))\n for (const r of results) opts.onResult?.(r)\n return { records: results.flatMap((r) => r.records), results }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * What to tell the operator about the sources that did not answer.\n *\n * A source silently contributing nothing is the worst outcome: the\n * corpus quietly develops a hole shaped like the missing tool, and the\n * grader reports the resulting gaps as though the fact did not exist\n * anywhere. Installing `wacli` is a one-line fix that nobody makes if\n * nobody is told. `failed` is left out — a transient error is noise, not\n * a task.\n */\nexport function installPrompts(\n results: FactSourceResult[],\n sources: FactSource[] = defaultSources(),\n): Array<{ source: string; kind: string; hint: string; provides: string[] }> {\n const provides = new Map(sources.map((s) => [s.name, s.provides]))\n return results\n .filter((r) => r.unavailable && r.unavailable.kind !== \"failed\")\n .map((r) => ({\n source: r.source,\n kind: r.unavailable!.kind,\n hint: r.unavailable!.hint,\n provides: provides.get(r.source) ?? [],\n }))\n}\n\nexport interface MergedEntity {\n name: string\n /** field → value, with the source that supplied it. */\n fields: Record<string, { value: string; source: string }>\n}\n\n/**\n * Merge per entity, first source to state a field wins.\n *\n * Order is the source order, which puts WhatsApp's number ahead of\n * Google's. That is intentional rather than arbitrary: the WhatsApp\n * number is the one the agent will actually message on, so where the two\n * disagree the messaging channel's own record is the operative fact.\n * Conflicts are kept and rendered, never silently resolved.\n */\nexport function mergeRecords(records: FactRecord[]): MergedEntity[] {\n const out = new Map<string, MergedEntity>()\n for (const r of records) {\n const key = r.name.toLowerCase().trim()\n let e = out.get(key)\n if (!e) { e = { name: r.name, fields: {} }; out.set(key, e) }\n for (const [k, v] of Object.entries(r.fields)) {\n if (!v?.trim()) continue\n const existing = e.fields[k]\n if (!existing) { e.fields[k] = { value: v, source: r.source }; continue }\n if (existing.value !== v) {\n // Two systems of record disagree. The writer should see both.\n e.fields[`${k} (${r.source})`] ??= { value: v, source: r.source }\n }\n }\n }\n return Array.from(out.values())\n}\n\n/**\n * The prompt block.\n *\n * Phrased as an instruction to copy rather than as context to consider.\n * Absorb's whole disposition is to summarise, and an identifier\n * summarised is an identifier lost — which is the failure this exists\n * to fix.\n */\nexport function renderFactsBlock(entities: MergedEntity[]): string {\n if (entities.length === 0) return \"\"\n const lines = entities\n .filter((e) => Object.keys(e.fields).length > 0)\n .map((e) => {\n const fields = Object.entries(e.fields)\n .map(([k, v]) => ` - ${k}: \\`${v.value}\\` _(${v.source})_`)\n .join(\"\\n\")\n return `- **${e.name}**\\n${fields}`\n })\n if (lines.length === 0) return \"\"\n return `\n## Verified facts\n\nThese were read from systems of record — WhatsApp, GitLab, Google, the\nERP — not from the entries. They are more reliable than anything the\nconversation implies, and they are the identity fields articles are\ngraded on.\n\nCopy every value that belongs to an article you write, **verbatim**, into\nits Identity section. Do not paraphrase an identifier, reformat it, or\nreplace it with the name of the channel it belongs to. Where a fact here\ncontradicts the entries, this wins and the entry is stale.\n\n${lines.join(\"\\n\")}\n`\n}\n"],"mappings":"4BAAA,OAAS,cAAAA,EAAY,gBAAAC,MAAoB,KACzC,OAAS,WAAAC,MAAe,OCDxB,OAAS,YAAAC,MAAgB,gBAQlB,SAASC,EACdC,EACAC,EACAC,EAAqD,CAAC,EACK,CAC3D,OAAO,IAAI,QAASC,GAAY,CAC9BL,EACEE,EACAC,EACA,CACE,QAASC,EAAK,WAAa,KAC3B,OAAQA,EAAK,OACb,UAAW,EAAI,KAAO,KAGtB,IAAK,CACH,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AAK,EAAG,SAChB,IAAMC,EAAW9B,EAAE,OAAO4B,CAAC,EAC3B,GAAI,CAACE,EAAU,CAAE9B,EAAE,OAAO4B,CAAC,EAAI,CAAE,MAAOC,EAAG,OAAQN,EAAE,MAAO,EAAG,SAC3DO,EAAS,QAAUD,IAErB7B,EAAE,OAAO,GAAG4B,MAAML,EAAE,SAAS,IAAM,CAAE,MAAOM,EAAG,OAAQN,EAAE,MAAO,IAItE,OAAO,MAAM,KAAKI,EAAI,OAAO,CAAC,CAChC,CAUO,SAASI,GAAiBC,EAAkC,CACjE,GAAIA,EAAS,SAAW,EAAG,MAAO,GAClC,IAAMC,EAAQD,EACX,OAAQhC,GAAM,OAAO,KAAKA,EAAE,MAAM,EAAE,OAAS,CAAC,EAC9C,IAAKA,GAAM,CACV,IAAMkC,EAAS,OAAO,QAAQlC,EAAE,MAAM,EACnC,IAAI,CAAC,CAAC4B,EAAGC,CAAC,IAAM,OAAOD,QAAQC,EAAE,aAAaA,EAAE,UAAU,EAC1D,KAAK;AAAA,CAAI,EACZ,MAAO,OAAO7B,EAAE;AAAA,EAAWkC,GAC7B,CAAC,EACH,OAAID,EAAM,SAAW,EAAU,GACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaPA,EAAM,KAAK;AAAA,CAAI;AAAA,CAEjB","names":["existsSync","readFileSync","resolve","execFile","run","cmd","args","opts","resolve","err","stdout","stderr","code","binaryExists","which","CC","countryFromPhone","phone","d","best","bestLen","code","name","parseContactsTable","stdout","out","line","t","cols","jid","country","createWacliSource","binaryExists","stderr","run","hints","signal","records","seen","h","q","queriesFor","hit","r","plausible","key","sameName","norm","s","a","b","parts","p","candidate","wanted","short","long","CHANNEL_FIELDS","contactsPath","agentxDir","resolve","loadContacts","path","existsSync","parsed","readFileSync","norm","s","namesOf","c","x","factsFrom","fields","key","raw","value","field","digits","country","countryFromPhone","createContactsSource","opts","hints","contacts","index","n","out","seen","h","createGitlabSource","opts","baseUrl","token","res","err","hints","signal","records","seen","h","url","users","u","key","fields","email","createGogSource","binaryExists","stdout","stderr","run","out","hints","signal","records","h","code","parsed","list","c","fields","phone","email","org","country","str","v","platformOf","source","recordsFromEntries","entries","byName","e","name","id","username","platform","fields","digits","country","countryFromPhone","handle","key","existing","k","memoizeAvailability","source","probe","hints","signal","defaultSources","createContactsSource","createWacliSource","createGitlabSource","createGogSource","extractHints","entries","opts","max","byName","e","s","isPersonName","ctx","key","known","n","haystack","name","NOT_A_PERSON","COLLECTION_NOUNS","words","w","resolveFacts","sources","picked","ac","timer","results","t0","why","records","err","r","installPrompts","provides","mergeRecords","out","k","v","existing","renderFactsBlock","entities","lines","fields"]}
|