@chibitek/chibi 0.1.209 → 0.1.210

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 (142) hide show
  1. package/dist/assets/{TerminalPanel-CHGq3udb.js → TerminalPanel-DxQoOfkY.js} +1 -1
  2. package/dist/assets/{abnfDiagram-O67JEVCF-BMaKhJ-b.js → abnfDiagram-O67JEVCF-Ds2qYdjS.js} +1 -1
  3. package/dist/assets/{arc-CYAiNWN8.js → arc-1O9tchZk.js} +1 -1
  4. package/dist/assets/{architectureDiagram-NJMV4G6O-CxJFFlbO.js → architectureDiagram-NJMV4G6O-CWuQ1x2F.js} +1 -1
  5. package/dist/assets/{blockDiagram-BEXU5L5S-C7AbPjRB.js → blockDiagram-BEXU5L5S-CNcEkXEx.js} +1 -1
  6. package/dist/assets/{c4Diagram-YGBWAQC7-DfVnCJmT.js → c4Diagram-YGBWAQC7-BKI_wi9I.js} +1 -1
  7. package/dist/assets/channel-CT5xRPK0.js +1 -0
  8. package/dist/assets/{chunk-2Q5K7J3B-CzAUFkgv.js → chunk-2Q5K7J3B-gO88emfN.js} +1 -1
  9. package/dist/assets/{chunk-3FUC2YCW-BgeBXphm.js → chunk-3FUC2YCW-DbKNT_-r.js} +2 -2
  10. package/dist/assets/{chunk-5VM5RSS4-DPRdTAXc.js → chunk-5VM5RSS4-BbJCoZVg.js} +1 -1
  11. package/dist/assets/{chunk-GTNCS2PH-BS-_dIVl.js → chunk-GTNCS2PH-DXurSCcp.js} +1 -1
  12. package/dist/assets/{chunk-GWA4HPMP-D6I7xMmd.js → chunk-GWA4HPMP-BWyt0I_m.js} +1 -1
  13. package/dist/assets/{chunk-JWPE2WC7-BKSKe7C9.js → chunk-JWPE2WC7-6iWSsogl.js} +1 -1
  14. package/dist/assets/{chunk-NETBCI7D-R48UYTRN.js → chunk-NETBCI7D-CFoqO9Hw.js} +1 -1
  15. package/dist/assets/{chunk-WEXAMYUT-C8z4mL-2.js → chunk-WEXAMYUT-BZEzAlNi.js} +1 -1
  16. package/dist/assets/{chunk-XXDRQBXY-Bml3ZRJ5.js → chunk-XXDRQBXY-W4hfC50f.js} +1 -1
  17. package/dist/assets/{classDiagram-v2-NBCMYWYE-w5wo22FO.js → classDiagram-v2-NBCMYWYE-BsGmL9e7.js} +1 -1
  18. package/dist/assets/{cose-bilkent-JH36ORCC-Cum9v--4.js → cose-bilkent-JH36ORCC-CYtTgIzk.js} +1 -1
  19. package/dist/assets/{cynefin-OW5HDTMX-BzN0-KsP.js → cynefin-OW5HDTMX-DLOi2Q2V.js} +1 -1
  20. package/dist/assets/{cynefinDiagram-VND7K2PF-CkOpm32D.js → cynefinDiagram-VND7K2PF-BXcXJ3hv.js} +1 -1
  21. package/dist/assets/{dagre-6A5THRUB-BItQkKZD.js → dagre-6A5THRUB-BdBOiuzt.js} +1 -1
  22. package/dist/assets/{diagram-22UHCM2B-BI0zDn7c.js → diagram-22UHCM2B-DCf3M4WE.js} +1 -1
  23. package/dist/assets/{diagram-3UASUU5V-jwcDxsu6.js → diagram-3UASUU5V-CzdF-UXi.js} +1 -1
  24. package/dist/assets/{diagram-ATOU4E4O-2RnY9egJ.js → diagram-ATOU4E4O-_UmmlMOD.js} +1 -1
  25. package/dist/assets/{diagram-CDSNMT55-eVdEZmEF.js → diagram-CDSNMT55-DrQODVuX.js} +1 -1
  26. package/dist/assets/{diagram-MLGK6HIB-BCDGCJJ0.js → diagram-MLGK6HIB-CE16iJlJ.js} +1 -1
  27. package/dist/assets/{diagram-MPIPVDR6-DtN5uO5w.js → diagram-MPIPVDR6-DJuTbhbP.js} +1 -1
  28. package/dist/assets/{ebnfDiagram-ZINNZB2B-B9GpXSEs.js → ebnfDiagram-ZINNZB2B-f1VEI2Po.js} +1 -1
  29. package/dist/assets/{elk-276RUBZZ-Bk_eaK4T.js → elk-276RUBZZ-BRbs9WzY.js} +1 -1
  30. package/dist/assets/{erDiagram-OPXOYQCR-BiGoW6C6.js → erDiagram-OPXOYQCR-DvMp_cQr.js} +1 -1
  31. package/dist/assets/{flowDiagram-KWPJA3E3-ZW5w0BaJ.js → flowDiagram-KWPJA3E3-CYS1A0fu.js} +1 -1
  32. package/dist/assets/{ganttDiagram-FUAMR5RP-yyrKgsx1.js → ganttDiagram-FUAMR5RP-qya_JE9x.js} +1 -1
  33. package/dist/assets/{gitGraphDiagram-X574FWY7-CeiDikzD.js → gitGraphDiagram-X574FWY7-ChMUJ3hH.js} +1 -1
  34. package/dist/assets/{index-CZGnshrJ.js → index-COH7BlyH.js} +196 -196
  35. package/dist/assets/index-H8vkXbLq.css +1 -0
  36. package/dist/assets/{index-DUFlRZuA.js → index-xE4Li_H2.js} +1 -1
  37. package/dist/assets/{infoDiagram-VRGFBTTK-q2B-KJFm.js → infoDiagram-VRGFBTTK-B2VudqsE.js} +1 -1
  38. package/dist/assets/{ishikawaDiagram-OU5B5YK6-D8gXFuc0.js → ishikawaDiagram-OU5B5YK6-Bdk47y0t.js} +1 -1
  39. package/dist/assets/{journeyDiagram-ZHPQQLJL-BmHL2mbq.js → journeyDiagram-ZHPQQLJL-A4StgNQ9.js} +1 -1
  40. package/dist/assets/{kanban-definition-PNTS6WVX-B9Ll2WkA.js → kanban-definition-PNTS6WVX-DZo45dQw.js} +1 -1
  41. package/dist/assets/{linear-CMVGYrKx.js → linear-D_rK-Ord.js} +1 -1
  42. package/dist/assets/{mermaid.core-qO11n1kV.js → mermaid.core-C7CvDDvz.js} +5 -5
  43. package/dist/assets/{mindmap-definition-NLK3R4M7-CxLGFX45.js → mindmap-definition-NLK3R4M7-6fmVPMyc.js} +1 -1
  44. package/dist/assets/{pegDiagram-GJSIUBJH-CxK1MJG4.js → pegDiagram-GJSIUBJH-CD4Qg24h.js} +1 -1
  45. package/dist/assets/{pieDiagram-5QR66LMP-H5jiF5Eu.js → pieDiagram-5QR66LMP-DmzQ883B.js} +1 -1
  46. package/dist/assets/{quadrantDiagram-O4NWA36T-CKaqCruv.js → quadrantDiagram-O4NWA36T-BW37utPZ.js} +1 -1
  47. package/dist/assets/{railroadDiagram-XR7U4H2S-BCzKiQOd.js → railroadDiagram-XR7U4H2S-CWXiMlAb.js} +1 -1
  48. package/dist/assets/{requirementDiagram-PLB6GJNP-Cqtr43DT.js → requirementDiagram-PLB6GJNP-DHSfr9U3.js} +1 -1
  49. package/dist/assets/{sankeyDiagram-IPEJSGJF-B2tQewX8.js → sankeyDiagram-IPEJSGJF-PebTt4eq.js} +1 -1
  50. package/dist/assets/{sequenceDiagram-PO4LG4MO-nggwQyrw.js → sequenceDiagram-PO4LG4MO-DPwp8fia.js} +1 -1
  51. package/dist/assets/{sizeCapture-INFHLROL-qSPXJBv2.js → sizeCapture-INFHLROL-BX_46o3S.js} +1 -1
  52. package/dist/assets/{stateDiagram-v2-GCMORJYK-DraPbL2T.js → stateDiagram-v2-GCMORJYK-W2e0RRrZ.js} +1 -1
  53. package/dist/assets/{swimlanes-2SLR337P-C6HVkIDA.js → swimlanes-2SLR337P-CkyXpQX9.js} +1 -1
  54. package/dist/assets/swimlanesDiagram-TC7HE7FX-BH9Yry0J.js +8 -0
  55. package/dist/assets/{timeline-definition-EJHVYXUP-DZmPRTsx.js → timeline-definition-EJHVYXUP-BS-sCjlN.js} +1 -1
  56. package/dist/assets/{usecaseDiagram-POWQR4AR-CsVuROW_.js → usecaseDiagram-POWQR4AR-BQre-k6x.js} +1 -1
  57. package/dist/assets/{vennDiagram-UO4OBE2U-B9IRbuhp.js → vennDiagram-UO4OBE2U-CEWCsi_s.js} +1 -1
  58. package/dist/assets/{wardleyDiagram-VNRHLVJA-CGmVK53n.js → wardleyDiagram-VNRHLVJA-CXUxqghG.js} +1 -1
  59. package/dist/assets/{xychartDiagram-PMCCYNJV-BAw-x9Y1.js → xychartDiagram-PMCCYNJV-DBgVMpwp.js} +1 -1
  60. package/dist/index.html +4 -2
  61. package/dist-server/accounts-proxy.js +19 -12
  62. package/dist-server/browser-proxy.js +19 -14
  63. package/dist-server/container-mcp.js +84 -12
  64. package/dist-server/drivers/agents-proxy.js +28 -13
  65. package/dist-server/drivers/phone-proxy.js +21 -13
  66. package/dist-server/index.js +3990 -2815
  67. package/dist-server/local-computer-proxy.js +77 -11
  68. package/dist-server/local-computer.js +2 -1
  69. package/dist-server/mcp-gate.js +53 -4
  70. package/dist-server/mcp-server.js +1 -1
  71. package/dist-server/openmausbot.js +443 -74
  72. package/dist-server/pair-cli.js +443 -74
  73. package/dist-server/server/accounts-proxy.js +3 -17
  74. package/dist-server/server/atomic-engine-release.js +7 -0
  75. package/dist-server/server/browser-proxy.js +3 -17
  76. package/dist-server/server/child-env.js +79 -0
  77. package/dist-server/server/config.js +11 -5
  78. package/dist-server/server/container-computer.js +1 -1
  79. package/dist-server/server/container-mcp.js +3 -2
  80. package/dist-server/server/control-client.js +7 -6
  81. package/dist-server/server/delegated-full-access.js +98 -0
  82. package/dist-server/server/desktop-loopback-gate.js +57 -0
  83. package/dist-server/server/drivers/acp/core.js +4 -4
  84. package/dist-server/server/drivers/acp/session-key.js +8 -0
  85. package/dist-server/server/drivers/agents-client.js +2 -14
  86. package/dist-server/server/drivers/gcloud-token.js +28 -0
  87. package/dist-server/server/drivers/github-copilot.js +152 -0
  88. package/dist-server/server/drivers/openai-chat-protocol.js +8 -0
  89. package/dist-server/server/drivers/openai-chat.js +10 -8
  90. package/dist-server/server/drivers/openai-compat.js +44 -9
  91. package/dist-server/server/drivers/phone-proxy.js +5 -18
  92. package/dist-server/server/engine-tiers.js +9 -9
  93. package/dist-server/server/harness/http.js +47 -1
  94. package/dist-server/server/index.js +54 -54
  95. package/dist-server/server/ladder-pick.js +18 -0
  96. package/dist-server/server/local-computer-proxy.js +3 -2
  97. package/dist-server/server/local-computer.js +1 -0
  98. package/dist-server/server/mcp-bridge.js +3 -2
  99. package/dist-server/server/mcp-gate.js +2 -1
  100. package/dist-server/server/mcp-registry.js +5 -1
  101. package/dist-server/server/model-gateway/failover.js +4 -1
  102. package/dist-server/server/model-gateway/route.js +64 -14
  103. package/dist-server/server/model-gateway/usage.js +66 -0
  104. package/dist-server/server/model-levels/aa-scale.js +42 -0
  105. package/dist-server/server/model-levels/aliases.js +16 -3
  106. package/dist-server/server/model-levels/index.js +8 -3
  107. package/dist-server/server/model-levels/rankings-build.js +76 -0
  108. package/dist-server/server/model-prices.js +6 -0
  109. package/dist-server/server/nexus-memory/index.js +5 -13
  110. package/dist-server/server/nexus-memory/policy.js +5 -17
  111. package/dist-server/server/oauth-account-vault.js +7 -2
  112. package/dist-server/server/provider-accounts.js +20 -1
  113. package/dist-server/server/provider-key-check.js +31 -1
  114. package/dist-server/server/registry-load.js +88 -0
  115. package/dist-server/server/request-auth.js +6 -28
  116. package/dist-server/server/routes/provider-accounts.js +124 -6
  117. package/dist-server/server/routine-daily-schedule.js +20 -0
  118. package/dist-server/server/routine-prompt-escape.js +18 -0
  119. package/dist-server/server/routine-tick-guard.js +16 -0
  120. package/dist-server/server/routine-tool-problems.js +36 -0
  121. package/dist-server/server/routines.js +36 -38
  122. package/dist-server/server/shutdown-triggers.js +18 -0
  123. package/dist-server/server/spend.js +23 -13
  124. package/dist-server/server/store.js +4 -13
  125. package/dist-server/server/terminal.js +2 -1
  126. package/dist-server/server/turn-token-file.js +79 -0
  127. package/dist-server/server/turn-token.js +23 -0
  128. package/dist-server/server/vps-container-mcp.js +3 -2
  129. package/dist-server/server/webhook-ingress.js +11 -1
  130. package/dist-server/server/webhook-prompt.js +82 -0
  131. package/dist-server/server/webhooks.js +8 -65
  132. package/dist-server/server/workspace-backup-policy.js +3 -3
  133. package/dist-server/server/workspace-backup.js +1 -1
  134. package/dist-server/server/workspace-time-zone.js +47 -0
  135. package/dist-server/shared/engine-choices.js +12 -1
  136. package/dist-server/shared/provider-accounts.js +114 -2
  137. package/dist-server/shared/zoned-time.js +55 -0
  138. package/dist-server/vps-container-mcp.js +84 -12
  139. package/package.json +1 -1
  140. package/dist/assets/channel-DxL_mLhm.js +0 -1
  141. package/dist/assets/index-Bi3hprmz.css +0 -1
  142. package/dist/assets/swimlanesDiagram-TC7HE7FX-gQUGsELo.js +0 -8
