@chibitek/chibi 0.1.199 → 0.1.201

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 (88) hide show
  1. package/dist/assets/{TerminalPanel-BD8tgP0L.js → TerminalPanel-CF3ynjQ5.js} +1 -1
  2. package/dist/assets/{abnfDiagram-O67JEVCF-nJPyKFj_.js → abnfDiagram-O67JEVCF-DsLr5Rkp.js} +1 -1
  3. package/dist/assets/{arc-B27uNTWr.js → arc-BP9MW1JT.js} +1 -1
  4. package/dist/assets/{architectureDiagram-NJMV4G6O-1g_zkN0g.js → architectureDiagram-NJMV4G6O-DqqmVruY.js} +1 -1
  5. package/dist/assets/{blockDiagram-BEXU5L5S-B94wHtES.js → blockDiagram-BEXU5L5S-DCZycPW_.js} +1 -1
  6. package/dist/assets/{c4Diagram-YGBWAQC7-BURkZEQS.js → c4Diagram-YGBWAQC7-DAt7A5JI.js} +1 -1
  7. package/dist/assets/channel-CfAu_VOE.js +1 -0
  8. package/dist/assets/{chunk-2Q5K7J3B-CwYChOa9.js → chunk-2Q5K7J3B-D4XUKzBr.js} +1 -1
  9. package/dist/assets/{chunk-3FUC2YCW-D2NA_sYk.js → chunk-3FUC2YCW-BvKRlW0a.js} +2 -2
  10. package/dist/assets/{chunk-5VM5RSS4-7v_eBXTK.js → chunk-5VM5RSS4-CpaqfcXB.js} +1 -1
  11. package/dist/assets/{chunk-GTNCS2PH-Ck73ze4k.js → chunk-GTNCS2PH-bFX_YBLa.js} +1 -1
  12. package/dist/assets/{chunk-GWA4HPMP-BsOQoPsv.js → chunk-GWA4HPMP-D4ceVX3-.js} +1 -1
  13. package/dist/assets/{chunk-JWPE2WC7-DjQCd7nq.js → chunk-JWPE2WC7-BrM5oyHo.js} +1 -1
  14. package/dist/assets/{chunk-NETBCI7D-jsNR61zL.js → chunk-NETBCI7D-DJCITo_6.js} +1 -1
  15. package/dist/assets/{chunk-WEXAMYUT-iYv-JXOK.js → chunk-WEXAMYUT-DE5Rbq8q.js} +1 -1
  16. package/dist/assets/{chunk-XXDRQBXY-6hDTxNh3.js → chunk-XXDRQBXY-C6QndzP7.js} +1 -1
  17. package/dist/assets/{classDiagram-v2-NBCMYWYE-CqYfoIdc.js → classDiagram-v2-NBCMYWYE-DupxtheF.js} +1 -1
  18. package/dist/assets/{cose-bilkent-JH36ORCC-BFoBUYoI.js → cose-bilkent-JH36ORCC-K2_JJ1Os.js} +1 -1
  19. package/dist/assets/{cynefin-OW5HDTMX-C8beDmoE.js → cynefin-OW5HDTMX-D1iCt_1r.js} +1 -1
  20. package/dist/assets/{cynefinDiagram-VND7K2PF-B14Y6q3s.js → cynefinDiagram-VND7K2PF-BxIP-LPT.js} +1 -1
  21. package/dist/assets/{dagre-6A5THRUB-Bxfl4ARR.js → dagre-6A5THRUB-C9f6kI0w.js} +1 -1
  22. package/dist/assets/{diagram-22UHCM2B-C0Y9Gxes.js → diagram-22UHCM2B-DX1Js_iQ.js} +1 -1
  23. package/dist/assets/{diagram-3UASUU5V-CT665UIR.js → diagram-3UASUU5V-Dok5oHqH.js} +1 -1
  24. package/dist/assets/{diagram-ATOU4E4O-DGXaVJI8.js → diagram-ATOU4E4O-CZjPw12I.js} +1 -1
  25. package/dist/assets/{diagram-CDSNMT55-B-k11v8T.js → diagram-CDSNMT55-CcdGyWm0.js} +1 -1
  26. package/dist/assets/{diagram-MLGK6HIB-DQd_tGlF.js → diagram-MLGK6HIB-BuyhR8Yt.js} +1 -1
  27. package/dist/assets/{diagram-MPIPVDR6-CookmvAU.js → diagram-MPIPVDR6-DyfzZWWJ.js} +1 -1
  28. package/dist/assets/{ebnfDiagram-ZINNZB2B-koVtdZMh.js → ebnfDiagram-ZINNZB2B-DbX8lcW9.js} +1 -1
  29. package/dist/assets/{elk-276RUBZZ-CCULrKTu.js → elk-276RUBZZ-B_1y08rH.js} +1 -1
  30. package/dist/assets/{erDiagram-OPXOYQCR-7tX_DN1F.js → erDiagram-OPXOYQCR-CMNLleGm.js} +1 -1
  31. package/dist/assets/{flowDiagram-KWPJA3E3-BP9lx54W.js → flowDiagram-KWPJA3E3-BWNxAxrN.js} +1 -1
  32. package/dist/assets/{ganttDiagram-FUAMR5RP-DrD3pdCf.js → ganttDiagram-FUAMR5RP-DIbuHGn_.js} +1 -1
  33. package/dist/assets/{gitGraphDiagram-X574FWY7-CGoBra5o.js → gitGraphDiagram-X574FWY7-DOQ7lEBd.js} +1 -1
  34. package/dist/assets/{index-DUPDb_l5.js → index-AVvV2BDP.js} +179 -179
  35. package/dist/assets/{index-0ryDWs_U.js → index-DwCyxkQ-.js} +1 -1
  36. package/dist/assets/{infoDiagram-VRGFBTTK-TBE6eo6e.js → infoDiagram-VRGFBTTK-B6jXr3vk.js} +1 -1
  37. package/dist/assets/{ishikawaDiagram-OU5B5YK6-CXFR0VYe.js → ishikawaDiagram-OU5B5YK6-BMzUYIuP.js} +1 -1
  38. package/dist/assets/{journeyDiagram-ZHPQQLJL-0i24WNpp.js → journeyDiagram-ZHPQQLJL-BSna9Sw4.js} +1 -1
  39. package/dist/assets/{kanban-definition-PNTS6WVX-BVO7zH5N.js → kanban-definition-PNTS6WVX-nGY_xsmB.js} +1 -1
  40. package/dist/assets/{linear-CJa9b6Jv.js → linear-ClawroOG.js} +1 -1
  41. package/dist/assets/{mermaid.core-Cr_zJcfI.js → mermaid.core-QWILSY7q.js} +5 -5
  42. package/dist/assets/{mindmap-definition-NLK3R4M7-DGOtBRni.js → mindmap-definition-NLK3R4M7-BHBjOj_N.js} +1 -1
  43. package/dist/assets/{pegDiagram-GJSIUBJH-a4X1U2M6.js → pegDiagram-GJSIUBJH-BEhI0umY.js} +1 -1
  44. package/dist/assets/{pieDiagram-5QR66LMP-C6YKVkOM.js → pieDiagram-5QR66LMP-BNrNnFcF.js} +1 -1
  45. package/dist/assets/{quadrantDiagram-O4NWA36T-tthWiJZV.js → quadrantDiagram-O4NWA36T-DU8ZKo3R.js} +1 -1
  46. package/dist/assets/{railroadDiagram-XR7U4H2S-BaCi4bjC.js → railroadDiagram-XR7U4H2S-CXpikGSY.js} +1 -1
  47. package/dist/assets/{requirementDiagram-PLB6GJNP-B1gkcVzT.js → requirementDiagram-PLB6GJNP-T2kWY6dy.js} +1 -1
  48. package/dist/assets/{sankeyDiagram-IPEJSGJF-Q6NzlkZ1.js → sankeyDiagram-IPEJSGJF-DUVsoHCX.js} +1 -1
  49. package/dist/assets/{sequenceDiagram-PO4LG4MO-DXkHQxwi.js → sequenceDiagram-PO4LG4MO-BqI-CnQQ.js} +1 -1
  50. package/dist/assets/{sizeCapture-INFHLROL-DFiBxWwr.js → sizeCapture-INFHLROL-CHRKcWjb.js} +1 -1
  51. package/dist/assets/{stateDiagram-v2-GCMORJYK-CWi-jeEW.js → stateDiagram-v2-GCMORJYK-Drb1kh-m.js} +1 -1
  52. package/dist/assets/{swimlanes-2SLR337P-DEMqxNj4.js → swimlanes-2SLR337P-D6bNO7iC.js} +1 -1
  53. package/dist/assets/swimlanesDiagram-TC7HE7FX-BBg0kB8F.js +8 -0
  54. package/dist/assets/{timeline-definition-EJHVYXUP-CutULAnt.js → timeline-definition-EJHVYXUP-30UJPQln.js} +1 -1
  55. package/dist/assets/{usecaseDiagram-POWQR4AR-Dbvwnx98.js → usecaseDiagram-POWQR4AR-CsfAqILe.js} +1 -1
  56. package/dist/assets/{vennDiagram-UO4OBE2U-HSO7dMBn.js → vennDiagram-UO4OBE2U-D63qiwyq.js} +1 -1
  57. package/dist/assets/{wardleyDiagram-VNRHLVJA-ShLPdgOQ.js → wardleyDiagram-VNRHLVJA-CwMexqnm.js} +1 -1
  58. package/dist/assets/{xychartDiagram-PMCCYNJV-DCdsZ7i5.js → xychartDiagram-PMCCYNJV-DFkAUNxr.js} +1 -1
  59. package/dist/index.html +1 -1
  60. package/dist-server/container-mcp.js +81 -81
  61. package/dist-server/drivers/agents-proxy.js +95 -83
  62. package/dist-server/index.js +2253 -1755
  63. package/dist-server/openmausbot.js +597 -566
  64. package/dist-server/pair-cli.js +597 -566
  65. package/dist-server/server/agents-token-file.js +23 -0
  66. package/dist-server/server/bot-work-modes.js +24 -12
  67. package/dist-server/server/chibitek-mcp-credentials.js +207 -0
  68. package/dist-server/server/chibitek-mcp-signin.js +124 -0
  69. package/dist-server/server/company-mcp-tenancy.js +2 -2
  70. package/dist-server/server/drivers/agents-client.js +23 -9
  71. package/dist-server/server/index.js +29 -13
  72. package/dist-server/server/mcp-tool-hints.js +15 -1
  73. package/dist-server/server/mcp-turn.js +2 -1
  74. package/dist-server/server/nexus-memory/backoff.js +40 -8
  75. package/dist-server/server/nexus-memory/client.js +44 -12
  76. package/dist-server/server/nexus-memory/index.js +3 -3
  77. package/dist-server/server/repo-github.js +128 -0
  78. package/dist-server/server/repos.js +11 -2
  79. package/dist-server/server/routes/repos.js +43 -1
  80. package/dist-server/server/routine-mochii-sync.js +1 -1
  81. package/dist-server/server/stiki-desktop-session.js +18 -5
  82. package/dist-server/server/stiki-session.js +3 -2
  83. package/dist-server/server/system-prompt.js +10 -1
  84. package/dist-server/server/workspace-backup-policy.js +4 -3
  85. package/dist-server/vps-container-mcp.js +81 -81
  86. package/package.json +1 -1
  87. package/dist/assets/channel-BBCt_i2t.js +0 -1
  88. package/dist/assets/swimlanesDiagram-TC7HE7FX-BebBq0sX.js +0 -8
