limixbot 0.3.145 → 0.3.146

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.
Files changed (149) hide show
  1. package/dist/assets/{ActivityPanel-CqObZQbN.js → ActivityPanel-DTqdgF9v.js} +1 -1
  2. package/dist/assets/{App-DcG1JmK6.js → App-FkCoivKo.js} +102 -102
  3. package/dist/assets/{AppEventEditor-DR01sHAK.js → AppEventEditor-hBLRTJCh.js} +1 -1
  4. package/dist/assets/{BotSettingsDialog-BHgSIU9E.js → BotSettingsDialog-0CLALU4h.js} +1 -1
  5. package/dist/assets/{BrowserPanel-g96rlnqQ.js → BrowserPanel-BjqIxdsD.js} +1 -1
  6. package/dist/assets/{BrowserProfilesManager-UJJC6OPf.js → BrowserProfilesManager-C2DEX5Dz.js} +1 -1
  7. package/dist/assets/{CloudAddDialog-BjPYPhnk.js → CloudAddDialog-Ce6eiErj.js} +1 -1
  8. package/dist/assets/{ComputerFilesPane-DA7MBSD0.js → ComputerFilesPane-CUls-HDE.js} +1 -1
  9. package/dist/assets/{ComputerPanel--rY7_KCN.js → ComputerPanel-CY6rmF7p.js} +2 -2
  10. package/dist/assets/{DataPanel-CEhe1WKo.js → DataPanel-BMItjksI.js} +1 -1
  11. package/dist/assets/{DesktopViewer-RNuariIo.js → DesktopViewer-uyCSG2he.js} +1 -1
  12. package/dist/assets/{GrokMoveDialog-DoUN6m5b.js → GrokMoveDialog-BjIt7fo_.js} +1 -1
  13. package/dist/assets/{InspectorPanel-CdCXUouJ.js → InspectorPanel-Be9J8vTL.js} +1 -1
  14. package/dist/assets/{KeyboardShortcutsModal-CZ-BQqzV.js → KeyboardShortcutsModal-CJhaJp59.js} +1 -1
  15. package/dist/assets/KnowledgePanel-BsdqL7-z.js +1 -0
  16. package/dist/assets/{LimixResizeHandles-BUe_6hSJ.js → LimixResizeHandles-DKdU_JFS.js} +1 -1
  17. package/dist/assets/{LiveDesktop-BnaxuTzU.js → LiveDesktop-QudEVPsj.js} +1 -1
  18. package/dist/assets/{LocalVmWorkspace-X1ev9Wov.js → LocalVmWorkspace-Cs2BgRNV.js} +1 -1
  19. package/dist/assets/{MacLocalControl-RXW-1ET9.js → MacLocalControl-Cq3ZxYZY.js} +1 -1
  20. package/dist/assets/{MarkdownFilePreview-CIYTKbNj.js → MarkdownFilePreview-CVTDyg_G.js} +1 -1
  21. package/dist/assets/{MenuMotion-C-qcisoG.js → MenuMotion-B0aZnuh_.js} +1 -1
  22. package/dist/assets/{NewBotDialog-D_22AmDd.js → NewBotDialog-aItvxrvB.js} +1 -1
  23. package/dist/assets/{PhoneAppDialog-WOhzSF82.js → PhoneAppDialog-8-dgtBhp.js} +1 -1
  24. package/dist/assets/{PlacesRail-DoUGQSpd.js → PlacesRail-tZyNm-l3.js} +1 -1
  25. package/dist/assets/{PluginsPanel-DxM_qWtC.js → PluginsPanel-DVS8g955.js} +6 -6
  26. package/dist/assets/{ProIntroduction-CQFDxYxi.js → ProIntroduction-DV0pDAEU.js} +1 -1
  27. package/dist/assets/{RemoteAgentSettingsPanel-CdQmz7Qu.js → RemoteAgentSettingsPanel-CNlzF4Cp.js} +1 -1
  28. package/dist/assets/{RoomPanel-DVsYTCX7.js → RoomPanel-Cc_GKn6x.js} +1 -1
  29. package/dist/assets/{RoutinesPage-DG30sQw7.js → RoutinesPage-DOBkHlRF.js} +3 -3
  30. package/dist/assets/{SettingsModal-BFeWJ1OS.js → SettingsModal-B7Qc3XzL.js} +1 -1
  31. package/dist/assets/{ShareTeamDialog-BLddRjax.js → ShareTeamDialog-CSlDvD9U.js} +1 -1
  32. package/dist/assets/{SignedInSites-BREmZ6gH.js → SignedInSites-D-0eKIyP.js} +1 -1
  33. package/dist/assets/{TeamLibraryPanel-Sg1D_gYP.js → TeamLibraryPanel-DM76EFJx.js} +1 -1
  34. package/dist/assets/{TeamMapPage-CP7ug7dF.js → TeamMapPage-DhrPVbXJ.js} +1 -1
  35. package/dist/assets/{TriggersPage-DmY-ibGg.js → TriggersPage-DjSUS5gg.js} +1 -1
  36. package/dist/assets/{VisibilitySection-BqQTMT_O.js → VisibilitySection-DwI5DSDK.js} +5 -5
  37. package/dist/assets/{WebhookTrigger-Bk2khhKt.js → WebhookTrigger-DZqMzEbP.js} +1 -1
  38. package/dist/assets/{WorksOnGrid-BhZTjLmG.js → WorksOnGrid-CDTdX4z9.js} +1 -1
  39. package/dist/assets/{abnfDiagram-YUKMZFIV-4h66COg4.js → abnfDiagram-YUKMZFIV-DDXPrZzl.js} +1 -1
  40. package/dist/assets/{activity-JVyqvn--.js → activity-BlL5ycb5.js} +1 -1
  41. package/dist/assets/{architectureDiagram-47P4ROYG-XVFtgz_w.js → architectureDiagram-47P4ROYG-BiqBgMDV.js} +1 -1
  42. package/dist/assets/{blockDiagram-E7TT5TSB-Bzpnrunu.js → blockDiagram-E7TT5TSB-vc1neoFp.js} +1 -1
  43. package/dist/assets/{c4Diagram-CRA5TL53-Baf7lWcX.js → c4Diagram-CRA5TL53-CQbtBKOv.js} +1 -1
  44. package/dist/assets/{calendar-days-DJ8Sk4Wo.js → calendar-days-_dtxyR4U.js} +1 -1
  45. package/dist/assets/channel-BzyEyDo_.js +1 -0
  46. package/dist/assets/{chunk-2Q5K7J3B-C01NJDuW.js → chunk-2Q5K7J3B-Dq_aCCIt.js} +1 -1
  47. package/dist/assets/{chunk-5VM5RSS4-zCxCK82Z.js → chunk-5VM5RSS4-EcX_ZXzF.js} +1 -1
  48. package/dist/assets/{chunk-7TKQ45FW-Dn3xzwzp.js → chunk-7TKQ45FW-BA7CgKU2.js} +1 -1
  49. package/dist/assets/{chunk-AW2ZBBNX-D5v1LEvi.js → chunk-AW2ZBBNX-DkvVwaph.js} +1 -1
  50. package/dist/assets/{chunk-FVRAUYC3-B_j2BQfP.js → chunk-FVRAUYC3-CdyGRg6v.js} +2 -2
  51. package/dist/assets/{chunk-HTAEGDNF-CYEfb4lj.js → chunk-HTAEGDNF-CS-veEVV.js} +1 -1
  52. package/dist/assets/{chunk-JWPE2WC7-DYxCqsdI.js → chunk-JWPE2WC7-BiUYpinX.js} +1 -1
  53. package/dist/assets/{chunk-KQW6MTUR-BVs1owNv.js → chunk-KQW6MTUR-DDPkIuwB.js} +1 -1
  54. package/dist/assets/{chunk-XXDRQBXY-oNREPc9w.js → chunk-XXDRQBXY-C4YyKEem.js} +1 -1
  55. package/dist/assets/{classDiagram-v2-K4WV4PDN-B8JOWdQM.js → classDiagram-v2-K4WV4PDN-BjmVbVHi.js} +1 -1
  56. package/dist/assets/{coins-D-zVxeJ6.js → coins-Cu3qn-3t.js} +1 -1
  57. package/dist/assets/{core-DGyt94O8.js → core-DBsdXcHm.js} +1 -1
  58. package/dist/assets/{cose-bilkent-JH36ORCC-Cvvvdg2x.js → cose-bilkent-JH36ORCC-Bra0B-5z.js} +1 -1
  59. package/dist/assets/{cynefin-EF2NZ3EQ-BlyJPVpP.js → cynefin-EF2NZ3EQ-BRMKNbnx.js} +1 -1
  60. package/dist/assets/{cynefinDiagram-3GCD6N5R-aXWhkS0N.js → cynefinDiagram-3GCD6N5R-DMhNix9A.js} +1 -1
  61. package/dist/assets/{dagre-W4DXFKR2-CK9mZlxS.js → dagre-W4DXFKR2-BWwdFKCx.js} +1 -1
  62. package/dist/assets/{diagram-2UJZ2QOL-ciDDPAUW.js → diagram-2UJZ2QOL-D_4J-D-V.js} +1 -1
  63. package/dist/assets/{diagram-OVF4WLC6-ZC2XGXAQ.js → diagram-OVF4WLC6-CQ4l30Dm.js} +1 -1
  64. package/dist/assets/{diagram-PFPMY2P6-B_UNW8Y1.js → diagram-PFPMY2P6-D3W2IEHX.js} +1 -1
  65. package/dist/assets/{diagram-UMYRVEAY-BzqwG15l.js → diagram-UMYRVEAY-C9cpNhET.js} +1 -1
  66. package/dist/assets/{diagram-YEKJPTXX-f7zBrJwE.js → diagram-YEKJPTXX-DIyquCXt.js} +1 -1
  67. package/dist/assets/{diagram-ZIFT7M5P-QClomp2E.js → diagram-ZIFT7M5P-CO6216kK.js} +1 -1
  68. package/dist/assets/{ebnfDiagram-VR2GEFS7-BwcmIXBL.js → ebnfDiagram-VR2GEFS7-BeHXJPN4.js} +1 -1
  69. package/dist/assets/{elk-IJKZMXRS-DPv8qzg-.js → elk-IJKZMXRS-BdT_tK3j.js} +1 -1
  70. package/dist/assets/{erDiagram-O2IAPWRE-BHknllso.js → erDiagram-O2IAPWRE-Cz_TiHab.js} +1 -1
  71. package/dist/assets/{file-up-B5lQ3tIu.js → file-up-flw1aUka.js} +1 -1
  72. package/dist/assets/{flowDiagram-OXPTDLAJ-LwDo9oFR.js → flowDiagram-OXPTDLAJ-BXLr0anm.js} +1 -1
  73. package/dist/assets/{ganttDiagram-R7TSEDQI-DDXQuF2p.js → ganttDiagram-R7TSEDQI-C37QIpaR.js} +1 -1
  74. package/dist/assets/{gitGraphDiagram-XJZIOB7I-DxAL8MxK.js → gitGraphDiagram-XJZIOB7I-Cs8fTfJZ.js} +1 -1
  75. package/dist/assets/{import-name-fUZKEQiu.js → import-name-DRn9LvPS.js} +1 -1
  76. package/dist/assets/{index-C_1rKgRm.js → index-CaQlk_HV.js} +3 -3
  77. package/dist/assets/{index-Bb6OwohQ.js → index-Cnv_eiqT.js} +2 -2
  78. package/dist/assets/{infoDiagram-5W2HQ5XZ-BxZNIlp6.js → infoDiagram-5W2HQ5XZ-BpliNVPR.js} +1 -1
  79. package/dist/assets/{ishikawaDiagram-K3B6WC7H-C6c1u1w2.js → ishikawaDiagram-K3B6WC7H-Dov7w4qz.js} +1 -1
  80. package/dist/assets/{journeyDiagram-COXZFDF6-BrngL-3X.js → journeyDiagram-COXZFDF6-DoihiGaK.js} +1 -1
  81. package/dist/assets/{kanban-definition-P3RFRI5V-BhTOtF-B.js → kanban-definition-P3RFRI5V-D_gNx8dG.js} +1 -1
  82. package/dist/assets/{mermaid.core-Cy9_uq1T.js → mermaid.core-BYPxVPn-.js} +4 -4
  83. package/dist/assets/{mindmap-definition-LZFPQGKD-Dr3QB9wA.js → mindmap-definition-LZFPQGKD-wH2aKxFy.js} +1 -1
  84. package/dist/assets/{minimize-Ct6C2khA.js → minimize-sGQL0Xsy.js} +1 -1
  85. package/dist/assets/{monitor-BZrhga_j.js → monitor-zecPzfR5.js} +1 -1
  86. package/dist/assets/{new-bot-DCA0S24E.js → new-bot-LJs5i8O5.js} +1 -1
  87. package/dist/assets/{org-library-DgVAGwBY.js → org-library-B4fn4bHb.js} +1 -1
  88. package/dist/assets/{package-format-BvWgfqGs.js → package-format-CbAOdMeR.js} +1 -1
  89. package/dist/assets/{pegDiagram-BGZESJAR-D0bSaHqd.js → pegDiagram-BGZESJAR-B7RTZksQ.js} +1 -1
  90. package/dist/assets/{pieDiagram-CAPJLFHJ-B8i7ox8l.js → pieDiagram-CAPJLFHJ-B5mPB7O-.js} +1 -1
  91. package/dist/assets/{quadrantDiagram-GDMTTRAM-BcJTpsdR.js → quadrantDiagram-GDMTTRAM-CZqo7j7U.js} +1 -1
  92. package/dist/assets/{rail-Bzq4BbCt.js → rail-Ok0cs7cA.js} +1 -1
  93. package/dist/assets/{railroadDiagram-SM67HX2B-DSO-XOKW.js → railroadDiagram-SM67HX2B-MFpfIts_.js} +1 -1
  94. package/dist/assets/{remote-desktop-panel-BVRS7AXc.js → remote-desktop-panel-0Aj0_kDX.js} +1 -1
  95. package/dist/assets/{requirementDiagram-X7JNWC4A-B5gEynme.js → requirementDiagram-X7JNWC4A-CJ49gC_q.js} +1 -1
  96. package/dist/assets/{sankeyDiagram-UM26HJRW-CK2T6Pgm.js → sankeyDiagram-UM26HJRW-DxpTSw3D.js} +1 -1
  97. package/dist/assets/{sequenceDiagram-ZO4K6R2Y-Dx9DVGEG.js → sequenceDiagram-ZO4K6R2Y-XEyCx2Ue.js} +1 -1
  98. package/dist/assets/{sizeCapture-INFHLROL-BbirmlCW.js → sizeCapture-INFHLROL-1Fx1tcNn.js} +1 -1
  99. package/dist/assets/{stateDiagram-v2-TBUQTH76-CuJOlmiS.js → stateDiagram-v2-TBUQTH76-CwxyNDK4.js} +1 -1
  100. package/dist/assets/styles-CMOouTIW.css +1 -0
  101. package/dist/assets/{styles-CLQR3ehf.js → styles-DO3EUxm2.js} +1 -1
  102. package/dist/assets/{swimlanes-N4OXWK64-BWFqBYF_.js → swimlanes-N4OXWK64-BuwwuENy.js} +1 -1
  103. package/dist/assets/swimlanesDiagram-K3J5GTZL-CcmXEgRh.js +8 -0
  104. package/dist/assets/{team-share-1e1FK9fo.js → team-share-CL18_anr.js} +1 -1
  105. package/dist/assets/{timeline-definition-YOQAKGHF-CzxPBKDi.js → timeline-definition-YOQAKGHF-CauwqKMA.js} +1 -1
  106. package/dist/assets/{usecaseDiagram-VIAY4XPW-B5-pXbU3.js → usecaseDiagram-VIAY4XPW-YZ3Cf2do.js} +1 -1
  107. package/dist/assets/{vennDiagram-BLWOH2XV-BccL1p-U.js → vennDiagram-BLWOH2XV-CDX8i7ID.js} +1 -1
  108. package/dist/assets/{vi-DyvsTHbT.js → vi-CiY3ddy3.js} +1 -1
  109. package/dist/assets/{wardleyDiagram-YMQ3BMBF-DdJ9Pves.js → wardleyDiagram-YMQ3BMBF-CCdRrEMh.js} +1 -1
  110. package/dist/assets/{xychartDiagram-TAQBALBS-BAg7I3YQ.js → xychartDiagram-TAQBALBS-Vz4NaN0U.js} +1 -1
  111. package/dist/index.html +3 -3
  112. package/dist/rail.html +5 -5
  113. package/dist-server/drivers/agents-proxy.js +412 -400
  114. package/dist-server/index.js +6844 -6649
  115. package/dist-server/knowledge-collection.worker.js +4737 -0
  116. package/dist-server/licenses/knowledge.txt +688 -0
  117. package/dist-server/limixbot.js +1560 -1542
  118. package/dist-server/package.json +1 -1
  119. package/dist-server/pair-cli.js +1560 -1542
  120. package/dist-server/server/agents-turn.js +1 -0
  121. package/dist-server/server/bot-moves.js +16 -13
  122. package/dist-server/server/drivers/agents-call.js +8 -0
  123. package/dist-server/server/drivers/agents-catalog-profile.js +1 -0
  124. package/dist-server/server/drivers/agents-catalog.js +4 -1
  125. package/dist-server/server/host/bot-access-gate.js +3 -0
  126. package/dist-server/server/index.js +52 -3
  127. package/dist-server/server/knowledge/core.bench.js +35 -0
  128. package/dist-server/server/knowledge/core.js +338 -0
  129. package/dist-server/server/knowledge/database.js +153 -0
  130. package/dist-server/server/knowledge/documents.js +169 -0
  131. package/dist-server/server/knowledge/files.js +64 -0
  132. package/dist-server/server/knowledge/host.js +158 -0
  133. package/dist-server/server/knowledge/memory.js +51 -0
  134. package/dist-server/server/knowledge/plugin.js +17 -0
  135. package/dist-server/server/knowledge/retrieval.js +90 -0
  136. package/dist-server/server/knowledge/schema.js +39 -0
  137. package/dist-server/server/knowledge/semantic.js +135 -0
  138. package/dist-server/server/knowledge/tools.js +58 -0
  139. package/dist-server/server/knowledge-collection-fetch.js +101 -0
  140. package/dist-server/server/knowledge-collection.js +300 -0
  141. package/dist-server/server/knowledge-collection.worker.js +142 -0
  142. package/dist-server/server/move-freeze.js +1 -16
  143. package/dist-server/server/plugin-hub.js +17 -0
  144. package/dist-server/server/routes/knowledge.js +48 -0
  145. package/dist-server/server/routes/move-freeze.js +2 -6
  146. package/package.json +1 -1
  147. package/dist/assets/channel-DJthUr0W.js +0 -1
  148. package/dist/assets/styles-CE5PtWhb.css +0 -1
  149. package/dist/assets/swimlanesDiagram-K3J5GTZL-BjpCZGc-.js +0 -8
