limixbot 0.3.139 → 0.3.140

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 (52) hide show
  1. package/dist/assets/{ActivityPanel-COfO9kz3.js → ActivityPanel-D6E89sXu.js} +1 -1
  2. package/dist/assets/{App-XogBV-zY.js → App-CU4DNgMp.js} +9 -9
  3. package/dist/assets/{AppEventEditor-BDUGn9JQ.js → AppEventEditor-Ck4sgNn_.js} +1 -1
  4. package/dist/assets/{BotSettingsDialog-B-QQjKGU.js → BotSettingsDialog-CjQJUCCI.js} +1 -1
  5. package/dist/assets/{BrowserPanel-gpGgHms3.js → BrowserPanel-CBsnU8X8.js} +1 -1
  6. package/dist/assets/{BrowserProfilesManager-y_0rgxx6.js → BrowserProfilesManager-BpXwgH-G.js} +1 -1
  7. package/dist/assets/{CloudAddDialog-ilsQ68Qb.js → CloudAddDialog-CRh5oPqb.js} +1 -1
  8. package/dist/assets/{ComputerFilesPane-oPSU8cF_.js → ComputerFilesPane-CXFT5Cyx.js} +1 -1
  9. package/dist/assets/{ComputerPanel-BPp3YoQQ.js → ComputerPanel-6IZImgTq.js} +2 -2
  10. package/dist/assets/{DataPanel-C_HhHiX2.js → DataPanel-BELccijF.js} +1 -1
  11. package/dist/assets/{GrokMoveDialog-KAfEBP8T.js → GrokMoveDialog-B6ulid29.js} +1 -1
  12. package/dist/assets/{InspectorPanel-CZlQbHob.js → InspectorPanel-TRCCEONY.js} +1 -1
  13. package/dist/assets/{KeyboardShortcutsModal-jVso0auj.js → KeyboardShortcutsModal-DvBBVPMo.js} +1 -1
  14. package/dist/assets/{LimixResizeHandles-kWhVXgUg.js → LimixResizeHandles-CHcC7B6u.js} +1 -1
  15. package/dist/assets/{LiveDesktop-BVNJPX_h.js → LiveDesktop-DZBDQKPB.js} +1 -1
  16. package/dist/assets/{LocalVmWorkspace-B-10kwYn.js → LocalVmWorkspace-BQ8o-Sqf.js} +1 -1
  17. package/dist/assets/{MacLocalControl-BQlB6oNZ.js → MacLocalControl-BMOWUy6p.js} +1 -1
  18. package/dist/assets/{MarkdownFilePreview-CKDCxBAx.js → MarkdownFilePreview-DMGDT496.js} +1 -1
  19. package/dist/assets/{NewBotDialog-DCt1ND3t.js → NewBotDialog-DivTZTqp.js} +1 -1
  20. package/dist/assets/{PhoneAppDialog-DQ9V4p_V.js → PhoneAppDialog-cY2obVld.js} +1 -1
  21. package/dist/assets/{PluginsPanel-Br_6z80C.js → PluginsPanel-D46R0ZKx.js} +1 -1
  22. package/dist/assets/{ProIntroduction-CPyFbdnM.js → ProIntroduction-B62nUDOS.js} +1 -1
  23. package/dist/assets/{RemoteAgentSettingsPanel-CU-TIrOi.js → RemoteAgentSettingsPanel-Dr1nHYOm.js} +1 -1
  24. package/dist/assets/{RoomPanel-DaUBFxP4.js → RoomPanel-i7Z3Iptr.js} +1 -1
  25. package/dist/assets/{RoutinesPage-C91dSD_m.js → RoutinesPage-sUwVY-65.js} +1 -1
  26. package/dist/assets/{SettingsModal-DbfAt-F4.js → SettingsModal-BtZBQ0gZ.js} +1 -1
  27. package/dist/assets/{ShareTeamDialog-BZlRFRFD.js → ShareTeamDialog-Ds6cJP3j.js} +1 -1
  28. package/dist/assets/{SignedInSites-DZTRiBI3.js → SignedInSites-CLmC1zEb.js} +1 -1
  29. package/dist/assets/{TeamLibraryPanel-C7fsWV2G.js → TeamLibraryPanel-6M9JNfWF.js} +1 -1
  30. package/dist/assets/{TeamMapPage-DmhWrV6j.js → TeamMapPage-CzbEqlVs.js} +1 -1
  31. package/dist/assets/{TriggersPage-DFyo9nf6.js → TriggersPage-BWzw6q27.js} +1 -1
  32. package/dist/assets/{VisibilitySection-DNI6SJel.js → VisibilitySection-QUqz3Nz-.js} +1 -1
  33. package/dist/assets/{WebhookTrigger-tAdGlws5.js → WebhookTrigger-DdRB7WoM.js} +1 -1
  34. package/dist/assets/{WorksOnGrid-BT5vH_EO.js → WorksOnGrid-D4bJMovq.js} +1 -1
  35. package/dist/assets/{core-BAGxQvVI.js → core-DiviRa7B.js} +1 -1
  36. package/dist/assets/{import-name-BiqwUM8m.js → import-name-BdbPuVgh.js} +1 -1
  37. package/dist/assets/{index-m7zGNgrr.js → index-B7iWCi3b.js} +2 -2
  38. package/dist/assets/{index-Bxu5GjYs.js → index-UUTfZrHw.js} +1 -1
  39. package/dist/assets/{new-bot-DU60NyAZ.js → new-bot-DCESQUvR.js} +1 -1
  40. package/dist/assets/{org-library-a2la24O2.js → org-library-BS5-sY6M.js} +1 -1
  41. package/dist/assets/{package-format-Dg1ECWML.js → package-format-CE-xmtGw.js} +1 -1
  42. package/dist/assets/{remote-desktop-panel-DxjQVZ3G.js → remote-desktop-panel-BTToRYMw.js} +1 -1
  43. package/dist/index.html +1 -1
  44. package/dist-server/index.js +2547 -2518
  45. package/dist-server/package.json +1 -1
  46. package/dist-server/server/index.js +83 -20
  47. package/dist-server/server/plugin-hub.js +2 -0
  48. package/dist-server/server/routes/bot-messages.js +19 -18
  49. package/dist-server/server/steer-queue.js +22 -10
  50. package/dist-server/server/workspace-read.js +276 -0
  51. package/dist-server/shared/mcp-name.js +1 -0
  52. package/package.json +1 -1
