@chibitek/chibi 0.1.208 → 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.
- package/dist/assets/{TerminalPanel-B5bwdaJ5.js → TerminalPanel-DxQoOfkY.js} +1 -1
- package/dist/assets/{abnfDiagram-O67JEVCF-BLKuHvdS.js → abnfDiagram-O67JEVCF-Ds2qYdjS.js} +1 -1
- package/dist/assets/{arc-BeOf3Y3d.js → arc-1O9tchZk.js} +1 -1
- package/dist/assets/{architectureDiagram-NJMV4G6O-DnXr729a.js → architectureDiagram-NJMV4G6O-CWuQ1x2F.js} +1 -1
- package/dist/assets/{blockDiagram-BEXU5L5S-CEiwrTaI.js → blockDiagram-BEXU5L5S-CNcEkXEx.js} +1 -1
- package/dist/assets/{c4Diagram-YGBWAQC7-C0-29khR.js → c4Diagram-YGBWAQC7-BKI_wi9I.js} +1 -1
- package/dist/assets/channel-CT5xRPK0.js +1 -0
- package/dist/assets/{chunk-2Q5K7J3B-D8dKbbui.js → chunk-2Q5K7J3B-gO88emfN.js} +1 -1
- package/dist/assets/{chunk-3FUC2YCW-fAEY1oOe.js → chunk-3FUC2YCW-DbKNT_-r.js} +2 -2
- package/dist/assets/{chunk-5VM5RSS4-Djza4B4b.js → chunk-5VM5RSS4-BbJCoZVg.js} +1 -1
- package/dist/assets/{chunk-GTNCS2PH-BWFGSXNt.js → chunk-GTNCS2PH-DXurSCcp.js} +1 -1
- package/dist/assets/{chunk-GWA4HPMP-BGo5oevY.js → chunk-GWA4HPMP-BWyt0I_m.js} +1 -1
- package/dist/assets/{chunk-JWPE2WC7-DIdxOMOn.js → chunk-JWPE2WC7-6iWSsogl.js} +1 -1
- package/dist/assets/{chunk-NETBCI7D-Dc4tJ9uD.js → chunk-NETBCI7D-CFoqO9Hw.js} +1 -1
- package/dist/assets/{chunk-WEXAMYUT-DvZ9F5yw.js → chunk-WEXAMYUT-BZEzAlNi.js} +1 -1
- package/dist/assets/{chunk-XXDRQBXY-BYUVYcxq.js → chunk-XXDRQBXY-W4hfC50f.js} +1 -1
- package/dist/assets/{classDiagram-v2-NBCMYWYE-BtnsJQvT.js → classDiagram-v2-NBCMYWYE-BsGmL9e7.js} +1 -1
- package/dist/assets/{cose-bilkent-JH36ORCC-DLDe1VHc.js → cose-bilkent-JH36ORCC-CYtTgIzk.js} +1 -1
- package/dist/assets/{cynefin-OW5HDTMX-a1GJE5iI.js → cynefin-OW5HDTMX-DLOi2Q2V.js} +1 -1
- package/dist/assets/{cynefinDiagram-VND7K2PF-DXxGLDlQ.js → cynefinDiagram-VND7K2PF-BXcXJ3hv.js} +1 -1
- package/dist/assets/{dagre-6A5THRUB-DAW_YZe9.js → dagre-6A5THRUB-BdBOiuzt.js} +1 -1
- package/dist/assets/{diagram-22UHCM2B-oq3saywD.js → diagram-22UHCM2B-DCf3M4WE.js} +1 -1
- package/dist/assets/{diagram-3UASUU5V-BhCP3hS9.js → diagram-3UASUU5V-CzdF-UXi.js} +1 -1
- package/dist/assets/{diagram-ATOU4E4O-ByFRn1dW.js → diagram-ATOU4E4O-_UmmlMOD.js} +1 -1
- package/dist/assets/{diagram-CDSNMT55-DWoCvkNH.js → diagram-CDSNMT55-DrQODVuX.js} +1 -1
- package/dist/assets/{diagram-MLGK6HIB-CSH5kSlk.js → diagram-MLGK6HIB-CE16iJlJ.js} +1 -1
- package/dist/assets/{diagram-MPIPVDR6-Cnpx1s-T.js → diagram-MPIPVDR6-DJuTbhbP.js} +1 -1
- package/dist/assets/{ebnfDiagram-ZINNZB2B-DPmX63Vg.js → ebnfDiagram-ZINNZB2B-f1VEI2Po.js} +1 -1
- package/dist/assets/{elk-276RUBZZ-DUtmO9kb.js → elk-276RUBZZ-BRbs9WzY.js} +1 -1
- package/dist/assets/{erDiagram-OPXOYQCR-SxwJeJu-.js → erDiagram-OPXOYQCR-DvMp_cQr.js} +1 -1
- package/dist/assets/{flowDiagram-KWPJA3E3--QZAAUjB.js → flowDiagram-KWPJA3E3-CYS1A0fu.js} +1 -1
- package/dist/assets/{ganttDiagram-FUAMR5RP-CRz6i2Pe.js → ganttDiagram-FUAMR5RP-qya_JE9x.js} +1 -1
- package/dist/assets/{gitGraphDiagram-X574FWY7-Dx9Cisl2.js → gitGraphDiagram-X574FWY7-ChMUJ3hH.js} +1 -1
- package/dist/assets/{index-vIsgWbJW.js → index-COH7BlyH.js} +196 -196
- package/dist/assets/index-H8vkXbLq.css +1 -0
- package/dist/assets/{index-BGkOob08.js → index-xE4Li_H2.js} +1 -1
- package/dist/assets/{infoDiagram-VRGFBTTK-CDLogk8N.js → infoDiagram-VRGFBTTK-B2VudqsE.js} +1 -1
- package/dist/assets/{ishikawaDiagram-OU5B5YK6-DsrF1wno.js → ishikawaDiagram-OU5B5YK6-Bdk47y0t.js} +1 -1
- package/dist/assets/{journeyDiagram-ZHPQQLJL-DUi8LEA6.js → journeyDiagram-ZHPQQLJL-A4StgNQ9.js} +1 -1
- package/dist/assets/{kanban-definition-PNTS6WVX-BAdWXobw.js → kanban-definition-PNTS6WVX-DZo45dQw.js} +1 -1
- package/dist/assets/{linear-Dha948ns.js → linear-D_rK-Ord.js} +1 -1
- package/dist/assets/{mermaid.core-BqT1aUP9.js → mermaid.core-C7CvDDvz.js} +5 -5
- package/dist/assets/{mindmap-definition-NLK3R4M7-XS1wDQ80.js → mindmap-definition-NLK3R4M7-6fmVPMyc.js} +1 -1
- package/dist/assets/{pegDiagram-GJSIUBJH-BphuafcF.js → pegDiagram-GJSIUBJH-CD4Qg24h.js} +1 -1
- package/dist/assets/{pieDiagram-5QR66LMP-JN9mbdiU.js → pieDiagram-5QR66LMP-DmzQ883B.js} +1 -1
- package/dist/assets/{quadrantDiagram-O4NWA36T-CkBF7Woa.js → quadrantDiagram-O4NWA36T-BW37utPZ.js} +1 -1
- package/dist/assets/{railroadDiagram-XR7U4H2S-Ie1GVpj5.js → railroadDiagram-XR7U4H2S-CWXiMlAb.js} +1 -1
- package/dist/assets/{requirementDiagram-PLB6GJNP-B8xGM6w4.js → requirementDiagram-PLB6GJNP-DHSfr9U3.js} +1 -1
- package/dist/assets/{sankeyDiagram-IPEJSGJF-BgTSlqMg.js → sankeyDiagram-IPEJSGJF-PebTt4eq.js} +1 -1
- package/dist/assets/{sequenceDiagram-PO4LG4MO-B1J4EIne.js → sequenceDiagram-PO4LG4MO-DPwp8fia.js} +1 -1
- package/dist/assets/{sizeCapture-INFHLROL-Cpcjc5oE.js → sizeCapture-INFHLROL-BX_46o3S.js} +1 -1
- package/dist/assets/{stateDiagram-v2-GCMORJYK-CtQKYLT4.js → stateDiagram-v2-GCMORJYK-W2e0RRrZ.js} +1 -1
- package/dist/assets/{swimlanes-2SLR337P-DpIk02zs.js → swimlanes-2SLR337P-CkyXpQX9.js} +1 -1
- package/dist/assets/swimlanesDiagram-TC7HE7FX-BH9Yry0J.js +8 -0
- package/dist/assets/{timeline-definition-EJHVYXUP-DsA7dQhy.js → timeline-definition-EJHVYXUP-BS-sCjlN.js} +1 -1
- package/dist/assets/{usecaseDiagram-POWQR4AR-BM42_rDz.js → usecaseDiagram-POWQR4AR-BQre-k6x.js} +1 -1
- package/dist/assets/{vennDiagram-UO4OBE2U-DgLtqgJF.js → vennDiagram-UO4OBE2U-CEWCsi_s.js} +1 -1
- package/dist/assets/{wardleyDiagram-VNRHLVJA-BKUUTKBJ.js → wardleyDiagram-VNRHLVJA-CXUxqghG.js} +1 -1
- package/dist/assets/{xychartDiagram-PMCCYNJV-B9RWvizV.js → xychartDiagram-PMCCYNJV-DBgVMpwp.js} +1 -1
- package/dist/index.html +4 -2
- package/dist-server/accounts-proxy.js +19 -12
- package/dist-server/browser-proxy.js +19 -14
- package/dist-server/container-mcp.js +84 -12
- package/dist-server/drivers/agents-proxy.js +28 -13
- package/dist-server/drivers/phone-proxy.js +21 -13
- package/dist-server/index.js +4000 -2834
- package/dist-server/local-computer-proxy.js +77 -11
- package/dist-server/local-computer.js +2 -1
- package/dist-server/mcp-gate.js +53 -4
- package/dist-server/mcp-server.js +1 -1
- package/dist-server/openmausbot.js +458 -93
- package/dist-server/pair-cli.js +458 -93
- package/dist-server/server/accounts-proxy.js +3 -17
- package/dist-server/server/atomic-engine-release.js +7 -0
- package/dist-server/server/browser-proxy.js +3 -17
- package/dist-server/server/child-env.js +79 -0
- package/dist-server/server/config.js +11 -5
- package/dist-server/server/container-computer.js +1 -1
- package/dist-server/server/container-mcp.js +3 -2
- package/dist-server/server/control-client.js +7 -6
- package/dist-server/server/delegated-full-access.js +98 -0
- package/dist-server/server/desktop-loopback-gate.js +57 -0
- package/dist-server/server/drivers/acp/core.js +4 -4
- package/dist-server/server/drivers/acp/hermes-hosts.js +9 -0
- package/dist-server/server/drivers/acp/hermes.js +6 -9
- package/dist-server/server/drivers/acp/session-key.js +8 -0
- package/dist-server/server/drivers/agents-client.js +2 -14
- package/dist-server/server/drivers/gcloud-token.js +28 -0
- package/dist-server/server/drivers/github-copilot.js +152 -0
- package/dist-server/server/drivers/openai-chat-protocol.js +8 -0
- package/dist-server/server/drivers/openai-chat.js +10 -8
- package/dist-server/server/drivers/openai-compat.js +44 -9
- package/dist-server/server/drivers/phone-proxy.js +5 -18
- package/dist-server/server/engine-tiers.js +9 -9
- package/dist-server/server/harness/http.js +47 -1
- package/dist-server/server/index.js +54 -54
- package/dist-server/server/ladder-pick.js +18 -0
- package/dist-server/server/local-computer-proxy.js +3 -2
- package/dist-server/server/local-computer.js +1 -0
- package/dist-server/server/mcp-bridge.js +3 -2
- package/dist-server/server/mcp-gate.js +2 -1
- package/dist-server/server/mcp-registry.js +5 -1
- package/dist-server/server/model-gateway/failover.js +4 -1
- package/dist-server/server/model-gateway/route.js +64 -14
- package/dist-server/server/model-gateway/usage.js +66 -0
- package/dist-server/server/model-levels/aa-scale.js +42 -0
- package/dist-server/server/model-levels/aliases.js +16 -3
- package/dist-server/server/model-levels/index.js +8 -3
- package/dist-server/server/model-levels/rankings-build.js +76 -0
- package/dist-server/server/model-prices.js +6 -0
- package/dist-server/server/nexus-memory/index.js +5 -13
- package/dist-server/server/nexus-memory/policy.js +5 -17
- package/dist-server/server/oauth-account-vault.js +7 -2
- package/dist-server/server/provider-accounts.js +20 -1
- package/dist-server/server/provider-key-check.js +31 -1
- package/dist-server/server/registry-load.js +88 -0
- package/dist-server/server/request-auth.js +6 -28
- package/dist-server/server/routes/provider-accounts.js +124 -6
- package/dist-server/server/routine-daily-schedule.js +20 -0
- package/dist-server/server/routine-prompt-escape.js +18 -0
- package/dist-server/server/routine-tick-guard.js +16 -0
- package/dist-server/server/routine-tool-problems.js +36 -0
- package/dist-server/server/routines.js +36 -38
- package/dist-server/server/shutdown-triggers.js +18 -0
- package/dist-server/server/spend.js +23 -13
- package/dist-server/server/store.js +4 -13
- package/dist-server/server/terminal.js +2 -1
- package/dist-server/server/turn-token-file.js +79 -0
- package/dist-server/server/turn-token.js +23 -0
- package/dist-server/server/vps-container-mcp.js +3 -2
- package/dist-server/server/webhook-ingress.js +11 -1
- package/dist-server/server/webhook-prompt.js +82 -0
- package/dist-server/server/webhooks.js +8 -65
- package/dist-server/server/workspace-backup-policy.js +3 -3
- package/dist-server/server/workspace-backup.js +1 -1
- package/dist-server/server/workspace-time-zone.js +47 -0
- package/dist-server/shared/engine-choices.js +12 -1
- package/dist-server/shared/engine-tiers.js +0 -12
- package/dist-server/shared/provider-accounts.js +114 -2
- package/dist-server/shared/zoned-time.js +55 -0
- package/dist-server/vps-container-mcp.js +84 -12
- package/package.json +1 -1
- package/dist/assets/channel-_JFliC5C.js +0 -1
- package/dist/assets/index-Bi3hprmz.css +0 -1
- package/dist/assets/swimlanesDiagram-TC7HE7FX-DPTl4zVS.js +0 -8
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { timingSafeEqual } from "node:crypto";
|
|
2
1
|
import { isIP } from "node:net";
|
|
2
|
+
import { companionOwnRead, desktopLoopbackRefusal, secureTokenMatch } from "./desktop-loopback-gate.js";
|
|
3
3
|
import { ASSISTANT_TOKEN_PREFIX } from "./connected-assistants.js";
|
|
4
4
|
import { denyReason as companionDenial } from "../companion/src/routes.js";
|
|
5
5
|
const LOOPBACK_SCOPES = ["admin", "client"];
|
|
@@ -377,27 +377,6 @@ export const clientTaskPatchViolation = clientPatchViolation(new Set(["title", "
|
|
|
377
377
|
const CLI_OWNER_HEADER = "x-openmausbot-cli-owner";
|
|
378
378
|
/** The only routes the serving CLI's secret opens: its pairing code. */
|
|
379
379
|
const CLI_OWNER_ROUTE = /^\/api\/auth\/pairing$/;
|
|
380
|
-
const DESKTOP_OWNER_HEADER = "x-chibi-desktop-owner";
|
|
381
|
-
function mutatingPublicRoute(method, path) {
|
|
382
|
-
const upper = method.toUpperCase();
|
|
383
|
-
if (["GET", "HEAD", "OPTIONS"].includes(upper))
|
|
384
|
-
return false;
|
|
385
|
-
// Agent integrations have their own high-entropy, per-boot authorization
|
|
386
|
-
// and narrower route semantics. Pairing-code exchange is intentionally
|
|
387
|
-
// public; possession of the one-time code is its authorization.
|
|
388
|
-
return !path.startsWith("/api/internal/") &&
|
|
389
|
-
path !== "/api/testing/internal-capability" &&
|
|
390
|
-
path !== "/api/auth/pair" &&
|
|
391
|
-
// The same exchange under the shape the companion apps send.
|
|
392
|
-
path !== "/api/pair";
|
|
393
|
-
}
|
|
394
|
-
function secureTokenMatch(actual, expected) {
|
|
395
|
-
if (!actual || !expected)
|
|
396
|
-
return false;
|
|
397
|
-
const left = Buffer.from(actual);
|
|
398
|
-
const right = Buffer.from(expected);
|
|
399
|
-
return left.length === right.length && timingSafeEqual(left, right);
|
|
400
|
-
}
|
|
401
380
|
/** An assistant runs on this machine and speaks plain HTTP to 127.0.0.1. So
|
|
402
381
|
* its token is refused through a proxy or the tunnel, under a non-loopback
|
|
403
382
|
* Host, and with any Origin at all (a web page that learned the token cannot
|
|
@@ -465,7 +444,8 @@ export function resolveRequestAuth(req, options) {
|
|
|
465
444
|
const loopback = !proxied && isLoopbackHost(headerValue(req.headers.host)) && isAllowedOrigin(headerValue(req.headers.origin));
|
|
466
445
|
if (loopback) {
|
|
467
446
|
const companionToken = headerValue(req.headers["x-openmausbot-companion-auth"]);
|
|
468
|
-
|
|
447
|
+
const desktop = options.loopbackMutationToken;
|
|
448
|
+
if (companionToken && desktop !== undefined && !companionOwnRead(req, method, path, options.companionMutationToken)) {
|
|
469
449
|
if (!secureTokenMatch(companionToken, options.companionMutationToken ?? "") ||
|
|
470
450
|
req.headers["x-openmausbot-companion"] !== "1" ||
|
|
471
451
|
!/^[\w-]{1,128}$/.test(headerValue(req.headers["x-openmausbot-companion-device"]) ?? "") ||
|
|
@@ -474,11 +454,9 @@ export function resolveRequestAuth(req, options) {
|
|
|
474
454
|
const device = headerValue(req.headers["x-openmausbot-companion-device"]);
|
|
475
455
|
return { auth: { kind: "loopback", scopes: LOOPBACK_SCOPES, device }, status: 401, error: "" };
|
|
476
456
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
return deny(403, "forbidden: this change must come from the desktop app or a paired device");
|
|
481
|
-
}
|
|
457
|
+
const refusal = desktop === undefined ? null : desktopLoopbackRefusal(req, method, path, { desktop, companion: options.companionMutationToken });
|
|
458
|
+
if (refusal)
|
|
459
|
+
return deny(403, refusal);
|
|
482
460
|
if (options.loopbackMutationToken === undefined && options.loopbackTrust === "service") {
|
|
483
461
|
// The CLI that started this server may still print a pairing code.
|
|
484
462
|
if (options.cliOwnerToken && CLI_OWNER_ROUTE.test(path) && ["GET", "POST"].includes(method.toUpperCase()) &&
|
|
@@ -1,10 +1,38 @@
|
|
|
1
|
+
// Settings → Engines → AI provider accounts (shared/provider-accounts.ts):
|
|
2
|
+
// GET /api/provider-accounts every provider with its accounts
|
|
3
|
+
// POST /api/provider-accounts { provider, displayName, key?, test?, home?, owner? }
|
|
4
|
+
// PATCH /api/provider-accounts/:id { displayName } or { planCreditUsd: number | null }
|
|
5
|
+
// PUT /api/provider-accounts/:id/key { key } ("" forgets it); ?secretStorage=external
|
|
6
|
+
// when the desktop app already sealed it
|
|
7
|
+
// POST /api/provider-accounts/:id/test { key? } the draft, else the saved key
|
|
8
|
+
// DELETE /api/provider-accounts/:id the account and its key
|
|
9
|
+
// POST /api/provider-accounts/device { provider } starts a device-code sign-in
|
|
10
|
+
// (GitHub Copilot): { flowId, userCode, verificationUri, interval, expiresIn }
|
|
11
|
+
// POST /api/provider-accounts/device/:flowId { displayName, owner?, sealed? } polls it once:
|
|
12
|
+
// { state: "pending" | "failed" } or 201 with the new account.
|
|
13
|
+
// The token is saved like a pasted key; only when the
|
|
14
|
+
// desktop app asks to seal it itself (sealed: true) is it
|
|
15
|
+
// returned, once, as `key`, exactly what Add would send.
|
|
16
|
+
// Admin scope (not in CLIENT_ALLOW), refused to a bot's capability token and
|
|
17
|
+
// on a hosted-models server. Responses report whether a key is saved, never
|
|
18
|
+
// the key.
|
|
19
|
+
import { randomUUID } from "node:crypto";
|
|
1
20
|
import { ACCOUNT_PROVIDERS, accountProvider, planTerms } from "../../shared/provider-accounts.js";
|
|
2
21
|
import { monthToDateByInstance, planCredit, resetPlanCreditCache } from "../plan-credit.js";
|
|
3
22
|
import { persistableInstanceConfigs } from "../config.js";
|
|
4
23
|
import { instanceKeys, removeInstanceKey, saveInstanceKey } from "../instance-keys.js";
|
|
5
|
-
import { accountHome, accountKeySchema, accountProviderFor, addAccountSchema, homeSignInCommand, newApiKeyAccount, newSignInAccount, planCreditSchema, renameAccountSchema, } from "../provider-accounts.js";
|
|
24
|
+
import { accountHome, accountKeySchema, accountProviderFor, accountSetup, addAccountSchema, homeSignInCommand, newApiKeyAccount, newSignInAccount, planCreditSchema, renameAccountSchema, } from "../provider-accounts.js";
|
|
6
25
|
import { PASS } from "./table.js";
|
|
26
|
+
import { COPILOT_NO_PLAN, CopilotAuthError, exchangeCopilotToken, pollCopilotDeviceSignIn, startCopilotDeviceSignIn, } from "../drivers/github-copilot.js";
|
|
27
|
+
import { z } from "zod";
|
|
7
28
|
const ACCOUNT = /^\/api\/provider-accounts\/([\w.-]+)(?:\/(key|test))?$/;
|
|
29
|
+
const DEVICE = /^\/api\/provider-accounts\/device(?:\/([\w-]{1,64}))?$/;
|
|
30
|
+
const DEVICE_FLOWS_MAX = 8;
|
|
31
|
+
const devicePollSchema = z.object({
|
|
32
|
+
displayName: z.string().trim().min(1).max(80).refine((value) => !/\p{Cc}/u.test(value)),
|
|
33
|
+
owner: z.enum(["company", "personal"]).optional(),
|
|
34
|
+
sealed: z.boolean().optional(),
|
|
35
|
+
}).strict();
|
|
8
36
|
function removable(instanceId, entry) {
|
|
9
37
|
// Claude accounts added before this registry carry no marker.
|
|
10
38
|
return entry.account !== undefined || (entry.driver === "claudeAgent" && instanceId !== "claude");
|
|
@@ -31,7 +59,7 @@ function account(provider, instanceId, entry, described, owner, spent) {
|
|
|
31
59
|
signedIn: described?.snapshot.authenticated ?? null,
|
|
32
60
|
};
|
|
33
61
|
if (provider.kind === "apiKey")
|
|
34
|
-
return { ...base, keyConfigured: instanceKeys().has(instanceId) };
|
|
62
|
+
return { ...base, keyConfigured: provider.keyless === true || instanceKeys().has(instanceId) };
|
|
35
63
|
// Antigravity signs each instance in inside Atomic: no folder, no command.
|
|
36
64
|
const homeEnv = provider.homeEnv;
|
|
37
65
|
if (homeEnv === null)
|
|
@@ -66,7 +94,10 @@ async function listing(deps) {
|
|
|
66
94
|
billing: provider.billing,
|
|
67
95
|
driver: provider.driver,
|
|
68
96
|
...(provider.icon ? { icon: provider.icon } : {}),
|
|
69
|
-
...(provider.kind === "apiKey" ? {
|
|
97
|
+
...(provider.kind === "apiKey" ? {
|
|
98
|
+
keyUrl: provider.keyUrl, ...(provider.keyTest ? { keyTest: provider.keyTest } : {}),
|
|
99
|
+
...(provider.deviceSignIn ? { deviceSignIn: provider.deviceSignIn } : {}), ...(provider.keyless ? { keyless: true } : {}), ...(provider.setup ? { setup: provider.setup } : {}),
|
|
100
|
+
} : {}),
|
|
70
101
|
...(provider.signupUrl ? { signupUrl: provider.signupUrl } : {}),
|
|
71
102
|
accounts: Object.entries(instances)
|
|
72
103
|
.filter(([, entry]) => accountProviderFor(entry)?.id === provider.id)
|
|
@@ -82,15 +113,98 @@ function statusOf(error) {
|
|
|
82
113
|
return typeof status === "number" && [400, 404, 409].includes(status) ? status : 500;
|
|
83
114
|
}
|
|
84
115
|
export function createProviderAccountRoutes(deps) {
|
|
116
|
+
// Device-code sign-ins in progress, by a random id: GitHub's device code
|
|
117
|
+
// never leaves the server.
|
|
118
|
+
const flows = new Map();
|
|
119
|
+
const deviceFetch = deps.deviceFetch ?? fetch;
|
|
85
120
|
return async ({ req, res, url, path, method, json, readBody }) => {
|
|
86
|
-
const
|
|
87
|
-
|
|
121
|
+
const device = DEVICE.exec(path);
|
|
122
|
+
const match = device ? null : ACCOUNT.exec(path);
|
|
123
|
+
if (path !== "/api/provider-accounts" && !match && !device)
|
|
88
124
|
return PASS;
|
|
89
125
|
res.setHeader("cache-control", "no-store");
|
|
90
126
|
if (deps.fromBot?.(req))
|
|
91
127
|
return json(res, 403, { error: "Bots cannot change provider accounts." });
|
|
92
128
|
if (deps.disabled())
|
|
93
129
|
return json(res, 403, { error: "Provider accounts are managed by this server's administrator." });
|
|
130
|
+
if (device) {
|
|
131
|
+
if (method !== "POST")
|
|
132
|
+
return json(res, 405, { error: "method not allowed" });
|
|
133
|
+
if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {
|
|
134
|
+
return json(res, 415, { error: "content-type must be application/json" });
|
|
135
|
+
}
|
|
136
|
+
const now = Date.now();
|
|
137
|
+
for (const [id, flow] of flows)
|
|
138
|
+
if (flow.expiresAt <= now)
|
|
139
|
+
flows.delete(id);
|
|
140
|
+
const flowId = device[1];
|
|
141
|
+
if (!flowId) {
|
|
142
|
+
const body = await readBody(req, 1_024);
|
|
143
|
+
const provider = accountProvider(body?.provider);
|
|
144
|
+
if (provider?.kind !== "apiKey" || provider.deviceSignIn !== "githubCopilot") {
|
|
145
|
+
return json(res, 400, { error: "This provider does not sign in with a device code." });
|
|
146
|
+
}
|
|
147
|
+
if (flows.size >= DEVICE_FLOWS_MAX)
|
|
148
|
+
return json(res, 429, { error: "Too many sign-ins are waiting. Finish or cancel one first." });
|
|
149
|
+
try {
|
|
150
|
+
const code = await startCopilotDeviceSignIn(deviceFetch);
|
|
151
|
+
const id = randomUUID();
|
|
152
|
+
flows.set(id, { provider: provider.id, deviceCode: code.deviceCode, expiresAt: now + code.expiresIn * 1000 });
|
|
153
|
+
return json(res, 200, { flowId: id, userCode: code.userCode, verificationUri: code.verificationUri, interval: code.interval, expiresIn: code.expiresIn });
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return json(res, 502, { error: "Could not reach GitHub to start the sign-in. Check the connection and try again." });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const flow = flows.get(flowId);
|
|
160
|
+
if (!flow)
|
|
161
|
+
return json(res, 404, { error: "This sign-in expired. Start again." });
|
|
162
|
+
const parsed = devicePollSchema.safeParse(await readBody(req, 4_096));
|
|
163
|
+
if (!parsed.success)
|
|
164
|
+
return json(res, 400, { error: "Enter an account name (up to 80 characters)." });
|
|
165
|
+
const polled = await pollCopilotDeviceSignIn(flow.deviceCode, deviceFetch);
|
|
166
|
+
if (polled.state === "pending")
|
|
167
|
+
return json(res, 200, polled);
|
|
168
|
+
flows.delete(flowId);
|
|
169
|
+
if (polled.state === "failed") {
|
|
170
|
+
return json(res, 200, { state: "failed", error: polled.reason === "denied" ? "The sign-in was cancelled on GitHub."
|
|
171
|
+
: polled.reason === "expired" ? "The code expired. Start again." : "GitHub gave an unexpected answer. Start again." });
|
|
172
|
+
}
|
|
173
|
+
// Prove the account has a Copilot plan before adding it.
|
|
174
|
+
try {
|
|
175
|
+
await exchangeCopilotToken(polled.token, deviceFetch);
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
return json(res, 200, { state: "failed", error: error instanceof CopilotAuthError ? error.message : COPILOT_NO_PLAN });
|
|
179
|
+
}
|
|
180
|
+
const provider = accountProvider(flow.provider);
|
|
181
|
+
if (provider?.kind !== "apiKey")
|
|
182
|
+
return json(res, 400, { error: "Choose a provider from the list." });
|
|
183
|
+
if (!deps.lock())
|
|
184
|
+
return json(res, 409, { error: "Provider settings are already being updated." });
|
|
185
|
+
try {
|
|
186
|
+
const created = newApiKeyAccount(deps.config(), provider, parsed.data.displayName, deps.dataDir);
|
|
187
|
+
if (!parsed.data.sealed)
|
|
188
|
+
saveInstanceKey(created.instanceId, polled.token, { external: false });
|
|
189
|
+
try {
|
|
190
|
+
await deps.persist(created.instanceId, created.instances);
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
removeInstanceKey(created.instanceId);
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
if (parsed.data.owner)
|
|
197
|
+
deps.setOwner?.(created.instanceId, parsed.data.owner);
|
|
198
|
+
return json(res, 201, { state: "done", instanceId: created.instanceId, ...(parsed.data.sealed ? { key: polled.token } : {}), ...await listing(deps) });
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
const status = statusOf(error);
|
|
202
|
+
return json(res, status, { error: status === 500 ? "Could not add the account." : error.message });
|
|
203
|
+
}
|
|
204
|
+
finally {
|
|
205
|
+
deps.unlock();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
94
208
|
if (!match) {
|
|
95
209
|
if (method === "GET")
|
|
96
210
|
return json(res, 200, await listing(deps));
|
|
@@ -111,6 +225,10 @@ export function createProviderAccountRoutes(deps) {
|
|
|
111
225
|
const secret = body.key?.trim() ?? "";
|
|
112
226
|
if (provider.kind === "signIn" && body.key !== undefined)
|
|
113
227
|
return json(res, 400, { error: "This provider signs in instead of using a key." });
|
|
228
|
+
if (provider.kind === "apiKey" && provider.keyless && body.key !== undefined)
|
|
229
|
+
return json(res, 400, { error: "This provider needs no key." });
|
|
230
|
+
if (provider.kind === "signIn" && (body.url !== undefined || body.model !== undefined))
|
|
231
|
+
return json(res, 400, { error: "This provider signs in instead." });
|
|
114
232
|
if (provider.kind === "apiKey" && body.home !== undefined)
|
|
115
233
|
return json(res, 400, { error: "API-key accounts have no sign-in folder." });
|
|
116
234
|
if (body.test && provider.kind === "apiKey" && provider.keyTest && secret) {
|
|
@@ -122,7 +240,7 @@ export function createProviderAccountRoutes(deps) {
|
|
|
122
240
|
return json(res, 409, { error: "Provider settings are already being updated." });
|
|
123
241
|
try {
|
|
124
242
|
const created = provider.kind === "apiKey"
|
|
125
|
-
? newApiKeyAccount(deps.config(), provider, body.displayName, deps.dataDir)
|
|
243
|
+
? newApiKeyAccount(deps.config(), provider, body.displayName, deps.dataDir, accountSetup(provider, body))
|
|
126
244
|
: newSignInAccount(deps.config(), provider, body.displayName, deps.dataDir, body.home);
|
|
127
245
|
if (secret)
|
|
128
246
|
saveInstanceKey(created.instanceId, secret, { external: false });
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// When a daily or weekday routine next fires. The time is a wall-clock
|
|
2
|
+
// reading in a time zone (the workspace's when the caller has one, else this
|
|
3
|
+
// computer's), found field by field so "9:00" stays 9:00 across a clock
|
|
4
|
+
// change and does not depend on the zone the host process runs in.
|
|
5
|
+
import { wallClock, weekdayOf, zonedInstant } from "../shared/zoned-time.js";
|
|
6
|
+
import { workspaceTimeZone } from "./workspace-time-zone.js";
|
|
7
|
+
/** Next instant strictly after `after` that reads `time` (HH:MM) on one of
|
|
8
|
+
* `weekdays` (Sunday = 0) in `timeZone`. */
|
|
9
|
+
export function nextDailyOccurrence(time, weekdays, after, timeZone = workspaceTimeZone()) {
|
|
10
|
+
const [hour, minute] = time.split(":").map(Number);
|
|
11
|
+
const allowed = new Set(weekdays);
|
|
12
|
+
const today = wallClock(after, timeZone);
|
|
13
|
+
for (let offset = 0; offset <= 8; offset++) {
|
|
14
|
+
const day = today.day + offset;
|
|
15
|
+
const at = zonedInstant({ year: today.year, month: today.month, day, hour: hour, minute: minute, second: 0 }, timeZone);
|
|
16
|
+
if (at > after && allowed.has(weekdayOf(today.year, today.month, day)))
|
|
17
|
+
return at;
|
|
18
|
+
}
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Text escaping for the prompt a routine run is started with (routines.ts
|
|
2
|
+
// composeExecutionPrompt).
|
|
3
|
+
/** Keep untrusted local paths inside the same quoted tag shape used by chat. */
|
|
4
|
+
export function escapeAttachmentPath(value) {
|
|
5
|
+
return value
|
|
6
|
+
.replaceAll("&", "&")
|
|
7
|
+
.replaceAll('"', """)
|
|
8
|
+
.replaceAll("<", "<")
|
|
9
|
+
.replaceAll(">", ">")
|
|
10
|
+
.replaceAll("\t", "	")
|
|
11
|
+
.replaceAll("\r", " ")
|
|
12
|
+
.replaceAll("\n", " ");
|
|
13
|
+
}
|
|
14
|
+
/** Preserve prose while preventing the report from introducing markup. This
|
|
15
|
+
* is formatting, not a guarantee that a model cannot follow injected text. */
|
|
16
|
+
export function fenceCarriedReport(output) {
|
|
17
|
+
return output.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
18
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// A bound on the scheduler's awaits (routines.ts tick): a start or an
|
|
2
|
+
// interrupt that never settles fails that one run instead of holding the
|
|
3
|
+
// tick, and with it every other routine, forever.
|
|
4
|
+
export const ROUTINE_START_BOUND_MS = 2 * 60_000;
|
|
5
|
+
export const ROUTINE_INTERRUPT_BOUND_MS = 30_000;
|
|
6
|
+
export const ROUTINE_START_TIMED_OUT = "The bot did not start this run in time. Run the routine again, and restart Atomic if it keeps happening.";
|
|
7
|
+
/** `work`, or a rejection with `message` once `ms` has passed. The work is
|
|
8
|
+
* not cancelled; whatever it does later is ignored by the caller. */
|
|
9
|
+
export function bounded(work, ms, message) {
|
|
10
|
+
if (!work)
|
|
11
|
+
return Promise.resolve(undefined);
|
|
12
|
+
return new Promise((resolve, reject) => {
|
|
13
|
+
const timer = setTimeout(() => reject(new Error(message)), ms);
|
|
14
|
+
work.then((value) => { clearTimeout(timer); resolve(value); }, (error) => { clearTimeout(timer); reject(error instanceof Error ? error : new Error(String(error))); });
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { redactSecretsInText } from "./redact.js";
|
|
2
|
+
// A routine's model turn can end "ok" while the tools it needed never
|
|
3
|
+
// worked: a server that would not start, or one that stopped mid-turn. The
|
|
4
|
+
// model then writes a polite reply and the run used to be filed as
|
|
5
|
+
// completed (the 2026-10-29 incident in
|
|
6
|
+
// docs/verification/mcp-discovery-recovery.md). What the gates reported
|
|
7
|
+
// against a run is kept here until the run settles, so the receipt can say
|
|
8
|
+
// the work may not have happened.
|
|
9
|
+
const MAX_DETAILS = 5;
|
|
10
|
+
const MAX_RUNS = 200;
|
|
11
|
+
export class RoutineToolProblems {
|
|
12
|
+
byRun = new Map();
|
|
13
|
+
note(runId, detail) {
|
|
14
|
+
const text = redactSecretsInText(detail).trim().slice(0, 200);
|
|
15
|
+
if (!text)
|
|
16
|
+
return;
|
|
17
|
+
const details = this.byRun.get(runId) ?? [];
|
|
18
|
+
if (details.includes(text) || details.length >= MAX_DETAILS)
|
|
19
|
+
return;
|
|
20
|
+
// Re-inserting keeps the map ordered by latest note, so a run that
|
|
21
|
+
// never settles here (stopped, failed elsewhere) ages out first.
|
|
22
|
+
this.byRun.delete(runId);
|
|
23
|
+
this.byRun.set(runId, [...details, text]);
|
|
24
|
+
while (this.byRun.size > MAX_RUNS)
|
|
25
|
+
this.byRun.delete(this.byRun.keys().next().value);
|
|
26
|
+
}
|
|
27
|
+
/** The receipt's failure text when this run's tools failed, else null. The
|
|
28
|
+
* record is consumed: a run settles once. */
|
|
29
|
+
settle(runId) {
|
|
30
|
+
const details = this.byRun.get(runId);
|
|
31
|
+
this.byRun.delete(runId);
|
|
32
|
+
if (!details?.length)
|
|
33
|
+
return null;
|
|
34
|
+
return `Tools failed during this run, so the work may not have been done: ${details.join("; ")}`;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -7,6 +7,10 @@ import { writeFileAtomic } from "./atomic.js";
|
|
|
7
7
|
import { redactSecretsInText } from "./redact.js";
|
|
8
8
|
import { normalizeCronSchedule, nextCronRuns } from "../shared/routine-schedule.js";
|
|
9
9
|
import { isRoutineProblemRun } from "../shared/routines.js";
|
|
10
|
+
import { nextDailyOccurrence } from "./routine-daily-schedule.js";
|
|
11
|
+
import { escapeAttachmentPath, fenceCarriedReport } from "./routine-prompt-escape.js";
|
|
12
|
+
import { bounded, ROUTINE_INTERRUPT_BOUND_MS, ROUTINE_START_BOUND_MS, ROUTINE_START_TIMED_OUT } from "./routine-tick-guard.js";
|
|
13
|
+
import { RoutineToolProblems } from "./routine-tool-problems.js";
|
|
10
14
|
const persistedSourceThreadId = z.string().trim().min(1).optional().catch(undefined);
|
|
11
15
|
const webhookRunReceiptSchema = z.object({
|
|
12
16
|
webhookId: z.string().min(1).max(200),
|
|
@@ -156,24 +160,8 @@ function cloneRun(run) {
|
|
|
156
160
|
denials: run.denials ? [...run.denials] : undefined,
|
|
157
161
|
};
|
|
158
162
|
}
|
|
159
|
-
/** Keep untrusted local paths inside the same quoted tag shape used by chat. */
|
|
160
|
-
function escapeAttachmentPath(value) {
|
|
161
|
-
return value
|
|
162
|
-
.replaceAll("&", "&")
|
|
163
|
-
.replaceAll('"', """)
|
|
164
|
-
.replaceAll("<", "<")
|
|
165
|
-
.replaceAll(">", ">")
|
|
166
|
-
.replaceAll("\t", "	")
|
|
167
|
-
.replaceAll("\r", " ")
|
|
168
|
-
.replaceAll("\n", " ");
|
|
169
|
-
}
|
|
170
163
|
/** Continuity reuses the bounded stored report, not the full transcript. */
|
|
171
164
|
const CONTINUITY_CHARS = 2_000;
|
|
172
|
-
/** Preserve prose while preventing the report from introducing markup. This
|
|
173
|
-
* is formatting, not a guarantee that a model cannot follow injected text. */
|
|
174
|
-
function fenceCarriedReport(output) {
|
|
175
|
-
return output.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
176
|
-
}
|
|
177
165
|
function composeExecutionPrompt(prompt, attachments, carry) {
|
|
178
166
|
const parts = [prompt];
|
|
179
167
|
if (carry) {
|
|
@@ -335,8 +323,8 @@ function nextAlignedInterval(schedule, after) {
|
|
|
335
323
|
const candidate = schedule.anchorAt + (intervalsElapsed + 1) * intervalMs;
|
|
336
324
|
return Number.isSafeInteger(candidate) && candidate <= MAX_DATE_MS ? candidate : null;
|
|
337
325
|
}
|
|
338
|
-
/** Next occurrence strictly after `after`: cron uses its saved zone, daily uses the host zone. */
|
|
339
|
-
export function nextOccurrence(schedule, after) {
|
|
326
|
+
/** Next occurrence strictly after `after`: cron uses its saved zone, daily uses `timeZone`, else the host zone. */
|
|
327
|
+
export function nextOccurrence(schedule, after, timeZone) {
|
|
340
328
|
if (schedule.type === "once")
|
|
341
329
|
return schedule.at > after ? schedule.at : null;
|
|
342
330
|
if (schedule.type === "cron")
|
|
@@ -357,16 +345,7 @@ export function nextOccurrence(schedule, after) {
|
|
|
357
345
|
}
|
|
358
346
|
return null;
|
|
359
347
|
}
|
|
360
|
-
|
|
361
|
-
const weekdays = new Set(cleanDays(schedule.weekdays));
|
|
362
|
-
for (let offset = 0; offset <= 8; offset++) {
|
|
363
|
-
const d = new Date(after);
|
|
364
|
-
d.setDate(d.getDate() + offset);
|
|
365
|
-
d.setHours(hour, minute, 0, 0);
|
|
366
|
-
if (d.getTime() > after && weekdays.has(d.getDay()))
|
|
367
|
-
return d.getTime();
|
|
368
|
-
}
|
|
369
|
-
return null;
|
|
348
|
+
return nextDailyOccurrence(schedule.time, cleanDays(schedule.weekdays), after, timeZone);
|
|
370
349
|
}
|
|
371
350
|
function latestIntervalOccurrence(schedule, at) {
|
|
372
351
|
const intervalMs = schedule.everyMinutes * 60_000;
|
|
@@ -461,10 +440,12 @@ export class RoutineManager {
|
|
|
461
440
|
options;
|
|
462
441
|
routines = [];
|
|
463
442
|
runs = [];
|
|
443
|
+
toolProblems = new RoutineToolProblems();
|
|
464
444
|
routineRequestReceipts = [];
|
|
465
445
|
webhookRunReceipts = [];
|
|
466
446
|
timer = null;
|
|
467
447
|
ticking = false;
|
|
448
|
+
tickAgain = false;
|
|
468
449
|
constructor(options) {
|
|
469
450
|
this.options = options;
|
|
470
451
|
this.file = options.file ?? join(DATA_DIR, "routines.json");
|
|
@@ -931,7 +912,7 @@ export class RoutineManager {
|
|
|
931
912
|
if (existing)
|
|
932
913
|
return existing;
|
|
933
914
|
if (this.options.botState(input.botId) === "missing") {
|
|
934
|
-
throw Object.assign(new Error("The assigned
|
|
915
|
+
throw Object.assign(new Error("The assigned bot no longer exists"), { status: 410 });
|
|
935
916
|
}
|
|
936
917
|
const run = {
|
|
937
918
|
id: randomUUID(),
|
|
@@ -1100,7 +1081,7 @@ export class RoutineManager {
|
|
|
1100
1081
|
}
|
|
1101
1082
|
async tick() {
|
|
1102
1083
|
if (this.ticking)
|
|
1103
|
-
return;
|
|
1084
|
+
return void (this.tickAgain = true);
|
|
1104
1085
|
this.ticking = true;
|
|
1105
1086
|
try {
|
|
1106
1087
|
const now = this.now();
|
|
@@ -1118,13 +1099,13 @@ export class RoutineManager {
|
|
|
1118
1099
|
if (!threadId)
|
|
1119
1100
|
continue;
|
|
1120
1101
|
if (run.target === "room-goal" && run.groupId) {
|
|
1121
|
-
await this.options.interruptGoal?.(run.groupId, threadId, {
|
|
1102
|
+
await bounded(this.options.interruptGoal?.(run.groupId, threadId, {
|
|
1122
1103
|
status: "limit-reached",
|
|
1123
1104
|
detail,
|
|
1124
|
-
}).catch(() => { });
|
|
1105
|
+
}), ROUTINE_INTERRUPT_BOUND_MS, "interrupt timed out").catch(() => { });
|
|
1125
1106
|
}
|
|
1126
1107
|
else {
|
|
1127
|
-
await this.options.interruptTurn?.(run.botId, threadId, run.runOn ?? "maus").catch(() => { });
|
|
1108
|
+
await bounded(this.options.interruptTurn?.(run.botId, threadId, run.runOn ?? "maus"), ROUTINE_INTERRUPT_BOUND_MS, "interrupt timed out").catch(() => { });
|
|
1128
1109
|
}
|
|
1129
1110
|
}
|
|
1130
1111
|
const dueRoutines = this.routines.filter((routine) => routine.enabled && routine.nextRunAt != null && routine.nextRunAt <= now);
|
|
@@ -1157,7 +1138,7 @@ export class RoutineManager {
|
|
|
1157
1138
|
routine.lastSkippedAt = scheduledFor;
|
|
1158
1139
|
}
|
|
1159
1140
|
routine.nextRunAt =
|
|
1160
|
-
routine.schedule.type === "once" ? null : nextOccurrence(routine.schedule, Math.max(now, scheduledFor));
|
|
1141
|
+
routine.schedule.type === "once" ? null : nextOccurrence(routine.schedule, Math.max(now, scheduledFor), this.options.timeZone);
|
|
1161
1142
|
// `updatedAt` is the optimistic definition revision carried by
|
|
1162
1143
|
// routine confirmation cards. Moving the scheduler cursor is runtime
|
|
1163
1144
|
// progress, not a definition edit, so recurring ticks must not make a
|
|
@@ -1212,7 +1193,7 @@ export class RoutineManager {
|
|
|
1212
1193
|
const mayDispatch = intervalAllowsOccurrence(definition.schedule, now) &&
|
|
1213
1194
|
(!requiresCurrentDayOccurrence || (latest !== null && isSameLocalDay(latest, now)));
|
|
1214
1195
|
if (!mayDispatch) {
|
|
1215
|
-
if (nextOccurrence(definition.schedule, now) === null) {
|
|
1196
|
+
if (nextOccurrence(definition.schedule, now, this.options.timeZone) === null) {
|
|
1216
1197
|
this.missQueuedRun(run, "The routine ended before this scheduled run could start");
|
|
1217
1198
|
}
|
|
1218
1199
|
continue;
|
|
@@ -1273,10 +1254,10 @@ export class RoutineManager {
|
|
|
1273
1254
|
this.failThread(task.threadId, "Room goal routines are unavailable");
|
|
1274
1255
|
continue;
|
|
1275
1256
|
}
|
|
1276
|
-
await this.options.startGoal(run.groupId, task.threadId, prompt, run.botId, run.id, (message) => this.failThread(task.threadId, message));
|
|
1257
|
+
await bounded(this.options.startGoal(run.groupId, task.threadId, prompt, run.botId, run.id, (message) => this.failThread(task.threadId, message)), this.options.startTimeoutMs ?? ROUTINE_START_BOUND_MS, ROUTINE_START_TIMED_OUT);
|
|
1277
1258
|
}
|
|
1278
1259
|
else {
|
|
1279
|
-
await this.options.startTurn(run.botId, task.threadId, composeExecutionPrompt(prompt, run.attachments, this.continuityCarry(run)), run.runOn ?? "maus", triggerSource, (message) => this.failThread(task.threadId, message));
|
|
1260
|
+
await bounded(this.options.startTurn(run.botId, task.threadId, composeExecutionPrompt(prompt, run.attachments, this.continuityCarry(run)), run.runOn ?? "maus", triggerSource, (message) => this.failThread(task.threadId, message)), this.options.startTimeoutMs ?? ROUTINE_START_BOUND_MS, ROUTINE_START_TIMED_OUT);
|
|
1280
1261
|
}
|
|
1281
1262
|
}
|
|
1282
1263
|
catch (error) {
|
|
@@ -1286,6 +1267,10 @@ export class RoutineManager {
|
|
|
1286
1267
|
}
|
|
1287
1268
|
finally {
|
|
1288
1269
|
this.ticking = false;
|
|
1270
|
+
if (this.tickAgain) {
|
|
1271
|
+
this.tickAgain = false;
|
|
1272
|
+
queueMicrotask(() => void this.tick());
|
|
1273
|
+
}
|
|
1289
1274
|
}
|
|
1290
1275
|
}
|
|
1291
1276
|
handleRuntimeEvent(event) {
|
|
@@ -1338,7 +1323,14 @@ export class RoutineManager {
|
|
|
1338
1323
|
queueMicrotask(() => void this.tick());
|
|
1339
1324
|
return cloneRun(run);
|
|
1340
1325
|
}
|
|
1326
|
+
this.options.beforeSettle?.(event.threadId);
|
|
1341
1327
|
const pending = this.options.hasPendingDelegations?.(event.threadId) === true;
|
|
1328
|
+
const toolFailure = pending ? null : this.toolProblems.settle(run.id);
|
|
1329
|
+
if (toolFailure) {
|
|
1330
|
+
this.failRun(run, toolFailure);
|
|
1331
|
+
queueMicrotask(() => void this.tick());
|
|
1332
|
+
return cloneRun(run);
|
|
1333
|
+
}
|
|
1342
1334
|
run.status = pending ? "waiting" : "completed";
|
|
1343
1335
|
run.attention = pending ? "Waiting for delegated work to finish" : undefined;
|
|
1344
1336
|
if (!pending)
|
|
@@ -1354,6 +1346,12 @@ export class RoutineManager {
|
|
|
1354
1346
|
queueMicrotask(() => void this.tick());
|
|
1355
1347
|
return cloneRun(run);
|
|
1356
1348
|
}
|
|
1349
|
+
/** A tool this thread's running routine needed failed (mcp-turn.ts). */
|
|
1350
|
+
noteToolProblem(threadId, detail) {
|
|
1351
|
+
const run = this.runs.find((r) => r.threadId === threadId && ["running", "waiting"].includes(r.status));
|
|
1352
|
+
if (run)
|
|
1353
|
+
this.toolProblems.note(run.id, detail);
|
|
1354
|
+
}
|
|
1357
1355
|
failThread(threadId, message) {
|
|
1358
1356
|
const run = this.runs.find((r) => r.threadId === threadId && ["running", "waiting"].includes(r.status));
|
|
1359
1357
|
if (!run)
|
|
@@ -1437,7 +1435,7 @@ export class RoutineManager {
|
|
|
1437
1435
|
// threshold from ever triggering for a "once" routine created late.
|
|
1438
1436
|
if (schedule.type === "once")
|
|
1439
1437
|
return schedule.at;
|
|
1440
|
-
return nextOccurrence(schedule, now);
|
|
1438
|
+
return nextOccurrence(schedule, now, this.options.timeZone);
|
|
1441
1439
|
}
|
|
1442
1440
|
newRun(routine, scheduledFor, manual, allocations, sourceThreadId = routine.sourceThreadId) {
|
|
1443
1441
|
if (routine.target === "bot" && this.options.resolveResultsThread) {
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Must match UTILITY_SERVER_SHUTDOWN_MESSAGE in electron/utility-server-stop.mjs. */
|
|
2
|
+
export const PARENT_SHUTDOWN_MESSAGE = "openmausbot:shutdown";
|
|
3
|
+
export function isParentShutdownMessage(raw) {
|
|
4
|
+
return !!raw && typeof raw === "object" && !Array.isArray(raw) &&
|
|
5
|
+
raw.type === PARENT_SHUTDOWN_MESSAGE;
|
|
6
|
+
}
|
|
7
|
+
/** Every way the server is asked to stop runs the same shutdown. Signals
|
|
8
|
+
* cover POSIX and Ctrl+C. The desktop also asks over its private parent port
|
|
9
|
+
* because Windows ends a child without delivering any signal, which would
|
|
10
|
+
* skip the cleanup that stops engine process trees. */
|
|
11
|
+
export function installShutdownTriggers(signals, port, shutdown) {
|
|
12
|
+
for (const signal of ["SIGINT", "SIGTERM"])
|
|
13
|
+
signals.on(signal, shutdown);
|
|
14
|
+
port?.on("message", (event) => {
|
|
15
|
+
if (isParentShutdownMessage(event?.data))
|
|
16
|
+
shutdown();
|
|
17
|
+
});
|
|
18
|
+
}
|
|
@@ -11,6 +11,8 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
|
11
11
|
import { join } from "node:path";
|
|
12
12
|
import { entitled } from "./enterprise.js";
|
|
13
13
|
import { readUsage, usageRowKey } from "./usage-ledger.js";
|
|
14
|
+
import { wallClock, zonedInstant } from "../shared/zoned-time.js";
|
|
15
|
+
import { workspaceTimeZone } from "./workspace-time-zone.js";
|
|
14
16
|
const DEFAULT_WARN_AT_PERCENT = 80;
|
|
15
17
|
const CACHE_MS = 15_000;
|
|
16
18
|
// Every turn start asks; reading the month file each time would be silly.
|
|
@@ -21,18 +23,25 @@ const cache = new Map();
|
|
|
21
23
|
// cost. The append is asynchronous, and a turn that ran longer than CACHE_MS
|
|
22
24
|
// would otherwise be re-read out of the month before its own row landed.
|
|
23
25
|
const unwritten = new Map();
|
|
24
|
-
|
|
25
|
-
|
|
26
|
+
// The cap's month is the calendar month where the workspace is: this
|
|
27
|
+
// computer's time zone. In UTC it would start over at 7 PM Eastern on the
|
|
28
|
+
// last day. Ledger files stay named by UTC month; only this window moves.
|
|
29
|
+
function monthOf(now, timeZone) {
|
|
30
|
+
const { year, month } = wallClock(now.getTime(), timeZone);
|
|
31
|
+
return `${year}-${String(month).padStart(2, "0")}`;
|
|
32
|
+
}
|
|
33
|
+
function monthStart(now, timeZone) {
|
|
34
|
+
const { year, month } = wallClock(now.getTime(), timeZone);
|
|
35
|
+
return new Date(zonedInstant({ year, month, day: 1, hour: 0, minute: 0, second: 0 }, timeZone));
|
|
26
36
|
}
|
|
27
37
|
const costOf = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0);
|
|
28
38
|
/** Reported and estimated cost this month so far: the ledger file (read at
|
|
29
39
|
* most every CACHE_MS) plus turns booked since whose rows have not landed. */
|
|
30
|
-
export function monthToDateSpend(dataDir, now = new Date()) {
|
|
31
|
-
const month = monthOf(now);
|
|
40
|
+
export function monthToDateSpend(dataDir, now = new Date(), timeZone = workspaceTimeZone()) {
|
|
41
|
+
const month = monthOf(now, timeZone);
|
|
32
42
|
let read = cache.get(dataDir);
|
|
33
43
|
if (!read || read.month !== month || now.getTime() - read.at >= CACHE_MS) {
|
|
34
|
-
const
|
|
35
|
-
const rows = readUsage(dataDir, { from, to: now });
|
|
44
|
+
const rows = readUsage(dataDir, { from: monthStart(now, timeZone), to: now });
|
|
36
45
|
read = { at: now.getTime(), month, fileUsd: rows.reduce((sum, row) => sum + costOf(row.costUsd), 0), keys: new Set(rows.map(usageRowKey)) };
|
|
37
46
|
cache.set(dataDir, read);
|
|
38
47
|
}
|
|
@@ -48,12 +57,12 @@ export function monthToDateSpend(dataDir, now = new Date()) {
|
|
|
48
57
|
* row lands it moves into the cached read, and a re-read that already sees
|
|
49
58
|
* the row never counts it twice. A write that failed stops counting, as
|
|
50
59
|
* the ledger has no row for it. */
|
|
51
|
-
export function noteSpend(dataDir, row, written) {
|
|
60
|
+
export function noteSpend(dataDir, row, written, timeZone = workspaceTimeZone()) {
|
|
52
61
|
const costUsd = costOf(row.costUsd);
|
|
53
62
|
if (!costUsd)
|
|
54
63
|
return;
|
|
55
64
|
const key = usageRowKey(row);
|
|
56
|
-
const month = row.at
|
|
65
|
+
const month = monthOf(new Date(row.at), timeZone);
|
|
57
66
|
const entries = unwritten.get(dataDir) ?? new Map();
|
|
58
67
|
unwritten.set(dataDir, entries);
|
|
59
68
|
entries.set(key, { month, costUsd });
|
|
@@ -68,21 +77,22 @@ export function noteSpend(dataDir, row, written) {
|
|
|
68
77
|
}
|
|
69
78
|
});
|
|
70
79
|
}
|
|
80
|
+
export { workspaceTimeZone, workspaceTimeZoneStatus } from "./workspace-time-zone.js";
|
|
71
81
|
export function resetSpendCacheForTests() {
|
|
72
82
|
cache.clear();
|
|
73
83
|
unwritten.clear();
|
|
74
84
|
}
|
|
75
85
|
/** The cap and where the month stands against it; null when there is no
|
|
76
86
|
* enforceable cap (no entitlement, or none set). */
|
|
77
|
-
export function spendState(cfg, dataDir, now = new Date(), isEntitled = entitled) {
|
|
87
|
+
export function spendState(cfg, dataDir, now = new Date(), isEntitled = entitled, timeZone = workspaceTimeZone()) {
|
|
78
88
|
const monthlyUsd = cfg.budgets?.monthlyUsd;
|
|
79
89
|
if (!isEntitled("budgets") || typeof monthlyUsd !== "number" || !Number.isFinite(monthlyUsd) || monthlyUsd <= 0)
|
|
80
90
|
return null;
|
|
81
|
-
const spentUsd = monthToDateSpend(dataDir, now);
|
|
91
|
+
const spentUsd = monthToDateSpend(dataDir, now, timeZone);
|
|
82
92
|
const warnAtPercent = cfg.budgets?.warnAtPercent ?? DEFAULT_WARN_AT_PERCENT;
|
|
83
93
|
const percent = Math.min(999, Math.round((spentUsd / monthlyUsd) * 100));
|
|
84
94
|
return {
|
|
85
|
-
month: monthOf(now),
|
|
95
|
+
month: monthOf(now, timeZone),
|
|
86
96
|
monthlyUsd,
|
|
87
97
|
spentUsd,
|
|
88
98
|
percent,
|
|
@@ -96,8 +106,8 @@ function usd(value) {
|
|
|
96
106
|
return Number.isInteger(Math.round(value * 1000) / 10) ? value.toFixed(2) : value.toFixed(3);
|
|
97
107
|
}
|
|
98
108
|
/** Throws the HTTP-shaped refusal a turn start gets once the cap is reached. */
|
|
99
|
-
export function assertWithinBudget(cfg, dataDir, now = new Date(), isEntitled = entitled) {
|
|
100
|
-
const state = spendState(cfg, dataDir, now, isEntitled);
|
|
109
|
+
export function assertWithinBudget(cfg, dataDir, now = new Date(), isEntitled = entitled, timeZone = workspaceTimeZone()) {
|
|
110
|
+
const state = spendState(cfg, dataDir, now, isEntitled, timeZone);
|
|
101
111
|
if (!state?.exceeded)
|
|
102
112
|
return;
|
|
103
113
|
throw Object.assign(new Error(`this workspace has reached its monthly spend limit of $${usd(state.monthlyUsd)} — an admin can raise it under Settings → Usage`), { status: 409, code: "spend_cap" });
|