@chibitek/chibi 0.1.186 → 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 (97) hide show
  1. package/dist/assets/{abnfDiagram-O67JEVCF-T4rFqxxY.js → abnfDiagram-O67JEVCF-CKDXgnYw.js} +1 -1
  2. package/dist/assets/{arc-BE0n08tb.js → arc--VPK-xet.js} +1 -1
  3. package/dist/assets/{architectureDiagram-NJMV4G6O-W248FhnN.js → architectureDiagram-NJMV4G6O-DSVjpq7n.js} +1 -1
  4. package/dist/assets/{blockDiagram-BEXU5L5S-YQUaYL76.js → blockDiagram-BEXU5L5S-BiQ1JgSl.js} +1 -1
  5. package/dist/assets/{c4Diagram-YGBWAQC7-DvtNnJ7Q.js → c4Diagram-YGBWAQC7-kWWEc-NZ.js} +1 -1
  6. package/dist/assets/channel-CQdxuHwI.js +1 -0
  7. package/dist/assets/{chunk-2Q5K7J3B-r9zB0AN4.js → chunk-2Q5K7J3B-QJYqMtWJ.js} +1 -1
  8. package/dist/assets/{chunk-3FUC2YCW-DcaWZ44l.js → chunk-3FUC2YCW-C7oGYTZS.js} +2 -2
  9. package/dist/assets/{chunk-5VM5RSS4-B9BoCCOM.js → chunk-5VM5RSS4-MahQWTzh.js} +1 -1
  10. package/dist/assets/{chunk-GTNCS2PH-jiyufqr5.js → chunk-GTNCS2PH-CQfOvr7l.js} +1 -1
  11. package/dist/assets/{chunk-GWA4HPMP-86KjuKSi.js → chunk-GWA4HPMP-b0lt02Pi.js} +1 -1
  12. package/dist/assets/{chunk-JWPE2WC7-P-CZmlpX.js → chunk-JWPE2WC7-J1_ylbx8.js} +1 -1
  13. package/dist/assets/{chunk-NETBCI7D-DOwQkah7.js → chunk-NETBCI7D-AWcL9tld.js} +1 -1
  14. package/dist/assets/{chunk-WEXAMYUT-BYpUWdau.js → chunk-WEXAMYUT-DpTrAXJV.js} +1 -1
  15. package/dist/assets/{chunk-XXDRQBXY-BNWicp85.js → chunk-XXDRQBXY-2_DCjtc9.js} +1 -1
  16. package/dist/assets/{classDiagram-v2-NBCMYWYE-DeSoK71a.js → classDiagram-v2-NBCMYWYE-BBQMtHHs.js} +1 -1
  17. package/dist/assets/{cose-bilkent-JH36ORCC-DRvyy4x6.js → cose-bilkent-JH36ORCC-CmxRmDe8.js} +1 -1
  18. package/dist/assets/{cynefin-OW5HDTMX-BPgTdM9o.js → cynefin-OW5HDTMX-DjlothXK.js} +1 -1
  19. package/dist/assets/{cynefinDiagram-VND7K2PF-CVqWmCzX.js → cynefinDiagram-VND7K2PF-D6HfzP26.js} +1 -1
  20. package/dist/assets/{dagre-6A5THRUB-C8Nn1Pd7.js → dagre-6A5THRUB-BtzaxY50.js} +1 -1
  21. package/dist/assets/{diagram-22UHCM2B-BoFPCHMw.js → diagram-22UHCM2B-DsyCiGJD.js} +1 -1
  22. package/dist/assets/{diagram-3UASUU5V-Bw55J1mb.js → diagram-3UASUU5V-CjjvxIr3.js} +1 -1
  23. package/dist/assets/{diagram-ATOU4E4O-DGQrBqML.js → diagram-ATOU4E4O-DDu2iVRb.js} +1 -1
  24. package/dist/assets/{diagram-CDSNMT55-COdY5ptf.js → diagram-CDSNMT55-BBTViw3h.js} +1 -1
  25. package/dist/assets/{diagram-MLGK6HIB-BPZDoncY.js → diagram-MLGK6HIB-D83j4C6w.js} +1 -1
  26. package/dist/assets/{diagram-MPIPVDR6-Fi29WkCR.js → diagram-MPIPVDR6-DTpmpL8Q.js} +1 -1
  27. package/dist/assets/{ebnfDiagram-ZINNZB2B-BXquz6x1.js → ebnfDiagram-ZINNZB2B-D3B4hz_Y.js} +1 -1
  28. package/dist/assets/{elk-276RUBZZ-C_e9eijP.js → elk-276RUBZZ-CbNicGf_.js} +1 -1
  29. package/dist/assets/{erDiagram-OPXOYQCR-C4PKtrfT.js → erDiagram-OPXOYQCR-DeSwxwFC.js} +1 -1
  30. package/dist/assets/{flowDiagram-KWPJA3E3-BlEulfZP.js → flowDiagram-KWPJA3E3-3n_Hk-ZR.js} +1 -1
  31. package/dist/assets/{ganttDiagram-FUAMR5RP-BksDszQx.js → ganttDiagram-FUAMR5RP-BsadEPTf.js} +1 -1
  32. package/dist/assets/{gitGraphDiagram-X574FWY7-EYJKMot5.js → gitGraphDiagram-X574FWY7-DOvqN3Jh.js} +1 -1
  33. package/dist/assets/{index-Bf2yMkX_.js → index-B9LCl5y3.js} +133 -133
  34. package/dist/assets/{index-Do0zrygp.js → index-BmYLMFD8.js} +1 -1
  35. package/dist/assets/{infoDiagram-VRGFBTTK-BuX8YJRd.js → infoDiagram-VRGFBTTK-CI3tfMt9.js} +1 -1
  36. package/dist/assets/{ishikawaDiagram-OU5B5YK6-BOOBBq5e.js → ishikawaDiagram-OU5B5YK6-BE7AjZYf.js} +1 -1
  37. package/dist/assets/{journeyDiagram-ZHPQQLJL-2VfxHa4O.js → journeyDiagram-ZHPQQLJL-DplNZPox.js} +1 -1
  38. package/dist/assets/{kanban-definition-PNTS6WVX-DniBc17b.js → kanban-definition-PNTS6WVX-Cos64we-.js} +1 -1
  39. package/dist/assets/{linear-CrF1eGjn.js → linear-DDfQb-jo.js} +1 -1
  40. package/dist/assets/{mermaid.core-BL_dHjXO.js → mermaid.core-BekbnuLb.js} +5 -5
  41. package/dist/assets/{mindmap-definition-NLK3R4M7-DUGzdUse.js → mindmap-definition-NLK3R4M7-DJ0MbzMW.js} +1 -1
  42. package/dist/assets/{pegDiagram-GJSIUBJH-CO3xT6J0.js → pegDiagram-GJSIUBJH-DZNZCZ4O.js} +1 -1
  43. package/dist/assets/{pieDiagram-5QR66LMP-8gmuAKxu.js → pieDiagram-5QR66LMP-COD5v2yC.js} +1 -1
  44. package/dist/assets/{quadrantDiagram-O4NWA36T-D0I0xUDm.js → quadrantDiagram-O4NWA36T-D4dlLWfv.js} +1 -1
  45. package/dist/assets/{railroadDiagram-XR7U4H2S-DY0BvxgQ.js → railroadDiagram-XR7U4H2S-CEpVYFKl.js} +1 -1
  46. package/dist/assets/{requirementDiagram-PLB6GJNP-DhGe1AaP.js → requirementDiagram-PLB6GJNP-DYD5GX0G.js} +1 -1
  47. package/dist/assets/{sankeyDiagram-IPEJSGJF-CeCrbMFN.js → sankeyDiagram-IPEJSGJF-C9bPeTfK.js} +1 -1
  48. package/dist/assets/{sequenceDiagram-PO4LG4MO-fWSeitKd.js → sequenceDiagram-PO4LG4MO-eXpmPg9C.js} +1 -1
  49. package/dist/assets/{sizeCapture-INFHLROL-Dtg_1bqe.js → sizeCapture-INFHLROL-DfqKWBhp.js} +1 -1
  50. package/dist/assets/{stateDiagram-v2-GCMORJYK-DGUAiQQE.js → stateDiagram-v2-GCMORJYK-DkIf90iA.js} +1 -1
  51. package/dist/assets/{swimlanes-2SLR337P-DebVwPYw.js → swimlanes-2SLR337P-Ds64cQxN.js} +1 -1
  52. package/dist/assets/swimlanesDiagram-TC7HE7FX-bO3Klz6Z.js +8 -0
  53. package/dist/assets/{timeline-definition-EJHVYXUP-Dg7oYgtr.js → timeline-definition-EJHVYXUP-Ci3-31qT.js} +1 -1
  54. package/dist/assets/{usecaseDiagram-POWQR4AR-uqTnPXSC.js → usecaseDiagram-POWQR4AR-DQUGgfBf.js} +1 -1
  55. package/dist/assets/{vennDiagram-UO4OBE2U-CzMUwXwR.js → vennDiagram-UO4OBE2U-DV5_nmWl.js} +1 -1
  56. package/dist/assets/{wardleyDiagram-VNRHLVJA-BsyaKB_7.js → wardleyDiagram-VNRHLVJA-DatPTthc.js} +1 -1
  57. package/dist/assets/{xychartDiagram-PMCCYNJV-7hUye0pF.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 +1235 -997
  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 +9 -9
  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 +16 -14
  76. package/dist-server/server/local-vm-run.js +10 -0
  77. package/dist-server/server/model-levels/aliases.js +7 -2
  78. package/dist-server/server/model-levels/index.js +7 -0
  79. package/dist-server/server/request-auth.js +15 -18
  80. package/dist-server/server/routes/message-file.js +1 -1
  81. package/dist-server/server/routines.js +6 -6
  82. package/dist-server/server/store.js +1 -1
  83. package/dist-server/server/stream-tail.js +25 -0
  84. package/dist-server/server/team-rooms/backend.js +9 -4
  85. package/dist-server/server/team-rooms/service.js +1 -1
  86. package/dist-server/server/team-rooms/testing/fake-rooms-backend.js +10 -4
  87. package/dist-server/server/vault/request.js +174 -0
  88. package/dist-server/server/vault/runtime.js +13 -3
  89. package/dist-server/server/vault/store.js +22 -4
  90. package/dist-server/server/vps-computer.js +12 -30
  91. package/dist-server/server/watch-along/budget.js +11 -3
  92. package/dist-server/server/watch-along/live.js +4 -2
  93. package/dist-server/shared/vault.js +7 -0
  94. package/dist-server/vps-container-mcp.js +3 -1
  95. package/package.json +1 -1
  96. package/dist/assets/channel-DhsCc8Nd.js +0 -1
  97. package/dist/assets/swimlanesDiagram-TC7HE7FX-B5p2N9qd.js +0 -8
@@ -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, {
@@ -18891,7 +18892,7 @@ const handleRequest = async (req, res) => {
18891
18892
  : json(res, 404, { error: "no such routine" });
18892
18893
  }
18893
18894
  if (path === "/api/routine-runs/seen-all" && method === "POST") {
18894
- return json(res, 200, { runs: routines.markAllSeen() });
18895
+ return json(res, 200, { runs: routines.markAllSeen((run) => routineVisible(run, visible)) });
18895
18896
  }
18896
18897
  const runMatch = path.match(/^\/api\/routine-runs\/([\w-]+)\/(cancel|seen)$/);
18897
18898
  if (runMatch && method === "POST") {
@@ -20901,11 +20902,9 @@ const handleRequest = async (req, res) => {
20901
20902
  if (!body || typeof body !== "object" || Array.isArray(body)) {
20902
20903
  return json(res, 400, { error: "body must be a JSON object" });
20903
20904
  }
20904
- if (auth.kind === "session" && !auth.scopes.includes("admin")) {
20905
- const field = clientBotPatchViolation(body);
20906
- if (field)
20907
- return json(res, 403, { error: `forbidden: this session may change how a bot looks, not "${field}" (needs the admin scope)` });
20908
- }
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)` });
20909
20908
  const existingBot = store.bot(m[1]);
20910
20909
  const builtinRefusal = builtinChibiPatchRefusal(existingBot, body, store.builtinChibi()) ?? personalPatchRefusal(existingBot, body);
20911
20910
  if (builtinRefusal)
@@ -22832,6 +22831,9 @@ const handleRequest = async (req, res) => {
22832
22831
  const current = store.projectBotForTask(m[1], m[2]);
22833
22832
  if (!current)
22834
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)` });
22835
22837
  const allowed = new Set(["title", "projectId", "modelSelection", "modelClass", "updateBotDefault", "resetApprovalToAsk", "approvalMode", "autoApprove", "requireAvailableModel", "pinnedMessageId", "acknowledgeLocalAuto", "archivedAt", "pinned", "surface"]);
22836
22838
  if (Object.keys(body).some((key) => !allowed.has(key)))
22837
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
+ }
@@ -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
+ }
@@ -4,6 +4,7 @@ import { VaultStore } from "./store.js";
4
4
  import { join } from "node:path";