@@ -91,8 +91,8 @@ import { accountBilling } from "./plan-credit.js";
91
91
  import { appendUsage, isUsageOwnerFilter, parseUsageRange, readUsage, summarizeUsage, usageCsv, usageForOwner, USAGE_GROUPINGS, flushUsageLedger } from "./usage-ledger.js";
92
92
  import { GroupUsageReader } from "./group-thread-usage.js";
93
93
  import { ledgerCost } from "./model-prices.js";
94
- import { checkProviderKey, openAiTeamHeaders, PROVIDER_KEY_KINDS } from "./provider-key-check.js";
95
- import { assertWithinBudget, noteSpend, spendAlertText, spendState, takeSpendAlert } from "./spend.js";
94
+ import { checkProviderKey, configuredProviderUrls, openAiTeamHeaders, pastedKeyTestUrl, PROVIDER_KEY_KINDS } from "./provider-key-check.js";
95
+ import { assertWithinBudget, noteSpend, spendAlertText, spendState, takeSpendAlert, workspaceTimeZone, workspaceTimeZoneStatus } from "./spend.js";
96
96
  import { fleetAvailable, fleetRequest, fleetSocketPath } from "./fleet-client.js";
97
97
  import { HOSTED_CONTRACT_HEADER, HOSTED_CONTRACT_METADATA, HOSTED_CONTRACT_VERSION } from "./hosted-contract.js";