@@ -59,6 +59,7 @@ import { fitsOnOneLine, parseBotProfilePatch } from "./bot-profile.js";
59
59
  import { groupTurnCwd } from "./room-cwd.js";
60
60
  import { RepoRegistry } from "./repos.js";
61
61
  import { checkedThreadRepoPatch, delegatedThreadRepoIds, planTurnRepos, repoPromptSection } from "./repo-links.js";
62
+ import { GitHubRepos } from "./repo-github.js";
62
63
  import { createThreadWorktree, githubCliStatus, openPullRequest, removeThreadWorktree, worktreeStatus } from "./repo-worktrees.js";
63
64
  import { createRepoRoutes } from "./routes/repos.js";
64
65
  import { createPinOrderRoutes } from "./routes/pin-order.js";
@@ -245,6 +246,7 @@ import { allowedScopes, createEmailSignIn, parseAllowList } from "./account-sign
245
246
  import { ProviderAuthSessions } from "./provider-auth-sessions.js";
246
247
  import { clearSessionCookie, clientBotPatchViolation, bearerToken, clientGroupPatchViolation, clientTaskPatchViolation, isLoopbackHost, isProxied, labelFromUserAgent, requestOrigin, requestSource, requiredScope, resolveLoopbackTrust, resolveRequestAuth, parseCookies, serializeSessionCookie, sessionCookieName, } from "./request-auth.js";
247
248
  import { cookieMaxAgeSeconds, formatPairingCode, SessionRegistry } from "./sessions.js";
249
+ import { writeAgentsTokenFile } from "./agents-token-file.js";
248
250
  import { editorHasEntry, editorInstalled, editorTarget, editorTargets, registerWithEditor, unregisterFromEditor } from "./editor-connect.js";
249
251
  import { claudeCodeHasEntry, claudeCodeMcpEntry, registerWithClaudeCode, unregisterFromClaudeCode } from "./claude-code-connect.js";
250
252
  import { appendAssistantAudit, ASSISTANT_TOKEN_PREFIX, assistantSenderId, ConnectedAssistants, isAssistantSender, withAssistantProvenance, recentAssistantAudit, removeAssistantToken, writeAssistantToken } from "./connected-assistants.js";