5
5
  import { ROUTES } from "../routes/table.js";
6
6
  import { createVaultRoutes } from "./routes.js";
7
+ import { createVaultBotRoutes } from "./request.js";
7
8
  const keyMessage = z.object({ type: z.literal("atomic:native-vault-key"), ownerId: z.string().uuid(), key: z.string().regex(/^[0-9a-f]{64}$/) }).strict();
8
9
  /** Constructed by the server, bootstrapped only on Electron's private port.
9
10
  * No HTTP endpoint can unlock the vault or replace its owner. */
@@ -29,6 +30,8 @@ export class NativeVaultRuntime {
29
30
  return true;
30
31
  }
31
32
  store() { return this.#store; }
33
+ /** The owner whose items bots may be granted: set with the key, never from a request. */
34
+ ownerId() { return this.#ownerId; }
32
35
  /** Until paired owner identity is established, remote clients fail closed.
33
36
  * GET needs the desktop capability too; loopback alone is not authority. */
34
37
  owner(req, auth, desktopToken) {
@@ -40,9 +43,16 @@ export class NativeVaultRuntime {
40
43
  return this.#ownerId ?? "pending";
41
44
  }
42
45
  }
43
- /** Keep bootstrapping and route registration together, outside index.ts. */
44
- export function installNativeVault(dataDir, port, desktopToken, fromBot) {
46
+ /** Keep bootstrapping and route registration together, outside index.ts.
47
+ * Owner routes refuse every bot. The bot routes answer only the agents tools
48
+ * of a bot's own turn on this computer, never an external runtime. */
49
+ export function installNativeVault(dataDir, port, desktopToken, caller) {
45
50
  const runtime = new NativeVaultRuntime(join(dataDir, "providers", "native-vault"));
46
51
  port?.on("message", (event) => { runtime.receive(event?.data); });
47
- ROUTES.push(createVaultRoutes({ store: () => runtime.store(), owner: (req, auth) => fromBot(req) ? null : runtime.owner(req, auth, desktopToken()) }));
52
+ ROUTES.push(createVaultRoutes({ store: () => runtime.store(), owner: (req, auth) => caller(req) ? null : runtime.owner(req, auth, desktopToken()) }));
53
+ ROUTES.push(createVaultBotRoutes({ store: () => runtime.store(), ownerId: () => runtime.ownerId(),
54
+ bot: (req) => vaultBot(caller(req)), downloadDir: (botId) => join(dataDir, "vault-downloads", botId) }));
55
+ }
56
+ export function vaultBot(caller) {
57
+ return caller && caller.kind === "agents" && !caller.externalRuntime ? caller.botId : null;
48
58
  }
@@ -1,11 +1,13 @@
1
- // Native Vault persistence. No API/OAuth credentials are stored here.
2
- // The caller supplies a key from the trusted runtime; this module never
3
- // creates a plaintext key file or returns stored secrets to a model.
1
+ // Native Vault persistence. Atomic's own provider and OAuth credentials are
2
+ // not stored here. The caller supplies a key from the trusted runtime; this
3
+ // module never creates a plaintext key file or returns stored secrets to a
4
+ // model. `apiKeyFor` hands a saved API key to the trusted request executor
5
+ // only, after the grant, expiry and destination checks.
4
6
  import { createCipheriv, createDecipheriv, randomBytes, randomUUID } from "node:crypto";
5
7
  import { lstatSync, mkdirSync, readFileSync, rmdirSync } from "node:fs";
6
8
  import { join } from "node:path";
7
9
  import { z } from "zod";
8
- import { vaultInputSchema, vaultMetadata } from "../../shared/vault.js";
10
+ import { vaultInputSchema, vaultMetadata, vaultUseAllowed } from "../../shared/vault.js";
9
11
  import { writeFileAtomic } from "../atomic.js";
10
12
  const MAX_BYTES = 16 * 1024 * 1024;
11
13
  const MAX_ITEMS = 3000;
@@ -129,6 +131,22 @@ export class VaultStore {
129
131
  owner(ownerId);
130
132
  return this.read().filter((item) => item.ownerId === ownerId).map(vaultMetadata);
131
133
  }
134
+ /** The API keys this bot may use now: granted to it and not expired. */
135
+ apiKeysFor(ownerId, botId, now) {
136
+ owner(ownerId);
137
+ return this.read().filter((item) => item.kind === "apiKey" && item.ownerId === ownerId && item.botIds.includes(botId)
138
+ && (item.expiresAt === null || now < item.expiresAt)).map(vaultMetadata);
139
+ }
140
+ /** The header to send for one use, or null when this bot may not use this
141
+ * item at this destination now. For the request executor only: the value
142
+ * must never reach a response, a log or a model. */
143
+ apiKeyFor(actor, id, now) {
144
+ owner(actor.ownerId);
145
+ const item = this.read().find((candidate) => candidate.id === id);
146
+ if (!item || item.kind !== "apiKey" || !vaultUseAllowed(item, actor, now))
147
+ return null;
148
+ return { header: item.header, value: item.prefix + item.secret, secret: item.secret };
149
+ }
132
150
  create(ownerId, input) {
133
151
  owner(ownerId);
134
152
  const parsed = vaultInputSchema.safeParse(input);