@chibitek/chibi 0.1.185 → 0.1.188

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 (98) hide show
  1. package/dist/assets/{abnfDiagram-O67JEVCF-CVenv9f1.js → abnfDiagram-O67JEVCF-CKDXgnYw.js} +1 -1
  2. package/dist/assets/{arc-CIRWjkSZ.js → arc--VPK-xet.js} +1 -1
  3. package/dist/assets/{architectureDiagram-NJMV4G6O-DmIpOaYd.js → architectureDiagram-NJMV4G6O-DSVjpq7n.js} +1 -1
  4. package/dist/assets/{blockDiagram-BEXU5L5S-BYhb8Ycm.js → blockDiagram-BEXU5L5S-BiQ1JgSl.js} +1 -1
  5. package/dist/assets/{c4Diagram-YGBWAQC7-B9rBcCno.js → c4Diagram-YGBWAQC7-kWWEc-NZ.js} +1 -1
  6. package/dist/assets/channel-CQdxuHwI.js +1 -0
  7. package/dist/assets/{chunk-2Q5K7J3B-CV6TX9gt.js → chunk-2Q5K7J3B-QJYqMtWJ.js} +1 -1
  8. package/dist/assets/{chunk-3FUC2YCW-DiOotfQU.js → chunk-3FUC2YCW-C7oGYTZS.js} +2 -2
  9. package/dist/assets/{chunk-5VM5RSS4-Br5QWC-1.js → chunk-5VM5RSS4-MahQWTzh.js} +1 -1
  10. package/dist/assets/{chunk-GTNCS2PH-BmvI8RMK.js → chunk-GTNCS2PH-CQfOvr7l.js} +1 -1
  11. package/dist/assets/{chunk-GWA4HPMP-Do93bTCh.js → chunk-GWA4HPMP-b0lt02Pi.js} +1 -1
  12. package/dist/assets/{chunk-JWPE2WC7-qIjG-mTw.js → chunk-JWPE2WC7-J1_ylbx8.js} +1 -1
  13. package/dist/assets/{chunk-NETBCI7D-DZFFFHT2.js → chunk-NETBCI7D-AWcL9tld.js} +1 -1
  14. package/dist/assets/{chunk-WEXAMYUT-qqsVaC1g.js → chunk-WEXAMYUT-DpTrAXJV.js} +1 -1
  15. package/dist/assets/{chunk-XXDRQBXY-EI-aQ-Wn.js → chunk-XXDRQBXY-2_DCjtc9.js} +1 -1
  16. package/dist/assets/{classDiagram-v2-NBCMYWYE-D9D8dkAx.js → classDiagram-v2-NBCMYWYE-BBQMtHHs.js} +1 -1
  17. package/dist/assets/{cose-bilkent-JH36ORCC-m575JDuA.js → cose-bilkent-JH36ORCC-CmxRmDe8.js} +1 -1
  18. package/dist/assets/{cynefin-OW5HDTMX-BMm2bhgv.js → cynefin-OW5HDTMX-DjlothXK.js} +1 -1
  19. package/dist/assets/{cynefinDiagram-VND7K2PF-Dl2MlsqG.js → cynefinDiagram-VND7K2PF-D6HfzP26.js} +1 -1
  20. package/dist/assets/{dagre-6A5THRUB-Cw8yJ-SY.js → dagre-6A5THRUB-BtzaxY50.js} +1 -1
  21. package/dist/assets/{diagram-22UHCM2B-DyY0F1qK.js → diagram-22UHCM2B-DsyCiGJD.js} +1 -1
  22. package/dist/assets/{diagram-3UASUU5V-sMOszbgV.js → diagram-3UASUU5V-CjjvxIr3.js} +1 -1
  23. package/dist/assets/{diagram-ATOU4E4O-DPo3fHpo.js → diagram-ATOU4E4O-DDu2iVRb.js} +1 -1
  24. package/dist/assets/{diagram-CDSNMT55-BAHqm-cq.js → diagram-CDSNMT55-BBTViw3h.js} +1 -1
  25. package/dist/assets/{diagram-MLGK6HIB-BdI4Tf9M.js → diagram-MLGK6HIB-D83j4C6w.js} +1 -1
  26. package/dist/assets/{diagram-MPIPVDR6-BxqEl_S5.js → diagram-MPIPVDR6-DTpmpL8Q.js} +1 -1
  27. package/dist/assets/{ebnfDiagram-ZINNZB2B-DLJ3VRtx.js → ebnfDiagram-ZINNZB2B-D3B4hz_Y.js} +1 -1
  28. package/dist/assets/{elk-276RUBZZ-Yhxabhx6.js → elk-276RUBZZ-CbNicGf_.js} +1 -1
  29. package/dist/assets/{erDiagram-OPXOYQCR-DZ4Es64N.js → erDiagram-OPXOYQCR-DeSwxwFC.js} +1 -1
  30. package/dist/assets/{flowDiagram-KWPJA3E3-E36WtrEY.js → flowDiagram-KWPJA3E3-3n_Hk-ZR.js} +1 -1
  31. package/dist/assets/{ganttDiagram-FUAMR5RP-OpUEVvtU.js → ganttDiagram-FUAMR5RP-BsadEPTf.js} +1 -1
  32. package/dist/assets/{gitGraphDiagram-X574FWY7-DTZFNsL8.js → gitGraphDiagram-X574FWY7-DOvqN3Jh.js} +1 -1
  33. package/dist/assets/{index-Bgf1dXAl.js → index-B9LCl5y3.js} +133 -133
  34. package/dist/assets/{index-Bzph058J.js → index-BmYLMFD8.js} +1 -1
  35. package/dist/assets/{infoDiagram-VRGFBTTK-mCP2UtfM.js → infoDiagram-VRGFBTTK-CI3tfMt9.js} +1 -1
  36. package/dist/assets/{ishikawaDiagram-OU5B5YK6-M71dvinX.js → ishikawaDiagram-OU5B5YK6-BE7AjZYf.js} +1 -1
  37. package/dist/assets/{journeyDiagram-ZHPQQLJL-B2VdVbYS.js → journeyDiagram-ZHPQQLJL-DplNZPox.js} +1 -1
  38. package/dist/assets/{kanban-definition-PNTS6WVX-l4HpN_KC.js → kanban-definition-PNTS6WVX-Cos64we-.js} +1 -1
  39. package/dist/assets/{linear-CN0tWTVj.js → linear-DDfQb-jo.js} +1 -1
  40. package/dist/assets/{mermaid.core-DpBToEGQ.js → mermaid.core-BekbnuLb.js} +5 -5
  41. package/dist/assets/{mindmap-definition-NLK3R4M7--DJgZ72R.js → mindmap-definition-NLK3R4M7-DJ0MbzMW.js} +1 -1
  42. package/dist/assets/{pegDiagram-GJSIUBJH-DmTBsA2I.js → pegDiagram-GJSIUBJH-DZNZCZ4O.js} +1 -1
  43. package/dist/assets/{pieDiagram-5QR66LMP-Cy6JwGMR.js → pieDiagram-5QR66LMP-COD5v2yC.js} +1 -1
  44. package/dist/assets/{quadrantDiagram-O4NWA36T-DjTftbBA.js → quadrantDiagram-O4NWA36T-D4dlLWfv.js} +1 -1
  45. package/dist/assets/{railroadDiagram-XR7U4H2S-DeKIQoik.js → railroadDiagram-XR7U4H2S-CEpVYFKl.js} +1 -1
  46. package/dist/assets/{requirementDiagram-PLB6GJNP-B02KsDuy.js → requirementDiagram-PLB6GJNP-DYD5GX0G.js} +1 -1
  47. package/dist/assets/{sankeyDiagram-IPEJSGJF-4RLO5vMI.js → sankeyDiagram-IPEJSGJF-C9bPeTfK.js} +1 -1
  48. package/dist/assets/{sequenceDiagram-PO4LG4MO-CcBW737M.js → sequenceDiagram-PO4LG4MO-eXpmPg9C.js} +1 -1
  49. package/dist/assets/{sizeCapture-INFHLROL-CaLSjl7R.js → sizeCapture-INFHLROL-DfqKWBhp.js} +1 -1
  50. package/dist/assets/{stateDiagram-v2-GCMORJYK-blyzRgvD.js → stateDiagram-v2-GCMORJYK-DkIf90iA.js} +1 -1
  51. package/dist/assets/{swimlanes-2SLR337P-BIi-tuCD.js → swimlanes-2SLR337P-Ds64cQxN.js} +1 -1
  52. package/dist/assets/swimlanesDiagram-TC7HE7FX-bO3Klz6Z.js +8 -0
  53. package/dist/assets/{timeline-definition-EJHVYXUP-oNE7PiRv.js → timeline-definition-EJHVYXUP-Ci3-31qT.js} +1 -1
  54. package/dist/assets/{usecaseDiagram-POWQR4AR-DzmCYS5I.js → usecaseDiagram-POWQR4AR-DQUGgfBf.js} +1 -1
  55. package/dist/assets/{vennDiagram-UO4OBE2U-T51P02io.js → vennDiagram-UO4OBE2U-DV5_nmWl.js} +1 -1
  56. package/dist/assets/{wardleyDiagram-VNRHLVJA-1GfD8Fys.js → wardleyDiagram-VNRHLVJA-DatPTthc.js} +1 -1
  57. package/dist/assets/{xychartDiagram-PMCCYNJV-BhNMe0uk.js → xychartDiagram-PMCCYNJV-ADaxt1QH.js} +1 -1
  58. package/dist/index.html +1 -1
  59. package/dist-server/drivers/agents-proxy.js +41 -1
  60. package/dist-server/index.js +1249 -1008
  61. package/dist-server/openmausbot.js +54 -34
  62. package/dist-server/pair-cli.js +54 -34
  63. package/dist-server/server/about-me-sync.js +16 -5
  64. package/dist-server/server/box.js +18 -14
  65. package/dist-server/server/browser-engine.js +4 -26
  66. package/dist-server/server/calendar-calls.js +2 -1
  67. package/dist-server/server/capped-body.js +26 -0
  68. package/dist-server/server/container-computer.js +23 -26
  69. package/dist-server/server/drivers/agents-call.js +3 -3
  70. package/dist-server/server/drivers/agents-catalog.js +2 -2
  71. package/dist-server/server/drivers/agents-credential.js +6 -0
  72. package/dist-server/server/drivers/agents-vault.js +35 -0
  73. package/dist-server/server/engine-failover.js +6 -3
  74. package/dist-server/server/engine-tiers.js +4 -4
  75. package/dist-server/server/index.js +22 -19
  76. package/dist-server/server/local-vm-run.js +10 -0
  77. package/dist-server/server/local-vm-start.js +22 -0
  78. package/dist-server/server/model-levels/aliases.js +7 -2
  79. package/dist-server/server/model-levels/index.js +7 -0
  80. package/dist-server/server/request-auth.js +15 -18
  81. package/dist-server/server/routes/message-file.js +1 -1
  82. package/dist-server/server/routines.js +6 -6
  83. package/dist-server/server/store.js +1 -1
  84. package/dist-server/server/stream-tail.js +25 -0
  85. package/dist-server/server/team-rooms/backend.js +9 -4
  86. package/dist-server/server/team-rooms/service.js +1 -1
  87. package/dist-server/server/team-rooms/testing/fake-rooms-backend.js +10 -4
  88. package/dist-server/server/vault/request.js +174 -0
  89. package/dist-server/server/vault/runtime.js +13 -3
  90. package/dist-server/server/vault/store.js +22 -4
  91. package/dist-server/server/vps-computer.js +13 -31
  92. package/dist-server/server/watch-along/budget.js +11 -3
  93. package/dist-server/server/watch-along/live.js +4 -2
  94. package/dist-server/shared/vault.js +7 -0
  95. package/dist-server/vps-container-mcp.js +3 -1
  96. package/package.json +1 -1
  97. package/dist/assets/channel-NYf_L8uU.js +0 -1
  98. package/dist/assets/swimlanesDiagram-TC7HE7FX-DWtkSjpb.js +0 -8