@@ -349,6 +351,7 @@ import { appClientEnabled, sourceEnabled } from "./watch-along/transcript-source
349
351
  import { pastedTranscriptProvider } from "./watch-along/pasted-transcript.js";
350
352
  import { publicTranscriptProvider } from "./watch-along/youtube-public-transcript.js";
351
353
  import { onStikiSessionChange, setStikiSessionSource, stikiSession } from "./stiki-session.js";
354
+ import { createChibitekMcpSignIn } from "./chibitek-mcp-signin.js";
352
355
  import { DesktopStikiSession } from "./stiki-desktop-session.js";
353
356
  import { CLEANUP_INSTRUCTIONS } from "./dictation.js";
354
357
  import { hipaaState } from "./hipaa.js";
@@ -1249,11 +1252,17 @@ const oauthAccounts = new OAuthAccounts({ vault: accountVault, clients: oauthCli
1249
1252
  // private channel (server/mcp-secrets.ts).
1250
1253
  if (DESKTOP_MANAGED && utilityParentPort)
1251
1254
  setMcpSecretSender(postDesktopPrivateMessage);
1252
- // The Chibitek sign-in (Team Rooms' identity): Electron main owns it and
1253
- // pushes the current token here; signed out until it does.
1255
+ // The Chibitek sign-in (Team Rooms' identity, and Nexus's and Mochii's: server/chibitek-mcp-signin.ts): Electron main owns it and pushes the current token here; signed out until it does.
1254
1256
  const desktopStiki = DESKTOP_MANAGED && utilityParentPort ? new DesktopStikiSession(postDesktopPrivateMessage) : null;
1255
1257
  if (desktopStiki)
1256
1258
  setStikiSessionSource(desktopStiki);
1259
+ const mcpSignIn = createChibitekMcpSignIn({ dataDir: DATA_DIR, session: stikiSession, servers: () => cfg.mcpServers, bridge: resolveMcpRemoteBridge, authState: () => mcpAuthState, notices: () => mcpAccessNotices, log: (line) => console.warn(`[chibitek-mcp] ${line}`), mayInstall: (name, url) => !hostedModels && !HOSTED_WORKSPACE && managedPolicy.mcpAllowed(name, url), changed: () => broadcast({ kind: "config", ...configStatus() }), persist: async (next) => { if (mcpConfigBusy)
1260
+ throw new Error("MCP servers are already being updated."); mcpConfigBusy = true; try {
1261
+ await persistMcpServers(next);
1262
+ }
1263
+ finally {
1264
+ mcpConfigBusy = false;
1265
+ } } });
1257
1266
  /** Why this server may not run GOD MODE, or null. A shared or hosted
1258
1267
  * workspace refuses it for the same reason it refuses a bot's Full access:
1259
1268
  * there, only the operator's own shared-workspace policy may grant Full. */
@@ -1568,6 +1577,9 @@ function agentsIntegration(botId, threadId, depth, skillAuthoring, generation, r
1568
1577
  roomCoordination,
1569
1578
  ownThreadCreation,
1570
1579
  });
1580
+ // Also on disk, read per call: an engine keeps the proxy process across
1581
+ // turns, so the spawn environment alone goes stale (agents-token-file.ts).
1582
+ const tokenFile = writeAgentsTokenFile(botId, threadId, token);
1571
1583
  return {
1572
1584
  command: process.execPath,
1573
1585
  args: [agentsProxyPath],
@@ -1577,6 +1589,7 @@ function agentsIntegration(botId, threadId, depth, skillAuthoring, generation, r
1577
1589
  OMB_BOT_ID: botId,
1578
1590
  OMB_THREAD_ID: threadId,
1579
1591
  OMB_COMMS_TOKEN: token,
1592
+ OMB_COMMS_TOKEN_FILE: tokenFile,
1580
1593
  OMB_TURN_DEPTH: String(depth),
1581
1594
  OMB_ROOM_TURN: roomCoordination ? "1" : "0",
1582
1595
  OMB_OWN_THREAD_CREATION: ownThreadCreation ? "1" : "0",
@@ -2393,7 +2406,7 @@ setInterval(() => void refreshPersonalMdm(), 5 * 60_000).unref?.();
2393
2406
  // MDM profile the Private Bot reads (NexusMemory, HipaaMode keys).
2394
2407
  const nexusMemory = new NexusMemory({
2395
2408
  dataDir: DATA_DIR,
2396
- config: () => cfg,
2409
+ config: () => cfg, serverSpec: (spec) => spec && mcpSignIn.credentialed(spec), signIn: { refresh: () => mcpSignIn.credentials.refreshAfterRejection() },
2397
2410
  // HIPAA mode is the one workspace switch (MDM, environment, or the
2398
2411
  // Administrator's setting): patient-data items never go to Nexus.
2399
2412
  mdm: () => ({ nexusMemoryAlways: personalMdm.nexusMemoryAlways(), hipaaManaged: workspaceHipaa().enabled }),
@@ -2432,7 +2445,7 @@ function noteNexusLocalMemory(botId) {
2432
2445
  }
2433
2446
  }
2434
2447
  nexusMemory.start();
2435
- const routineMochiiSync = RoutineMochiiSync.start({ dataDir: DATA_DIR, config: () => cfg, listRoutines: () => routines?.listRoutines() ?? [], listRuns: () => routines?.listRuns() ?? [], botName: (id) => store.bot(id)?.name, timeZone: () => routineTimeZone() });
2448
+ const routineMochiiSync = RoutineMochiiSync.start({ dataDir: DATA_DIR, config: () => cfg, serverSpec: (spec) => spec && mcpSignIn.credentialed(spec), listRoutines: () => routines?.listRoutines() ?? [], listRuns: () => routines?.listRuns() ?? [], botName: (id) => store.bot(id)?.name, timeZone: () => routineTimeZone() });
2436
2449
  // Register the Private Bot's Nexus key as soon as there is a Private Bot, so
2437
2450
  // nothing else can register first (Nexus trusts the first key).
2438
2451
  // (Deferred: the store is created further down.)
@@ -13628,7 +13641,7 @@ function botInterviewContext(mode) {
13628
13641
  // page nobody opened.
13629
13642
  const bridge = isChibitekMochii(parsed.server) || isChibitekNexus(parsed.server);
13630
13643
  const spec = customMcpServers(cfg, [name])[name];
13631
- const status = bridge && !(spec && mcpToolHints.seen(name, spec)) ? "signIn" : "ready";
13644
+ const status = bridge && !mcpSignIn.signedIn(spec) && !(spec && mcpToolHints.seen(name, spec)) ? "signIn" : "ready";
13632
13645
  tools.push({ id: `mcp:${name}`, kind: "mcp", name: isChibitekMochii(parsed.server) ? "mochii" : isChibitekNexus(parsed.server) ? "nexus" : name, status });
13633
13646
  }
13634
13647
  const accounts = oauthAccounts.status();
@@ -14555,7 +14568,7 @@ function mcpServerResponse() {
14555
14568
  // which keys sit in the OS secure store, and what needs the person;
14556
14569
  // names and ids only, never a value
14557
14570
  const secrets = mcpServerSecretView(server.name, cfg.mcpServers?.[server.name]);
14558
- return { ...listed, ...secrets, ...(unavailable ? { unavailable } : {}), ...(auth ? { auth } : {}) };
14571
+ return { ...listed, ...secrets, ...(unavailable ? { unavailable } : {}), ...(auth ? { auth } : {}), ...(mcpSignIn.signedInAs(spec) ? { chibitekSignIn: mcpSignIn.signedInAs(spec) } : {}) };
14559
14572
  });
14560
14573
  return {
14561
14574
  servers,
@@ -14756,7 +14769,7 @@ function warmMcpToolHints(custom) {
14756
14769
  if (result.notice)
14757
14770
  mcpAccessNotices.set(name, result.notice);
14758
14771
  // A background check is a background start: a missing sign-in backs the server off, never opens a browser.
14759
- if (result.signInRequired)
14772
+ if (result.signInRequired && !mcpSignIn.refused(name, spec))
14760
14773
  mcpAuthState.noteSignInRequired(name, spec);
14761
14774
  return result;
14762
14775
  })).catch(() => { });
@@ -14765,7 +14778,7 @@ function warmMcpToolHints(custom) {
14765
14778
  /** Each configured server's sign-in state, and whether it is otherwise broken. */
14766
14779
  const mcpAuthState = new McpAuthStateStore(join(DATA_DIR, "mcp-auth-state.json"));
14767
14780
  const mcpHealth = new McpHealthStore();
14768
- const mcpTurn = mcpTurnPolicy({ auth: mcpAuthState, health: mcpHealth, signalDir: mcpAuthSignalDir, specs: () => customMcpServers(cfg),
14781
+ const mcpTurn = mcpTurnPolicy({ auth: mcpAuthState, health: mcpHealth, signalDir: mcpAuthSignalDir, specs: () => customMcpServers(cfg), credentialRefused: (name, spec) => mcpSignIn.refused(name, spec),
14769
14782
  reportUnavailable: (threadId, detail) => { const bot = store.botByThread(threadId); if (bot)
14770
14783
  reportIncident({ kind: "mcp-unavailable", bot, threadId, detail }); } });
14771
14784
  function syncMcpAuthState() { mcpTurn.sync(); }
@@ -14787,7 +14800,7 @@ function engineMcpServers(bot) {
14787
14800
  // "nexus_not_enabled") is not mounted: no turn waits on a refusal.
14788
14801
  const servers = mcpAccessNotices.without(managedPolicy.filterMcp(customMcpServers(cfg, connectionsFor(bot, requested, personalCfg().connections.mcpServers))));
14789
14802
  for (const [name, spec] of Object.entries(servers))
14790
- servers[name] = bridgedMcpServer(spec, false);
14803
+ servers[name] = mcpSignIn.credentialed(bridgedMcpServer(spec, false));
14791
14804
  return servers;
14792
14805
  }
14793
14806
  /** Save `mcpServers`: secrets sealed in the desktop's encrypted store first,
@@ -15316,6 +15329,7 @@ function watchAccess() {
15316
15329
  const watchPolicy = () => ({ hipaa: workspaceHipaa().enabled, chibitekSignedIn: watchAccess().allowed });
15317
15330
  // Signing in or out of Stiki can change who sees Watch-Along.
15318
15331
  onStikiSessionChange(() => broadcast({ kind: "config", ...configStatus() }));
15332
+ mcpSignIn.start(); // the Chibitek MCP sign-in's stores all exist by now
15319
15333
  const watchInputs = () => killSwitchInputs({ settings: switchLayer(cfg.watchAlong), managed: managedLayer(personalMdm.watchAlong()), remote: watchRemoteFlags.current() });
15320
15334
  /** HIPAA mode, the workspace's or the bot's own: no Watch-Along model call
15321
15335
  * and no frame leaves this Mac. */
@@ -16186,6 +16200,8 @@ ROUTES.push(createPinOrderRoutes({ store, visible: (auth) => visibleTo(viewerFor
16186
16200
  // server/routes/repos.ts for the routes and docs/chibitek/README.md.
16187
16201
  ROUTES.push(createRepoRoutes({
16188
16202
  registry: repoRegistry,
16203
+ github: new GitHubRepos(repoRegistry),
16204
+ threadRepoIds: (threadId) => store.repoThread(threadId) ? threadEffectiveRepoIds(threadId) : null,
16189
16205
  fromBot: (req) => authorizedInternalCapability(req.headers.authorization) !== null,
16190
16206
  setThreadRepos: (threadId, patch) => {
16191
16207
  const owner = store.repoThread(threadId);
@@ -23915,7 +23931,7 @@ const handleRequest = async (req, res) => {
23915
23931
  const testBlocked = mcpLaunchBlocker(parsed.server);
23916
23932
  if (testBlocked)
23917
23933
  return json(res, 409, { error: `${mcpTest[1]} cannot start yet: ${mcpLaunchBlockerReason(testBlocked)}`, code: testBlocked });
23918
- if (mcpProbesInFlight >= MAX_CONCURRENT_MCP_PROBES && !interactiveMcpProbe.has(bridgedMcpServer(parsed.server, true))) {
23934
+ if (mcpProbesInFlight >= MAX_CONCURRENT_MCP_PROBES && !interactiveMcpProbe.has(mcpSignIn.credentialed(bridgedMcpServer(parsed.server, true)))) {
23919
23935
  return json(res, 429, { error: "Two MCP connection tests are already running." });
23920
23936
  }
23921
23937
  const controller = new AbortController();
@@ -23928,7 +23944,7 @@ const handleRequest = async (req, res) => {
23928
23944
  try {
23929
23945
  // Test may open a browser even without ?connect=1. Keep its callback
23930
23946
  // listener alive for the same MFA window as Reconnect.
23931
- const probed = await interactiveMcpProbe(bridgedMcpServer(parsed.server, true), controller.signal);
23947
+ const probed = await mcpSignIn.probe(parsed.server, () => interactiveMcpProbe(mcpSignIn.credentialed(bridgedMcpServer(parsed.server, true)), controller.signal));
23932
23948
  if (probed.ok) {
23933
23949
  mcpAuthState.noteOk(mcpTest[1]);
23934
23950
  mcpHealth.noteOk(mcpTest[1]);
@@ -23967,7 +23983,7 @@ const handleRequest = async (req, res) => {
23967
23983
  const reconnectBlocked = mcpLaunchBlocker(parsed.server);
23968
23984
  if (reconnectBlocked)
23969
23985
  return json(res, 409, { error: `${name} cannot start yet: ${mcpLaunchBlockerReason(reconnectBlocked)}`, code: reconnectBlocked });
23970
- if (mcpProbesInFlight >= MAX_CONCURRENT_MCP_PROBES && !interactiveMcpProbe.has(bridgedMcpServer(parsed.server, true))) {
23986
+ if (mcpProbesInFlight >= MAX_CONCURRENT_MCP_PROBES && !interactiveMcpProbe.has(mcpSignIn.credentialed(bridgedMcpServer(parsed.server, true)))) {
23971
23987
  return json(res, 429, { error: "Two MCP connection tests are already running." });
23972
23988
  }
23973
23989
  const controller = new AbortController();
@@ -23978,7 +23994,7 @@ const handleRequest = async (req, res) => {
23978
23994
  res.once("close", disconnect);
23979
23995
  mcpProbesInFlight += 1;
23980
23996
  try {
23981
- const probed = await interactiveMcpProbe(bridgedMcpServer(parsed.server, true), controller.signal);
23997
+ const probed = await mcpSignIn.probe(parsed.server, () => interactiveMcpProbe(mcpSignIn.credentialed(bridgedMcpServer(parsed.server, true)), controller.signal));
23982
23998
  if (probed.ok) {
23983
23999
  mcpAuthState.noteOk(name);
23984
24000
  mcpHealth.noteOk(name);
@@ -22,6 +22,7 @@ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
22
22
  import { dirname } from "node:path";
23
23
  import { MCP_TOOL_NAME as TOOL_NAME } from "../shared/mcp-tool-ref.js";
24
24
  import { mcpRemoteTarget } from "./mcp-remote-bridge.js";
25
+ import { STIKI_BEARER_HEADER_ARG } from "./chibitek-mcp-credentials.js";
25
26
  const HINT_KEYS = ["readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint"];
26
27
  const SNAKE = {
27
28
  readOnlyHint: "read_only_hint",
@@ -49,6 +50,19 @@ export function toolAnnotations(raw) {
49
50
  export function isReadOnlyMcpTool(annotations) {
50
51
  return annotations?.readOnlyHint === true && annotations.destructiveHint !== true;
51
52
  }
53
+ /** The Chibitek sign-in's header (server/chibitek-mcp-credentials.ts) is a
54
+ * credential, not a different server: a signed-in start is the same server. */
55
+ function withoutStikiHeader(args) {
56
+ const out = [];
57
+ for (let index = 0; index < args.length; index += 1) {
58
+ if (args[index] === "--header" && args[index + 1] === STIKI_BEARER_HEADER_ARG) {
59
+ index += 1;
60
+ continue;
61
+ }
62
+ out.push(args[index]);
63
+ }
64
+ return out;
65
+ }
52
66
  /** Identifies a server's transport target, never its credentials: hints
53
67
  * learned from one command or address are not reused for another server
54
68
  * that was later given the same name. */
@@ -58,7 +72,7 @@ export function mcpServerFingerprint(spec) {
58
72
  const bridge = "url" in spec ? null : mcpRemoteTarget(spec);
59
73
  const target = "url" in spec
60
74
  ? { type: spec.type, url: spec.url }
61
- : bridge ? { mcpRemote: bridge.url, args: bridge.extraArgs } : { command: spec.command, args: spec.args };
75
+ : bridge ? { mcpRemote: bridge.url, args: withoutStikiHeader(bridge.extraArgs) } : { command: spec.command, args: spec.args };
62
76
  return createHash("sha256").update(JSON.stringify(target)).digest("hex").slice(0, 32);
63
77
  }
64
78
  /** Hints older than this are not trusted at all: a tool that changed from a
@@ -7,7 +7,8 @@ export function mcpTurnPolicy(deps) {
7
7
  if (!signals.length)
8
8
  return;
9
9
  const specs = deps.specs();
10
- deps.auth.ingest(signals, specs);
10
+ const refused = (signal) => signal.kind === "sign-in-required" && Boolean(specs[signal.name]) && deps.credentialRefused?.(signal.name, specs[signal.name]) === true;
11
+ deps.auth.ingest(signals.filter((signal) => !refused(signal)), specs);
11
12
  for (const signal of deps.health.ingest(signals, specs)) {
12
13
  if (signal.threadId)
13
14
  deps.reportUnavailable(signal.threadId, `the "${signal.name}" MCP server ${signal.kind === "crashed" ? "stopped during the turn" : "would not start"}; the turn ran on without its tools`);
@@ -1,7 +1,7 @@
1
- import { NexusInitializeError, NexusUnavailableError } from "./client.js";
1
+ import { NexusAuthError, NexusInitializeError, NexusUnavailableError } from "./client.js";
2
2
  // One shared wait after Nexus fails: 1, 5, 15, then 30 minutes while the
3
- // outage lasts (unreachable, or signed out, which makes the bridge open a
4
- // sign-in page). A failure more than an hour after the previous one is a
3
+ // outage lasts (unreachable, or a refused sign-in that a refresh could not
4
+ // fix). A failure more than an hour after the previous one is a
5
5
  // new blip and starts over at one minute, so a night of Wi-Fi drops does
6
6
  // not leave every later call blocked for half an hour.
7
7
  const WAITS_MS = [60_000, 300_000, 900_000, 1_800_000];
@@ -27,20 +27,48 @@ export class UnavailableBackoff {
27
27
  }
28
28
  }
29
29
  /** One failed initialize is retried and does not count. The retry failing
30
- * trips the breaker. Any other outage trips immediately. */
31
- export function guardNexusClient(client, backoff, now, log) {
30
+ * trips the breaker. A refused sign-in (NexusAuthError) is not an outage: it
31
+ * refreshes the Chibitek sign-in and retries at once on a client built with
32
+ * the new token; only when no new token comes back does it trip the breaker.
33
+ * Any other outage trips immediately.
34
+ *
35
+ * `client` may be a getter so a retry after a refresh reaches the client the
36
+ * new token built (nexus-memory/index.ts rebuilds it when the spec changes). */
37
+ export function guardNexusClient(client, backoff, now, log, signIn) {
38
+ const current = () => {
39
+ const resolved = typeof client === "function" ? client() : client;
40
+ if (!resolved)
41
+ throw new NexusUnavailableError("Nexus is not connected on this computer");
42
+ return resolved;
43
+ };
32
44
  const finish = async (tool, args, timeoutMs) => {
33
45
  try {
34
- const result = await client.call(tool, args, timeoutMs);
46
+ const result = await current().call(tool, args, timeoutMs);
35
47
  backoff.succeeded();
36
48
  return result;
37
49
  }
38
50
  catch (error) {
39
- if (!(error instanceof NexusInitializeError) && error instanceof NexusUnavailableError)
51
+ if (!(error instanceof NexusInitializeError) && !(error instanceof NexusAuthError) && error instanceof NexusUnavailableError)
40
52
  backoff.failed(now());
41
53
  throw error;
42
54
  }
43
55
  };
56
+ const afterSignInRefused = async (error, tool, args, timeoutMs) => {
57
+ if (signIn && await signIn.refresh().catch(() => false)) {
58
+ log("Nexus refused the sign-in; refreshed the Chibitek sign-in and retrying now");
59
+ try {
60
+ return await finish(tool, args, timeoutMs);
61
+ }
62
+ catch (again) {
63
+ if (again instanceof NexusAuthError || again instanceof NexusInitializeError)
64
+ backoff.failed(now());
65
+ throw again;
66
+ }
67
+ }
68
+ // Nothing new to try: wait like any outage rather than resend a refused token.
69
+ backoff.failed(now());
70
+ throw error;
71
+ };
44
72
  return {
45
73
  call: async (tool, args, timeoutMs) => {
46
74
  const remaining = backoff.remainingMs(now());
@@ -50,6 +78,8 @@ export function guardNexusClient(client, backoff, now, log) {
50
78
  return await finish(tool, args, timeoutMs);
51
79
  }
52
80
  catch (error) {
81
+ if (error instanceof NexusAuthError)
82
+ return afterSignInRefused(error, tool, args, timeoutMs);
53
83
  if (!(error instanceof NexusInitializeError))
54
84
  throw error;
55
85
  log("Nexus initialize failed; retrying once");
@@ -57,12 +87,14 @@ export function guardNexusClient(client, backoff, now, log) {
57
87
  return await finish(tool, args, timeoutMs);
58
88
  }
59
89
  catch (again) {
90
+ if (again instanceof NexusAuthError)
91
+ return afterSignInRefused(again, tool, args, timeoutMs);
60
92
  if (again instanceof NexusInitializeError)
61
93
  backoff.failed(now());
62
94
  throw again;
63
95
  }
64
96
  }
65
97
  },
66
- close: () => client.close(),
98
+ close: () => current().close(),
67
99
  };
68
100
  }
@@ -1,7 +1,8 @@
1
- // How the harness itself calls Nexus tools. Atomic holds no Nexus token: bots
2
- // reach Nexus through the configured `nexus` MCP server, which on a Chibitek
3
- // install is the bundled mcp-remote bridge holding the person's own Stiki
4
- // sign-in in its own cache. The harness speaks MCP to that same server, so
1
+ // How the harness itself calls Nexus tools. Bots reach Nexus through the
2
+ // configured `nexus` MCP server: on a Chibitek install, the bundled mcp-remote
3
+ // bridge carrying the person's Chibitek (Stiki) sign-in from Atomic itself
4
+ // (server/chibitek-mcp-credentials.ts), or its own cached browser sign-in
5
+ // when nobody signed in to Atomic. The harness speaks MCP to that same server, so
5
6
  // every write lands under the signed-in person and no auth code changes.
6
7
  // A remote `nexus` entry (url + headers) is spoken to over HTTP instead.
7
8
  import { PROVIDER_CREDENTIAL_ENV, stripWorkspaceCredentialEnv } from "../config.js";
@@ -9,6 +10,7 @@ import { augmentedPath } from "../env-path.js";
9
10
  import { createLineSplitter } from "../mcp-bridge.js";
10
11
  import { McpHttpError, RemoteMcpClient } from "../mcp-http.js";
11
12
  import { isRemoteMcpServer } from "../mcp-registry.js";
13
+ import { exitMeansSignInRequired, MCP_SIGN_IN_REQUIRED_MARKER } from "../mcp-remote-bridge.js";
12
14
  import { killCliTree, spawnCli } from "../procs.js";
13
15
  /** Nexus could not be reached (offline, signed out, timed out): retry later. */
14
16
  export class NexusUnavailableError extends Error {
@@ -24,6 +26,15 @@ export class NexusInitializeError extends NexusUnavailableError {
24
26
  this.name = "NexusInitializeError";
25
27
  }
26
28
  }
29
+ /** Nexus refused the sign-in (401, an expired or rejected token, or a bridge
30
+ * that would need a browser sign-in). Not an outage: the caller refreshes the
31
+ * Chibitek sign-in and retries at once (backoff.ts). */
32
+ export class NexusAuthError extends NexusUnavailableError {
33
+ constructor(message) {
34
+ super(message);
35
+ this.name = "NexusAuthError";
36
+ }
37
+ }
27
38
  /** Nexus answered and refused this call (bad input): retrying will not help. */
28
39
  export class NexusRejectedError extends Error {
29
40
  constructor(message) {
@@ -35,7 +46,15 @@ const DEFAULT_TIMEOUT_MS = 20_000;
35
46
  const PROTOCOL_VERSION = "2025-06-18";
36
47
  /** Messages that mean "try again later", not "this input is wrong". */
37
48
  const PRIVATE_SCOPE_ANSWER = /\b(?:private_scope_\w+|private_proof_invalid|personal_scope_requires_private_bot|personal_memory_cannot_be_shared)\b/;
38
- const TRANSIENT = /unauthori[sz]ed|sign ?in|token|timed? ?out|timeout|ECONN|ENOTFOUND|EAI_AGAIN|fetch failed|network|socket|503|502|504|429|temporar|unavailable|not provisioned/i;
49
+ /** Messages that mean "the sign-in was refused", checked before TRANSIENT. */
50
+ const AUTH_REFUSED = /unauthori[sz]ed|sign ?in|\btoken\b|\b401\b|ATOMIC_MCP_SIGN_IN_REQUIRED/i;
51
+ const TRANSIENT = /timed? ?out|timeout|ECONN|ENOTFOUND|EAI_AGAIN|fetch failed|network|socket|503|502|504|429|temporar|unavailable|not provisioned/i;
52
+ /** The error a refusal message stands for: sign-in, try-later, or final. */
53
+ function refusalError(message) {
54
+ if (AUTH_REFUSED.test(message))
55
+ return new NexusAuthError(message);
56
+ return TRANSIENT.test(message) ? new NexusUnavailableError(message) : new NexusRejectedError(message);
57
+ }
39
58
  const BRIDGE_URL = /https?:\/\/[^\s"'<>]+/gi;
40
59
  const BRIDGE_SECRET = /\b(bearer|token|access_token|refresh_token|id_token|authorization|client_secret|api[_-]?key|password|code)\b(\s*[:=]\s*)\S+/gi;
41
60
  const BRIDGE_JWT = /\beyJ[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]{8,}){2}\b/g;
@@ -73,7 +92,7 @@ export function parseToolResult(result) {
73
92
  // Nexus's private-scope answers are final, never "try later" (chibitek/nexus#151).
74
93
  if (PRIVATE_SCOPE_ANSWER.test(message))
75
94
  throw new NexusRejectedError(message);
76
- throw TRANSIENT.test(message) ? new NexusUnavailableError(message) : new NexusRejectedError(message);
95
+ throw refusalError(message);
77
96
  }
78
97
  return parsed;
79
98
  }
@@ -93,13 +112,15 @@ class HttpNexusClient {
93
112
  }
94
113
  catch (error) {
95
114
  await client.close().catch(() => undefined);
115
+ if (error instanceof McpHttpError && error.kind === "status" && error.status === 401)
116
+ throw new NexusAuthError("Nexus answered HTTP 401");
96
117
  throw new NexusInitializeError(error instanceof Error ? error.message : "Nexus initialize failed");
97
118
  }
98
119
  this.client = client;
99
120
  return client;
100
121
  })().catch((error) => {
101
122
  this.ready = null;
102
- throw error instanceof NexusInitializeError ? error : new NexusInitializeError(error instanceof Error ? error.message : "Nexus initialize failed");
123
+ throw error instanceof NexusInitializeError || error instanceof NexusAuthError ? error : new NexusInitializeError(error instanceof Error ? error.message : "Nexus initialize failed");
103
124
  });
104
125
  return this.ready;
105
126
  }
@@ -114,6 +135,9 @@ class HttpNexusClient {
114
135
  throw error;
115
136
  // A dropped session must re-handshake next time.
116
137
  await this.reset();
138
+ if (error instanceof McpHttpError && error.kind === "status" && error.status === 401) {
139
+ throw new NexusAuthError("Nexus answered HTTP 401");
140
+ }
117
141
  if (error instanceof McpHttpError && error.kind === "status" && error.status && error.status < 500 && ![401, 403, 408, 429].includes(error.status)) {
118
142
  throw new NexusRejectedError(`Nexus answered HTTP ${error.status}`);
119
143
  }
@@ -217,7 +241,7 @@ class StdioNexusClient {
217
241
  clearTimeout(entry.timer);
218
242
  if (frame.error !== undefined) {
219
243
  const message = isRecord(frame.error) && typeof frame.error.message === "string" ? frame.error.message : "Nexus error";
220
- entry.reject(TRANSIENT.test(message) ? new NexusUnavailableError(message) : new NexusRejectedError(message));
244
+ entry.reject(refusalError(message));
221
245
  }
222
246
  else
223
247
  entry.resolve(frame.result);
@@ -225,7 +249,10 @@ class StdioNexusClient {
225
249
  child.stdout.on("data", (chunk) => splitter.push(chunk));
226
250
  let logged = 0;
227
251
  let handshook = false;
252
+ let signInRefused = false;
228
253
  const errSplit = createLineSplitter((line) => {
254
+ if (line.includes(MCP_SIGN_IN_REQUIRED_MARKER))
255
+ signInRefused = true;
229
256
  const redacted = redactBridgeLine(line);
230
257
  // ponytail: 20 lines per child; raise if a handshake needs more of the log
231
258
  if (!redacted || logged >= 20)
@@ -234,14 +261,19 @@ class StdioNexusClient {
234
261
  this.log?.(`bridge: ${redacted}`);
235
262
  });
236
263
  child.stderr.on("data", (chunk) => errSplit.push(chunk));
237
- const gone = (message) => {
264
+ const gone = (message, code) => {
238
265
  errSplit.flush();
239
266
  if (this.child !== child)
240
267
  return;
241
- this.fail(handshook ? new NexusUnavailableError(message) : new NexusInitializeError(message));
268
+ // The bridge exits 77 when the server refused its sign-in and it may
269
+ // not open a browser (server/mcp-remote-bridge.ts).
270
+ if (signInRefused || exitMeansSignInRequired(code ?? null))
271
+ this.fail(new NexusAuthError("Nexus refused the sign-in"));
272
+ else
273
+ this.fail(handshook ? new NexusUnavailableError(message) : new NexusInitializeError(message));
242
274
  };
243
275
  child.once("error", () => gone("Nexus bridge failed"));
244
- child.once("close", () => gone("Nexus bridge stopped"));
276
+ child.once("close", (code) => gone("Nexus bridge stopped", code));
245
277
  await this.send("initialize", {
246
278
  protocolVersion: PROTOCOL_VERSION,
247
279
  capabilities: {},
@@ -252,7 +284,7 @@ class StdioNexusClient {
252
284
  })().catch((error) => {
253
285
  const message = error instanceof Error ? error.message : String(error);
254
286
  this.fail(error instanceof Error ? error : new Error(message));
255
- throw error instanceof NexusInitializeError ? error : new NexusInitializeError(message);
287
+ throw error instanceof NexusInitializeError || error instanceof NexusAuthError ? error : new NexusInitializeError(message);
256
288
  });
257
289
  return this.ready;
258
290
  }
@@ -171,8 +171,8 @@ export class NexusMemory {
171
171
  this.client ??= this.deps.clientFor(cfg);
172
172
  return this.client;
173
173
  }
174
- const spec = customMcpServers(cfg).nexus;
175
- const key = JSON.stringify(spec ?? null);
174
+ const spec = this.deps.serverSpec ? this.deps.serverSpec(customMcpServers(cfg).nexus) : customMcpServers(cfg).nexus;
175
+ const key = JSON.stringify(spec ?? null); // holds a mounted token (memory only): a refreshed token builds a new client
176
176
  if (key !== this.clientKey) {
177
177
  void this.client?.close();
178
178
  this.client = nexusClientFor(spec, (message) => this.log(message));
@@ -185,7 +185,7 @@ export class NexusMemory {
185
185
  const client = this.rawClient();
186
186
  if (!client)
187
187
  return null;
188
- return guardNexusClient(client, this.backoff, this.now, this.log);
188
+ return guardNexusClient(() => this.rawClient(), this.backoff, this.now, this.log, this.deps.signIn);
189
189
  }
190
190
  // ── the Private Bot's signed calls ─────────────────────────────────────
191
191
  privateKey() {
@@ -0,0 +1,128 @@
1
+ // GitHub repositories the signed-in GitHub CLI can reach, and clones of
2
+ // them into the default clone folder (~/repos), so a conversation can link
3
+ // a repo that is not on this computer yet. Everything goes through `gh`
4
+ // without a shell; nothing here pushes. A clone runs in the background and
5
+ // the job is reported until it is done, because a phone's request times out
6
+ // long before a large clone finishes.
7
+ import { existsSync, mkdirSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { basename, join } from "node:path";
10
+ import { githubCliStatus, runCommand } from "./repo-worktrees.js";
11
+ /** owner/name as GitHub allows it; nothing that could leave the clone folder. */
12
+ export const GITHUB_REPO_NAME = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9_.-]{1,100}$/;
13
+ const LIST_URL = "user/repos?per_page=100&sort=pushed&affiliation=owner,collaborator,organization_member";
14
+ const JOB_TTL_MS = 60 * 60 * 1000;
15
+ export class GitHubRepos {
16
+ jobs = new Map();
17
+ // Plain fields, not parameter properties: Node's type stripping (the dev
18
+ // and verification server) refuses those.
19
+ registry;
20
+ run;
21
+ folder;
22
+ constructor(registry, run = runCommand, folder = join(homedir(), "repos")) {
23
+ this.registry = registry;
24
+ this.run = run;
25
+ this.folder = folder;
26
+ }
27
+ /** The newest hundred repos the account can push to or read as a member. */
28
+ async list() {
29
+ const cli = await this.cli();
30
+ if (!cli.ok)
31
+ return cli;
32
+ const result = await this.run("gh", ["api", LIST_URL], { cwd: this.cwd(), timeout: 30_000 });
33
+ if (result.code !== 0)
34
+ return { ok: false, status: 502, error: `GitHub did not answer: ${result.stderr.trim().split("\n").pop() ?? "unknown error"}` };
35
+ let rows;
36
+ try {
37
+ rows = JSON.parse(result.stdout);
38
+ }
39
+ catch {
40
+ return { ok: false, status: 502, error: "GitHub sent something Atomic could not read" };
41
+ }
42
+ if (!Array.isArray(rows))
43
+ return { ok: false, status: 502, error: "GitHub sent something Atomic could not read" };
44
+ const byPath = new Map(this.registry.list().map((repo) => [repo.path, repo.id]));
45
+ const repos = rows.flatMap((row) => {
46
+ const r = row;
47
+ if (typeof r.full_name !== "string" || !GITHUB_REPO_NAME.test(r.full_name))
48
+ return [];
49
+ const repoId = byPath.get(join(this.folder, basename(r.full_name)));
50
+ return [{
51
+ nameWithOwner: r.full_name,
52
+ description: typeof r.description === "string" ? r.description : null,
53
+ private: r.private === true,
54
+ pushedAt: typeof r.pushed_at === "string" ? r.pushed_at : null,
55
+ ...(repoId ? { repoId } : {}),
56
+ }];
57
+ });
58
+ return { ok: true, repos, clones: this.clones() };
59
+ }
60
+ clones() {
61
+ const cutoff = Date.now() - JOB_TTL_MS;
62
+ for (const [key, job] of this.jobs)
63
+ if (job.state !== "cloning" && job.startedAt < cutoff)
64
+ this.jobs.delete(key);
65
+ return [...this.jobs.values()].map((job) => ({ ...job }));
66
+ }
67
+ /** Clone into the clone folder (or reuse the folder already there),
68
+ * register it and, with a thread, link it. Returns at once with the job;
69
+ * `done` means the repo is registered and linked. */
70
+ async clone(nameWithOwner, threadId, link) {
71
+ if (typeof nameWithOwner !== "string" || !GITHUB_REPO_NAME.test(nameWithOwner))
72
+ return { ok: false, status: 400, error: "nameWithOwner must look like owner/name" };
73
+ const running = this.jobs.get(nameWithOwner);
74
+ if (running?.state === "cloning")
75
+ return { ok: true, job: { ...running } };
76
+ const target = join(this.folder, basename(nameWithOwner));
77
+ const job = { nameWithOwner, state: "cloning", startedAt: Date.now(), ...(threadId ? { threadId } : {}) };
78
+ this.jobs.set(nameWithOwner, job);
79
+ if (existsSync(target)) {
80
+ await this.finish(job, target, link);
81
+ return { ok: true, job: { ...job } };
82
+ }
83
+ const cli = await this.cli();
84
+ if (!cli.ok) {
85
+ this.jobs.delete(nameWithOwner);
86
+ return cli;
87
+ }
88
+ void this.run("gh", ["repo", "clone", nameWithOwner, target], { cwd: this.cwd(), timeout: 10 * 60_000 }).then(async (result) => {
89
+ if (result.code !== 0) {
90
+ job.state = "failed";
91
+ job.error = `Clone failed: ${result.stderr.trim().split("\n").pop() || "unknown error"}`;
92
+ return;
93
+ }
94
+ await this.finish(job, target, link);
95
+ });
96
+ return { ok: true, job: { ...job } };
97
+ }
98
+ async finish(job, target, link) {
99
+ const ensured = await this.registry.ensure(target);
100
+ if (!ensured.ok) {
101
+ job.state = "failed";
102
+ job.error = ensured.error;
103
+ return;
104
+ }
105
+ job.repoId = ensured.repo.id;
106
+ if (job.threadId) {
107
+ const linked = link(job.threadId, ensured.repo.id);
108
+ if (!linked.ok) {
109
+ job.state = "failed";
110
+ job.error = linked.error;
111
+ return;
112
+ }
113
+ }
114
+ job.state = "done";
115
+ }
116
+ async cli() {
117
+ const gh = await githubCliStatus(this.run, this.cwd());
118
+ if (!gh.available)
119
+ return { ok: false, status: 409, error: "The GitHub CLI (gh) is not installed on this computer." };
120
+ if (!gh.authenticated)
121
+ return { ok: false, status: 409, error: "The GitHub CLI is not signed in. Run gh auth login in a terminal on this computer, then try again." };
122
+ return { ok: true };
123
+ }
124
+ cwd() {
125
+ mkdirSync(this.folder, { recursive: true });
126
+ return this.folder;
127
+ }
128
+ }
@@ -144,6 +144,15 @@ export class RepoRegistry {
144
144
  /** Register a repository by path. The path must be an existing git
145
145
  * repository; a subfolder registers its top level. */
146
146
  async add(input) {
147
+ const ensured = await this.ensure(input);
148
+ if (!ensured.ok)
149
+ return ensured;
150
+ if (!ensured.added)
151
+ return { ok: false, status: 409, error: `${ensured.repo.name} is already in your repos` };
152
+ return { ok: true, repo: ensured.repo };
153
+ }
154
+ /** The repo at `input`, registered now when it was not yet. */
155
+ async ensure(input) {
147
156
  const folder = checkedFolder(input);
148
157
  if (!folder.ok)
149
158
  return { ok: false, status: 400, error: folder.error };
@@ -152,7 +161,7 @@ export class RepoRegistry {
152
161
  return { ok: false, status: 400, error: facts.error };
153
162
  const existing = this.repos.find((repo) => repo.path === facts.path);
154
163
  if (existing)
155
- return { ok: false, status: 409, error: `${existing.name} is already in your repos` };
164
+ return { ok: true, repo: { ...existing }, added: false };
156
165
  const now = Date.now();
157
166
  const repo = {
158
167
  id: newId(),
@@ -165,7 +174,7 @@ export class RepoRegistry {
165
174
  };
166
175
  this.repos.push(repo);
167
176
  this.save();
168
- return { ok: true, repo: { ...repo } };
177
+ return { ok: true, repo: { ...repo }, added: true };
169
178
  }
170
179
  /** Read remote and default branch again. A repo whose folder is gone
171
180
  * stays listed, with the reason, so links to it are not lost silently. */