@chibitek/chibi 0.1.209 → 0.1.211

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 (155) hide show
  1. package/dist/assets/{TerminalPanel-CHGq3udb.js → TerminalPanel-Dro3aeVy.js} +1 -1
  2. package/dist/assets/{abnfDiagram-O67JEVCF-BMaKhJ-b.js → abnfDiagram-O67JEVCF-kzAr7vQ8.js} +1 -1
  3. package/dist/assets/{arc-CYAiNWN8.js → arc-DKMhcYud.js} +1 -1
  4. package/dist/assets/{architectureDiagram-NJMV4G6O-CxJFFlbO.js → architectureDiagram-NJMV4G6O-_XDnZ7Jz.js} +1 -1
  5. package/dist/assets/{blockDiagram-BEXU5L5S-C7AbPjRB.js → blockDiagram-BEXU5L5S-D5MoWro9.js} +1 -1
  6. package/dist/assets/{c4Diagram-YGBWAQC7-DfVnCJmT.js → c4Diagram-YGBWAQC7-CGvTMpGE.js} +1 -1
  7. package/dist/assets/channel-YcZdlysP.js +1 -0
  8. package/dist/assets/{chunk-2Q5K7J3B-CzAUFkgv.js → chunk-2Q5K7J3B-pjTwr5y0.js} +1 -1
  9. package/dist/assets/{chunk-3FUC2YCW-BgeBXphm.js → chunk-3FUC2YCW-BR6zkd-l.js} +2 -2
  10. package/dist/assets/{chunk-5VM5RSS4-DPRdTAXc.js → chunk-5VM5RSS4-CfVFFBeH.js} +1 -1
  11. package/dist/assets/{chunk-GTNCS2PH-BS-_dIVl.js → chunk-GTNCS2PH-TIoAkccw.js} +1 -1
  12. package/dist/assets/{chunk-GWA4HPMP-D6I7xMmd.js → chunk-GWA4HPMP-BNFBgzbt.js} +1 -1
  13. package/dist/assets/{chunk-JWPE2WC7-BKSKe7C9.js → chunk-JWPE2WC7-B_3QFchU.js} +1 -1
  14. package/dist/assets/{chunk-NETBCI7D-R48UYTRN.js → chunk-NETBCI7D-Cj9q80P-.js} +1 -1
  15. package/dist/assets/{chunk-WEXAMYUT-C8z4mL-2.js → chunk-WEXAMYUT-DFZPGo9K.js} +1 -1
  16. package/dist/assets/{chunk-XXDRQBXY-Bml3ZRJ5.js → chunk-XXDRQBXY-CekDrT9T.js} +1 -1
  17. package/dist/assets/{classDiagram-v2-NBCMYWYE-w5wo22FO.js → classDiagram-v2-NBCMYWYE-C3R6Z4Qe.js} +1 -1
  18. package/dist/assets/{cose-bilkent-JH36ORCC-Cum9v--4.js → cose-bilkent-JH36ORCC-C1CKyj0L.js} +1 -1
  19. package/dist/assets/{cynefin-OW5HDTMX-BzN0-KsP.js → cynefin-OW5HDTMX-Deh9QGb0.js} +1 -1
  20. package/dist/assets/{cynefinDiagram-VND7K2PF-CkOpm32D.js → cynefinDiagram-VND7K2PF-BIlWyG_M.js} +1 -1
  21. package/dist/assets/{dagre-6A5THRUB-BItQkKZD.js → dagre-6A5THRUB-Dx4bWOog.js} +1 -1
  22. package/dist/assets/{diagram-22UHCM2B-BI0zDn7c.js → diagram-22UHCM2B-DPxb-FUO.js} +1 -1
  23. package/dist/assets/{diagram-3UASUU5V-jwcDxsu6.js → diagram-3UASUU5V-BLPCNc4m.js} +1 -1
  24. package/dist/assets/{diagram-ATOU4E4O-2RnY9egJ.js → diagram-ATOU4E4O-DOCbp2Dw.js} +1 -1
  25. package/dist/assets/{diagram-CDSNMT55-eVdEZmEF.js → diagram-CDSNMT55-62uSG-tn.js} +1 -1
  26. package/dist/assets/{diagram-MLGK6HIB-BCDGCJJ0.js → diagram-MLGK6HIB-De1ZAWVZ.js} +1 -1
  27. package/dist/assets/{diagram-MPIPVDR6-DtN5uO5w.js → diagram-MPIPVDR6-CIGX9tku.js} +1 -1
  28. package/dist/assets/{ebnfDiagram-ZINNZB2B-B9GpXSEs.js → ebnfDiagram-ZINNZB2B-CegjStdk.js} +1 -1
  29. package/dist/assets/{elk-276RUBZZ-Bk_eaK4T.js → elk-276RUBZZ-ClI52Pqm.js} +1 -1
  30. package/dist/assets/{erDiagram-OPXOYQCR-BiGoW6C6.js → erDiagram-OPXOYQCR-BQuzjt2-.js} +1 -1
  31. package/dist/assets/{flowDiagram-KWPJA3E3-ZW5w0BaJ.js → flowDiagram-KWPJA3E3-D1xbKgbB.js} +1 -1
  32. package/dist/assets/{ganttDiagram-FUAMR5RP-yyrKgsx1.js → ganttDiagram-FUAMR5RP-CH1jGSZz.js} +1 -1
  33. package/dist/assets/{gitGraphDiagram-X574FWY7-CeiDikzD.js → gitGraphDiagram-X574FWY7-BvAUPEmQ.js} +1 -1
  34. package/dist/assets/{index-CZGnshrJ.js → index-BcXDfnlQ.js} +197 -197
  35. package/dist/assets/{index-DUFlRZuA.js → index-DbkR_erP.js} +1 -1
  36. package/dist/assets/index-H8vkXbLq.css +1 -0
  37. package/dist/assets/{infoDiagram-VRGFBTTK-q2B-KJFm.js → infoDiagram-VRGFBTTK-CyMmMbMv.js} +1 -1
  38. package/dist/assets/{ishikawaDiagram-OU5B5YK6-D8gXFuc0.js → ishikawaDiagram-OU5B5YK6-Uw-hE1tO.js} +1 -1
  39. package/dist/assets/{journeyDiagram-ZHPQQLJL-BmHL2mbq.js → journeyDiagram-ZHPQQLJL-ClEDnNRB.js} +1 -1
  40. package/dist/assets/{kanban-definition-PNTS6WVX-B9Ll2WkA.js → kanban-definition-PNTS6WVX-erx0BEal.js} +1 -1
  41. package/dist/assets/{linear-CMVGYrKx.js → linear-CSSxpyL0.js} +1 -1
  42. package/dist/assets/{mermaid.core-qO11n1kV.js → mermaid.core-n13K6vlC.js} +5 -5
  43. package/dist/assets/{mindmap-definition-NLK3R4M7-CxLGFX45.js → mindmap-definition-NLK3R4M7-BcTEIqpD.js} +1 -1
  44. package/dist/assets/{pegDiagram-GJSIUBJH-CxK1MJG4.js → pegDiagram-GJSIUBJH-CJdsm3en.js} +1 -1
  45. package/dist/assets/{pieDiagram-5QR66LMP-H5jiF5Eu.js → pieDiagram-5QR66LMP-C7rk-ash.js} +1 -1
  46. package/dist/assets/{quadrantDiagram-O4NWA36T-CKaqCruv.js → quadrantDiagram-O4NWA36T-BSXOYov0.js} +1 -1
  47. package/dist/assets/{railroadDiagram-XR7U4H2S-BCzKiQOd.js → railroadDiagram-XR7U4H2S-Cmg_FtZY.js} +1 -1
  48. package/dist/assets/{requirementDiagram-PLB6GJNP-Cqtr43DT.js → requirementDiagram-PLB6GJNP-B_9aE6Mg.js} +1 -1
  49. package/dist/assets/{sankeyDiagram-IPEJSGJF-B2tQewX8.js → sankeyDiagram-IPEJSGJF-DyxaQPy3.js} +1 -1
  50. package/dist/assets/{sequenceDiagram-PO4LG4MO-nggwQyrw.js → sequenceDiagram-PO4LG4MO-D5CJeESq.js} +1 -1
  51. package/dist/assets/{sizeCapture-INFHLROL-qSPXJBv2.js → sizeCapture-INFHLROL-9-Q4eosQ.js} +1 -1
  52. package/dist/assets/{stateDiagram-v2-GCMORJYK-DraPbL2T.js → stateDiagram-v2-GCMORJYK-jgsHnEQl.js} +1 -1
  53. package/dist/assets/{swimlanes-2SLR337P-C6HVkIDA.js → swimlanes-2SLR337P-MIVacUbv.js} +1 -1
  54. package/dist/assets/swimlanesDiagram-TC7HE7FX-Dekwo1KL.js +8 -0
  55. package/dist/assets/{timeline-definition-EJHVYXUP-DZmPRTsx.js → timeline-definition-EJHVYXUP-Ch8ins-D.js} +1 -1
  56. package/dist/assets/{usecaseDiagram-POWQR4AR-CsVuROW_.js → usecaseDiagram-POWQR4AR-BDwBIuhZ.js} +1 -1
  57. package/dist/assets/{vennDiagram-UO4OBE2U-B9IRbuhp.js → vennDiagram-UO4OBE2U-BiiDxcHO.js} +1 -1
  58. package/dist/assets/{wardleyDiagram-VNRHLVJA-CGmVK53n.js → wardleyDiagram-VNRHLVJA-D79CK2__.js} +1 -1
  59. package/dist/assets/{xychartDiagram-PMCCYNJV-BAw-x9Y1.js → xychartDiagram-PMCCYNJV-CI7S0o-6.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 +165 -93
  64. package/dist-server/drivers/agents-proxy.js +109 -94
  65. package/dist-server/drivers/phone-proxy.js +21 -13
  66. package/dist-server/index.js +6487 -4926
  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 +1068 -642
  72. package/dist-server/pair-cli.js +1068 -642
  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/auto-approve.js +12 -0
  76. package/dist-server/server/browser-proxy.js +3 -17
  77. package/dist-server/server/child-env.js +79 -0
  78. package/dist-server/server/config.js +11 -5
  79. package/dist-server/server/container-computer.js +1 -1
  80. package/dist-server/server/container-mcp.js +3 -2
  81. package/dist-server/server/control-client.js +7 -6
  82. package/dist-server/server/delegated-full-access.js +98 -0
  83. package/dist-server/server/desktop-loopback-gate.js +57 -0
  84. package/dist-server/server/drivers/acp/core.js +4 -4
  85. package/dist-server/server/drivers/acp/custom.js +3 -1
  86. package/dist-server/server/drivers/acp/hermes.js +2 -1
  87. package/dist-server/server/drivers/acp/session-key.js +8 -0
  88. package/dist-server/server/drivers/agents-client.js +2 -14
  89. package/dist-server/server/drivers/gcloud-token.js +28 -0
  90. package/dist-server/server/drivers/github-copilot.js +152 -0
  91. package/dist-server/server/drivers/hermes-context-floor.js +68 -0
  92. package/dist-server/server/drivers/openai-chat-protocol.js +8 -0
  93. package/dist-server/server/drivers/openai-chat.js +10 -8
  94. package/dist-server/server/drivers/openai-compat.js +44 -9
  95. package/dist-server/server/drivers/phone-proxy.js +5 -18
  96. package/dist-server/server/engine-tiers.js +9 -9
  97. package/dist-server/server/god-mode-goal.js +78 -0
  98. package/dist-server/server/god-mode-run-host.js +69 -0
  99. package/dist-server/server/harness/http.js +47 -1
  100. package/dist-server/server/index.js +86 -86
  101. package/dist-server/server/ladder-pick.js +18 -0
  102. package/dist-server/server/local-computer-proxy.js +3 -2
  103. package/dist-server/server/local-computer.js +1 -0
  104. package/dist-server/server/mcp-bridge.js +3 -2
  105. package/dist-server/server/mcp-gate.js +2 -1
  106. package/dist-server/server/mcp-registry.js +5 -1
  107. package/dist-server/server/model-fallback-repair.js +20 -0
  108. package/dist-server/server/model-gateway/failover.js +4 -1
  109. package/dist-server/server/model-gateway/route.js +64 -14
  110. package/dist-server/server/model-gateway/usage.js +66 -0
  111. package/dist-server/server/model-levels/aa-scale.js +42 -0
  112. package/dist-server/server/model-levels/aliases.js +16 -3
  113. package/dist-server/server/model-levels/index.js +8 -3
  114. package/dist-server/server/model-levels/rankings-build.js +76 -0
  115. package/dist-server/server/model-prices.js +6 -0
  116. package/dist-server/server/nexus-memory/index.js +5 -13
  117. package/dist-server/server/nexus-memory/policy.js +5 -17
  118. package/dist-server/server/oauth-account-vault.js +7 -2
  119. package/dist-server/server/personal-goal-runtime.js +29 -3
  120. package/dist-server/server/personal-goal-turn.js +2 -1
  121. package/dist-server/server/personal-goals.js +20 -2
  122. package/dist-server/server/provider-accounts.js +20 -1
  123. package/dist-server/server/provider-key-check.js +31 -1
  124. package/dist-server/server/registry-load.js +88 -0
  125. package/dist-server/server/request-auth.js +6 -28
  126. package/dist-server/server/routes/provider-accounts.js +124 -6
  127. package/dist-server/server/routine-daily-schedule.js +20 -0
  128. package/dist-server/server/routine-prompt-escape.js +18 -0
  129. package/dist-server/server/routine-tick-guard.js +16 -0
  130. package/dist-server/server/routine-tool-problems.js +36 -0
  131. package/dist-server/server/routines.js +36 -38
  132. package/dist-server/server/shutdown-triggers.js +18 -0
  133. package/dist-server/server/spend.js +23 -13
  134. package/dist-server/server/store.js +4 -13
  135. package/dist-server/server/terminal.js +2 -1
  136. package/dist-server/server/turn-token-file.js +79 -0
  137. package/dist-server/server/turn-token.js +23 -0
  138. package/dist-server/server/vps-container-mcp.js +3 -2
  139. package/dist-server/server/webhook-ingress.js +11 -1
  140. package/dist-server/server/webhook-prompt.js +82 -0
  141. package/dist-server/server/webhooks.js +8 -65
  142. package/dist-server/server/workspace-backup-policy.js +3 -3
  143. package/dist-server/server/workspace-backup.js +1 -1
  144. package/dist-server/server/workspace-time-zone.js +47 -0
  145. package/dist-server/shared/engine-choices.js +12 -1
  146. package/dist-server/shared/god-mode-run.js +173 -0
  147. package/dist-server/shared/personal-goal.js +42 -0
  148. package/dist-server/shared/provider-accounts.js +114 -2
  149. package/dist-server/shared/zoned-time.js +55 -0
  150. package/dist-server/vps-container-mcp.js +165 -93
  151. package/package.json +1 -1
  152. package/dist/assets/channel-DxL_mLhm.js +0 -1
  153. package/dist/assets/index-Bi3hprmz.css +0 -1
  154. package/dist/assets/swimlanesDiagram-TC7HE7FX-gQUGsELo.js +0 -8
  155. package/dist-server/server/agents-token-file.js +0 -26
@@ -120,6 +120,11 @@ export class DesktopAccountVault {
120
120
  }
121
121
  }