@@ -0,0 +1,35 @@
1
+ export async function callVaultTool(args, api) {
2
+ try {
3
+ if (args.item_id === undefined && args.url === undefined) {
4
+ const r = await api("/api/internal/vault/keys");
5
+ const items = Array.isArray(r.items) ? r.items : [];
6
+ if (!items.length) {
7
+ return { text: "No Vault API keys are shared with you. The person can add one in Settings > Vault > New API key and tick your name under Allowed bots." };
8
+ }
9
+ return { text: JSON.stringify(items, null, 2) };
10
+ }
11
+ const r = await api("/api/internal/vault/request", { method: "POST", body: JSON.stringify(args) });
12
+ return { text: JSON.stringify(r, null, 2) };
13
+ }
14
+ catch (error) {
15
+ return { text: error instanceof Error ? error.message : "Vault could not complete the request.", isError: true };
16
+ }
17
+ }
18
+ export const vaultTools = [
19
+ {
20
+ name: "vault_request",
21
+ description: "Use an API key from the person's Atomic Vault without seeing it. No arguments: list the keys shared with you (id, name, allowed HTTPS addresses, header). With item_id and url: Atomic sends that request and adds the key header itself, so never set it. Text comes back; other files are saved and their path returned. Check here before asking for an API key.",
22
+ inputSchema: {
23
+ type: "object",
24
+ properties: {
25
+ item_id: { type: "string" },
26
+ url: { type: "string", description: "https:// endpoint at one of the item's addresses." },
27
+ method: { type: "string", enum: ["GET", "POST", "PUT", "PATCH", "DELETE"] },
28
+ headers: { type: "object", additionalProperties: { type: "string" } },
29
+ body: { type: "string" },
30
+ save_as: { type: "string", description: "File name for a response to keep." },
31
+ },
32
+ additionalProperties: false,
33
+ },
34
+ },
35
+ ];
@@ -64,10 +64,13 @@ export const NO_ANSWER_FAILURE = "The engine ended the turn without an answer.";
64
64
  function unrecognisedFailure(turn) {
65
65
  return { kind: "provider_error", message: turn.lastError ?? NO_ANSWER_FAILURE };
66
66
  }