@@ -1 +1 @@
1
- {"type":"module","version":"0.3.139"}
1
+ {"type":"module","version":"0.3.140"}
@@ -207,6 +207,7 @@ import { FACTORY, factoryMount } from "./limix-factory.js";
207
207
  import { industryGuestFacts, isIndustryCareBot, withIndustryCareMcp } from "./industry-care.js";
208
208
  import { attachCustomMcp } from "./mcp-result-budget.js";
209
209
  import { mcpToolProblem } from "./mcp-failure.js";
210
+ import { bindWorkspaceRead, sameWorkspacePath, workspaceReadRootCurrent, workspaceReadRpc, WORKSPACE_READ, WORKSPACE_READ_PATH } from "./workspace-read.js";
210
211
  import { MCP_OAUTH_CALLBACK_PATH, McpOAuthManager } from "./mcp-oauth.js";
211
212
  import { GROUP_GOAL_WAIT_MAX_MS, groupGoalCompletionTurnId, parseGroupGoalDecision, visibleCoordinatorText, runGoalRun, selectGroupGoalCoordinator, } from "./group-goal-run.js";
212
213
  import { createGoalTurns } from "./host/goal-turns.js";
@@ -1706,7 +1707,7 @@ function beginInternalCapabilityGeneration(threadId, generation = randomUUID())
1706
1707
  // Security invariant: a turn's depth, the hand-off it runs for and whether it may author skills are read from that record on every call, never
1707
1708
  // from the engine, so a person's message and a teammate's report keep one bearer.
1708
1709
  const sessionCredentials = new Map();
1709
- function sessionGrants({ generation: _turn, depth: _depth, roomHandoffId: _handoff, skillAuthoring: _skills, ...grants }) {
1710
+ function sessionGrants({ generation: _turn, depth: _depth, roomHandoffId: _handoff, skillAuthoring: _skills, workspaceReadRoot: _workspace, ...grants }) {
1710
1711
  const thread = botForThread(grants.botId, grants.threadId);
1711
1712
  return JSON.stringify({ ...grants, approval: thread ? approvalModeFor(thread) : null });
1712
1713
  }
@@ -1851,12 +1852,26 @@ const MAX_WORKSPACE_BOTS = 100;
1851
1852
  const phoneProxyPath = SPAWNED_PROXIES.phone;
1852
1853
  const researchAvailability = createResearchAvailability({ credential: () => researchCredential(cfg.treg?.key) });
1853
1854
  researchAvailability.available();
1854
- function agentsIntegration(botId, threadId, depth, skillAuthoring, generation, roomHandoffId, hostFiles = false, automated = false) {
1855
+ function agentsIntegration(botId, threadId, depth, skillAuthoring, generation, roomHandoffId, hostFiles = false, automated = false, workspaceRead = false) {
1855
1856
  const bot = store.bot(botId), speaking = botForThread(botId, threadId) ?? bot;
1856
1857
  // Only advertises the tools; the routes behind them refuse regardless.
1857
- const host = { pluginRead: Boolean(bot && pluginHub.hasComponents(bot, Object.keys(engineMcpServers(bot)))), skillAuthoring: skillAuthoringEnabled(cfg), sharedComputers: botLending(), cloudHome: Boolean(CLOUD_HOME), team: Boolean(CLOUD_TEAM),
1858
+ 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),
1858
1859
  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) };
1859
- 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 }), `http://127.0.0.1:${PORT}`) };
1860
+ 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}`) };
1861
+ }
1862
+ function workspaceReadAllowed(bot, threadId, cwd) {
1863
+ return sameWorkspacePath(bot.cwd, cwd) && sameWorkspacePath(store.taskByThread(bot.id, threadId)?.cwd, cwd)
1864
+ && !CLOUD_HOME && !CLOUD_TEAM && !HOSTED_WORKSPACE && !botBox.enabled()
1865
+ && !cloudGuestDriven(threadId) && !botApiThread(threadId) && !proactive.fence.confines(threadId)
1866
+ && managedPolicy.mcpAllowed(WORKSPACE_READ)
1867
+ && canUseMcpServer(bot.toolScope, WORKSPACE_READ) && pluginHub.requiresServer(bot, WORKSPACE_READ);
1868
+ }
1869
+ function liveWorkspaceRead(capability) {
1870
+ const bot = store.bot(capability.botId);
1871
+ const switching = computerSelectionTurns.get(capability.threadId);
1872
+ return Boolean(bot && capability.workspaceReadRoot && internalCapabilityIsActive(capability)
1873
+ && !(switching?.generation === capability.generation && switching.selected)
1874
+ && workspaceReadAllowed(bot, capability.threadId, capability.workspaceReadRoot.path));
1860
1875
  }
1861
1876
  const hooksEnabled = () => process.env.OMB_HOOKS !== "0";
1862
1877
  function hooksIntegration(botId, threadId, generation) {
@@ -8587,8 +8602,21 @@ async function beginTurn(botId, text, opts) {
8587
8602
  }
8588
8603
  // One reachability rule: a bot is never told about a peer that coordinate_bots would refuse.
8589
8604
  const sectionPeers = personalReach.peers(store.bots, bot, threadId);
8605
+ const workspaceBot = store.bot(bot.id);
8606
+ const workspaceReadRoot = cwd && workspaceBot && !guestConfined && (computerKind === null || computerKind === "local")
8607
+ && instance.adapter.capabilities.customMcp === true && workspaceReadAllowed(workspaceBot, threadId, cwd)
8608
+ ? await bindWorkspaceRead(cwd, DATA_DIR) : undefined;
8609
+ if (workspaceReadRoot && directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) {
8610
+ const token = mintInternalCapability({
8611
+ botId: bot.id, threadId, generation: dispatchClaimId, kind: "workspace-read", depth: 0, skillAuthoring: false,
8612
+ workspaceReadRoot, createdBots: 0, openedThreads: 0,
8613
+ }, { perTurn: true });
8614
+ integrations.custom = { ...integrations.custom, [WORKSPACE_READ]: {
8615
+ type: "http", url: `http://127.0.0.1:${PORT}${WORKSPACE_READ_PATH}`, headers: { Authorization: `Bearer ${token}` },
8616
+ } };
8617
+ }
8590
8618
  if (agentsMounted) {
8591
- integrations.agents = agentsIntegration(bot.id, threadId, commsDepth, skillAuthoring, dispatchClaimId, opts?.coordination?.id, worksInWorkspace, opts?.automationSource !== undefined);
8619
+ integrations.agents = agentsIntegration(bot.id, threadId, commsDepth, skillAuthoring, dispatchClaimId, opts?.coordination?.id, worksInWorkspace, opts?.automationSource !== undefined, Boolean(integrations.custom?.[WORKSPACE_READ]));
8592
8620
  }