122
122
  const FILE_VERSION = 1;
123
+ const AUTH_TAG_BYTES = 16;
124
+ /** Node accepts GCM tags as short as 4 bytes unless told otherwise, and a
125
+ * short tag is far easier to forge, so only the full tag this file is written
126
+ * with is read back. */
127
+ const fullAuthTag = z.string().refine((tag) => Buffer.from(tag, "base64").length === AUTH_TAG_BYTES);
123
128
  /** One encrypted file for servers without Electron. The directory sits under
124
129
  * providers/, which workspace backups never export. */
125
130
  export class FileAccountVault {
@@ -152,8 +157,8 @@ export class FileAccountVault {
152
157
  return {};
153
158
  }
154
159
  try {
155
- const envelope = z.object({ v: z.literal(FILE_VERSION), iv: z.string(), tag: z.string(), data: z.string() }).parse(JSON.parse(raw));
156
- const decipher = createDecipheriv("aes-256-gcm", this.key(), Buffer.from(envelope.iv, "base64"));
160
+ const envelope = z.object({ v: z.literal(FILE_VERSION), iv: z.string(), tag: fullAuthTag, data: z.string() }).parse(JSON.parse(raw));
161
+ const decipher = createDecipheriv("aes-256-gcm", this.key(), Buffer.from(envelope.iv, "base64"), { authTagLength: AUTH_TAG_BYTES });
157
162
  decipher.setAuthTag(Buffer.from(envelope.tag, "base64"));
158
163
  const plain = Buffer.concat([decipher.update(Buffer.from(envelope.data, "base64")), decipher.final()]).toString("utf8");
159
164
  return parseStoredAccounts(JSON.parse(plain));
@@ -1,5 +1,9 @@
1
1
  import { GOAL_HELP } from "../shared/personal-goal.js";
2
2
  import { PersonalGoals } from "./personal-goals.js";
3
+ import { godModeNextAttemptDelay } from "./god-mode-goal.js";
4
+ import { formatGodModeCountdown } from "../shared/god-mode-run.js";
5
+ /** A restarted app gives its providers this long before a run's next attempt. */
6
+ const GOD_MODE_RESUME_DELAY_MS = 5_000;
3
7
  /** Serial continuation per goal; every provider turn still passes normal admission. */
4
8
  export class PersonalGoalRuntime {
5
9
  goals;
@@ -9,6 +13,12 @@ export class PersonalGoalRuntime {
9
13
  constructor(path, host) {
10
14
  this.host = host;
11
15
  this.goals = new PersonalGoals(path, (goal) => host.changed(goal));
16
+ // A GOD MODE run is non stop: one that was working when Atomic stopped
17
+ // carries on with its remaining time.
18
+ for (const goal of this.goals.liveGodModeRuns()) {
19
+ this.running.add(goal.id);
20
+ setTimeout(() => void this.run(goal), GOD_MODE_RESUME_DELAY_MS).unref?.();
21
+ }
12
22
  }
13
23
  async command(botId, threadId, command, trigger) {
14
24
  if (command.action === "help")
@@ -21,6 +31,9 @@ export class PersonalGoalRuntime {
21
31
  if (command.action === "start" || command.action === "resume") {
22
32
  if (this.host.busy(botId, threadId) || (goal && this.running.has(goal.id)))
23
33
  throw new Error("This conversation is still working. Wait for its turn to settle.");
34
+ if (command.action === "start" && command.godModeMs && !this.host.godMode?.(botId)) {
35
+ throw new Error("A GOD MODE run needs GOD MODE on for this bot. Turn it on in Settings, then start the run again.");
36
+ }
24
37
  goal = command.action === "start" ? this.goals.start(botId, threadId, { ...command, ...(trigger?.kind === "user" || trigger?.kind === "owner" ? { trigger } : {}) }) : this.goals.resume(threadId, command);
25
38
  // Persist the human command before provider setup reads the conversation.
26
39
  this.running.add(goal.id);
@@ -40,6 +53,8 @@ export class PersonalGoalRuntime {
40
53
  return this.describe(goal);
41
54
  }
42
55
  describe(goal) {
56
+ if (goal.godMode)
57
+ return `GOD MODE run ${goal.status}: ${goal.objective}\n${goal.detail}\nTime left: ${formatGodModeCountdown(goal.godMode.endsAt - Date.now())}. Attempts: ${goal.godMode.attempts + 1}.`;
43
58
  return `${goal.status}: ${goal.objective}\n${goal.detail}\nTurns: ${goal.turnCount}/${goal.maxTurns}. Tokens: ${goal.tokensUsed}${goal.tokenBudget === undefined ? "" : `/${goal.tokenBudget}`}.`;
44
59
  }
45
60
  steer(threadId) {
@@ -54,10 +69,21 @@ export class PersonalGoalRuntime {
54
69
  this.running.add(goal.id);
55
70
  try {
56
71
  while (this.goals.begin(goal.id)) {
57
- const result = await this.host.run(goal);
72
+ if (goal.godMode && this.host.godMode && !this.host.godMode(goal.botId)) {
73
+ goal.status = "stopped";
74
+ goal.detail = "GOD MODE was turned off, so the run stopped.";
75
+ this.goals.touch(goal);
76
+ break;
77
+ }
78
+ // A GOD MODE run treats a turn that could not start as a failed
79
+ // attempt (settle keeps it working); an ordinary goal pauses below.
80
+ const result = goal.godMode
81
+ ? await this.host.run(goal).catch((error) => ({ ok: false, text: error instanceof Error ? error.message : String(error), tools: 0 }))
82
+ : await this.host.run(goal);
58
83
  this.goals.settle(goal.id, result);
59
- // Give queued human input priority before reserving another turn.
60
- await new Promise((resolve) => setTimeout(resolve, 0));
84
+ // Give queued human input priority before reserving another turn; a
85
+ // GOD MODE run also pauses briefly after failed attempts.
86
+ await new Promise((resolve) => setTimeout(resolve, godModeNextAttemptDelay(goal)));
61
87
  }
62
88
  }
63
89
  catch {
@@ -3,7 +3,8 @@ export function updatePersonalGoalReceipt(goal, store) {
3
3
  return;
4
4
  const goalRun = { runId: goal.id, goal: goal.objective, status: goal.status,
5
5
  coordinatorBotId: goal.botId, coordinatorName: store.bot(goal.botId)?.name ?? "Bot",
6
- turnCount: goal.turnCount, maxTurns: goal.maxTurns, detail: `${goal.detail} Tokens: ${goal.tokensUsed}${goal.tokenBudget === undefined ? "" : `/${goal.tokenBudget}`}.`, startedAt: goal.createdAt };
6
+ turnCount: goal.turnCount, maxTurns: goal.maxTurns, detail: `${goal.detail} Tokens: ${goal.tokensUsed}${goal.tokenBudget === undefined ? "" : `/${goal.tokenBudget}`}.`, startedAt: goal.createdAt,
7
+ ...(goal.godMode ? { godMode: { endsAt: goal.godMode.endsAt, attempts: goal.godMode.attempts, log: goal.godMode.log.slice(-100) } } : {}) };
7
8
  if (goal.receiptMessageId)
8
9
  store.patchMessage(goal.threadId, goal.receiptMessageId, { goalRun });
9
10
  else
@@ -4,6 +4,9 @@ import { createHash, randomUUID } from "node:crypto";
4
4
  import { z } from "zod";
5
5
  import { writeFileAtomic } from "./atomic.js";
6
6
  import { parseGroupGoalDecision } from "./group-goal-run.js";
7
+ import { GOD_MODE_ACTIONS, GOD_MODE_STOP_KINDS, godModeRunInstructions } from "../shared/god-mode-run.js";
8
+ import { beginGodModeTurn, godModeRunLive, newGodModeRun, settleGodModeTurn } from "./god-mode-goal.js";
9
+ const godModeLog = z.object({ at: z.number(), stop: z.enum(GOD_MODE_STOP_KINDS), action: z.enum(GOD_MODE_ACTIONS), detail: z.string() });
7
10
  const goalSchema = z.object({
8
11
  id: z.string(), botId: z.string(), threadId: z.string(), objective: z.string(),
9
12
  criteria: z.array(z.string()), maxTurns: z.number().int().positive().max(1000),
@@ -14,6 +17,9 @@ const goalSchema = z.object({
14
17
  trigger: z.union([z.object({ kind: z.literal("owner") }), z.object({ kind: z.literal("user"), email: z.string().optional(), label: z.string().optional() })]).optional(),
15
18
  receiptMessageId: z.string().optional(), missing: z.number(), noProgress: z.number(),
16
19
  repeated: z.number(), lastReply: z.string(), lastBlocker: z.string(), blockers: z.number(),
20
+ /** A GOD MODE run (server/god-mode-goal.ts): bounded by time, not turns. */
21
+ godMode: z.object({ startedAt: z.number(), endsAt: z.number(), attempts: z.number(), failures: z.number(),
22
+ log: z.array(godModeLog) }).optional(),
17
23
  });
18
24
  const terminal = (goal) => goal.status === "completed" || goal.status === "stopped";
19
25
  /** A single durable objective per conversation. No provider, timer or authority lives here. */
@@ -33,7 +39,7 @@ export class PersonalGoals {
33
39
  this.loadError = "Saved goal state could not be read. It has been preserved for recovery; goals are paused.";
34
40
  }
35
41
  for (const goal of this.records)
36
- if (goal.status === "working") {
42
+ if (goal.status === "working" && !godModeRunLive(goal, Date.now())) {
37
43
  goal.status = "paused";
38
44
  goal.detail = "Atomic restarted. Use /goal resume to continue.";
39
45
  goal.updatedAt = Date.now();
@@ -46,6 +52,8 @@ export class PersonalGoals {
46
52
  save() { writeFileAtomic(this.path, JSON.stringify(this.records), { mode: 0o600 }); }
47
53
  touch(goal) { goal.updatedAt = Date.now(); goal.detail = redactSecretsInText(goal.detail); this.changed(goal); this.save(); }
48
54
  get(threadId) { return this.records.findLast((goal) => goal.threadId === threadId); }
55
+ /** GOD MODE runs still inside their time, e.g. after a restart. */
56
+ liveGodModeRuns() { return this.records.filter((goal) => godModeRunLive(goal, Date.now())); }
49
57
  byId(id) { return this.records.find((goal) => goal.id === id); }
50
58
  start(botId, threadId, input) {
51
59
  if (this.loadError)
@@ -53,7 +61,8 @@ export class PersonalGoals {
53
61
  const previous = this.get(threadId);
54
62
  if (previous && !terminal(previous))
55
63
  throw new Error("This conversation already has a goal. Resume it or stop it first.");
56
- const goal = goalSchema.parse({ ...input, objective: redactSecretsInText(input.objective), criteria: input.criteria.map(redactSecretsInText), id: randomUUID(), botId, threadId,
64
+ const { godModeMs, ...plain } = input;
65
+ const goal = goalSchema.parse({ ...plain, ...(godModeMs ? { godMode: newGodModeRun(Date.now(), godModeMs) } : {}), objective: redactSecretsInText(input.objective), criteria: input.criteria.map(redactSecretsInText), id: randomUUID(), botId, threadId,
57
66
  tokensUsed: 0, turnCount: 0, status: "working", detail: "Starting goal.",
58
67
  createdAt: Date.now(), updatedAt: Date.now(), missing: 0, noProgress: 0, repeated: 0, lastReply: "", lastBlocker: "", blockers: 0 });
59
68
  this.records.push(goal);
@@ -95,6 +104,10 @@ export class PersonalGoals {
95
104
  const goal = this.byId(id);
96
105
  if (!goal || goal.status !== "working")
97
106
  return false;
107
+ if (goal.godMode && !beginGodModeTurn(goal, Date.now())) {
108
+ this.touch(goal);
109
+ return false;
110
+ }
98
111
  if (goal.turnCount >= goal.maxTurns || (goal.tokenBudget !== undefined && goal.tokensUsed >= goal.tokenBudget)) {
99
112
  goal.status = "limit-reached";
100
113
  goal.detail = "Goal budget reached.";
@@ -167,6 +180,9 @@ export class PersonalGoals {
167
180
  else {
168
181
  goal.detail = decision?.detail ?? "Continue the objective and report a valid goal status.";
169
182
  }
183
+ // A GOD MODE run never stops on a failure, a question or a blocker.
184
+ if (goal.godMode && goal.status !== "completed")
185
+ settleGodModeTurn(goal, Date.now(), result, decision);
170
186
  if (goal.status === "working") {
171
187
  if (goal.turnCount >= goal.maxTurns || (goal.tokenBudget !== undefined && goal.tokensUsed >= goal.tokenBudget)) {
172
188
  goal.status = "limit-reached";
@@ -181,6 +197,8 @@ export class PersonalGoals {
181
197
  }
182
198
  }
183
199
  export function personalGoalInstructions(goal) {
200
+ if (goal.godMode)
201
+ return godModeRunInstructions({ ...goal, godMode: goal.godMode }, Date.now());
184
202
  return [
185
203
  "You are pursuing this conversation's durable goal. Complete authorized work; ordinary turn completion does not end the goal.",
186
204
  `Objective: ${goal.objective}`,
@@ -24,6 +24,9 @@ export const addAccountSchema = z.object({
24
24
  home: z.string().trim().min(1).max(4096).refine(noControl, "Folder cannot contain control characters").optional(),
25
25
  /** Whose account this is (shared/personal-bot.ts): absent is the company's. */
26
26
  owner: z.enum(["company", "personal"]).optional(),
27
+ /** The account's own endpoint and model, for providers that ask (setup). */
28
+ url: z.string().trim().max(512).optional(),
29
+ model: z.string().trim().min(1).max(200).refine(noControl, "Model cannot contain control characters").optional(),
27
30
  }).strict();
28
31
  export const renameAccountSchema = z.object({ displayName }).strict();
29
32
  /** PATCH body that sets (a number) or clears (null) an account's included
@@ -102,12 +105,28 @@ function installedCli(instances, driver) {
102
105
  .find((value) => typeof value === "string" && value.trim() !== "");
103
106
  return cli ? { cli } : {};
104
107
  }
105
- export function newApiKeyAccount(cfg, provider, name, dataDir) {
108
+ /** The endpoint and model a provider's add form asks for, checked against
109
+ * the provider's own pattern; anything it does not ask for is refused. */
110
+ export function accountSetup(provider, body) {
111
+ const ask = provider.setup;
112
+ if (body.url !== undefined && !ask?.url)
113
+ throw failure(400, "This provider has a fixed address.");
114
+ if (body.model !== undefined && !ask?.model)
115
+ throw failure(400, "This provider picks its model in the engine settings.");
116
+ const url = body.url?.replace(/\/+$/, "");
117
+ if (ask?.url && !(url && new RegExp(ask.url.pattern).test(url)))
118
+ throw failure(400, `Enter the address in this form: ${ask.url.example}`);
119
+ if (ask?.model?.required && !body.model)
120
+ throw failure(400, "Enter the model or deployment name.");
121
+ return { ...(url ? { url } : {}), ...(body.model ? { model: body.model } : {}) };
122
+ }
123
+ export function newApiKeyAccount(cfg, provider, name, dataDir, setup = {}) {
106
124
  const instances = persistableInstanceConfigs(cfg);
107
125
  const instanceId = `${provider.driver}-${randomUUID()}`;
108
126
  const config = {
109
127
  ...installedCli(instances, provider.driver),
110
128
  ...provider.config,
129
+ ...setup,
111
130
  // A Claude API account still needs a directory of its own, or it would
112
131
  // share (and collide with) the default Claude login's folder.
113
132
  ...(provider.driver === "claudeAgent" ? { configDir: join(dataDir, "providers", instanceId) } : {}),
@@ -1,10 +1,11 @@
1
- export const PROVIDER_KEY_KINDS = ["anthropic", "openaiCompat", "xai", "mistral", "ollamaCloud"];
1
+ export const PROVIDER_KEY_KINDS = ["anthropic", "openaiCompat", "xai", "mistral", "ollamaCloud", "huggingface"];
2
2
  const DEFAULT_URLS = {
3
3
  anthropic: "https://api.anthropic.com",
4
4
  openaiCompat: "https://openrouter.ai/api/v1",
5
5
  xai: "https://api.x.ai/v1",
6
6
  mistral: "https://api.mistral.ai/v1",
7
7
  ollamaCloud: "https://ollama.com/v1",
8
+ huggingface: "https://huggingface.co/api",
8
9
  };
9
10
  /** OpenAI's team headers (https://developers.openai.com/api/reference/overview):
10
11
  * which organization and project a key's requests count against. Only sent
@@ -15,6 +16,27 @@ export function openAiTeamHeaders(ids) {
15
16
  ...(ids.project?.trim() ? { "OpenAI-Project": ids.project.trim() } : {}),
16
17
  };
17
18
  }
19
+ const sameAddress = (left, right) => left.trim().replace(/\/+$/, "") === right.trim().replace(/\/+$/, "");
20
+ /** Every provider address this workspace already has configured on an engine. */
21
+ export function configuredProviderUrls(cfg) {
22
+ return Object.values(cfg.instances ?? {}).flatMap((instance) => {
23
+ const url = instance?.config?.url;
24
+ return typeof url === "string" && url.trim() ? [url.trim()] : [];
25
+ });
26
+ }
27
+ /** The address a key test may go to instead of the saved one. A caller may
28
+ * name any address for a key it pastes in the same request. A saved key is
29
+ * only ever sent to an address this workspace already configured, so no
30
+ * caller can have the server post a stored key to a host of its choosing. */
31
+ export function pastedKeyTestUrl(body, configured = []) {
32
+ const draft = body && typeof body === "object" ? body : null;
33
+ const url = typeof draft?.url === "string" ? draft.url.trim() : "";
34
+ if (!url)
35
+ return undefined;
36
+ if (typeof draft?.key === "string")
37
+ return url;
38
+ return configured.some((known) => sameAddress(known, url)) ? url : undefined;
39
+ }
18
40
  const MAX_MODELS = 5;
19
41
  function isLoopback(hostname) {
20
42
  const host = hostname.replace(/^\[|\]$/g, "");
@@ -25,6 +47,8 @@ export function providerModelsUrl(provider, base) {
25
47
  const root = (base?.trim() || DEFAULT_URLS[provider]).replace(/\/+$/, "");
26
48
  if (provider === "anthropic")
27
49
  return root.endsWith("/v1") ? `${root}/models` : `${root}/v1/models`;
50
+ if (provider === "huggingface")
51
+ return `${root}/whoami-v2`;
28
52
  return `${root}/models`;
29
53
  }
30
54
  function modelIds(body) {
@@ -74,6 +98,12 @@ export async function checkProviderKey(input, fetchImpl = fetch, timeoutMs = 10_
74
98
  const body = await response.json().catch(() => null);
75
99
  if (!body || typeof body !== "object")
76
100
  return { ok: false, reason: "unexpected", status: response.status };
101
+ if (input.provider === "huggingface") {
102
+ // whoami-v2 also returns the account's name, email and orgs; none belong in this verdict.
103
+ return typeof body.name === "string"
104
+ ? { ok: true, check: "authentication", models: [] }
105
+ : { ok: false, reason: "unexpected", status: response.status };
106
+ }
77
107
  if (authenticate) {
78
108
  const data = body.data;
79
109
  if (!data || typeof data !== "object" || Array.isArray(data)
@@ -0,0 +1,88 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { writeFileAtomic } from "./atomic.js";
3
+ // The roster files (bots.json, groups.json) are rewritten whole on every
4
+ // change, so what the server loads at boot is what the next save writes
5
+ // back. Reading a damaged file as "no bots" would therefore erase the
6
+ // roster for good. A missing file is a new workspace; anything else that
7
+ // cannot be read as a list of records is a failure, answered from the copy
8
+ // kept at the last good boot or, with no such copy, by refusing to start.
9
+ export class RegistryUnreadableError extends Error {
10
+ file;
11
+ reason;
12
+ kept;
13
+ constructor(file, reason, kept) {
14
+ super(`${file} could not be read (${reason}) and there is no earlier good copy to fall back on. `
15
+ + "Atomic will not start with an empty roster, because the next save would replace this file. "
16
+ + (kept ? `The unreadable file was copied to ${kept}. ` : "")
17
+ + "Restore the file from a backup, or move it aside to start a new roster.");
18
+ this.name = "RegistryUnreadableError";
19
+ this.file = file;
20
+ this.reason = reason;
21
+ this.kept = kept;
22
+ }
23
+ }
24
+ export function lastGoodPath(file) {
25
+ return `${file}.last-good`;
26
+ }
27
+ function readRecords(file) {
28
+ let text;
29
+ try {
30
+ text = readFileSync(file, "utf8");
31
+ }
32
+ catch (error) {
33
+ const code = error.code;
34
+ if (code === "ENOENT")
35
+ return { state: "missing" };
36
+ return { state: "bad", text: null, reason: code ?? "read failed" };
37
+ }
38
+ let parsed;
39
+ try {
40
+ parsed = JSON.parse(text);
41
+ }
42
+ catch {
43
+ return { state: "bad", text, reason: "not valid JSON" };
44
+ }
45
+ if (!Array.isArray(parsed))
46
+ return { state: "bad", text, reason: "not a list" };
47
+ if (!parsed.every((entry) => entry !== null && typeof entry === "object" && !Array.isArray(entry))) {
48
+ return { state: "bad", text, reason: "an entry is not a record" };
49
+ }
50
+ return { state: "ok", text, records: parsed };
51
+ }
52
+ function keepUnreadable(file, text, now) {
53
+ if (text === null)
54
+ return null;
55
+ const kept = `${file}.unreadable-${now()}`;
56
+ try {
57
+ writeFileAtomic(kept, text, { mode: 0o600 });
58
+ return kept;
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ export function loadRegistry(file, options = {}) {
65
+ const warn = options.warn ?? ((message) => console.error(message));
66
+ const primary = readRecords(file);
67
+ if (primary.state === "missing")
68
+ return [];
69
+ if (primary.state === "ok") {
70
+ const good = readRecords(lastGoodPath(file));
71
+ if (good.state !== "ok" || good.text !== primary.text) {
72
+ try {
73
+ writeFileAtomic(lastGoodPath(file), primary.text, { mode: 0o600 });
74
+ }
75
+ catch (error) {
76
+ warn(`[registry] could not keep a good copy of ${file}: ${error.message}`);
77
+ }
78
+ }
79
+ return primary.records;
80
+ }
81
+ const kept = keepUnreadable(file, primary.text, options.now ?? Date.now);
82
+ const good = readRecords(lastGoodPath(file));
83
+ if (good.state !== "ok")
84
+ throw new RegistryUnreadableError(file, primary.reason, kept);
85
+ warn(`[registry] ${file} could not be read (${primary.reason}); loaded the copy kept at the last good start instead.`
86
+ + (kept ? ` The unreadable file was copied to ${kept}.` : ""));
87
+ return good.records;
88
+ }
@@ -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
- if (companionToken && options.loopbackMutationToken !== undefined) {
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
- if (options.loopbackMutationToken !== undefined &&
478
- mutatingPublicRoute(method, path) &&
479
- !secureTokenMatch(headerValue(req.headers[DESKTOP_OWNER_HEADER]), options.loopbackMutationToken)) {
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" ? { keyUrl: provider.keyUrl, ...(provider.keyTest ? { keyTest: provider.keyTest } : {}) } : {}),
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 match = ACCOUNT.exec(path);
87
- if (path !== "/api/provider-accounts" && !match)
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
+ }