67
- /** Stops that must not dispatch the request again: cancellation or a broken
68
- * checkpoint whose accepted prompt may already have executed actions.
67
+ /** Stops that must not dispatch the request again: cancellation, a broken
68
+ * checkpoint whose accepted prompt may already have executed actions, and a
69
+ * turn ended over failed or denied tool runs (tool_error). Tools are the
70
+ * harness's, not the engine's, so another engine faces the same failure or
71
+ * the same human denial; it must not settle a turn the person refused.
69
72
  * The next explicit turn rebuilds that checkpoint from retained history. */
70
- const NOT_A_PROVIDER_FAILURE = new Set(["interrupted", "cancelled", "invalid_checkpoint"]);
73
+ const NOT_A_PROVIDER_FAILURE = new Set(["interrupted", "cancelled", "invalid_checkpoint", "tool_error"]);
71
74
  export class FailoverGate {
72
75
  turns = new Map();
73
76
  onFailure;
@@ -318,10 +318,10 @@ export function resolveLadder(ladder, stored, context) {
318
318
  key.sort((a, b) => a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
319
319
  free.sort((a, b) => a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
320
320
  for (const { step, entry, candidate, band } of [...subscription, ...key, ...free]) {
321
- const reason = band === "key" && context.keyBandPaused ? "paused"
322
- : band === "free" && !context.includeFree ? "free-off"
323
- : band === "free" && context.clientData ? "client-data"
324
- : skipReason(entry, candidate, context, step < ladder.length);
321
+ // "paused" names a key kept off this turn by policy alone: a key that could not take it anyway (signed out, resting, refused) keeps its real reason.
322
+ const reason = band === "free" && !context.includeFree ? "free-off"
323
+ : band === "free" && context.clientData ? "client-data"
324
+ : skipReason(entry, candidate, context, step < ladder.length) ?? (band === "key" && context.keyBandPaused ? "paused" : undefined);
325
325
  if (reason) {
326
326
  skipped.push({ step, instanceId: candidate.instanceId, reason, band });
327
327
  continue;
@@ -76,7 +76,7 @@ import { turnTimingFinish, turnTimingMark, turnTimingStart } from "./turn-timing
76
76
  import { ATOMIC_TEAM_PACKAGE_ID, BUILTIN_CHIBI_REFUSALS, builtinChibiPatchRefusal } from "./builtin-chibi.js";
77
77
  import { canAccessTeam, canContactTeamOf, canManagePeer, canReachPeer, canReachTeam, coordinatorSupervises, peerAllowed, peerName, peerRosterSystemPrompt, peerStatus, peerStatusWords, reachablePeers, reachesEveryTeam, roomBoundaryHolds, teamStatusPrompt, PEER_ROSTER_MAX, routeTeammates, roomPeerRosterSystemPrompt, rosterAbout, roomRosterLine, PEER_ACCESS_HELP } from "./peer-roster.js";
78
78
  import { openMausStatusSystemPrompt } from "./openmaus-status-capsule.js";
79
- import { containerComputerAction, managedImageNeedsUpgrade, containerComputerExists, containerComputerFrame, containerComputerMcp, containerComputerScreenshot, containerComputerStatus, recentContainerComputerStatus, containerRuntimeStatus, ensureContainerRuntime, containerRuntimeError, localVmRecreatableOnDemand, perBotLocalVmTarget, SHARED_LOCAL_VM_TARGET, setupCommands, } from "./container-computer.js";
79
+ import { containerComputerAction, managedImageNeedsUpgrade, containerComputerExists, containerComputerFrame, containerComputerMcp, containerComputerScreenshot, containerComputerStatus, recentContainerComputerStatus, containerRuntimeStatus, ensureContainerRuntime, containerRuntimeError, localVmRecreatableOnDemand, localVmStartableWhenStopped, perBotLocalVmTarget, SHARED_LOCAL_VM_TARGET, setupCommands, } from "./container-computer.js";
80
80
  import { ensureDirs, instanceConfigs, loadConfig, providerReloadKeys, localVmMaxInstances, localVmAutoStartRuntime, localVmMode, parseConfigPatch, roomTurnTimeoutMinutes, threadEventLogMaxBytes, maxConcurrentBotThreads, threadEventLogRetentionDays, saveConfig, showToolCallsEnabled, claudeUserMcpEnabled, userMcpEnabledFor, addonEnabled, skillAuthoringEnabled, sharedComputersEnabled, teamRoomsEnabled, builtInBrowserEnabled, llmThreadTitlesEnabled, onDeviceHelpersEnabled, browserProfileReplacementConflict, browserProfilePartitionTarget, syncCredentialEnv, withInstanceCli, persistableInstanceConfigs, vpsSshAlias, browserEngineAttachCdpUrl, DATA_DIR, EVENTS_DIR, NATIVE_DIR, customMcpServers, roomHandoffLimits, onConfigSaved, accountBotGrantPolicy, } from "./config.js";
81
81
  import { sweepThreadEventLogs } from "./thread-retention.js";
82
82
  import { GodModeSwitch } from "./god-mode.js";
@@ -243,7 +243,7 @@ import { applyPendingWorkspaceRestore, readLastWorkspaceRestore } from "./worksp
243
243
  import { createCustomDomainVerifier, customDomainIpv4, normalizeCustomDomain } from "./custom-domain.js";
244
244
  import { allowedScopes, createEmailSignIn, parseAllowList } from "./account-signin.js";
245
245
  import { ProviderAuthSessions } from "./provider-auth-sessions.js";
246
- import { clearSessionCookie, clientBotPatchViolation, bearerToken, clientGroupPatchViolation, isLoopbackHost, isProxied, labelFromUserAgent, requestOrigin, requestSource, requiredScope, resolveLoopbackTrust, resolveRequestAuth, parseCookies, serializeSessionCookie, sessionCookieName, } from "./request-auth.js";
246
+ import { clearSessionCookie, clientBotPatchViolation, bearerToken, clientGroupPatchViolation, clientTaskPatchViolation, isLoopbackHost, isProxied, labelFromUserAgent, requestOrigin, requestSource, requiredScope, resolveLoopbackTrust, resolveRequestAuth, parseCookies, serializeSessionCookie, sessionCookieName, } from "./request-auth.js";
247
247
  import { cookieMaxAgeSeconds, formatPairingCode, SessionRegistry } from "./sessions.js";
248
248
  import { editorHasEntry, editorInstalled, editorTarget, editorTargets, registerWithEditor, unregisterFromEditor } from "./editor-connect.js";
249
249
  import { claudeCodeHasEntry, claudeCodeMcpEntry, registerWithClaudeCode, unregisterFromClaudeCode } from "./claude-code-connect.js";
@@ -1163,7 +1163,7 @@ const availableSkills = () => mergeSkills(bundledSkills, loadUserSkills(join(DAT
1163
1163
  // SAFETY: Electron's utility-process runtime is the only environment that
1164
1164
  // supplies parentPort; plain Node intentionally leaves it absent.
1165
1165
  const utilityParentPort = process.parentPort;
1166
- installNativeVault(DATA_DIR, utilityParentPort, () => desktopMutationToken, req => authorizedInternalCapability(req.headers.authorization) !== null);
1166
+ installNativeVault(DATA_DIR, utilityParentPort, () => desktopMutationToken, req => authorizedInternalCapability(req.headers.authorization));
1167
1167
  installWorkspaceSecrets(utilityParentPort, DATA_DIR, restoredThisBoot);
1168
1168
  function postDesktopPrivateMessage(message) {
1169
1169
  if (!utilityParentPort)
@@ -3929,8 +3929,8 @@ function jevRerunOnNextRung(c, replyIds) {
3929
3929
  const profile = store.bot(c.botId);
3930
3930
  const projected = profile ? store.projectBotForTask(c.botId, c.threadId) : undefined;
3931
3931
  const tried = new Set(record.tried);
3932
- if (!profile || !projected || tried.size >= MAX_ENGINES_PER_TURN)
3933
- return null;
3932
+ if (!profile || !projected || tried.size > MAX_ENGINES_PER_TURN)
3933
+ return null; // tried includes the engine that answered: the failure cap is a strict bound here
3934
3934
  const candidates = engineSnapshots.current() ?? [];
3935
3935
  const tier = turnTier(profile, c.threadId);
3936
3936
  const plan = enginePlan(profile, c.threadId, tier);
@@ -8663,10 +8663,11 @@ function reportIncident(input) {
8663
8663
  // the report carries the broken bot's name as its provenance: it is about
8664
8664
  // that bot's work and nobody was at the keyboard
8665
8665
  const peerAsk = { botId: bot.id, name: bot.name, unattended: true };
8666
- if (botAtThreadCapacity(chief.id) || activeGroupTurnForBot(chief.id)) {
8667
- queueSteeredMessage(chief.id, incidents.threadId, text, { reason: "capacity", unattended: true, peerAsk });
8668
- return;
8669
- }
8666
+ // A Chief still on the last incident (a failover, then that turn's capped
8667
+ // stop) gets this one next; startTurn would refuse the busy thread and bounce it to the person.
8668
+ const reason = botAtThreadCapacity(chief.id) || activeGroupTurnForBot(chief.id) ? "capacity" : undefined;
8669
+ if (reason || threadBusy(chief.id, incidents.threadId))
8670
+ return void queueSteeredMessage(chief.id, incidents.threadId, text, { reason, unattended: true, peerAsk });
8670
8671
  void startTurn(chief.id, text, { threadId: incidents.threadId, unattended: true, peerAsk }).catch((error) => {
8671
8672
  const why = error instanceof Error ? error.message : String(error);
8672
8673
  store.appendMessage(incidents.threadId, {
@@ -14355,21 +14356,22 @@ async function readyLocalVmForTurn(botId, target, isCurrent = () => true, onNote
14355
14356
  noteLocalVmSeen(target, status);
14356
14357
  if (!isCurrent())
14357
14358
  return status;
14358
- if (status.ready || !localVmRecreatableOnDemand(status) || !status.runtime)
14359
- return status;
14359
+ const start = localVmStartableWhenStopped(status);
14360
+ if (status.ready || !(start || localVmRecreatableOnDemand(status)) || !status.runtime)
14361
+ return status; // start: a stopped VM keeps its disk, never recreated
14360
14362
  // Another creation is already mid-flight and its container is not yet
14361
14363
  // visible to a count, so the safe answer is the inspected status —
14362
14364
  // exactly what the over-cap path below returns.
14363
14365
  if (!ownsProvision)
14364
14366
  return status;
14365
- if (target.key !== SHARED_LOCAL_VM_TARGET.key) {
14367
+ if (!start && target.key !== SHARED_LOCAL_VM_TARGET.key) {
14366
14368
  const count = await existingPerBotLocalVmCount(status.runtime);
14367
14369
  if (!isCurrent() || count >= localVmMaxInstances(cfg))
14368
14370
  return status;
14369
14371
  }
14370
14372
  broadcast({ kind: "computer", botId, state: "provisioning" });
14371
14373
  try {
14372
- status = await containerComputerAction("run", undefined, undefined, target);
14374
+ status = await containerComputerAction(start ? "start" : "run", undefined, undefined, target);
14373
14375
  }
14374
14376
  catch {
14375
14377
  // Keep the inspected status: its `problem` names the real obstacle,
@@ -18890,7 +18892,7 @@ const handleRequest = async (req, res) => {
18890
18892
  : json(res, 404, { error: "no such routine" });
18891
18893
  }
18892
18894
  if (path === "/api/routine-runs/seen-all" && method === "POST") {
18893
- return json(res, 200, { runs: routines.markAllSeen() });
18895
+ return json(res, 200, { runs: routines.markAllSeen((run) => routineVisible(run, visible)) });
18894
18896
  }
18895
18897
  const runMatch = path.match(/^\/api\/routine-runs\/([\w-]+)\/(cancel|seen)$/);
18896
18898
  if (runMatch && method === "POST") {
@@ -20900,11 +20902,9 @@ const handleRequest = async (req, res) => {
20900
20902
  if (!body || typeof body !== "object" || Array.isArray(body)) {
20901
20903
  return json(res, 400, { error: "body must be a JSON object" });
20902
20904
  }
20903
- if (auth.kind === "session" && !auth.scopes.includes("admin")) {
20904
- const field = clientBotPatchViolation(body);
20905
- if (field)
20906
- return json(res, 403, { error: `forbidden: this session may change how a bot looks, not "${field}" (needs the admin scope)` });
20907
- }
20905
+ const clientField = auth.kind === "session" && !auth.scopes.includes("admin") ? clientBotPatchViolation(body) : null;
20906
+ if (clientField)
20907
+ return json(res, 403, { error: `forbidden: this session may change how a bot looks, not "${clientField}" (needs the admin scope)` });
20908
20908
  const existingBot = store.bot(m[1]);
20909
20909
  const builtinRefusal = builtinChibiPatchRefusal(existingBot, body, store.builtinChibi()) ?? personalPatchRefusal(existingBot, body);
20910
20910
  if (builtinRefusal)
@@ -22831,6 +22831,9 @@ const handleRequest = async (req, res) => {
22831
22831
  const current = store.projectBotForTask(m[1], m[2]);
22832
22832
  if (!current)
22833
22833
  return json(res, 404, { error: "no such task" });
22834
+ const clientField = auth.kind === "session" && !auth.scopes.includes("admin") ? clientTaskPatchViolation(body) : null;
22835
+ if (clientField)
22836
+ return json(res, 403, { error: `forbidden: this session may organise a thread, not "${clientField}" (needs the admin scope)` });
22834
22837
  const allowed = new Set(["title", "projectId", "modelSelection", "modelClass", "updateBotDefault", "resetApprovalToAsk", "approvalMode", "autoApprove", "requireAvailableModel", "pinnedMessageId", "acknowledgeLocalAuto", "archivedAt", "pinned", "surface"]);
22835
22838
  if (Object.keys(body).some((key) => !allowed.has(key)))
22836
22839
  return json(res, 400, { error: "unsupported thread setting" });
@@ -0,0 +1,10 @@
1
+ /** The Local VM launch with the viewer password moved out of argv, which any
2
+ * local user can read through `ps`. Docker and Podman resolve a bare `-e NAME`
3
+ * from the client's own environment. Apple container keeps the inline form:
4
+ * its CLI is not known to do the same. */
5
+ export function viewerSecretToEnv(runtime, args) {
6
+ const at = args.findIndex((arg, index) => arg.startsWith("VNC_PW=") && args[index - 1] === "-e");
7
+ if (runtime === "container" || at < 0)
8
+ return { args };
9
+ return { args: args.with(at, "VNC_PW"), env: { VNC_PW: args[at].slice("VNC_PW=".length) } };
10
+ }
@@ -0,0 +1,22 @@
1
+ /** Whether a stopped Local VM can simply be started again, disk and all: the
2
+ * container Atomic made, on the current image, with its safety limits intact.
3
+ *
4
+ * A stopped VM was once never started ("its desktop leaves a stale X lock on
5
+ * stop"), so every restart of the Mac or of the container runtime left the
6
+ * person at "remove and recreate it", losing whatever was installed inside.
7
+ * The image's own start script removes that lock before the display starts
8
+ * (start-vnc.sh: `rm -f /tmp/.X1-lock /tmp/.X11-unix/X1`), and a stopped VM
9
+ * comes back with display, desktop and Cua Driver after a clean stop and
10
+ * after a killed runtime alike (checked on driver-0.20.0-v6, 2026-11-11). If
11
+ * a start ever does leave the desktop down, `statusProblem` says so. */
12
+ export function localVmStartableWhenStopped(status) {
13
+ return Boolean(status.runtime)
14
+ && status.daemonUp === true
15
+ && status.image === true
16
+ && status.container === "stopped"
17
+ && status.imageMatches === true
18
+ && status.managed === true
19
+ && status.network !== "unsafe"
20
+ && status.security !== "unsafe"
21
+ && status.persistence !== "unsafe";
22
+ }
@@ -280,10 +280,15 @@ export function catalogIdFor(driverKind, model, catalog = MODEL_CATALOG) {
280
280
  return catalog.find((entry) => entry.runs.some((r) => r.driverKind === driverKind && r.model === model))?.id ??
281
281
  catalog.find((entry) => entry.runs.some((r) => r.model === model))?.id ?? null;
282
282
  }
283
- /** The model id without a router prefix: "nous:openai/gpt-6-sol" is "gpt-6-sol". */
283
+ /** What follows the colon in an Ollama id: "cloud", "latest" or a size such as "8b". */
284
+ const OLLAMA_TAG = /:(?:cloud|latest|\d+(?:\.\d+)?[bkm](?:[-_][\w.-]+)?)$/i;
285
+ /** The model id without a router prefix or an Ollama tag: "nous:openai/gpt-6-sol"
286
+ * is "gpt-6-sol" and "qwen3-coder:cloud" is "qwen3-coder". */
284
287
  export function bareModelId(model) {
285
288
  const last = model.split("/").pop() ?? model;
286
- return last.replace(/^[\w.-]+:(?!:)/, "");
289
+ if (last.includes("::"))
290
+ return last;
291
+ return last.replace(OLLAMA_TAG, "").replace(/^[\w.-]+:/, "");
287
292
  }
288
293
  /** The catalog with every model the engines offer: a model the catalog
289
294
  * already knows under another id joins that entry's runs, and anything else
@@ -163,6 +163,13 @@ export function createModelLevels(options) {
163
163
  const classOf = (driverKind, model) => {
164
164
  const models = graded();
165
165
  const byId = (id) => models.find((entry) => entry.id === id);
166
+ // An override written for the engine's own model id ("opencode-go/kimi-k3")
167
+ // names exactly this model. Once the engine offers it, the model also
168
+ // joins the catalog under its bare id ("kimi-k3", withOfferedModels), and
169
+ // reading only that entry dropped the person's class.
170
+ const exact = byId(model);
171
+ if (exact?.overrideOnly)
172
+ return { modelClass: exact.modelClass.modelClass, source: exact.modelClass.source };
166
173
  const found = byId(catalogIdFor(driverKind, model, catalog) ?? model);
167
174
  if (found && found.modelClass.source !== "default")
168
175
  return { modelClass: found.modelClass.modelClass, source: found.modelClass.source };
@@ -353,27 +353,24 @@ export function requiredScope(method, path, features = {}) {
353
353
  }
354
354
  return "admin";
355
355
  }
356
+ function clientPatchViolation(fields) {
357
+ return (body) => {
358
+ if (!body || typeof body !== "object" || Array.isArray(body))
359
+ return "body";
360
+ for (const key of Object.keys(body))
361
+ if (!fields.has(key))
362
+ return key;
363
+ return null;
364
+ };
365
+ }
356
366
  /** Fields a client session may change on a bot: how it looks in the list,
357
367
  * never what it may do. Returns the first offending field, or null. */
358
- const CLIENT_BOT_PATCH_FIELDS = new Set(["unread", "pinned", "pinnedMessageId", "color", "mascotExpression", "mascotBody"]);
359
- export function clientBotPatchViolation(body) {
360
- if (!body || typeof body !== "object" || Array.isArray(body))
361
- return "body";
362
- for (const key of Object.keys(body))
363
- if (!CLIENT_BOT_PATCH_FIELDS.has(key))
364
- return key;
365
- return null;
366
- }
368
+ export const clientBotPatchViolation = clientPatchViolation(new Set(["unread", "pinned", "pinnedMessageId", "color", "mascotExpression", "mascotBody"]));
367
369
  /** Same for a room: name and reading state, never its folder or who answers. */
368
- const CLIENT_GROUP_PATCH_FIELDS = new Set(["name", "bulletin", "unread", "pinned", "pinnedMessageId", "section"]);
369
- export function clientGroupPatchViolation(body) {
370
- if (!body || typeof body !== "object" || Array.isArray(body))
371
- return "body";
372
- for (const key of Object.keys(body))
373
- if (!CLIENT_GROUP_PATCH_FIELDS.has(key))
374
- return key;
375
- return null;
376
- }
370
+ export const clientGroupPatchViolation = clientPatchViolation(new Set(["name", "bulletin", "unread", "pinned", "pinnedMessageId", "section"]));
371
+ /** Same for a bot's thread: its title and shelf placement, never its model,
372
+ * class, approval mode or computer. */
373
+ export const clientTaskPatchViolation = clientPatchViolation(new Set(["title", "projectId", "archivedAt", "pinned", "pinnedMessageId"]));
377
374
  const CLI_OWNER_HEADER = "x-openmausbot-cli-owner";
378
375
  /** The only routes the serving CLI's secret opens: its pairing code. */
379
376
  const CLI_OWNER_ROUTE = /^\/api\/auth\/pairing$/;
@@ -25,7 +25,7 @@ export function createMessageFileRoutes({ store, attachments: ATTACHMENTS_DIR, w
25
25
  return json(res, 400, { error: "ref must identify a rendered image" });
26
26
  }
27
27
  const href = method === "POST"
28
- ? (typeof body.path === "string" ? body.path : "")
28
+ ? (typeof body?.path === "string" ? body.path : "")
29
29
  : messageImageTargetAt(message.text ?? "", Number(rawReference));
30
30
  if (!href)
31
31
  return json(res, 400, { error: "path is required" });
@@ -1065,17 +1065,17 @@ export class RoutineManager {
1065
1065
  return cloneRun(run);
1066
1066
  }
1067
1067
  /** Clear every failure indicator at once: stamp seenAt on each unseen
1068
- * failed/missed run in one committed save, then emit the updated runs so
1069
- * connected clients drop their dots immediately. A failed save rolls the
1070
- * stamps back so a retry still finds the unseen runs. */
1071
- markAllSeen() {
1072
- if (!this.runs.some((run) => !run.seenAt && isRoutineProblemRun(run)))
1068
+ * failed/missed run the caller may see (`include`, so a member's sweep
1069
+ * never touches a restricted bot's runs) in one committed save, then emit
1070
+ * the updated runs. A failed save rolls the stamps back for a retry. */
1071
+ markAllSeen(include = () => true) {
1072
+ if (!this.runs.some((run) => !run.seenAt && isRoutineProblemRun(run) && include(run)))
1073
1073
  return [];
1074
1074
  const stampAt = this.now();
1075
1075
  const updated = [];
1076
1076
  this.commitMutation(() => {
1077
1077
  for (const run of this.runs) {
1078
- if (run.seenAt || !isRoutineProblemRun(run))
1078
+ if (run.seenAt || !isRoutineProblemRun(run) || !include(run))
1079
1079
  continue;
1080
1080
  run.seenAt = stampAt;
1081
1081
  updated.push(run);
@@ -334,7 +334,7 @@ export function mentionedBots(text, peers) {
334
334
  const found = [];
335
335
  let at = -1;
336
336
  while ((at = lower.indexOf("@", at + 1)) !== -1) {
337
- if (!isMentionBoundary(text, at))
337
+ if (!isMentionBoundary(lower, at))
338
338
  continue; // user@host, not a tag
339
339
  const rest = lower.slice(at + 1);
340
340
  const hit = candidates.find((p) => {
@@ -0,0 +1,25 @@
1
+ const STREAM_CAP_CHARS = 16 * 1024 * 1024;
2
+ /** Keeps the LAST 16MB of a stream without rebuilding one giant string per
3
+ * chunk (a 10-minute `docker build` stream made that rebuild quadratic).
4
+ * Chunks fall off the front as soon as the tail alone covers the cap; the
5
+ * final slice preserves the exact cap semantics of the old accumulator. */
6
+ export function tailCollector() {
7
+ const chunks = [];
8
+ let total = 0;
9
+ return {
10
+ push(chunk) {
11
+ chunks.push(chunk);
12
+ total += chunk.length;
13
+ for (;;) {
14
+ const first = chunks[0];
15
+ if (chunks.length < 2 || first === undefined || total - first.length < STREAM_CAP_CHARS)
16
+ break;
17
+ chunks.shift();
18
+ total -= first.length;
19
+ }
20
+ },
21
+ text() {
22
+ return chunks.join("").slice(-STREAM_CAP_CHARS);
23
+ },
24
+ };
25
+ }
@@ -75,10 +75,15 @@ export class RoomsBackend {
75
75
  async update(table, query, patch) {
76
76
  return this.authed(`/rest/v1/${table}?${query}`, { method: "PATCH", body: patch, headers: { prefer: "return=representation" } });
77
77
  }
78
- async upsert(table, row, onConflict) {
79
- await this.authed(`/rest/v1/${table}?on_conflict=${encodeURIComponent(onConflict)}`, {
80
- method: "POST", body: row, headers: { prefer: "resolution=merge-duplicates,return=minimal" },
81
- });
78
+ /** Write `patch` to the row with this key, creating the row when it is
79
+ * missing. Not PostgREST's merge-duplicates: that rewrites the key columns
80
+ * too, and clients hold no UPDATE privilege on them, so every write after
81
+ * the first was refused. */
82
+ async upsert(table, key, patch) {
83
+ const query = Object.entries(key).map(([column, value]) => `${column}=eq.${encodeURIComponent(value)}`).join("&");
84
+ const updated = await this.update(table, query, patch);
85
+ if (!updated.length)
86
+ await this.insert(table, { ...key, ...patch });
82
87
  }
83
88
  async authed(path, init) {
84
89
  const session = await this.session();
@@ -607,7 +607,7 @@ export class TeamRoomsService {
607
607
  const hosted = [...this.rooms.values()].flatMap((s) => s.bots)
608
608
  .filter((b) => b.owner_user_id === me && b.host_install_id === this.deps.installId).map((b) => b.id);
609
609
  try {
610
- await this.deps.backend.upsert("room_presence", { user_id: me, install_id: this.deps.installId, device: this.deps.device, hosted_bot_ids: hosted, last_seen: new Date(this.now()).toISOString() }, "user_id,install_id");
610
+ await this.deps.backend.upsert("room_presence", { user_id: me, install_id: this.deps.installId }, { device: this.deps.device, hosted_bot_ids: hosted, last_seen: new Date(this.now()).toISOString() });
611
611
  }
612
612
  catch (error) {
613
613
  if (!(error instanceof RoomsApiError && error.code === "offline"))
@@ -117,11 +117,15 @@ export class FakeRoomsBackend {
117
117
  return reply(403, { code: "42501" });
118
118
  const rows = this.tables.room_presence;
119
119
  const at = rows.findIndex((r) => r.user_id === body.user_id && r.install_id === body.install_id);
120
+ // As the real grants do: clients may insert a row, but an upsert that
121
+ // lands on an existing row rewrites user_id and install_id, which
122
+ // they hold no UPDATE privilege on.
123
+ if (at >= 0 && url.searchParams.has("on_conflict"))
124
+ return reply(403, { message: "permission denied for table room_presence", code: "42501" });
120
125
  if (at >= 0)
121
- rows[at] = { ...rows[at], ...body };
122
- else
123
- rows.push(body);
124
- return reply(201, undefined);
126
+ return reply(409, { message: "duplicate key value violates unique constraint", code: "23505" });
127
+ rows.push(body);
128
+ return reply(201, [body]);
125
129
  }
126
130
  if (method === "PATCH") {
127
131
  const rows = this.query(table, url.searchParams, me);
@@ -130,6 +134,8 @@ export class FakeRoomsBackend {
130
134
  continue;
131
135
  if (table === "room_members" && row.user_id !== me.id)
132
136
  continue;
137
+ if (table === "room_presence" && (row.user_id !== me.id || "user_id" in body || "install_id" in body))
138
+ continue;
133
139
  Object.assign(this.tables[table].find((r) => r === row || (r.id && r.id === row.id) || (r.room_id === row.room_id && r.user_id === row.user_id)), body);
134
140
  }
135
141
  return reply(200, rows);
@@ -0,0 +1,174 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { z } from "zod";
5
+ import { vaultOrigin } from "../../shared/vault.js";
6
+ import { PASS } from "../routes/table.js";
7
+ import { VaultError } from "./store.js";
8
+ const MAX_REQUEST_BODY = 1_000_000;
9
+ const MAX_TEXT = 100_000;
10
+ const MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
11
+ const REQUEST_TIMEOUT_MS = 120_000;
12
+ const DOWNLOAD_KEEP_MS = 7 * 24 * 60 * 60_000;
13
+ // Set by the transport, or able to reroute or smuggle the request.
14
+ const REFUSED_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "upgrade", "proxy-authorization", "te", "trailer"]);
15
+ const EXTENSIONS = {
16
+ "audio/mpeg": ".mp3", "audio/wav": ".wav", "audio/x-wav": ".wav", "audio/ogg": ".ogg", "audio/flac": ".flac", "audio/mp4": ".m4a",
17
+ "video/mp4": ".mp4", "video/webm": ".webm", "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "image/gif": ".gif",
18
+ "application/pdf": ".pdf", "application/zip": ".zip", "application/json": ".json", "text/plain": ".txt", "text/csv": ".csv",
19
+ };
20
+ const requestSchema = z.object({
21
+ item_id: z.string().uuid(),
22
+ url: z.string().min(1).max(4096),
23
+ method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).default("GET"),
24
+ headers: z.record(z.string().regex(/^[A-Za-z0-9-]{1,64}$/), z.string().regex(/^[\x20-\x7E]{0,4096}$/))
25
+ .refine((headers) => Object.keys(headers).length <= 40).default({}),
26
+ body: z.string().max(MAX_REQUEST_BODY).optional(),
27
+ save_as: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/).optional(),
28
+ }).strict();
29
+ const REFUSED = "This bot may not use that Vault item at that address. Call vault_request with no arguments to see each item's allowed addresses.";
30
+ function isText(contentType) {
31
+ return /^text\/|[/+](?:json|xml)\b|^application\/(?:x-www-form-urlencoded|javascript|x-ndjson)\b/i.test(contentType);
32
+ }
33
+ async function readCapped(response) {
34
+ if (!response.body)
35
+ return Buffer.alloc(0);
36
+ const chunks = [];
37
+ let total = 0;
38
+ const reader = response.body.getReader();
39
+ for (;;) {
40
+ const { done, value } = await reader.read();
41
+ if (done)
42
+ break;
43
+ total += value.byteLength;
44
+ if (total > MAX_RESPONSE_BYTES) {
45
+ await reader.cancel().catch(() => undefined);
46
+ return null;
47
+ }
48
+ chunks.push(Buffer.from(value));
49
+ }
50
+ return Buffer.concat(chunks);
51
+ }
52
+ function save(directory, name, data, now) {
53
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
54
+ for (const entry of readdirSync(directory)) {
55
+ const file = join(directory, entry);
56
+ try {
57
+ if (now - statSync(file).mtimeMs > DOWNLOAD_KEEP_MS)
58
+ unlinkSync(file);
59
+ }
60
+ catch { /* another turn removed it */ }
61
+ }
62
+ const file = join(directory, `${now}-${randomBytes(3).toString("hex")}-${name}`);
63
+ writeFileSync(file, data, { mode: 0o600, flag: "wx" });
64
+ return file;
65
+ }
66
+ /** One request on a bot's behalf. Every refusal reads the same whether the
67
+ * item is missing, another owner's, not granted, expired, of another kind or
68
+ * bound to a different address. */
69
+ export async function vaultRequest(raw, deps) {
70
+ const parsed = requestSchema.safeParse(raw);
71
+ if (!parsed.success)
72
+ return { ok: false, status: 400, error: "vault_request needs item_id and an HTTPS url. method, headers, body and save_as are optional." };
73
+ const input = parsed.data;
74
+ const now = (deps.now ?? Date.now)();
75
+ const destination = vaultOrigin(input.url);
76
+ if (!destination)
77
+ return { ok: false, status: 400, error: "The url must be an https:// address with no username or password in it." };
78
+ let key;
79
+ try {
80
+ key = deps.store.apiKeyFor({ ownerId: deps.ownerId, botId: deps.botId, destination }, input.item_id, now);
81
+ }
82
+ catch (error) {
83
+ return { ok: false, status: 503, error: error instanceof VaultError ? error.message : "Vault could not complete the request." };
84
+ }
85
+ if (!key)
86
+ return { ok: false, status: 403, error: REFUSED };
87
+ const headers = new Headers();
88
+ for (const [name, value] of Object.entries(input.headers)) {
89
+ const lower = name.toLowerCase();
90
+ if (REFUSED_HEADERS.has(lower))
91
+ return { ok: false, status: 400, error: `The ${name} header cannot be set.` };
92
+ if (lower === key.header.toLowerCase())
93
+ return { ok: false, status: 400, error: `Leave out the ${name} header. Atomic adds it from the Vault item.` };
94
+ headers.set(name, value);
95
+ }
96
+ headers.set(key.header, key.value);
97
+ let response;
98
+ let data;
99
+ try {
100
+ response = await (deps.fetch ?? fetch)(input.url, {
101
+ method: input.method, headers, redirect: "manual", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
102
+ ...(input.body !== undefined && input.method !== "GET" ? { body: input.body } : {}),
103
+ });
104
+ data = await readCapped(response);
105
+ }
106
+ catch (error) {
107
+ const timedOut = error instanceof Error && error.name === "TimeoutError";
108
+ return { ok: false, status: 502, error: timedOut ? "The service did not answer in time." : "The service could not be reached." };
109
+ }
110
+ if (!data)
111
+ return { ok: false, status: 502, error: "The response was larger than 50 MB and was not kept." };
112
+ const contentType = (response.headers.get("content-type") ?? "").slice(0, 200);
113
+ const result = { ok: true, status: response.status, contentType, bytes: data.length };
114
+ // A redirect could carry the key to an address the owner never listed.
115
+ const location = response.status >= 300 && response.status < 400 ? response.headers.get("location") : null;
116
+ if (location)
117
+ result.location = location.split(key.secret).join("[redacted]").slice(0, 2048);
118
+ const text = isText(contentType) || data.length === 0;
119
+ const scrubbed = text ? data.toString("utf8").split(key.value).join("[redacted]").split(key.secret).join("[redacted]") : "";
120
+ if (text && !input.save_as) {
121
+ result.text = scrubbed.slice(0, MAX_TEXT);
122
+ if (scrubbed.length > MAX_TEXT)
123
+ result.truncated = true;
124
+ return result;
125
+ }
126
+ const mime = contentType.split(";")[0].trim().toLowerCase();
127
+ const name = input.save_as ?? `response${EXTENSIONS[mime] ?? ".bin"}`;
128
+ try {
129
+ result.savedTo = save(deps.downloadDir, name, text ? Buffer.from(scrubbed) : data, now);
130
+ }
131
+ catch {
132
+ return { ok: false, status: 503, error: "The response could not be saved on this computer." };
133
+ }
134
+ return result;
135
+ }
136
+ /** The two routes the vault tools call, on the loopback internal API. `bot`
137
+ * answers from the capability the harness minted for the turn; nothing in
138
+ * the request body says who is asking. */
139
+ export function createVaultBotRoutes(deps) {
140
+ return async ({ req, res, path, method, json, readBody }) => {
141
+ if (!path.startsWith("/api/internal/vault/"))
142
+ return PASS;
143
+ res.setHeader("cache-control", "no-store");
144
+ const botId = deps.bot(req);
145
+ if (!botId)
146
+ return json(res, 401, { error: "Vault tools are available to a bot during its own turn only." });
147
+ const store = deps.store();
148
+ const ownerId = deps.ownerId();
149
+ if (!store || !ownerId)
150
+ return json(res, 503, { error: "Vault is locked on this computer. It unlocks when the Atomic desktop app is open." });
151
+ try {
152
+ if (path === "/api/internal/vault/keys" && method === "GET") {
153
+ const items = store.apiKeysFor(ownerId, botId, (deps.now ?? Date.now)())
154
+ .map(({ id, label, hints, origins, header, expiresAt }) => ({ id, label, hints, origins, header, expiresAt }));
155
+ return json(res, 200, { items });
156
+ }
157
+ if (path === "/api/internal/vault/request" && method === "POST") {
158
+ const body = await readBody(req, MAX_REQUEST_BODY + 200_000).catch(() => null);
159
+ if (deps.bot(req) !== botId || deps.store() !== store)
160
+ return json(res, 403, { error: "Vault access changed. Try again." });
161
+ const result = await vaultRequest(body, { store, ownerId, botId, downloadDir: deps.downloadDir(botId), fetch: deps.fetch, now: deps.now });
162
+ const item = body && typeof body === "object" && "item_id" in body ? String(body.item_id).slice(0, 36) : "";
163
+ console.log(`[vault] bot=${botId} item=${item} status=${result.status}${result.ok ? "" : " refused"}`);
164
+ return result.ok ? json(res, 200, result) : json(res, result.status, { error: result.error });
165
+ }
166
+ }
167
+ catch (error) {
168
+ if (error instanceof VaultError)
169
+ return json(res, 503, { error: error.message });
170
+ return json(res, 503, { error: "Vault could not complete the request." });
171
+ }
172
+ return json(res, 404, { error: "not found" });
173
+ };
174
+ }