8593
8621
  if (instance.adapter.capabilities.hooks === true && hooksEnabled()) {
8594
8622
  integrations.hooks = hooksIntegration(bot.id, threadId, dispatchClaimId);
@@ -13466,18 +13494,19 @@ const handleRequest = async (req, res) => {
13466
13494
  ? "hooks"
13467
13495
  : path === "/api/internal/browser/mcp"
13468
13496
  ? "browser"
13469
- : path === DATA_INTERNAL_MCP_PATH
13470
- ? "data"
13471
- : path === EMAIL_INTERNAL_MCP_PATH ? "email"
13472
- : path === PHONE_INTERNAL_MCP_PATH
13473
- ? "device" : isLentMcpPath(path) ? "lent"
13474
- : path === "/api/internal/phone/claim"
13475
- ? "phone"
13476
- : path.startsWith("/api/internal/connectors/")
13477
- ? "connectors"
13478
- : path === "/api/internal/computer-control" || path === "/api/internal/computer/mcp" || path === COMPUTER_JOURNAL_PATH
13479
- ? "computer"
13480
- : "agents";
13497
+ : path === WORKSPACE_READ_PATH ? "workspace-read"
13498
+ : path === DATA_INTERNAL_MCP_PATH
13499
+ ? "data"
13500
+ : path === EMAIL_INTERNAL_MCP_PATH ? "email"
13501
+ : path === PHONE_INTERNAL_MCP_PATH
13502
+ ? "device" : isLentMcpPath(path) ? "lent"
13503
+ : path === "/api/internal/phone/claim"
13504
+ ? "phone"
13505
+ : path.startsWith("/api/internal/connectors/")
13506
+ ? "connectors"
13507
+ : path === "/api/internal/computer-control" || path === "/api/internal/computer/mcp" || path === COMPUTER_JOURNAL_PATH
13508
+ ? "computer"
13509
+ : "agents";
13481
13510
  if (internalCapability.kind !== requiredCapabilityKind) {
13482
13511
  return json(res, 403, { error: "this internal capability cannot access that service" });
13483
13512
  }
@@ -13494,8 +13523,8 @@ const handleRequest = async (req, res) => {
13494
13523
  if (claimedThread !== null && claimedThread !== internalCapability.threadId) {
13495
13524
  return json(res, 403, { error: "the internal capability belongs to a different conversation" });
13496
13525
  }
13497
- const readInternalBody = async () => {
13498
- const body = await readBody(req);
13526
+ const readInternalBody = async (maxBytes) => {
13527
+ const body = await readBody(req, maxBytes);
13499
13528
  // Authorization at header time is not a lease: if the owning turn settled meanwhile, die before any side effect.
13500
13529
  if (!internalCapabilityIsActive(internalCapability)) {
13501
13530
  throw Object.assign(new Error(TURN_ENDED_REFUSAL), { status: 401 });
@@ -13514,6 +13543,31 @@ const handleRequest = async (req, res) => {
13514
13543
  }
13515
13544
  return body;
13516
13545
  };
13546
+ if (path === WORKSPACE_READ_PATH) {
13547
+ const root = internalCapability.workspaceReadRoot;
13548
+ if (!root || !liveWorkspaceRead(internalCapability) || !await workspaceReadRootCurrent(root) || !liveWorkspaceRead(internalCapability)) {
13549
+ return json(res, 403, { error: "Workspace access is unavailable for this turn." });
13550
+ }
13551
+ if (method !== "POST") {
13552
+ res.writeHead(405, { allow: "POST" });
13553
+ res.end();
13554
+ return;
13555
+ }
13556
+ const frame = await readInternalBody(16 * 1024);
13557
+ if (!liveWorkspaceRead(internalCapability))
13558
+ return json(res, 403, { error: "Workspace access is unavailable for this turn." });
13559
+ const allowed = (name, args) => liveWorkspaceRead(internalCapability)
13560
+ && allowsTool(store.bot(internalSender.id)?.toolScope, { kind: "mcp", server: WORKSPACE_READ, name }, args);
13561
+ const result = await workspaceReadRpc(root, frame, allowed);
13562
+ if (!liveWorkspaceRead(internalCapability))
13563
+ return json(res, 403, { error: "Workspace access is unavailable for this turn." });
13564
+ if (result === undefined) {
13565
+ res.writeHead(202);
13566
+ res.end();
13567
+ return;
13568
+ }
13569
+ return json(res, 200, result);
13570
+ }
13517
13571
  const requireActiveInternalCapability = () => {
13518
13572
  if (!internalCapabilityIsActive(internalCapability)) {
13519
13573
  throw Object.assign(new Error(TURN_ENDED_REFUSAL), { status: 401 });
@@ -14247,7 +14301,16 @@ const handleRequest = async (req, res) => {
14247
14301
  internalCapability.pluginReads = (internalCapability.pluginReads ?? 0) + 1;
14248
14302
  if (!allowsTool(internalSender.toolScope, { kind: "mcp", server: "agents", name: "plugin_read" }, input))
14249
14303
  return json(res, 403, { error: "Plugin reads disabled for this bot" });
14250
- const allowed = () => Object.keys(engineMcpServers(internalSender)).filter(name => canUseMcpServer(internalSender.toolScope, name));
14304
+ const allowed = () => {
14305
+ const bot = store.bot(internalSender.id);
14306
+ if (!bot)
14307
+ return [];
14308
+ const names = Object.keys(engineMcpServers(bot)).filter(name => canUseMcpServer(bot.toolScope, name));
14309
+ const cwd = store.taskByThread(bot.id, internalCapability.threadId)?.cwd;
14310
+ if (internalCapability.workspaceReadMounted && cwd && workspaceReadAllowed(bot, internalCapability.threadId, cwd))
14311
+ names.push(WORKSPACE_READ);
14312
+ return names;
14313
+ };
14251
14314
  const result = await readPluginComponent(pluginHub, resolvePluginServer, internalSender, allowed, input, DATA_DIR, mcpServersHost.probeAs({ bot: internalSender.id }), origin => {
14252
14315
  if (internalCapability.pluginOrigin && internalCapability.pluginOrigin !== origin)
14253
14316
  return false;
@@ -361,6 +361,8 @@ export function createPluginHub(dir, targets, load = download) {
361
361
  if (!state.installed.some(p => p.teams.includes(from)))
362
362
  return;
363
363
  save({ ...state, installed: state.installed.map(p => ({ ...p, teams: p.teams.flatMap(team => team !== from ? [team] : to ? [to] : []) })) });
364
+ }, requiresServer(bot, server) {
365
+ return active(bot, [server]).some(row => row.requiresMcp.includes(server) && !row.manifest?.source);
364
366
  }, instructions(bot, availableMcp) {
365
367
  const rows = active(bot, availableMcp);
366
368
  const legacy = rows.filter(p => !p.manifest).map(p => "\n\nPlugin " + p.id + " (" + p.version + ")\n" + p.instructions).join("");
@@ -322,25 +322,24 @@ export function createBotMessageRoutes(deps) {
322
322
  // The steer awaited adapter work: re-read every ownership invariant before writing anything.
323
323
  const current = store.projectBotForTask(bot.id, bot.threadId);
324
324
  // "indeterminate" never restores: the words may already be in the live turn, and a replay would run them twice.
325
- if ((steered === "steered" && current?.busy ||
326
- steered === "indeterminate" && current) &&
327
- store.taskByThread(bot.id, bot.threadId)) {
325
+ if (steered !== "refused" && current && store.taskByThread(bot.id, bot.threadId)) {
328
326
  if (auth.kind === "session" || DESKTOP_MANAGED)
329
327
  clearUnattended(bot.threadId);
330
- const messages = held.items.map((item) => store.appendMessage(bot.threadId, {
331
- role: "user",
332
- kind: "text",
333
- text: item.text,
334
- replyToId: item.replyToId,
335
- sendId: item.sendId,
336
- ...(item.dataContext ? { dataContext: item.dataContext } : {}),
337
- queueId: item.messageId,
338
- peerAsk: item.peerAsk,
339
- steered: true,
340
- sender: item.sender,
341
- ...spokenLineFields(item.via, item.callId),
342
- ...(item.fromApp ? { fromApp: item.fromApp } : {}),
343
- }));
328
+ const messages = held.items.map((item) => (item.rowId ? store.messagesFor(bot.threadId).find(message => message.id === item.rowId) : undefined)
329
+ ?? store.appendMessage(bot.threadId, {
330
+ role: "user",
331
+ kind: "text",
332
+ text: item.text,
333
+ replyToId: item.replyToId,
334
+ sendId: item.sendId,
335
+ ...(item.dataContext ? { dataContext: item.dataContext } : {}),
336
+ queueId: item.messageId,
337
+ peerAsk: item.peerAsk,
338
+ steered: true,
339
+ sender: item.sender,
340
+ ...spokenLineFields(item.via, item.callId),
341
+ ...(item.fromApp ? { fromApp: item.fromApp } : {}),
342
+ }));
344
343
  const asked = messages.filter((_, index) => !held.items[index]?.unattended && !held.items[index]?.peerAsk).at(-1);
345
344
  if (asked)
346
345
  store.setTaskAskedAt(bot.id, bot.threadId, asked.at);
@@ -348,9 +347,11 @@ export function createBotMessageRoutes(deps) {
348
347
  handoffs.steered(bot.threadId, steerTarget, instance?.instanceId, message.id);
349
348
  const queueIds = held.items.map((item) => item.messageId);
350
349
  settleHeldSteeredQueue(held);
350
+ if (!current.busy)
351
+ drainQueuedSends();
351
352
  return json(res, 200, { ok: true, steered: true, threadId: bot.threadId, messages, queueIds });
352
353
  }
353
- if (steered === "indeterminate") {
354
+ if (steered !== "refused") {
354
355
  // No destination left: settle, so a restart cannot replay words a dead turn may have run.
355
356
  settleHeldSteeredQueue(held);
356
357
  if (!store.taskByThread(bot.id, bot.threadId)) {
@@ -5,8 +5,10 @@ import { drainCoalesceHead } from "./admission.js";
5
5
  import { spokenLineFields } from "./live-call-record.js";
6
6
  import { workOriginSchema } from "./peer-provenance.js";
7
7
  const queues = new Map();
8
+ const heldQueues = new Map();
8
9
  export function restoreSteeredMessages() {
9
10
  queues.clear();
11
+ heldQueues.clear();
10
12
  for (const row of chatFollowups("bot")) {
11
13
  if (row.status !== "pending")
12
14
  continue;
@@ -40,7 +42,11 @@ const changed = () => {
40
42
  /** Public pending chips only: never expose provider prompts or reply context. `shownSender`: where several people write,
41
43
  * whose each chip is. */
42
44
  export function queuedSteerSnapshot(ownsThread, whyHeld = () => undefined, shownSender = () => undefined) {
43
- return Object.fromEntries([...queues]
45
+ const visible = new Map(queues);
46
+ for (const [threadId, held] of heldQueues) {
47
+ visible.set(threadId, { botId: held.botId, items: [...held.items, ...(queues.get(threadId)?.items ?? [])] });
48
+ }
49
+ return Object.fromEntries([...visible]
44
50
  .filter(([threadId, entry]) => ownsThread(entry.botId, threadId))
45
51
  .map(([threadId, entry]) => [threadId, entry.items.filter((item) => !item.rowId).map((item) => ({
46
52
  queueId: item.messageId, text: item.text, ...(item.reason ? { reason: item.reason, why: whyHeld(threadId, item.reason) } : {}),
@@ -127,7 +133,7 @@ export function drainSteeredMessages(store, run, isBlocked) {
127
133
  changed();
128
134
  continue;
129
135
  }
130
- if (bot.busy || isBlocked?.(entry.botId, threadId, entry.items[0]))
136
+ if (bot.busy || heldQueues.has(threadId) || isBlocked?.(entry.botId, threadId, entry.items[0]))
131
137
  continue;
132
138
  // isBlocked can re-enter this drain; if a nested drain took this entry, it is stale.
133
139
  if (queues.get(threadId) !== entry)
@@ -140,7 +146,6 @@ export function drainSteeredMessages(store, run, isBlocked) {
140
146
  queues.set(threadId, { botId: entry.botId, items: rest });
141
147
  else
142
148
  queues.delete(threadId);
143
- changed();
144
149
  const appended = [];
145
150
  for (const item of group) {
146
151
  const recorded = item.rowId ? store.messagesFor?.(threadId).find((message) => message.id === item.rowId) : undefined;
@@ -160,6 +165,7 @@ export function drainSteeredMessages(store, run, isBlocked) {
160
165
  ...(item.reaction ? { reaction: item.reaction } : {}),
161
166
  }));
162
167
  }
168
+ changed();
163
169
  const last = appended.at(-1);
164
170
  if (!last)
165
171
  continue;
@@ -191,10 +197,8 @@ function coalesceIdentity(item) {
191
197
  return item.via === "call" ? `call:${item.callId ?? ""}|${person}` : person;
192
198
  }
193
199
  export function queuedSteeredMessage(botId, threadId, sendId) {
194
- const entry = queues.get(threadId);
195
- if (!entry || entry.botId !== botId)
196
- return null;
197
- const item = entry.items.find((candidate) => candidate.sendId === sendId);
200
+ const matchingSend = (entry) => entry?.botId === botId ? entry.items.find((candidate) => candidate.sendId === sendId) : undefined;
201
+ const item = matchingSend(heldQueues.get(threadId)) ?? matchingSend(queues.get(threadId));
198
202
  return item ? { id: item.messageId, text: item.text, replyToId: item.replyToId, ...(item.reason ? { reason: item.reason } : {}) } : null;
199
203
  }
200
204
  /** Whose waiting line this is, or null when nothing waits under that id. */
@@ -224,13 +228,16 @@ export function cancelSteeredMessage(botId, messageId, expectedThreadId) {
224
228
  /** The entry leaves first, so a racing settle cannot also dispatch these words; the caller must restore or settle it. */
225
229
  export function holdSteeredQueue(botId, threadId, queueId) {
226
230
  const entry = queues.get(threadId);
227
- if (!entry || entry.botId !== botId || !entry.items.some((item) => item.messageId === queueId))
231
+ if (heldQueues.has(threadId) || !entry || entry.botId !== botId || !entry.items.some((item) => item.messageId === queueId))
228
232
  return null;
233
+ const held = { botId, threadId, items: entry.items };
234
+ heldQueues.set(threadId, held);
229
235
  queues.delete(threadId);
230
- changed();
231
- return { botId, threadId, items: entry.items };
236
+ return held;
232
237
  }
233
238
  export function restoreHeldSteeredQueue(held) {
239
+ if (heldQueues.get(held.threadId) !== held)
240
+ return;
234
241
  const existing = queues.get(held.threadId);
235
242
  if (existing && existing.botId !== held.botId)
236
243
  throw new Error("queued task belongs to another bot");
@@ -238,10 +245,15 @@ export function restoreHeldSteeredQueue(held) {
238
245
  botId: held.botId,
239
246
  items: existing ? [...held.items, ...existing.items] : held.items,
240
247
  });
248
+ heldQueues.delete(held.threadId);
241
249
  changed();
242
250
  }
243
251
  export function settleHeldSteeredQueue(held) {
252
+ if (heldQueues.get(held.threadId) !== held)
253
+ return;
244
254
  settleChatFollowups(held.items.map((item) => item.messageId), null);
255
+ heldQueues.delete(held.threadId);
256
+ changed();
245
257
  }
246
258
  export function _queuedCount(threadId) {
247
259
  return queues.get(threadId)?.items.length ?? 0;
@@ -0,0 +1,276 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, open, opendir, realpath } from "node:fs/promises";
3
+ import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ export const WORKSPACE_READ = "limix-workspace-read";
5
+ export const WORKSPACE_READ_PATH = "/api/internal/workspace-read/mcp";
6
+ const MAX_FILE_BYTES = 128 * 1024;
7
+ const MAX_SCAN_BYTES = 1024 * 1024;
8
+ const MAX_ENTRIES = 512;
9
+ const MAX_FILES = 128;
10
+ const MAX_ITEMS = 8;
11
+ const MAX_LINE_BYTES = 216;
12
+ const MAX_ITEM_BYTES = 850;
13
+ const files = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".md", ".txt", ".py", ".rs", ".go", ".java", ".cs", ".css", ".html", ".vue", ".svelte", ".sql"]);
14
+ const ignored = new Set(["node_modules", "vendor", "dist", "build", "coverage", "target"]);
15
+ const decoder = new TextDecoder("utf-8", { fatal: true });
16
+ const readFlags = process.platform === "win32" ? constants.O_RDONLY : constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
17
+ const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
18
+ const within = (root, path) => {
19
+ const suffix = relative(root, path);
20
+ return suffix !== ".." && !suffix.startsWith(".." + sep) && !isAbsolute(suffix);
21
+ };
22
+ export function sameWorkspacePath(left, right) {
23
+ return Boolean(left && right && isAbsolute(left) && isAbsolute(right) && relative(resolve(left), resolve(right)) === "");
24
+ }
25
+ export async function bindWorkspaceRead(path, dataDir) {
26
+ try {
27
+ const canonical = await realpath(path);
28
+ const data = await realpath(dataDir);
29
+ if (within(data, canonical) || within(canonical, data) || canonical.startsWith("\\\\"))
30
+ return;
31
+ const stat = await lstat(path, { bigint: true });
32
+ if (stat.isDirectory() && !stat.isSymbolicLink() && stat.ino !== 0n)
33
+ return { path, canonical, dev: stat.dev, ino: stat.ino };
34
+ }
35
+ catch { }
36
+ }
37
+ export async function workspaceReadRootCurrent(root) {
38
+ try {
39
+ const stat = await lstat(root.path, { bigint: true });
40
+ return stat.isDirectory() && stat.dev === root.dev && stat.ino === root.ino && sameWorkspacePath(root.canonical, await realpath(root.path));
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
46
+ const pathSchema = { type: "string", description: "Workspace-relative file path with forward slashes.", minLength: 1, maxLength: 160 };
47
+ const lineSchema = { type: "integer", minimum: 1, maximum: MAX_FILE_BYTES };
48
+ const objectSchema = (properties, required) => ({ type: "object", properties, required, additionalProperties: false });
49
+ const batchSchema = (key, items) => objectSchema({ [key]: { type: "array", items, minItems: 1, maxItems: MAX_ITEMS } }, [key]);
50
+ const tools = [
51
+ { name: "batch_search", description: "Find independent case-sensitive literal strings in supported workspace text files. An optional exact path skips the bounded directory scan.", inputSchema: batchSchema("queries", objectSchema({ text: { type: "string", minLength: 1, maxLength: 128 }, path: pathSchema }, ["text"])) },
52
+ { name: "quick_outline", description: "Find simple named declarations in JavaScript and TypeScript files. Verify exact code with read_slices.", inputSchema: batchSchema("paths", pathSchema) },
53
+ { name: "read_slices", description: "Read inclusive 1-based line ranges from supported workspace text files.", inputSchema: batchSchema("ranges", objectSchema({ path: pathSchema, start: lineSchema, end: lineSchema }, ["path", "start", "end"])) },
54
+ ].map(tool => ({ ...tool, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } }));
55
+ function allowedName(name) {
56
+ return name.length > 0 && !name.startsWith(".") && !ignored.has(name.toLowerCase()) && !/[\\:\x00-\x1f\x7f]/u.test(name)
57
+ && !/[. ]$/u.test(name) && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(name);
58
+ }
59
+ function supportedPath(path) {
60
+ return typeof path === "string" && Buffer.byteLength(path) <= 160
61
+ && path.split("/").every(allowedName) && files.has(extname(path).toLowerCase());
62
+ }
63
+ async function readWorkspaceFile(root, path) {
64
+ if (!supportedPath(path))
65
+ throw new Error("Expected a supported relative workspace file.");
66
+ const target = join(root.canonical, path);
67
+ try {
68
+ if (!sameWorkspacePath(target, await realpath(target)))
69
+ throw new Error();
70
+ const before = await lstat(target, { bigint: true });
71
+ if (!before.isFile() || before.nlink !== 1n || before.ino === 0n || before.size > BigInt(MAX_FILE_BYTES)
72
+ || !sameWorkspacePath(target, await realpath(target)))
73
+ throw new Error();
74
+ const file = await open(target, readFlags);
75
+ try {
76
+ // Validate the opened file before reading so replacing the path cannot redirect the read.
77
+ const opened = await file.stat({ bigint: true });
78
+ if (!opened.isFile() || opened.nlink !== 1n || opened.dev !== before.dev || opened.ino !== before.ino
79
+ || opened.size > BigInt(MAX_FILE_BYTES) || !await workspaceReadRootCurrent(root)
80
+ || !sameWorkspacePath(target, await realpath(target)))
81
+ throw new Error();
82
+ const buffer = Buffer.alloc(Number(opened.size) + 1);
83
+ let length = 0;
84
+ while (length < buffer.length) {
85
+ const { bytesRead } = await file.read(buffer, length, buffer.length - length, length);
86
+ if (!bytesRead)
87
+ break;
88
+ length += bytesRead;
89
+ }
90
+ const after = await lstat(target, { bigint: true });
91
+ if (length !== Number(opened.size) || after.dev !== opened.dev || after.ino !== opened.ino
92
+ || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs
93
+ || !sameWorkspacePath(target, await realpath(target)))
94
+ throw new Error();
95
+ const text = decoder.decode(buffer.subarray(0, length));
96
+ if (text.includes("\0"))
97
+ throw new Error();
98
+ return { path, length, lines: text ? text.replace(/(?:\r\n|\n|\r)$/u, "").split(/\r\n|\n|\r/u) : [] };
99
+ }
100
+ finally {
101
+ await file.close();
102
+ }
103
+ }
104
+ catch {
105
+ throw new Error("File unavailable as bounded UTF-8 workspace text.");
106
+ }
107
+ }
108
+ async function scanWorkspace(root) {
109
+ const paths = [];
110
+ const pending = [""];
111
+ let entries = 0;
112
+ let truncated = false;
113
+ while (pending.length && !truncated) {
114
+ const directory = pending.shift();
115
+ const target = join(root.canonical, directory);
116
+ try {
117
+ if (!sameWorkspacePath(target, await realpath(target))) {
118
+ truncated = true;
119
+ break;
120
+ }
121
+ for await (const entry of await opendir(target)) {
122
+ if (++entries > MAX_ENTRIES) {
123
+ truncated = true;
124
+ break;
125
+ }
126
+ if (!allowedName(entry.name))
127
+ continue;
128
+ const path = directory ? directory + "/" + entry.name : entry.name;
129
+ if (entry.isDirectory() && path.split("/").length < 8)
130
+ pending.push(path);
131
+ else if (entry.isDirectory())
132
+ truncated = true;
133
+ else if (entry.isFile() && supportedPath(path))
134
+ paths.push(path);
135
+ }
136
+ }
137
+ catch {
138
+ truncated = true;
139
+ }
140
+ }
141
+ const contents = [];
142
+ let bytes = 0;
143
+ for (const path of paths.sort().slice(0, MAX_FILES)) {
144
+ const file = await readWorkspaceFile(root, path).catch(() => null);
145
+ if (!file) {
146
+ truncated = true;
147
+ continue;
148
+ }
149
+ bytes += file.length;
150
+ if (bytes > MAX_SCAN_BYTES) {
151
+ truncated = true;
152
+ break;
153
+ }
154
+ contents.push(file);
155
+ }
156
+ return { contents, truncated: truncated || paths.length > MAX_FILES };
157
+ }
158
+ function prefix(text, bytes) {
159
+ let length = 0;
160
+ let chars = 0;
161
+ for (const point of text) {
162
+ length += Buffer.byteLength(point);
163
+ if (length > bytes)
164
+ break;
165
+ chars += point.length;
166
+ }
167
+ return text.slice(0, chars);
168
+ }
169
+ function boundedRows(index, candidates, truncated = false) {
170
+ const rows = [];
171
+ let bytes = 0;
172
+ for (const candidate of candidates) {
173
+ const text = prefix(candidate.text, MAX_LINE_BYTES);
174
+ const row = { ...candidate, text, ...(text !== candidate.text ? { clipped: true } : {}) };
175
+ bytes += Buffer.byteLength(JSON.stringify(row)) + 1;
176
+ if (rows.length === 12 || bytes > MAX_ITEM_BYTES) {
177
+ truncated = true;
178
+ break;
179
+ }
180
+ truncated ||= row.clipped === true;
181
+ rows.push(row);
182
+ }
183
+ return { index, rows, truncated };
184
+ }
185
+ const declaration = /^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:function(?:\s*\*\s*|\s+)|(?:class|interface|type|enum|namespace|const|let|var)\s+)[A-Za-z_$][\w$]*/u;
186
+ function* matchingLines(contents, match, start = 1, end = MAX_FILE_BYTES) {
187
+ for (const { path, lines } of contents) {
188
+ for (let line = start; line <= Math.min(end, lines.length); line++) {
189
+ const text = lines[line - 1];
190
+ if (match(text))
191
+ yield { path, line, text };
192
+ }
193
+ }
194
+ }
195
+ function* searchLines(contents, query) {
196
+ for (const row of matchingLines(contents, line => line.includes(query))) {
197
+ if (prefix(row.text, MAX_LINE_BYTES).includes(query))
198
+ yield row;
199
+ else
200
+ yield { ...row, text: row.text.slice(row.text.indexOf(query)), clipped: true };
201
+ }
202
+ }
203
+ function textResult(text, isError = false) {
204
+ return { content: [{ type: "text", text }], ...(isError ? { isError } : {}) };
205
+ }
206
+ async function callWorkspace(root, name, args) {
207
+ const key = name === "batch_search" ? "queries" : name === "quick_outline" ? "paths" : "ranges";
208
+ const items = args[key];
209
+ if (Object.keys(args).length !== 1 || !Array.isArray(items) || items.length < 1 || items.length > MAX_ITEMS) {
210
+ return textResult("Expected one batch of 1–8 items.", true);
211
+ }
212
+ let scan;
213
+ const results = [];
214
+ for (const [index, item] of items.entries()) {
215
+ try {
216
+ if (name === "batch_search") {
217
+ if (!record(item) || Object.keys(item).some(key => key !== "text" && key !== "path") || typeof item.text !== "string"
218
+ || !item.text || Buffer.byteLength(item.text) > 128 || /[\r\n]/u.test(item.text))
219
+ throw new Error("Expected a nonempty single-line search literal.");
220
+ const query = item.text;
221
+ const selected = Object.hasOwn(item, "path") ? { contents: [await readWorkspaceFile(root, item.path)], truncated: false } : (scan ??= await scanWorkspace(root));
222
+ results.push(boundedRows(index, searchLines(selected.contents, query), selected.truncated));
223
+ }
224
+ else if (name === "quick_outline") {
225
+ if (typeof item !== "string" || !/\.(?:[mc]?[jt]s|[jt]sx)$/iu.test(item))
226
+ throw new Error("Expected a JavaScript or TypeScript path.");
227
+ results.push(boundedRows(index, matchingLines([await readWorkspaceFile(root, item)], line => declaration.test(line))));
228
+ }
229
+ else {
230
+ if (!record(item) || Object.keys(item).length !== 3 || typeof item.start !== "number" || typeof item.end !== "number"
231
+ || !Number.isInteger(item.start) || !Number.isInteger(item.end) || item.start < 1 || item.end < item.start
232
+ || item.end > MAX_FILE_BYTES)
233
+ throw new Error("Expected a valid inclusive line range.");
234
+ const file = await readWorkspaceFile(root, item.path);
235
+ if (item.start > file.lines.length)
236
+ throw new Error("Start line is beyond the end of the file.");
237
+ results.push(boundedRows(index, matchingLines([file], () => true, item.start, item.end)));
238
+ }
239
+ }
240
+ catch (error) {
241
+ results.push({ index, rows: [], truncated: false, error: error.message });
242
+ }
243
+ }
244
+ return textResult(JSON.stringify({ results }));
245
+ }
246
+ export async function workspaceReadRpc(root, request, allowed) {
247
+ const valid = record(request) && request.jsonrpc === "2.0" && typeof request.method === "string";
248
+ const id = valid && (typeof request.id === "string" || typeof request.id === "number") ? request.id : null;
249
+ const reply = (result) => ({ jsonrpc: "2.0", id, result });
250
+ const error = (code, message) => ({ jsonrpc: "2.0", id, error: { code, message } });
251
+ if (!valid)
252
+ return error(-32600, "Invalid MCP request.");
253
+ if (!Object.hasOwn(request, "id"))
254
+ return;
255
+ if (request.method === "initialize") {
256
+ const asked = record(request.params) ? request.params.protocolVersion : undefined;
257
+ const protocolVersion = typeof asked === "string" && ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"].includes(asked) ? asked : "2025-11-25";
258
+ return reply({ protocolVersion, capabilities: { tools: {} }, serverInfo: { name: WORKSPACE_READ, version: "1.0.0" } });
259
+ }
260
+ if (request.method === "ping")
261
+ return reply({});
262
+ if (request.method === "tools/list")
263
+ return reply({ tools: tools.filter(tool => allowed(tool.name, {})) });
264
+ if (request.method !== "tools/call")
265
+ return error(-32601, "Method not found.");
266
+ const params = request.params;
267
+ if (!record(params) || typeof params.name !== "string" || !record(params.arguments)
268
+ || !tools.some(tool => tool.name === params.name))
269
+ return error(-32602, "Invalid workspace tool call.");
270
+ const { name, arguments: args } = params;
271
+ if (!allowed(name, args))
272
+ return error(-32602, "Workspace tool is outside the current access scope.");
273
+ const result = await callWorkspace(root, name, args);
274
+ return allowed(name, args) && await workspaceReadRootCurrent(root) && allowed(name, args)
275
+ ? reply(result) : error(-32602, "Workspace access changed during the call.");
276
+ }
@@ -9,6 +9,7 @@ export const RESERVED_MCP_NAMES = new Set([
9
9
  "email",
10
10
  "device",
11
11
  "phone",
12
+ "limix-workspace-read",
12
13
  "dweb",
13
14
  "openmausbot_connectors",
14
15
  "openmausbot_phone",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limixbot",
3
- "version": "0.3.139",
3
+ "version": "0.3.140",
4
4
  "description": "Run the Limix Bot server anywhere and pair your devices to it (Leox ৹ Limix AI)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",