98
98
  import { describeSpawnFailure, execCli } from "./procs.js";
@@ -236,6 +236,7 @@ import { modelContextWindow } from "./model-context-window.js";
236
236
  import { autoPinMayYield, autoPinMovedLine, parseSurface, resolveSurface, surfaceLabel, surfaceOfComputerKind, surfacePrompt } from "./surface.js";
237
237
  import { PendingTurnCancellations, ProviderTurnGenerationRegistry, RetiredTurnRegistry, guardTurnDispatch, isTurnAdmissionBlocked, isTurnEventQuarantined, } from "./turn-dispatch-guard.js";
238
238
  import { createGracefulShutdown } from "./graceful-shutdown.js";
239
+ import { installShutdownTriggers } from "./shutdown-triggers.js";
239
240
  import { acquireDataDirLeaseForProcess } from "./data-dir-lease.js";
240
241
  import { createWorkspaceAccess, describeEdition, entitled, editionStatus, hostedWorkspaceConfiguration, hostedWorkspaceConfigured, editionForMembers, LICENSE_WARN_DAYS, licenseWarning, sharedWorkspaceFullAccessConfigured, loadEnterpriseLayer, workspaceMembership } from "./enterprise.js";
241
242
  import { environmentDescriptor, loadEnvironmentId, serverVersion } from "./environment.js";
@@ -247,7 +248,7 @@ import { allowedScopes, createEmailSignIn, parseAllowList } from "./account-sign
247
248
  import { ProviderAuthSessions } from "./provider-auth-sessions.js";
248
249
  import { clearSessionCookie, clientBotPatchViolation, bearerToken, clientGroupPatchViolation, clientTaskPatchViolation, isLoopbackHost, isProxied, labelFromUserAgent, requestOrigin, requestSource, requiredScope, resolveLoopbackTrust, resolveRequestAuth, parseCookies, serializeSessionCookie, sessionCookieName, } from "./request-auth.js";
249
250
  import { cookieMaxAgeSeconds, formatPairingCode, SessionRegistry } from "./sessions.js";
250
- import { writeAgentsTokenFile } from "./agents-token-file.js";
251
+ import { controlTurnToken, forgetThreadTurnTokens, turnTokenEnv, writeAgentsTokenFile } from "./turn-token-file.js";
251
252
  import { editorHasEntry, editorInstalled, editorTarget, editorTargets, registerWithEditor, unregisterFromEditor } from "./editor-connect.js";
252
253
  import { claudeCodeHasEntry, claudeCodeMcpEntry, registerWithClaudeCode, unregisterFromClaudeCode } from "./claude-code-connect.js";
253
254
  import { appendAssistantAudit, ASSISTANT_TOKEN_PREFIX, assistantSenderId, ConnectedAssistants, isAssistantSender, withAssistantProvenance, recentAssistantAudit, removeAssistantToken, writeAssistantToken } from "./connected-assistants.js";
@@ -260,7 +261,8 @@ import { DeviceRouteRegistry, removeStream } from "./device-routing.js";
260
261
  import { PHONE_SECRET_PROTOCOL_VERSION, PhoneSecretBridge, PhoneSecretError, PhoneSecretSubmissionRegistry, assertPhoneSecretRequestMatches, phoneSecretOperationId, } from "./phone-secret.js";
261
262
  // Keep these two last: a route module may import any server module, and
262
263
  // loading the table after everything above leaves module start-up order as is.
263
- import { json, onJsonBody, parsedBodyOf, readBody } from "./harness/http.js";
264
+ import { crossSiteMutation, json, onJsonBody, parsedBodyOf, readBody, staticHeaders } from "./harness/http.js";
265
+ import { DelegatedFullAccess, delegatedFullAccessActive, delegatedFullAccessLabel } from "./delegated-full-access.js";
264
266
  import { BotWorkModes, createBotWorkModeRoutes, ownBotApprovalMode, legacyGodModeCovers, dispatchWorkMode, trustedPlanChangeForStore, invalidAllThreadScope } from "./bot-work-modes.js";
265
267
  import { ROUTES, dispatchRoutes } from "./routes/table.js";
266
268
  import { createThreadStopRoutes } from "./routes/thread-stop.js";
@@ -279,7 +281,7 @@ import { totalmem } from "node:os";
279
281
  import { loadInstanceKeys } from "./instance-keys.js";
280
282
  import { createProviderAccountRoutes } from "./routes/provider-accounts.js";
281
283
  import { accountStops, failureRestScope, injectedModel, modelScope, restScope } from "./injected-model-rest.js";
282
- import { accountProvider } from "../shared/provider-accounts.js";
284
+ import { accountProvider, keylessAccount } from "../shared/provider-accounts.js";
283
285
  import { createAccountRoutes } from "./routes/accounts.js";
284
286
  import { installNativeVault } from "./vault/runtime.js";
285
287
  import { installWorkspaceSecrets } from "./workspace-backup-secrets.js";
@@ -300,7 +302,7 @@ import { createEngineTierRoutes } from "./routes/engine-tiers.js";
300
302
  import { createModelGatewayRoutes } from "./model-gateway/route.js";
301
303
  import { applyChibiDefaults, chibiDefaultSelection } from "./chibi-defaults.js";
302
304
  import { createPrimaryBotRoutes } from "./routes/primary-bot.js";
303
- import { EngineSnapshotCache, botTier, canDriveComputer, classLadder, engineAccount, engineHealth, engineLabel, engineTierClasses, engineTierLadders, failoverClassOrder, engineTiersIncludeFree, generateLadders, handlesClientData, ladderForClass, keyBased, needsDelegation, resolveFailover, resolveLadder } from "./engine-tiers.js";
305
+ import { EngineSnapshotCache, botTier, canDriveComputer, classLadder, engineAccount, engineHealth, engineLabel, engineTierClasses, engineTierLadders, failoverClassOrder, engineTiersIncludeFree, generateLadders, handlesClientData, ladderForClass, keyBased, needsDelegation, needsWiderWalk, resolveFailover, takeWider, resolveLadder } from "./engine-tiers.js";
304
306
  import { PRIMARY_BOT_THREAD_TITLE, PRIMARY_BOT_TRIGGER, PrimaryBotStore, routesAsSweep, PrimaryBotSweeper } from "./primary-bot.js";
305
307
  import { PRIMARY_BOT_LOCKED, primaryBotChoiceField, isPrimaryBot } from "../shared/primary-bot.js";
306
308
  import { moveIntoChibi } from "./move-into-chibi.js";
@@ -1580,8 +1582,7 @@ function agentsIntegration(botId, threadId, depth, skillAuthoring, generation, r
1580
1582
  roomCoordination,
1581
1583
  ownThreadCreation,
1582
1584
  });