@@ -16,6 +16,7 @@ export function agentsServerEnv(conversation, turn, bearer, harnessUrl) {
16
16
  OMB_COMMS_TOKEN: bearer(turn),
17
17
  OMB_SKILL_AUTHORING_ENABLED: flag(host.skillAuthoring),
18
18
  ...(host.pluginRead ? { OMB_PLUGIN_READ: "1" } : {}),
19
+ ...(host.knowledge ? { LIMIX_KNOWLEDGE: "1" } : {}),
19
20
  OMB_MEMORY_ENABLED: flag(bot.memoryEnabled !== false),
20
21
  OMB_SHARED_COMPUTERS_ENABLED: flag(host.sharedComputers),
21
22
  OMB_CLOUD_HOME: flag(host.cloudHome), OMB_TEAM_PEOPLE: flag(host.team), OMB_ROOM: flag(conversation.room),
@@ -36,16 +36,12 @@ export function createBotMoves(deps) {
36
36
  if (wait.botId === botId)
37
37
  waits.cancel(wait.id, botId);
38
38
  };
39
- /** A room some of whose bots stay goes on here without this one; one all of whose bots left is kept as it was. */
40
- const leaveRooms = (botId) => {
41
- for (const room of deps.store.groups ?? []) {
42
- if (room.dm || !room.memberIds.includes(botId))
43
- continue;
44
- if (room.memberIds.every((id) => id === botId || deps.store.bot(id)?.movedTo || deps.store.bot(id)?.defaultBot))
45
- continue;
46
- deps.store.patchGroup?.(room.id, { memberIds: room.memberIds.filter((id) => id !== botId) });
39
+ for (const bot of deps.store.bots ?? []) {
40
+ const held = movedOf(bot);
41
+ if (held?.state === "moved" && held.team.id === MY_CLOUD_TEAM) {
42
+ deps.store.patchBot(bot.id, { hidden: false, movedTo: undefined, personalCloudCopyAt: held.at });
47
43
  }
48
- };
44
+ }
49
45
  return {
50
46
  /** The bot stops here for the move: no turns, its automations off and its waits cancelled. Busy while it answers; a
51
47
  * bot already moved stays moved. Holding it again keeps what the first hold switched off. */
@@ -94,13 +90,18 @@ export function createBotMoves(deps) {
94
90
  moved(botId, team) {
95
91
  const bot = deps.store.bot(botId);
96
92
  const held = movedOf(bot);
93
+ if (team.id === MY_CLOUD_TEAM && bot && !held && bot.personalCloudCopyAt !== undefined) {
94
+ return { movedTo: { team, state: "moved", at: bot.personalCloudCopyAt } };
95
+ }
97
96
  if (!bot || !held || held.team.id !== team.id)
98
97
  return { refused: "This bot is not moving to that team." };
98
+ if (team.id === MY_CLOUD_TEAM) {
99
+ const completed = { ...held, state: "moved", at: now() };
100
+ deps.store.patchBot(botId, { movedTo: undefined, hidden: false, personalCloudCopyAt: completed.at });
101
+ return { movedTo: completed };
102
+ }
99
103
  if (held.state !== "moved") {
100
- if (team.id === MY_CLOUD_TEAM)
101
- leaveRooms(botId);
102
- else
103
- deps.routines()?.removeForBot(botId);
104
+ deps.routines()?.removeForBot(botId);
104
105
  cancelWaits(botId);
105
106
  deps.store.patchBot(botId, { movedTo: { ...held, state: "moved", at: now() }, hidden: true });
106
107
  }
@@ -110,6 +111,8 @@ export function createBotMoves(deps) {
110
111
  back(botId) {
111
112
  const bot = deps.store.bot(botId);
112
113
  const held = movedOf(bot);
114
+ if (bot && !held && bot.personalCloudCopyAt !== undefined)
115
+ deps.store.patchBot(botId, { personalCloudCopyAt: undefined });
113
116
  if (!bot || !held)
114
117
  return { released: true };
115
118
  if (held.team.id !== MY_CLOUD_TEAM)
@@ -193,6 +193,14 @@ export async function callTool(called, input, context) {
193
193
  const member = agentsCallMember(name, args);
194
194
  const { botId: BOT_ID, threadId: THREAD_ID } = context;
195
195
  const { api, apiResponse } = context.client;
196
+ if (name.startsWith("knowledge_")) {
197
+ const result = await apiResponse("/api/internal/knowledge/" + name.slice("knowledge_".length), { method: "POST", body: JSON.stringify(args) });
198
+ if (!result.ok)
199
+ return { text: String(result.body.error ?? "Knowledge request failed."), isError: true };
200
+ const text = JSON.stringify(result.body);
201
+ const data = text.length <= 16_000 ? result.body : { truncated: true, excerpt: text.slice(0, 15_000), hint: "Narrow the search, reduce the limit or request one document." };
202
+ return { text: JSON.stringify(data), passthrough: { content: [{ type: "text", text: JSON.stringify(data) }], structuredContent: data } };
203
+ }
196
204
  if (name === "vm_exec") {
197
205
  const { ok, body } = await apiResponse("/api/internal/vm-exec", {
198
206
  method: "POST",
@@ -3,6 +3,7 @@ import { toolsOffFromEnv } from "../../shared/tool-groups.js";
3
3
  export function catalogProfileFromEnv(env) {
4
4
  return {
5
5
  ...(env.OMB_PLUGIN_READ === "1" ? { pluginRead: true } : {}),
6
+ ...(env.LIMIX_KNOWLEDGE === "1" ? { knowledge: true } : {}),
6
7
  skillAuthoring: env.OMB_SKILL_AUTHORING_ENABLED === "1",
7
8
  sharedComputers: env.OMB_SHARED_COMPUTERS_ENABLED === "1",
8
9
  voiceNotes: env.OMB_VOICE_NOTES === "1",
@@ -13,6 +13,7 @@ import { COMPUTER_ASK_TOOL_DEFINITIONS, COMPUTER_ASK_TOOL_NAMES } from "./agents
13
13
  import { IMAGE_TOOL_DEFINITIONS, IMAGE_TOOL_NAMES } from "./agents-image-tools.js";
14
14
  import { MEETING_TOOL_DEFINITIONS, MEETING_TOOL_NAMES } from "./agents-meeting-tools.js";
15
15
  import { MAUSBOT_TOOL_DEFINITIONS } from "./agents-mausbot-tools.js";
16
+ import { knowledgeTools } from "../knowledge/tools.js";
16
17
  import { PERSON_TOOL_DEFINITIONS } from "./agents-person-tools.js";
17
18
  import { RESEARCH_TOOL_DEFINITIONS, RESEARCH_TOOL_NAMES, X_TOOL_NAMES } from "./agents-research-tools.js";
18
19
  import { advertisedSchema } from "./agents-schema.js";
@@ -155,6 +156,7 @@ const TRIGGER_FIELDS_SCHEMA = {
155
156
  const CHIEF_PROFILE_TARGET = " A Chief of Staff may pass for_bot_id (from list_bots) for a requested change to another bot in its section.";
156
157
  const APPLIES_OUTCOME = " Read the result: it applies immediately at every access level, and the person sees it with an Undo where possible. If applied, continue the work without another confirmation. Only a pending result (a Cloud conversation its owner did not drive) means ending the turn to wait for the owner. Never claim success without an applied result; report failures honestly. This does not elevate another bot's execution permissions.";
157
158
  const TOOL_DEFINITIONS = [
159
+ ...knowledgeTools.filter(tool => tool.name !== "knowledge_archive"),
158
160
  {
159
161
  name: "create_options_card",
160
162
  description: "Show the person a native card with 2-6 choices in this Watcher conversation. The card is passive: a click returns the selected words as a reply and never authorizes or performs an external action. Use it for Watcher's review and draft-selection steps, then wait for the person's response.",
@@ -927,7 +929,8 @@ export function fullInputSchema(name) {
927
929
  return FULL_INPUT_SCHEMAS.get(name);
928
930
  }
929
931
  function catalogTools(profile) {
930
- const BOT_SCOPED_TOOLS = TOOL_DEFINITIONS.filter((tool) => (tool.name !== "plugin_read" || profile.pluginRead === true) &&
932
+ const BOT_SCOPED_TOOLS = TOOL_DEFINITIONS.filter((tool) => (profile.knowledge === true || !tool.name.startsWith("knowledge_")) &&
933
+ (tool.name !== "plugin_read" || profile.pluginRead === true) &&
931
934
  (profile.botId === WATCHER_OPTIONS_CARD_BOT_ID || !WATCHER_TOOL_NAMES.has(tool.name)) &&
932
935
  (profile.memoryEnabled !== false || (tool.name !== "memory_update" && tool.name !== "memory_log")) &&
933
936
  (profile.computerSelection === true || tool.name !== "select_computer") &&
@@ -10,6 +10,9 @@ export function levelNeeded(method, path) {
10
10
  const verb = method.toUpperCase();
11
11
  if (verb === "GET" || verb === "HEAD")
12
12
  return "view";
13
+ const knowledge = /^\/api\/bots\/[\w-]+\/knowledge\/([a-z_]+)$/.exec(path);
14
+ if (knowledge && verb === "POST")
15
+ return /^(list|read|search|list_sources|history|backlinks|graph|get_stats|memory_recall|memory_consolidate|export|archive|jobs)$/.test(knowledge[1]) ? "view" : "edit";
13
16
  if (/^\/api\/bots\/[\w-]+$/.test(path))
14
17
  return null;
15
18
  if (/^\/api\/bots\/[\w-]+\/(?:access|bot-api(?:\/new-key)?)$/.test(path))
@@ -544,6 +544,9 @@ import { createPluginMcpRoutes, readPluginComponent } from "./routes/plugin-mcp.
544
544
  import { customMcpServers as pluginServerSpecs } from "./config.js";
545
545
  import { withMcpSignIn } from "./mcp-oauth.js";
546
546
  import { createPluginHub } from "./plugin-hub.js";
547
+ import { createKnowledgeHost } from "./knowledge/host.js";
548
+ import { KnowledgeError } from "./knowledge/schema.js";
549
+ import { knowledgeFailure, knowledgeRoutes } from "./routes/knowledge.js";
547
550
  import { limixBundledFor, limixSelectBundled, limixSkillDefaultsMigration } from "./limix-skill-store.js";
548
551
  import { createSkillShareRoutes } from "./routes/skill-share.js";
549
552
  import { createTeamContextRoutes } from "./routes/team-context.js";
@@ -1859,7 +1862,7 @@ function agentsIntegration(botId, threadId, depth, skillAuthoring, generation, r
1859
1862
  // Only advertises the tools; the routes behind them refuse regardless.
1860
1863
  const host = { pluginRead: Boolean(bot && pluginHub.hasComponents(bot, [...Object.keys(engineMcpServers(bot)), ...(workspaceRead ? [WORKSPACE_READ] : [])])), skillAuthoring: skillAuthoringEnabled(cfg), sharedComputers: botLending(), cloudHome: Boolean(CLOUD_HOME), team: Boolean(CLOUD_TEAM),
1861
1864
  voiceNotes: tts.voiceReady(cfg, speaking?.voice) && speaking?.voiceNotes !== false, x: Boolean(researchCredential(cfg.treg?.key)), research: researchAvailability.available(), imageGeneration: imageGenerationReady(cfg), meetings: boat.boatConfigured(cfg) };
1862
- return { ...agentsProxyLaunch(), env: agentsServerEnv({ threadId, bot: bot ?? { id: botId }, room: Boolean(store.groupByThread(threadId)), teamComputer: Boolean(bot && inheritedTeamComputer(bot)), botDriven: automated || botDrivenConversation(store.taskByThread(botId, threadId)), host }, { generation, depth, skillAuthoring, roomHandoffId, ...(hostFiles && !CLOUD_HOME && !HOSTED_WORKSPACE ? { deliversSavedFiles: true } : {}) }, (turn) => mintInternalCapability({ botId, threadId, kind: "agents", createdBots: 0, openedThreads: 0, ...turn, ...(workspaceRead ? { workspaceReadMounted: true } : {}) }), `http://127.0.0.1:${PORT}`) };
1865
+ return { ...agentsProxyLaunch(), env: agentsServerEnv({ threadId, bot: bot ?? { id: botId }, room: Boolean(store.groupByThread(threadId)), teamComputer: Boolean(bot && inheritedTeamComputer(bot)), botDriven: automated || botDrivenConversation(store.taskByThread(botId, threadId)), host: { ...host, knowledge: Boolean(bot && knowledge.enabled(bot) && !cloudGuestDriven(threadId) && !botApiThread(threadId) && !proactive.fence.confines(threadId)) } }, { generation, depth, skillAuthoring, roomHandoffId, ...(hostFiles && !CLOUD_HOME && !HOSTED_WORKSPACE ? { deliversSavedFiles: true } : {}) }, (turn) => mintInternalCapability({ botId, threadId, kind: "agents", createdBots: 0, openedThreads: 0, ...turn, ...(workspaceRead ? { workspaceReadMounted: true } : {}) }), `http://127.0.0.1:${PORT}`) };
1863
1866
  }
1864
1867
  function workspaceReadAllowed(bot, threadId, cwd) {
1865
1868
  return sameWorkspacePath(bot.cwd, cwd) && sameWorkspacePath(store.taskByThread(bot.id, threadId)?.cwd, cwd)
@@ -2994,7 +2997,7 @@ const wireTask = (task, botModel, awaiting = threadsAwaitingTeammates()) => {
2994
2997
  };
2995
2998
  /** Strips provider session ids (resumeCursors) here, not at call sites, so no broadcast or paired phone ever gets them. */
2996
2999
  const wireBot = (bot) => {
2997
- const { resumeCursors: _resumeCursors, tasks, approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, ...rest } = bot;
3000
+ const { resumeCursors: _resumeCursors, tasks, approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, personalCloudCopyAt: _personalCloudCopyAt, ...rest } = bot;
2998
3001
  // Clients see Ask while an elevated grant awaits the desktop's confirmation, never a grant that may still roll back.
2999
3002
  const visible = approvalGrant && !approvalGrant.threadOnly
3000
3003
  ? { ...rest, approvalMode: "ask", autoApprove: false }
@@ -3014,7 +3017,7 @@ function toolScopeForTurn(botId) {
3014
3017
  return parsed.scope;
3015
3018
  }
3016
3019
  const wireTrustedApprovalBot = (bot) => {
3017
- const { resumeCursors: _resumeCursors, tasks, approvalGrant: _approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, ...rest } = bot;
3020
+ const { resumeCursors: _resumeCursors, tasks, approvalGrant: _approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, personalCloudCopyAt: _personalCloudCopyAt, ...rest } = bot;
3018
3021
  const awaiting = threadsAwaitingTeammates();
3019
3022
  return { ...rest, approvalMode: approvalModeFor(rest), mainThreadId: botMainThread(bot.id), avatarUrl: rest.avatarUrl ?? null, ...(tasks ? { tasks: tasks.map((task) => wireTask(task, bot.modelSelection, awaiting)) } : {}) };
3020
3023
  };
@@ -12633,6 +12636,22 @@ const pluginHub = createPluginHub(DATA_DIR, () => ({
12633
12636
  teams: store.sections.filter(Boolean),
12634
12637
  }));
12635
12638
  pluginHub.pruneTeams(store.sections);
12639
+ const knowledge = createKnowledgeHost(DATA_DIR, ENVIRONMENT_ID, pluginHub, id => store.bot(id));
12640
+ ROUTES.push(knowledgeRoutes(knowledge, (auth, botId) => {
12641
+ const admin = ownerOrAdmin(auth) && !(auth.kind === "loopback" && auth.companionDevice);
12642
+ if ((!CLOUD_TEAM && !admin) || (CLOUD_PERSONAL && !cloudOwnerSession(auth)) ||
12643
+ (auth.kind === "loopback" && (auth.trust === "service" || auth.companionDevice)))
12644
+ throw new KnowledgeError(403, "Workspace access required.");
12645
+ if (auth.kind === "session" && !sessions.list().some(session => session.id === auth.session.id && session.expiresAt > Date.now()))
12646
+ throw new KnowledgeError(403, "Session expired.");
12647
+ const level = levelOf(auth, botId);
12648
+ if ((!admin && level === "none") || !store.bot(botId))
12649
+ throw new KnowledgeError(404, "Unknown bot.");
12650
+ const ownerId = CLOUD_TEAM && auth.kind === "session" ? personKey(auth.session) : "workspace-owner";
12651
+ const canWrite = admin || level === "edit";
12652
+ return { ownerId, canManage: admin, canWrite, human: true, memoryWrite: canWrite,
12653
+ memoryId: CLOUD_TEAM ? layerId(botId, memberAudience(ownerId)) : botId };
12654
+ }));
12636
12655
  async function resolvePluginServer(name, botId) {
12637
12656
  if (!Object.hasOwn(cfg.mcpServers ?? {}, name) || teamConnections.personMcp().includes(name))
12638
12657
  return null;
@@ -14303,6 +14322,36 @@ const handleRequest = async (req, res) => {
14303
14322
  task: store.taskByThread(from.id, threadId)?.title,
14304
14323
  });
14305
14324
  }
14325
+ if (method === "POST" && path.startsWith("/api/internal/knowledge/")) {
14326
+ const action = path.slice("/api/internal/knowledge/".length);
14327
+ const input = await readInternalBody(256_000);
14328
+ const identify = () => {
14329
+ const bot = store.bot(internalSender.id);
14330
+ const thread = internalCapability.threadId;
14331
+ if (!internalCapabilityIsActive(internalCapability) || !bot || cloudGuestDriven(thread) || botApiThread(thread)
14332
+ || proactive.fence.confines(thread) || outsideDrivenThread(thread) || !allowsTool(bot.toolScope, { kind: "mcp", server: "agents", name: "knowledge_" + action }, input)
14333
+ || (CLOUD_PERSONAL && cloudHomeOwnTurnRefusal(cloudLendingTurn(internalCapability)) !== null))
14334
+ throw new KnowledgeError(403, "Knowledge is unavailable in this conversation.");
14335
+ const audience = teamHost.audienceOf(thread);
14336
+ const room = store.groupByThread(thread);
14337
+ const ownerId = CLOUD_TEAM ? audienceMember(audience) ?? "audience-" + createHash("sha256").update(audience).digest("hex") : "workspace-owner";
14338
+ return { ownerId, canManage: false, human: false, canWrite: true,
14339
+ memoryWrite: (!room || roomFeedsBot(room, bot)) && turnOrigin(internalCapability).kind === "user",
14340
+ memoryId: teamHost.layer(bot.id, thread) };
14341
+ };
14342
+ if (action === "archive")
14343
+ return json(res, 403, { error: "Only available in the offline viewer." });
14344
+ if ((internalCapability.pluginReads ?? 0) >= 32)
14345
+ return json(res, 429, { error: "Knowledge tool budget exhausted for this turn." });
14346
+ internalCapability.pluginReads = (internalCapability.pluginReads ?? 0) + 1;
14347
+ try {
14348
+ return json(res, 200, await knowledge.run(internalSender.id, action, input, identify, callSignal));
14349
+ }
14350
+ catch (error) {
14351
+ const failure = knowledgeFailure(error);
14352
+ return json(res, failure.status, failure.body);
14353
+ }
14354
+ }
14306
14355
  if (method === "POST" && path === "/api/internal/plugin-read") {
14307
14356
  const input = await readInternalBody();
14308
14357
  if ((internalCapability.pluginReads ?? 0) >= 32)
@@ -0,0 +1,35 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ const fixture = mkdtempSync(join(tmpdir(), "limix-knowledge-bench-"));
5
+ process.env.OMB_DATA_DIR = fixture;
6
+ const { KnowledgeVault } = await import("./core.js");
7
+ const vault = new KnowledgeVault(fixture);
8
+ const scope = { workspaceId: "bench", ownerId: "person", botId: "one" };
9
+ const count = 200;
10
+ try {
11
+ const begin = performance.now();
12
+ for (let n = 0; n < count; n++)
13
+ vault.execute(scope, "create", {
14
+ title: "Research " + n, body: "Limix Knowledge Engine\n" + ("Nghiên cứu quy trình giao hàng. ".repeat(40)) + "\nFact for reference" + n,
15
+ });
16
+ const writeMs = performance.now() - begin;
17
+ vault.execute(scope, "search", { query: "reference199" });
18
+ const durations = [];
19
+ let topOne = 0;
20
+ for (let n = 0; n < count; n++) {
21
+ const start = performance.now();
22
+ const results = vault.search(scope, { query: "reference" + n, token_budget: 128 }).results;
23
+ durations.push(performance.now() - start);
24
+ if (results[0]?.title === "Research " + n)
25
+ topOne++;
26
+ }
27
+ durations.sort((a, b) => a - b);
28
+ console.log(JSON.stringify({ node: process.version, platform: process.platform, documents: count, queries: count, top_one_correct: topOne,
29
+ note_bytes: vault.stats(scope).bytes, total_create_ms: Math.round(writeMs), bm25_p50_ms: +durations[Math.floor(count * 0.5)].toFixed(2),
30
+ bm25_p95_ms: +durations[Math.floor(count * 0.95)].toFixed(2), workload: "Warm FTS5, exact unique reference per note" }));
31
+ }
32
+ finally {
33
+ vault.close();
34
+ rmSync(fixture, { recursive: true, force: true });
35
+ }
@@ -0,0 +1,338 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { ZodError } from "zod";
3
+ import { decode, mayWrite, readable, scopeArgs } from "./database.js";
4
+ import { analyze, cleanProperties, foldedTitle, hash, normalizeBody, parseFile, scrub, sourceUrl } from "./documents.js";
5
+ import { fileParts, filePath, readNote } from "./files.js";
6
+ import { nativeMemory } from "./memory.js";
7
+ import { KnowledgeRetrieval } from "./retrieval.js";
8
+ import { KnowledgeError, knowledgeSchemas as s } from "./schema.js";
9
+ export { KnowledgeError } from "./schema.js";
10
+ function checkScope(scope) {
11
+ if (!scope || ![scope.workspaceId, scope.ownerId, scope.botId].every(id => typeof id === "string" && id.length > 0 && id.length <= 256 && !/[\x00-\x1f]/.test(id))) {
12
+ throw new KnowledgeError(403, "Missing knowledge access.");
13
+ }
14
+ }
15
+ function argumentsOf(schema, input) {
16
+ const validated = schema.safeParse(input);
17
+ if (!validated.success)
18
+ throw new KnowledgeError(400, "Invalid knowledge tool input: " + validated.error.issues.map(issue => issue.path.join(".") || "arguments").slice(0, 3).join(", "));
19
+ return validated.data;
20
+ }
21
+ export class KnowledgeVault extends KnowledgeRetrieval {
22
+ scans = new Map();
23
+ persist(scope, work) {
24
+ const result = this.transaction(work);
25
+ this.flush(scope);
26
+ return result;
27
+ }
28
+ owned(scope, id, version) {
29
+ const doc = this.document(scope, id);
30
+ if (!mayWrite(scope, doc))
31
+ throw new KnowledgeError(403, "Write access required.");
32
+ if (doc.version !== version)
33
+ throw new KnowledgeError(409, "Document version changed. Read it again.");
34
+ const path = fileParts(doc);
35
+ if (!this.db.prepare("SELECT 1 FROM projection WHERE path=?").get(path.join("/"))) {
36
+ const contents = readNote(filePath(this.root, path));
37
+ const row = this.db.prepare("SELECT disk_hash FROM documents WHERE id=?").get(id);
38
+ if (contents === null || hash(contents) !== row.disk_hash)
39
+ throw new KnowledgeError(409, "Document changed on disk. Index it before editing.");
40
+ }
41
+ return doc;
42
+ }
43
+ create(scope, input, action, importedId) {
44
+ if (scope.canWrite === false)
45
+ throw new KnowledgeError(403, "Write access required.");
46
+ const visibility = input.visibility ?? "private";
47
+ if (visibility === "shared" && !scope.writeShared)
48
+ throw new KnowledgeError(403, "Shared write access required.");
49
+ const format = input.format ?? "md", body = normalizeBody(input.body, format), digest = hash(body);
50
+ const url = sourceUrl(input.source_url);
51
+ const now = new Date().toISOString();
52
+ const existing = this.db.prepare(`SELECT payload FROM documents WHERE workspace=? AND (visibility='shared' OR (owner=? AND bot=?)) AND visibility=? AND format=? AND hash=? AND url IS ? AND title=? ORDER BY updated DESC LIMIT 1`)
53
+ .get(scope.workspaceId, scope.ownerId, scope.botId, visibility, format, digest, url, foldedTitle(scrub(input.title)));
54
+ if (existing && action !== "publish")
55
+ return { document: { ...decode(existing), can_write: true }, duplicate: true };
56
+ const doc = { document_id: importedId ?? randomUUID(), workspace_id: scope.workspaceId, owner_id: scope.ownerId, bot_id: scope.botId, visibility,
57
+ title: scrub(input.title), body, format, source_type: input.source_type ?? "note", source_url: url, source_hash: input.source_hash ?? null,
58
+ archive_id: input.archive_id ?? null, fetched_at: input.fetched_at ?? null, author: input.author ? scrub(input.author) : null,
59
+ content_hash: digest, created_at: now, updated_at: now, verification_status: "unverified", confidence: null, version: 1, retention_policy: "manual", properties: cleanProperties(input.properties),
60
+ quality: { has_source: !!url, has_substance: body.length >= 120, needs_review: true },
61
+ ...analyze(body, input.tags ?? []) };
62
+ this.save(scope, doc, action);
63
+ return { document: { ...doc, can_write: true }, duplicate: false };
64
+ }
65
+ revise(scope, doc, changes, action) {
66
+ const next = { ...doc, verification_status: "unverified", confidence: null, ...changes, updated_at: new Date().toISOString(), version: doc.version + 1 };
67
+ next.quality = { has_source: !!next.source_url, has_substance: next.body.length >= 120, needs_review: next.verification_status !== "verified" };
68
+ this.save(scope, next, action);
69
+ return { document: { ...next, can_write: true } };
70
+ }
71
+ publish(scope, record) {
72
+ checkScope(scope);
73
+ if (scope.canWrite === false)
74
+ throw new KnowledgeError(403, "Write access required.");
75
+ const input = argumentsOf(s.create, record);
76
+ if (!input.source_url || !input.source_hash || !input.fetched_at || input.source_type !== "web")
77
+ throw new KnowledgeError(400, "Missing collection provenance.");
78
+ if (input.visibility === "shared" && !scope.writeShared)
79
+ throw new KnowledgeError(403, "Shared write access required.");
80
+ this.flush(scope);
81
+ return this.persist(scope, () => {
82
+ const url = sourceUrl(input.source_url), body = normalizeBody(input.body, "md"), digest = hash(body);
83
+ const rows = this.db.prepare(`SELECT payload,(SELECT action FROM versions WHERE doc=d.id ORDER BY version DESC LIMIT 1) AS action FROM documents d
84
+ WHERE workspace=? AND owner=? AND bot=? AND visibility=? AND url=? AND json_extract(payload,'$.source_type')='web' ORDER BY updated DESC,id LIMIT 100`)
85
+ .all(scope.workspaceId, scope.ownerId, scope.botId, input.visibility ?? "private", url);
86
+ for (const row of rows) {
87
+ const doc = decode(row);
88
+ if (doc.source_hash === input.source_hash && doc.content_hash === digest)
89
+ return { document: { ...doc, can_write: true }, duplicate: true };
90
+ }
91
+ const current = rows[0];
92
+ if (current && current.action === "publish") {
93
+ const doc = decode(current);
94
+ this.owned(scope, doc.document_id, doc.version);
95
+ return { ...this.revise(scope, doc, { title: scrub(input.title), body, content_hash: digest, source_hash: input.source_hash,
96
+ archive_id: input.archive_id ?? null, fetched_at: input.fetched_at, author: input.author ? scrub(input.author) : null,
97
+ ...analyze(body, input.tags ?? []) }, "publish"), duplicate: false };
98
+ }
99
+ return this.create(scope, input, "publish");
100
+ });
101
+ }
102
+ index(scope, incremental) {
103
+ if (scope.canWrite === false)
104
+ return { indexed: 0, deleted: 0, skipped: 0 };
105
+ const key = JSON.stringify([scope.workspaceId, scope.ownerId, scope.botId, !!scope.writeShared]);
106
+ const scan = this.scans.get(key);
107
+ if (incremental && scan && Date.now() - scan.at < 15_000)
108
+ return { indexed: 0, deleted: 0, skipped: 0 };
109
+ const cursor = incremental && scan ? scan.cursor : "";
110
+ const rows = this.db.prepare(`SELECT id,path,disk_hash,payload FROM documents d WHERE ${readable("d")} AND id>? ORDER BY id LIMIT ?`).all(...scopeArgs(scope), cursor, incremental ? 12 : 2048);
111
+ let indexed = 0, deleted = 0, skipped = 0;
112
+ for (const row of rows) {
113
+ const doc = decode(row);
114
+ if (!mayWrite(scope, doc))
115
+ continue;
116
+ let content, parsed;
117
+ try {
118
+ content = readNote(filePath(this.root, String(row.path).split("/")));
119
+ if (content !== null && hash(content) !== row.disk_hash)
120
+ parsed = parseFile(String(row.path), content);
121
+ }
122
+ catch (error) {
123
+ if (!(error instanceof KnowledgeError))
124
+ throw error;
125
+ skipped++;
126
+ continue;
127
+ }
128
+ const onDisk = content === null ? null : hash(content);
129
+ if (onDisk === row.disk_hash)
130
+ continue;
131
+ // An editor can change the bytes while a server is indexing. Only the live SQL revision may be replaced.
132
+ this.persist(scope, () => {
133
+ const current = this.document(scope, doc.document_id);
134
+ if (current.version !== doc.version || this.db.prepare("SELECT 1 FROM projection WHERE path=?").get(row.path))
135
+ return;
136
+ if (content === null) {
137
+ this.remove(scope, doc);
138
+ deleted++;
139
+ return;
140
+ }
141
+ if (!parsed)
142
+ return;
143
+ const title = doc.format === "md" ? parsed.title : doc.title;
144
+ this.revise(scope, doc, { body: parsed.body, title, content_hash: hash(parsed.body), properties: parsed.properties,
145
+ ...analyze(parsed.body, doc.format === "md" ? parsed.tags ?? [] : doc.tags) }, "external_edit");
146
+ indexed++;
147
+ });
148
+ }
149
+ if (this.scans.size >= 256)
150
+ this.scans.delete(this.scans.keys().next().value);
151
+ this.scans.set(key, { at: Date.now(), cursor: rows.length === 12 && incremental ? String(rows.at(-1).id) : "" });
152
+ return { indexed, deleted, skipped };
153
+ }
154
+ importFiles(scope, files, dryRun) {
155
+ if (files.reduce((n, f) => n + Buffer.byteLength(f.content), 0) > 2 * 1024 * 1024)
156
+ throw new KnowledgeError(413, "Import exceeds 2 MiB.");
157
+ const names = new Set(), ids = new Map();
158
+ const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
159
+ const notes = files.map(file => {
160
+ const name = foldedTitle(file.path);
161
+ if (names.has(name))
162
+ throw new KnowledgeError(400, "Duplicate import path.");
163
+ names.add(name);
164
+ const key = name.split("/").at(-1).replace(/\.[^.]+$/, "");
165
+ return { key, input: argumentsOf(s.create, parseFile(file.path, file.content)) };
166
+ });
167
+ const mappedId = (key) => {
168
+ if (!uuid.test(key))
169
+ return key;
170
+ const existing = this.db.prepare("SELECT id FROM documents WHERE id=? AND workspace=? AND owner=? AND bot=? AND visibility='private'").get(key, scope.workspaceId, scope.ownerId, scope.botId);
171
+ if (existing)
172
+ return key;
173
+ const h = hash(JSON.stringify([scope.workspaceId, scope.ownerId, scope.botId, key]));
174
+ return [h.slice(0, 8), h.slice(8, 12), "8" + h.slice(13, 16), "a" + h.slice(17, 20), h.slice(20, 32)].join("-");
175
+ };
176
+ const resolve = (key) => ids.get(key.toLowerCase()) ?? mappedId(key.toLowerCase());
177
+ let imported = 0, duplicates = 0;
178
+ const run = () => {
179
+ for (const { key } of notes)
180
+ if (uuid.test(key))
181
+ ids.set(key, mappedId(key));
182
+ for (const { key, input } of notes) {
183
+ input.body = input.body.replace(/(\[\[(?:[^\]\n|#/]+\/)*)([a-f\d-]{36})(?=\]\]|[#|])/gi, (_full, prefix, link) => prefix + resolve(link));
184
+ if (input.format === "canvas") {
185
+ const canvas = JSON.parse(input.body);
186
+ let changed = false;
187
+ for (const node of canvas.nodes)
188
+ if (node.type === "file" && node.file) {
189
+ const normalized = node.file.replace(/^(?:.*\/)?([a-f\d-]{36})\.(md|base|canvas)$/i, (_all, id, ext) => `private/${resolve(id)}.${ext}`);
190
+ if (node.file !== normalized) {
191
+ node.file = normalized;
192
+ changed = true;
193
+ }
194
+ }
195
+ if (changed)
196
+ input.body = JSON.stringify(canvas, null, 2);
197
+ }
198
+ const chosen = ids.get(key);
199
+ // A bundle cannot replace a live document by naming its UUID; changed imports become separate review candidates.
200
+ const fresh = chosen && !this.db.prepare("SELECT 1 FROM documents WHERE id=?").get(chosen) ? chosen : undefined;
201
+ const created = this.create(scope, input, "import", fresh);
202
+ if (created.duplicate)
203
+ duplicates++;
204
+ else
205
+ imported++;
206
+ }
207
+ };
208
+ if (dryRun) {
209
+ this.db.exec("SAVEPOINT import_preview");
210
+ try {
211
+ run();
212
+ }
213
+ finally {
214
+ this.db.exec("ROLLBACK TO import_preview; RELEASE import_preview");
215
+ }
216
+ }
217
+ else
218
+ this.persist(scope, run);
219
+ return { imported, duplicates, dry_run: dryRun };
220
+ }
221
+ execute(scope, action, input = {}) {
222
+ checkScope(scope);
223
+ this.flush(scope);
224
+ if (["list", "search", "list_sources", "get_stats", "graph"].includes(action))
225
+ this.index(scope, true);
226
+ switch (action) {
227
+ case "list":
228
+ case "list_sources": return this.list(scope, argumentsOf(s.list, input), action === "list_sources");
229
+ case "search": return this.search(scope, argumentsOf(s.search, input));
230
+ case "get_stats":
231
+ argumentsOf(s.get_stats, input);
232
+ return this.stats(scope);
233
+ case "read": {
234
+ const a = argumentsOf(s.read, input);
235
+ const current = this.document(scope, a.document_id);
236
+ if (!a.version || current.version === a.version)
237
+ return { document: { ...current, can_write: mayWrite(scope, current) } };
238
+ const row = this.db.prepare("SELECT payload FROM versions WHERE doc=? AND version=?").get(a.document_id, a.version);
239
+ if (!row)
240
+ throw new KnowledgeError(404, "Version not found.");
241
+ return { document: { ...decode(row), can_write: false } };
242
+ }
243
+ case "create": {
244
+ const a = argumentsOf(s.create, input);
245
+ if (a.source_type === "web" || a.source_hash || a.archive_id || a.fetched_at)
246
+ throw new KnowledgeError(400, "Collected source metadata is server-assigned.");
247
+ return this.persist(scope, () => this.create(scope, a, "create"));
248
+ }
249
+ case "update": {
250
+ const a = argumentsOf(s.update, input);
251
+ return this.persist(scope, () => {
252
+ const doc = this.owned(scope, a.document_id, a.version);
253
+ const body = a.body === undefined ? doc.body : normalizeBody(a.body, doc.format);
254
+ const title = a.title === undefined ? doc.title : scrub(a.title);
255
+ const intelligence = analyze(body, a.tags ?? doc.tags);
256
+ const properties = cleanProperties(a.properties ?? doc.properties);
257
+ if (body === doc.body && title === doc.title && JSON.stringify(intelligence.tags) === JSON.stringify(doc.tags) && JSON.stringify(properties) === JSON.stringify(doc.properties ?? {}))
258
+ return { document: { ...doc, can_write: true } };
259
+ return this.revise(scope, doc, { body, title, properties, content_hash: hash(body), ...intelligence }, "update");
260
+ });
261
+ }
262
+ case "verify_source": {
263
+ if (!scope.review)
264
+ throw new KnowledgeError(403, "Review access required.");
265
+ const a = argumentsOf(s.verify_source, input);
266
+ return this.persist(scope, () => {
267
+ const doc = this.owned(scope, a.document_id, a.version);
268
+ if (doc.verification_status === a.verification_status)
269
+ return { document: { ...doc, can_write: true } };
270
+ return this.revise(scope, doc, { verification_status: a.verification_status, confidence: a.verification_status === "unverified" ? null : Number(a.verification_status === "verified") }, "review");
271
+ });
272
+ }
273
+ case "delete": {
274
+ const a = argumentsOf(s.delete, input);
275
+ return this.persist(scope, () => { const doc = this.owned(scope, a.document_id, a.version); this.remove(scope, doc); return { deleted: true, document_id: doc.document_id, archive_id: doc.archive_id }; });
276
+ }
277
+ case "history": {
278
+ const { document_id } = argumentsOf(s.history, input);
279
+ this.document(scope, document_id);
280
+ const history = this.db.prepare("SELECT version,action,json_extract(payload,'$.updated_at') AS updated_at,json_extract(payload,'$.content_hash') AS content_hash FROM versions WHERE doc=? ORDER BY version DESC").all(document_id);
281
+ return { history };
282
+ }
283
+ case "link": {
284
+ const a = argumentsOf(s.link, input);
285
+ return this.persist(scope, () => {
286
+ const doc = this.owned(scope, a.document_id, a.version), target = this.document(scope, a.target_id);
287
+ if (doc.format !== "md" || doc.document_id === target.document_id)
288
+ throw new KnowledgeError(400, "Choose two different documents and a Markdown source.");
289
+ if (doc.visibility === "shared" && target.visibility !== "shared")
290
+ throw new KnowledgeError(403, "A shared link needs a shared target.");
291
+ const marker = `[[${target.document_id}|${target.title.replace(/[\[\]|\r\n]/g, " ")}]]`;
292
+ if (doc.body.includes(marker))
293
+ return { document: { ...doc, can_write: true } };
294
+ const body = normalizeBody(doc.body + "\n\n" + marker, "md");
295
+ return this.revise(scope, doc, { body, content_hash: hash(body), ...analyze(body, doc.tags) }, "link");
296
+ });
297
+ }
298
+ case "backlinks": return this.backlinks(scope, argumentsOf(s.backlinks, input).document_id);
299
+ case "graph": {
300
+ const a = argumentsOf(s.graph, input);
301
+ return this.graph(scope, a.document_id, a.limit);
302
+ }
303
+ case "index":
304
+ argumentsOf(s.index, input);
305
+ return this.index(scope, false);
306
+ case "import": {
307
+ const a = argumentsOf(s.import, input);
308
+ return this.importFiles(scope, a.files, !!a.dry_run);
309
+ }
310
+ case "export": {
311
+ const a = argumentsOf(s.export, input);
312
+ const docs = a.document_id ? [this.document(scope, a.document_id)] : this.list(scope, { limit: a.limit ?? 32, offset: a.offset }).documents.map(meta => this.document(scope, meta.document_id));
313
+ const files = [];
314
+ let bytes = 0;
315
+ for (const doc of docs) {
316
+ const content = this.render(scope, doc);
317
+ bytes += Buffer.byteLength(content);
318
+ if (bytes > 2 * 1024 * 1024)
319
+ break;
320
+ files.push({ path: `${doc.visibility}/${doc.document_id}.${doc.format}`, content });
321
+ }
322
+ return { files, next_offset: !a.document_id && files.length && (files.length < docs.length || docs.length === (a.limit ?? 32)) ? (a.offset ?? 0) + files.length : null };
323
+ }
324
+ case "memory_store":
325
+ case "memory_recall":
326
+ case "memory_consolidate":
327
+ try {
328
+ return nativeMemory(scope, action, input);
329
+ }
330
+ catch (error) {
331
+ if (error instanceof ZodError)
332
+ throw new KnowledgeError(400, "Invalid memory tool input.");
333
+ throw error;
334
+ }
335
+ default: throw new KnowledgeError(400, "Unknown knowledge tool.");
336
+ }
337
+ }
338
+ }