1583
- // Also on disk, read per call: an engine keeps the proxy process across
1584
- // turns, so the spawn environment alone goes stale (agents-token-file.ts).
1585
+ // An engine keeps the proxy across turns: spawn env goes stale (turn-token-file.ts).
1585
1586
  const tokenFile = writeAgentsTokenFile(botId, threadId, token);
1586
1587
  return {
1587
1588
  command: process.execPath,
@@ -2094,7 +2095,7 @@ async function browserIntegration(botId, profile, turn) {
2094
2095
  kind: "browser", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 });
2095
2096
  return { profile: partitionId, session, spec, integration: {
2096
2097
  command: process.execPath, args: [SPAWNED_PROXIES.browser], env: {
2097
- ...AGENTS_NODE_FLAG, OMB_BROWSER_TOKEN: token, OMB_BROWSER_TOKEN_FILE: writeAgentsTokenFile(botId, turn.threadId, token, undefined, "browser"), OMB_HARNESS_URL: `http://127.0.0.1:${PORT}`,
2098
+ ...AGENTS_NODE_FLAG, ...turnTokenEnv("browser", "OMB_BROWSER_TOKEN", botId, turn.threadId, token), OMB_HARNESS_URL: `http://127.0.0.1:${PORT}`,
2098
2099
  },
2099
2100
  } };
2100
2101
  }
@@ -2125,7 +2126,7 @@ function phoneIntegration(botId, threadId, generation) {
2125
2126
  });
2126
2127
  const env = {
2127
2128
  ...AGENTS_NODE_FLAG,
2128
- OMB_PHONE_TOKEN: token, OMB_PHONE_TOKEN_FILE: writeAgentsTokenFile(botId, threadId, token, undefined, "phone"),
2129
+ ...turnTokenEnv("phone", "OMB_PHONE_TOKEN", botId, threadId, token),
2129
2130
  OMB_HARNESS_URL: `http://127.0.0.1:${PORT}`,
2130
2131
  };
2131
2132
  if (process.env.OMB_ADB_PATH)
@@ -2153,7 +2154,7 @@ function accountsIntegration(botId, threadId, generation) {
2153
2154
  return {
2154
2155
  command: process.execPath,
2155
2156
  args: [SPAWNED_PROXIES.accounts],
2156
- env: { ...AGENTS_NODE_FLAG, OMB_ACCOUNTS_TOKEN: token, OMB_ACCOUNTS_TOKEN_FILE: writeAgentsTokenFile(botId, threadId, token, undefined, "accounts"), OMB_HARNESS_URL: `http://127.0.0.1:${PORT}` },
2157
+ env: { ...AGENTS_NODE_FLAG, ...turnTokenEnv("accounts", "OMB_ACCOUNTS_TOKEN", botId, threadId, token), OMB_HARNESS_URL: `http://127.0.0.1:${PORT}` },
2157
2158
  readOnlyTools: ACCOUNT_TOOLS.filter((tool) => isReadOnlyAccountTool(tool.name)).map((tool) => tool.name),
2158
2159
  askTools: ACCOUNT_TOOLS.filter((tool) => !isReadOnlyAccountTool(tool.name)).map((tool) => tool.name),
2159
2160
  };
@@ -2222,7 +2223,7 @@ const routineRequestEnvelopeSchema = z.discriminatedUnion("action", [
2222
2223
  function controlIntegration(botId, threadId, generation, localVmTarget) {
2223
2224
  return {
2224
2225
  url: `http://127.0.0.1:${PORT}/api/internal/computer-control?botId=${encodeURIComponent(botId)}`,
2225
- token: mintInternalCapability({
2226
+ ...controlTurnToken(botId, threadId, localVmTarget, mintInternalCapability({
2226
2227
  botId,
2227
2228
  threadId,
2228
2229
  generation,
@@ -2233,7 +2234,7 @@ function controlIntegration(botId, threadId, generation, localVmTarget) {
2233
2234
  skillAuthoring: false,
2234
2235
  createdBots: 0,
2235
2236
  openedThreads: 0,
2236
- }),
2237
+ })),
2237
2238
  };
2238
2239
  }
2239
2240
  function askBotAndWait(targetBotId, message, depth, fromBotId, fromThreadId, targetThreadId) {
@@ -2351,7 +2352,7 @@ const tierCandidates = (described) => {
2351
2352
  // flat plan used through a key (the Qwen Coding Plan) is a subscription.
2352
2353
  // Ollama Team's included credit decides while it lasts (server/plan-credit.ts).
2353
2354
  const billing = accountBilling(instance.instanceId, configs[instance.instanceId], DATA_DIR);
2354
- return billing ? { ...instance, billing } : instance;
2355
+ return billing ? { ...instance, billing, ...(keylessAccount(configs[instance.instanceId]?.account) ? { keyless: true } : {}) } : instance;
2355
2356
  });
2356
2357
  };
2357
2358
  /** Engine tiers choose a turn's engine synchronously, from the engines as
@@ -3128,9 +3129,9 @@ function ladderTurnEngineChoice(profile, projected, threadId, needs, runOn, subs
3128
3129
  // unless that engine is resting.
3129
3130
  // An own engine that cannot drive the turn's computer is as good as resting.
3130
3131
  const ownOut = Boolean(own && (engineResting(own, projected.modelSelection.model) || !canDriveComputer(own, computer)));
3131
- if (resolution.choice?.band === "key" || (!resolution.choice && ownOut)) {
3132
+ if (needsWiderWalk(resolution.choice, ownOut)) {
3132
3133
  const across = wider(new Set(), plan.modelClass);
3133
- if (across.choice?.band === "subscription" || !resolution.choice)
3134
+ if (takeWider(resolution.choice, across.choice))
3134
3135
  resolution = across;
3135
3136
  }
3136
3137
  if (!resolution.choice && own && ownOut && !resolution.skipped.some((skip) => skip.reason === "paused")) {
@@ -3629,7 +3630,7 @@ function noteEngineBack(event) {
3629
3630
  const model = selection?.instanceId === instanceId ? selection.model : undefined;
3630
3631
  for (const scope of new Set([candidate ? restScope(candidate, model) : undefined, modelScope(model)]))
3631
3632
  engineRests.noteBack(instanceId, candidate ? engineAccount(candidate) : undefined, scope);
3632
- if (candidate && !keyBased(candidate) && !freeCandidate(candidate) && !(model && perTokenModel(candidate, model)))
3633
+ if (candidate && !keyBased(candidate) && !freeCandidate(candidate) && !(model && (perTokenModel(candidate, model) || injectedModel(model))))
3633
3634
  (instanceOwner(instanceId) === "personal" ? personalPayPerUse : payPerUse).subscriptionAnswered();
3634
3635
  }
3635
3636
  /** Rest a refused engine and continue on an eligible engine, or show an actionable line. */
@@ -4435,7 +4436,7 @@ function previewSystemPrompt(bot, opts = {}) {
4435
4436
  async function botOverview(bot) {
4436
4437
  const engine = registry.get(bot.modelSelection.instanceId)?.adapter.capabilities ?? null;
4437
4438
  const sectionPeers = reachablePeers(store.bots, bot).filter((peer) => !isPersonalBot(peer)).length;
4438
- const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
4439
+ const timeZone = workspaceTimeZone();
4439
4440
  // Same flush as GET /history: profile-change rows queue in
4440
4441
  // profile-versions.ts and land asynchronously, so a client checking the
4441
4442
  // overview right after causing a change must see its own row.
@@ -4496,9 +4497,14 @@ async function botOverview(bot) {
4496
4497
  const botWorkModes = new BotWorkModes(join(DATA_DIR, "bot-work-modes.json"));
4497
4498
  for (const id of botWorkModes.expired(id => sessions.isLive(id)))
4498
4499
  store.setAllThreadApprovalMode(id, "ask", true);
4500
+ const delegatedFull = new DelegatedFullAccess(join(DATA_DIR, "delegated-full-access.json"));
4501
+ for (const stale of delegatedFull.reconcile(store.bots, id => store.messagesFor(id)))
4502
+ store.patchTask(stale.botId, stale.threadId, { approvalMode: "ask", autoApprove: false, alwaysAllow: [] });
4499
4503
  const approvalModeForTurn = (bot, peerInitiated = false) => godModeElevates(bot) ? "full" : ownApprovalModeForTurn(bot, peerInitiated);
4500
- /** The bot's (or thread's) own level for a turn, GOD MODE aside. */
4501
- const ownApprovalModeForTurn = (bot, peerInitiated = false) => ownBotApprovalMode(bot, registry.cliTarget(bot.modelSelection.instanceId)?.driverKind, peerInitiated, botWorkModes.permits(approvalModeFor(bot)));
4504
+ /** The bot's (or thread's) own level for a turn, GOD MODE aside. A thread a
4505
+ * Chief delegated into is Full only while that Chief's conversation still is
4506
+ * (`derived`); nothing is saved on the thread, so it ends when the source does. */
4507
+ const ownApprovalModeForTurn = (bot, peerInitiated = false, derived = true) => derived && botWorkModes.permits("full") && delegatedFullAccessActive(bot.threadId, { source: id => delegatedFull.source(id), stillGrants: source => Boolean(store.bot(source.botId) && delegatedFullAccess(store.bot(source.botId), source.threadId, bot)) }) ? "full" : ownBotApprovalMode(bot, registry.cliTarget(bot.modelSelection.instanceId)?.driverKind, peerInitiated, botWorkModes.permits(approvalModeFor(bot)));
4502
4508
  function godModeCovers(bot) {
4503
4509
  return legacyGodModeCovers(bot, godModeActive() && botWorkModes.permits("full"), botWorkModes.selected(bot.id) !== undefined);
4504
4510
  }
@@ -4537,7 +4543,7 @@ function fullAccessForSource(botId, threadId, { ownLevel = false } = {}) {
4537
4543
  return false;
4538
4544
  const bot = store.projectBotForTask(botId, threadId) ?? owner.bot;
4539
4545
  // Origin changes Custom to Auto, never Full; no live-turn state is needed.
4540
- return (ownLevel ? ownApprovalModeForTurn(bot) : approvalModeForTurn(bot)) === "full";
4546
+ return (ownLevel ? ownApprovalModeForTurn(bot, false, false) : approvalModeForTurn(bot)) === "full";
4541
4547
  }
4542
4548
  function peerReviewRequired(bot, threadId) {
4543
4549
  return Boolean(bot.approvePeerComms && !peerApprovalWaived(bot.id, threadId));
@@ -4569,19 +4575,15 @@ function delegatedFullAccess(from, fromThreadId, target) {
4569
4575
  recipientDriverKind: registry.cliTarget(target.modelSelection.instanceId)?.driverKind,
4570
4576
  });
4571
4577
  }
4572
- /** Make a delegated thread Full and say so in it once, so the level the
4573
- * chip shows and the level the turns run at agree, and the person can see
4574
- * where the access came from. Idempotent: a pair conversation is reused
4575
- * across delegations and must not collect a chip per request. */
4576
- function grantDelegatedFullAccess(from, target, threadId) {
4577
- if (store.taskByThread(target.id, threadId)?.approvalMode === "full")
4578
+ /** Note the newest delegation into a thread: where its Full access comes
4579
+ * from, or that it has none. Nothing is written to the thread's own level.
4580
+ * The thread says where the access came from once per Chief. */
4581
+ function noteDelegatedFullAccess(from, fromThreadId, target, threadId) {
4582
+ if (!delegatedFullAccess(from, fromThreadId, target))
4583
+ return delegatedFull.clear(threadId);
4584
+ if (!delegatedFull.record(threadId, { botId: from.id, threadId: fromThreadId }))
4578
4585
  return;
4579
- store.patchTask(target.id, threadId, { approvalMode: "full", autoApprove: false, alwaysAllow: [] });
4580
- store.appendMessage(threadId, {
4581
- role: "bot",
4582
- kind: "activity",
4583
- tool: { name: `GOD MODE: delegated by ${from.name}, a Chief of Staff with GOD MODE`, ok: true },
4584
- });
4586
+ store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: delegatedFullAccessLabel(from.name), ok: true } });
4585
4587
  }
4586
4588
  /** The person a conversation is working for, by the name their messages
4587
4589
  * carry; the owner's profile name when the line names nobody. */
@@ -5851,6 +5853,7 @@ store.onChange((change) => {
5851
5853
  break;
5852
5854
  case "thread.deleted":
5853
5855
  directRequestOwners.delete(change.threadId);
5856
+ forgetThreadTurnTokens(change.threadId);
5854
5857
  routines?.forgetRoutineRequestReceiptsForThread(change.threadId);
5855
5858
  // A deleted destination must not strand an approval in an internal
5856
5859
  // task. Keep each run's snapshot and expose its execution as fallback.
@@ -7238,7 +7241,7 @@ async function mountBotVps(bot, owner, opts) {
7238
7241
  return {
7239
7242
  integration: {
7240
7243
  ...vpsMcp,
7241
- env: { ...vpsMcp.env, OMB_CONTROL_URL: vpsControl.url, OMB_CONTROL_TOKEN: vpsControl.token },
7244
+ env: { ...vpsMcp.env, OMB_CONTROL_URL: vpsControl.url, OMB_CONTROL_TOKEN: vpsControl.token, OMB_CONTROL_TOKEN_FILE: vpsControl.tokenFile },
7242
7245
  },
7243
7246
  };
7244
7247
  }
@@ -11202,7 +11205,7 @@ const commsBus = {
11202
11205
  };
11203
11206
  _loadPending();
11204
11207
  routines = new RoutineManager({
11205
- emit: broadcast,
11208
+ emit: broadcast, beforeSettle: () => syncMcpAuthState(),
11206
11209
  hasPendingDelegations: (threadId) => pendingThreads().includes(threadId) ||
11207
11210
  [...delegationWatch.values()].some((watch) => watch.sourceThreadId === threadId) ||
11208
11211
  pendingDelegationWakes.has(threadId),
@@ -11782,7 +11785,7 @@ async function resolveAndSendTeamSetup(res, args, ownerReview) {
11782
11785
  return true;
11783
11786
  }
11784
11787
  const ROUTINE_WEEKDAY_NAMES = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
11785
- const routineTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
11788
+ const routineTimeZone = () => workspaceTimeZone();
11786
11789
  const routineTimestamp = (value) => value !== undefined && Number.isFinite(value) ? new Date(value).toISOString() : null;
11787
11790
  const agentRoutine = (routine, latestRun) => {
11788
11791
  // Routines created in the calendar predate chat-card redaction and may
@@ -13657,7 +13660,7 @@ function botInterviewContext(mode) {
13657
13660
  }
13658
13661
  }
13659
13662
  return {
13660
- timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
13663
+ timeZone: workspaceTimeZone(),
13661
13664
  takenNames: store.bots.filter((bot) => !bot.hidden).map((bot) => bot.name),
13662
13665
  tools,
13663
13666
  accountProviders: accounts.storage === "unavailable" ? [] : accounts.providers.flatMap((provider) => provider.configured && provider.id !== "apple" ? [provider.id] : []),
@@ -14486,7 +14489,7 @@ function configStatus() {
14486
14489
  // whether this person sees Watch-Along (server/watch-along/access.ts)
14487
14490
  watchAlong: { access: watchAccess().allowed },
14488
14491
  // not a secret — the settings picker shows it; "" = follow the system
14489
- language: cfg.language ?? "",
14492
+ language: cfg.language ?? "", timeZone: workspaceTimeZoneStatus(),
14490
14493
  rooms: { turnTimeoutMinutes: roomTurnTimeoutMinutes(cfg) },
14491
14494
  // absent effort = no level is sent, so clients can tell it from any level
14492
14495
  newBots: cfg.newBots?.effort ? { effort: cfg.newBots.effort } : {},
@@ -14783,7 +14786,7 @@ function warmMcpToolHints(custom) {
14783
14786
  const mcpAuthState = new McpAuthStateStore(join(DATA_DIR, "mcp-auth-state.json"));
14784
14787
  const mcpHealth = new McpHealthStore();
14785
14788
  const mcpTurn = mcpTurnPolicy({ auth: mcpAuthState, health: mcpHealth, signalDir: mcpAuthSignalDir, specs: () => customMcpServers(cfg), credentialRefused: (name, spec) => mcpSignIn.refused(name, spec),
14786
- reportUnavailable: (threadId, detail) => { const bot = store.botByThread(threadId); if (bot)
14789
+ reportUnavailable: (threadId, detail) => { routines?.noteToolProblem(threadId, detail); const bot = store.botByThread(threadId); if (bot)
14787
14790
  reportIncident({ kind: "mcp-unavailable", bot, threadId, detail }); } });
14788
14791
  function syncMcpAuthState() { mcpTurn.sync(); }
14789
14792
  /** How a start runs an mcp-remote bridge: background starts never open a
@@ -15067,11 +15070,10 @@ const claudeUpdatesInFlight = new Set();
15067
15070
  function serveStatic(res, path) {
15068
15071
  if (!STATIC_DIR)
15069
15072
  return false;
15070
- const safe = path === "/" ? "/index.html" : path.replace(/\.\./g, "");
15071
- const file = join(STATIC_DIR, safe);
15073
+ const file = join(STATIC_DIR, path === "/" ? "/index.html" : path.replace(/\.\./g, ""));
15072
15074
  try {
15073
15075
  const data = readFileSync(file);
15074
- res.writeHead(200, { "content-type": MIME[extname(file)] ?? "application/octet-stream" });
15076
+ res.writeHead(200, staticHeaders(MIME[extname(file)] ?? "application/octet-stream"));
15075
15077
  res.end(data);
15076
15078
  return true;
15077
15079
  }
@@ -15079,7 +15081,7 @@ function serveStatic(res, path) {
15079
15081
  // SPA fallback
15080
15082
  try {
15081
15083
  const data = readFileSync(join(STATIC_DIR, "index.html"));
15082
- res.writeHead(200, { "content-type": "text/html" });
15084
+ res.writeHead(200, staticHeaders("text/html"));
15083
15085
  res.end(data);
15084
15086
  return true;
15085
15087
  }
@@ -16198,7 +16200,7 @@ const deliverableAccess = (senderId, auth) => sharedDeliverableAccess(sharedDeli
16198
16200
  canSeeGroup: auth ? (id) => visibleTo(viewerFor(auth)).group(id) : () => true,
16199
16201
  });
16200
16202
  ROUTES.push(createSharedDeliverablesRoutes(sharedDeliverables, () => deliverableAccess(undefined).sharedBlockedRoots ?? []));
16201
- ROUTES.push(createMessageFileRoutes({ store, attachments: ATTACHMENTS_DIR, workspaceDir, access: deliverableAccess }), createModelGatewayRoutes());
16203
+ ROUTES.push(createMessageFileRoutes({ store, attachments: ATTACHMENTS_DIR, workspaceDir, access: deliverableAccess }), createModelGatewayRoutes({ withinBudget: () => assertWithinBudget(cfg, DATA_DIR), book: bookTurnUsage }));
16202
16204
  ROUTES.push(createPinOrderRoutes({ store, visible: (auth) => visibleTo(viewerFor(auth)), personalHidden: personalBotHidden, fromBot: (req) => authorizedInternalCapability(req.headers.authorization) !== null }));
16203
16205
  // Linked repos: Settings > Repos, per-thread links and worktrees. See
16204
16206
  // server/routes/repos.ts for the routes and docs/chibitek/README.md.
@@ -16245,6 +16247,8 @@ const handleRequest = async (req, res) => {
16245
16247
  let m = null;
16246
16248
  let releaseWorkspaceRequest;
16247
16249
  try {
16250
+ if (crossSiteMutation(req))
16251
+ return json(res, 403, { error: "forbidden: cross-site request" });
16248
16252
  // Unlike the legacy reachability probe, this attests the running
16249
16253
  // server's portal-membership capability, including live entitlement.
16250
16254
  if (method === "GET" && path === "/api/health/hosted") {
@@ -18121,9 +18125,7 @@ const handleRequest = async (req, res) => {
18121
18125
  // shared by every assignment between two bots, so it names nobody.
18122
18126
  if (resolved.created && resolved.task.openedBy?.kind === "work")
18123
18127
  threadStarters.set(resolved.task.threadId, threadPersonKey(address.threadId));
18124
- if (delegatedFullAccess(internalSender, internalCapability.threadId, store.bot(target.botId))) {
18125
- grantDelegatedFullAccess(internalSender, store.bot(target.botId), target.threadId);
18126
- }
18128
+ noteDelegatedFullAccess(internalSender, internalCapability.threadId, store.bot(target.botId), target.threadId);
18127
18129
  }
18128
18130
  // A teammate's conversation gets the delegator's repos; a room
18129
18131
  // thread keeps the room's own links.
@@ -18413,8 +18415,7 @@ const handleRequest = async (req, res) => {
18413
18415
  applyDelegatedRepos(task.threadId, repos.ids);
18414
18416
  // The work is still for the person whose request the opener is on.
18415
18417
  threadStarters.set(task.threadId, threadPersonKey(fromThreadId));
18416
- if (delegatedFullAccess(from, fromThreadId, target))
18417
- grantDelegatedFullAccess(from, target, task.threadId);
18418
+ noteDelegatedFullAccess(from, fromThreadId, target, task.threadId);
18418
18419
  const queued = queueDelegation(commsBus, from, { toBotId: target.id, message, depth, targetThreadId: task.threadId, ...(verified.authorizations.length ? { authorizations: verified.authorizations } : {}) }, MAX_COMMS_DEPTH, fromThreadId);
18419
18420
  if (queued.result !== "ok" || !queued.id) {
18420
18421
  // nothing will ever run there: take the row back before the person
@@ -23520,10 +23521,10 @@ const handleRequest = async (req, res) => {
23520
23521
  return json(res, 400, { error: "No key to test. Paste one or save one first." });
23521
23522
  if (key.length > 512)
23522
23523
  return json(res, 400, { error: "That does not look like an API key." });
23523
- const url = typeof body?.url === "string" && body.url.trim() ? body.url.trim() : (saved && "url" in saved ? saved.url : undefined);
23524
+ const asked = pastedKeyTestUrl(body, configuredProviderUrls(cfg)), url = asked ?? (saved && "url" in saved ? saved.url : undefined);
23524
23525
  // The workspace connection's OpenAI organization and project go along,
23525
23526
  // so a team key is checked the way turns will use it.
23526
- const headers = kind === "openaiCompat" && !body?.url ? openAiTeamHeaders(cfg.openaiCompat ?? {}) : undefined;
23527
+ const headers = kind === "openaiCompat" && !asked ? openAiTeamHeaders(cfg.openaiCompat ?? {}) : undefined;
23527
23528
  res.setHeader("cache-control", "no-store");
23528
23529
  return json(res, 200, await checkProviderKey({ provider: kind, key, url, ...(headers ? { headers } : {}) }));
23529
23530
  }
@@ -25484,9 +25485,8 @@ const gracefulShutdown = createGracefulShutdown({
25484
25485
  process.exit(code);
25485
25486
  },
25486
25487
  });
25487
- for (const signal of ["SIGINT", "SIGTERM"]) {
25488
- process.on(signal, gracefulShutdown);
25489
- }
25488
+ // The desktop asks over the parent port: Windows delivers no signal to a child.
25489
+ installShutdownTriggers(process, utilityParentPort, gracefulShutdown);
25490
25490
  // Last line of defence for every exit, including an uncaught exception, which
25491
25491
  // skips gracefulShutdown entirely: an orphaned browser daemon keeps running
25492
25492
  // from the app bundle and (on macOS) blocks the next update's install.
@@ -0,0 +1,18 @@
1
+ /** Whether the class-aware walk is worth running: the ladder found no
2
+ * subscription (a free model, a key, or nothing while the thread's own
3
+ * engine is out). */
4
+ export function needsWiderWalk(first, ownOut) {
5
+ return first ? first.band !== "subscription" : ownOut;
6
+ }
7
+ /** Whether the class-aware pick replaces the ladder's: always when the ladder
8
+ * found nothing; a subscription always beats a free model or a key; a free
9
+ * model picked in class order beats one picked by the order it was added. */
10
+ export function takeWider(first, wider) {
11
+ if (!first)
12
+ return true;
13
+ if (first.band === "subscription" || !wider)
14
+ return false;
15
+ if (wider.band === "subscription")
16
+ return true;
17
+ return first.band === "free" && wider.band === "free";
18
+ }
@@ -2,7 +2,8 @@
2
2
  // travel in environment variables, never command-line arguments or logs.
3
3
  import { runMcpBridge } from "./mcp-bridge.js";
4
4
  import { augmentedPath } from "./env-path.js";
5
- const { OMB_CUA_COMMAND: command, OMB_CUA_ARGS: encodedArgs, OMB_CONTROL_URL: url, OMB_CONTROL_TOKEN: token, ...childEnv } = process.env;
5
+ import { turnTokenReader } from "./turn-token.js";
6
+ const { OMB_CUA_COMMAND: command, OMB_CUA_ARGS: encodedArgs, OMB_CONTROL_URL: url, OMB_CONTROL_TOKEN: token, OMB_CONTROL_TOKEN_FILE: _tokenFile, ...childEnv } = process.env;
6
7
  let args;
7
8
  try {
8
9
  const parsed = JSON.parse(encodedArgs ?? "");
@@ -24,5 +25,5 @@ runMcpBridge({
24
25
  args,
25
26
  env: { ...childEnv, PATH: augmentedPath() },
26
27
  label: "Local Cua Driver",
27
- gate: { url: url, token: token },
28
+ gate: { url: url, token: turnTokenReader(process.env, "OMB_CONTROL_TOKEN") },
28
29
  });
@@ -32,6 +32,7 @@ export function gatedLocalComputer(connection, control) {
32
32
  OMB_CUA_ARGS: JSON.stringify(connection.args),
33
33
  OMB_CONTROL_URL: control.url,
34
34
  OMB_CONTROL_TOKEN: control.token,
35
+ ...(control.tokenFile ? { OMB_CONTROL_TOKEN_FILE: control.tokenFile } : {}),
35
36
  },
36
37
  };
37
38
  }
@@ -4,6 +4,7 @@ import { dirname } from "node:path";
4
4
  import { StringDecoder } from "node:string_decoder";
5
5
  import { writeFileAtomic } from "./atomic.js";
6
6
  import { CONTROL_REFUSAL_PLAIN, createControlClient } from "./control-client.js";
7
+ import { childEnv } from "./child-env.js";
7
8
  import { augmentedPath } from "./env-path.js";
8
9
  import { createToolListNormalizer } from "./mcp-tool-schema.js";
9
10
  // 45s of TOTAL silence before the bridge even probes. An MCP session is
@@ -20,7 +21,7 @@ export function runLivenessProbe(probe, timeoutMs = PROBE_TIMEOUT_MS) {
20
21
  return new Promise((resolve) => {
21
22
  const child = spawnCommand(probe.command, probe.args, {
22
23
  shell: false,
23
- env: { ...process.env, PATH: augmentedPath() },
24
+ env: childEnv(process.env, { PATH: augmentedPath() }),
24
25
  stdio: ["ignore", "ignore", "ignore"],
25
26
  });
26
27
  const timer = setTimeout(() => {
@@ -333,7 +334,7 @@ export function runMcpBridge(options) {
333
334
  // npx, uvx and friends are .cmd shims on Windows: spawnCommand runs them.
334
335
  const started = spawnCommand(options.command, options.args, {
335
336
  shell: false,
336
- env: options.env ?? { ...process.env, PATH: augmentedPath() },
337
+ env: options.env ?? childEnv(process.env, { PATH: augmentedPath() }),
337
338
  stdio: ["pipe", "pipe", "pipe"],
338
339
  });
339
340
  child = started;
@@ -20,6 +20,7 @@ import { spawn } from "node:child_process";
20
20
  import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
21
21
  import { join } from "node:path";
22
22
  import { createInterface } from "node:readline";
23
+ import { childEnv as upstreamEnv } from "./child-env.js";
23
24
  import { resolveCliSpawn } from "./env-path.js";
24
25
  import { planOptions } from "./spawn-command.js";
25
26
  import { DEFAULT_RESULT_BUDGET, trimResultText, trimStructured } from "./mcp-trim.js";
@@ -142,7 +143,7 @@ function trimCallResult(result, tool) {
142
143
  const spec = upstreamSpec();
143
144
  if (SPILL_DIR)
144
145
  sweepSpill(SPILL_DIR);
145
- const childEnv = { ...process.env, ...spec.env };
146
+ const childEnv = upstreamEnv(process.env, spec.env);
146
147
  for (const key of GATE_ENV_KEYS)
147
148
  delete childEnv[key];
148
149
  // The CLI used to spawn this server itself, on every platform, so the gate
@@ -14,7 +14,11 @@ export function mcpReadOnlyAutoAllow(raw, name) {
14
14
  export function isRemoteMcpServer(server) {
15
15
  return "url" in server;
16
16
  }
17
- export const MAX_MCP_SERVERS = 20;
17
+ /** A guard against a runaway config, not a budget: a person may add as many
18
+ * servers as they use (Erick, 2026-11-22, "remove this limitation"). An
19
+ * engine that takes fewer per session is capped by its own driver
20
+ * (AcpSupport.mcpServerLimit: Hermes 16), never by refusing to add one. */
21
+ export const MAX_MCP_SERVERS = 500;
18
22
  const MAX_ARGS = 64;
19
23
  const MAX_ENV = 64;
20
24
  const MAX_HEADERS = 32;
@@ -17,7 +17,7 @@ export class GatewayRests {
17
17
  rest(model, ms = REST_MS) { this.until.set(model, this.now() + ms); }
18
18
  resting = (model) => (this.until.get(model) ?? 0) > this.now();
19
19
  }
20
- export async function firstAnswer(models, send, rests) {
20
+ export async function firstAnswer(models, send, rests, gone) {
21
21
  const failovers = [];
22
22
  let last = { status: 404, error: "No model is available behind Atomic right now. Start Ollama, or sign in to Ollama for its cloud models." };
23
23
  for (const model of models) {
@@ -27,6 +27,9 @@ export async function firstAnswer(models, send, rests) {
27
27
  }
28
28
  catch (error) {
29
29
  failovers.push(model);
30
+ // The caller hung up: there is no one left to try the next model for.
31
+ if (gone?.aborted)
32
+ return { ok: false, status: 499, error: "The caller went away.", failovers };
30
33
  last = { status: 502, error: `Ollama did not answer (${error.message}).` };
31
34
  continue;
32
35
  }
@@ -12,12 +12,31 @@
12
12
  // answers every other GET path.
13
13
  import { Readable } from "node:stream";
14
14
  import { hostApiKey, localHost } from "../drivers/local-inject.js";
15
+ import { DEFAULT_IDLE_TIMEOUT_MS } from "../drivers/openai-compat.js";
15
16
  import { PASS } from "../routes/table.js";
16
17
  import { firstAnswer, GatewayRests } from "./failover.js";
17
18
  import { ATOMIC_AUTO_GATEWAY_MODEL, modelsFor } from "./ladder.js";
19
+ import { usageMeter } from "./usage.js";
18
20
  const PREFIX = "/api/v1/";
19
21
  const PASS_THROUGH = new Set(["responses", "chat/completions", "messages"]);
20
22
  const MAX_BODY = 32 * 1024 * 1024;
23
+ const LOG_MAX = 120;
24
+ /** A caller's string made safe for one log line: printable ASCII, bounded. */
25
+ export function forLog(value) {
26
+ return value.slice(0, LOG_MAX).replace(/[^\x20-\x7e]/g, "?") + (value.length > LOG_MAX ? "..." : "");
27
+ }
28
+ /** Aborts when nothing has arrived for `ms`; `touch` on every byte. */
29
+ function idleWatch(ms) {
30
+ const controller = new AbortController();
31
+ let timer;
32
+ const clear = () => clearTimeout(timer);
33
+ const touch = () => {
34
+ clear();
35
+ timer = setTimeout(() => controller.abort(new Error(`no answer in ${Math.round(ms / 1000)} seconds`)), ms);
36
+ };
37
+ touch();
38
+ return { signal: controller.signal, touch, clear };
39
+ }
21
40
  const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1", "localhost"]);
22
41
  /** The socket and the Host header both name this computer. */
23
42
  export function fromLoopback(remoteAddress, host) {
@@ -37,12 +56,13 @@ export function createModelGatewayRoutes(deps = {}) {
37
56
  const rests = deps.rests ?? new GatewayRests();
38
57
  const log = deps.log ?? ((line) => console.info(line));
39
58
  const upstream = () => (deps.upstream ?? ollama)();
40
- async function served() {
59
+ const idleMs = deps.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
60
+ async function served(gone) {
41
61
  const base = upstream();
42
62
  if (!base)
43
63
  return [];
44
64
  try {
45
- const res = await fetchImpl(`${base.baseUrl}/models`, { headers: base.apiKey ? { authorization: `Bearer ${base.apiKey}` } : {}, signal: AbortSignal.timeout(5_000) });
65
+ const res = await fetchImpl(`${base.baseUrl}/models`, { headers: base.apiKey ? { authorization: `Bearer ${base.apiKey}` } : {}, signal: AbortSignal.any([AbortSignal.timeout(5_000), gone]) });
46
66
  const body = res.ok ? await res.json() : {};
47
67
  return (body.data ?? []).map((row) => row.id).filter((id) => typeof id === "string" && id.length > 0);
48
68
  }
@@ -60,7 +80,18 @@ export function createModelGatewayRoutes(deps = {}) {
60
80
  return json(res, 403, { error: "Atomic's model source answers only on this computer." });
61
81
  if (auth.kind !== "assistant")
62
82
  return json(res, 401, { error: "Send a connected assistant's token from Atomic Settings → Connected assistants." });
63
- const available = await served();
83
+ if (method === "POST") {
84
+ try {
85
+ deps.withinBudget?.();
86
+ }
87
+ catch (error) {
88
+ return json(res, 409, { error: error instanceof Error ? error.message : String(error), code: "spend_cap" });
89
+ }
90
+ }
91
+ // A caller that hangs up takes its upstream request with it.
92
+ const closed = new AbortController();
93
+ res.on("close", () => closed.abort());
94
+ const available = await served(closed.signal);
64
95
  if (tail === "models") {
65
96
  const ids = [ATOMIC_AUTO_GATEWAY_MODEL, ...available];
66
97
  return json(res, 200, { object: "list", data: ids.map((id) => ({ id, object: "model", owned_by: id === ATOMIC_AUTO_GATEWAY_MODEL ? "atomic" : "ollama", ...(id === ATOMIC_AUTO_GATEWAY_MODEL ? { display_name: "Atomic Engine (Auto)" } : {}) })) });
@@ -85,20 +116,39 @@ export function createModelGatewayRoutes(deps = {}) {
85
116
  headers["x-api-key"] = base.apiKey ?? "ollama";
86
117
  headers["anthropic-version"] = String(req.headers["anthropic-version"] ?? "2023-06-01");
87
118
  }
88
- const answer = await firstAnswer(models, (model) => fetchImpl(`${base.baseUrl}/${tail}`, { method: "POST", headers, body: JSON.stringify({ ...body, model }) }), rests);
89
- log(`[model-gateway] ${tail} asked=${asked} used=${answer.ok ? answer.model : "none"} failovers=${answer.failovers.join(",") || "none"}`);
119
+ let watch;
120
+ const send = (model) => {
121
+ watch?.clear();
122
+ watch = idleWatch(idleMs);
123
+ return fetchImpl(`${base.baseUrl}/${tail}`, { method: "POST", headers, body: JSON.stringify({ ...body, model }), signal: AbortSignal.any([closed.signal, watch.signal]) });
124
+ };
125
+ const answer = await firstAnswer(models, send, rests, closed.signal);
126
+ log(`[model-gateway] ${tail} asked=${forLog(asked)} used=${answer.ok ? forLog(answer.model) : "none"} failovers=${forLog(answer.failovers.join(",")) || "none"}`);
127
+ if (closed.signal.aborted)
128
+ return void watch?.clear();
90
129
  if (!answer.ok)
91
- return json(res, answer.status === 404 ? 503 : answer.status, { error: answer.error });
130
+ return void (watch?.clear(), json(res, answer.status === 404 ? 503 : answer.status, { error: answer.error }));
92
131
  const type = answer.response.headers.get("content-type") ?? "application/json";
93
- res.writeHead(answer.response.status, { "content-type": type, "cache-control": "no-cache", "x-atomic-model": answer.model });
94
- if (!answer.response.body)
95
- return void res.end();
132
+ const meter = usageMeter(type);
133
+ res.writeHead(answer.response.status, { "content-type": type, "cache-control": "no-cache", "x-atomic-model": forLog(answer.model) });
96
134
  // Past the first byte there is no failing over: the harness has started reading.
97
- await new Promise((resolve) => {
98
- const stream = Readable.fromWeb(answer.response.body);
99
- stream.on("error", () => { res.destroy(); resolve(); });
100
- res.on("close", () => { stream.destroy(); resolve(); });
101
- stream.pipe(res).on("finish", () => resolve());
135
+ if (answer.response.body)
136
+ await new Promise((resolve) => {
137
+ const stream = Readable.fromWeb(answer.response.body);
138
+ stream.on("data", (chunk) => { watch?.touch(); meter.push(chunk); });
139
+ stream.on("error", () => { res.destroy(); resolve(); });
140
+ res.on("close", () => { stream.destroy(); resolve(); });
141
+ stream.pipe(res).on("finish", () => resolve());
142
+ });
143
+ else
144
+ res.end();
145
+ watch?.clear();
146
+ if (!answer.response.ok)
147
+ return;
148
+ const usage = meter.total();
149
+ deps.book?.({
150
+ botId: `assistant:${auth.assistant.id}`, botName: auth.assistant.label, threadId: "model-gateway", instanceId: "ollama", driverKind: "ollama",
151
+ model: answer.model, input: usage?.input ?? 0, output: usage?.output ?? 0, costUsd: null, trigger: { kind: "owner" }, source: "atomic/auto",
102
152
  });
103
153
  };
104
154
  }