@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
@@ -0,0 +1,23 @@
1
+ // The agents proxy's current bearer, on disk. The harness rewrites it every
2
+ // turn; the proxy reads it per call. An ACP engine keeps the proxy process it
3
+ // connected at session/new for the whole pooled session (Hermes skips
4
+ // already-connected MCP names on session/load), so a token carried only in
5
+ // the spawn environment is revoked by turn two and every peer tool call
6
+ // answers INTERNAL_CAPABILITY_EXPIRED until the session idles out. Same
7
+ // pattern as the Claude driver's hook tokens; never exported in a backup.
8
+ import { createHash } from "node:crypto";
9
+ import { mkdirSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { writeFileAtomic } from "./atomic.js";
12
+ import { DATA_DIR } from "./config.js";
13
+ export function agentsTokenFile(botId, threadId, dataDir = DATA_DIR) {
14
+ const digest = createHash("sha256").update(`${botId}\0${threadId}`).digest("hex").slice(0, 24);
15
+ return join(dataDir, "agents-tokens", `${digest}.token`);
16
+ }
17
+ /** Writes this turn's token (0600) and returns the path the proxy reads. */
18
+ export function writeAgentsTokenFile(botId, threadId, token, dataDir = DATA_DIR) {
19
+ const path = agentsTokenFile(botId, threadId, dataDir);
20
+ mkdirSync(join(dataDir, "agents-tokens"), { recursive: true, mode: 0o700 });
21
+ writeFileAtomic(path, token, { mode: 0o600 });
22
+ return path;
23
+ }
@@ -39,7 +39,7 @@ export class BotWorkModes {
39
39
  settings() { return { allowed: this.allowed }; }
40
40
  permits(mode) { return mode === "plan" || !valid(mode) || this.allowed.includes(mode); }
41
41
  expired(live) {
42
- return [...new Set(Object.values(this.selections).filter(item => item.mode !== "ask" && !live(item.sessionId)).map(item => item.sessionId))].flatMap(id => this.revoke(id));
42
+ return [...new Set(Object.values(this.selections).filter(item => item.mode !== "ask" && !companionOwned(item.sessionId) && !live(item.sessionId)).map(item => item.sessionId))].flatMap(id => this.revoke(id));
43
43
  }
44
44
  configure(modes) {
45
45
  if (!Array.isArray(modes) || !modes.every(valid))
@@ -88,19 +88,31 @@ export class BotWorkModes {
88
88
  return ids.filter(id => this.selections[id].mode !== "plan");
89
89
  }
90
90
  }
91
- export function pairedModeAuthority(auth, desktopManaged) {
92
- return desktopManaged && auth.kind === "session" && auth.via === "bearer" && auth.scopes.includes("admin");
91
+ /** The paired device a mode selection belongs to, or undefined when the caller may not change modes.
92
+ * A phone paired through the desktop companion reaches the server as a loopback relay carrying its
93
+ * device id; the sidecar authenticates that device on every request, so it is as paired as a bearer. */
94
+ export function pairedModeOwner(auth, desktopManaged) {
95
+ if (!desktopManaged)
96
+ return undefined;
97
+ if (auth.kind === "loopback")
98
+ return auth.device && auth.trust !== "service" ? `companion:${auth.device}` : undefined;
99
+ return auth.kind === "session" && auth.via === "bearer" && auth.scopes.includes("admin") ? auth.session.id : undefined;
93
100
  }
101
+ export const pairedModeAuthority = (auth, desktopManaged) => pairedModeOwner(auth, desktopManaged) !== undefined;
102
+ /** Companion devices have no server session to expire; the desktop revokes them at its sidecar. */
103
+ const companionOwned = (id) => id.startsWith("companion:");
94
104
  export function createBotWorkModeRoutes(deps) {
95
105
  return async ({ path, method, auth, req, res, readBody, json }) => {
96
106
  const settings = path === "/api/work-modes";
97
107
  const match = /^\/api\/bots\/([\w-]+)\/work-mode$/.exec(path);
98
108
  if (!settings && !match)
99
109
  return PASS;
100
- if (!pairedModeAuthority(auth, deps.desktopManaged) || auth.kind !== "session" || !deps.live(auth.session.id))
110
+ const owner = pairedModeOwner(auth, deps.desktopManaged);
111
+ const live = (id) => companionOwned(id) || deps.live(id);
112
+ if (!owner || !live(owner))
101
113
  return json(res, 403, { error: "Mode changes require an Administrator's paired device connected to the desktop app." });
102
114
  const body = method === "POST" || method === "PUT" ? await readBody(req) : {};
103
- if (!deps.live(auth.session.id))
115
+ if (!live(owner))
104
116
  return json(res, 403, { error: "Pairing expired" });
105
117
  if (settings) {
106
118
  if (method === "GET")
@@ -113,7 +125,7 @@ export function createBotWorkModeRoutes(deps) {
113
125
  const affected = deps.affected(["ask", ...body.allowed]);
114
126
  const ids = [...new Set([...affected, ...deps.modes.configure(body.allowed)])];
115
127
  for (const id of ids) {
116
- deps.modes.set(id, "ask", auth.session.id);
128
+ deps.modes.set(id, "ask", owner);
117
129
  deps.apply(id, "ask", true);
118
130
  await deps.stop(id);
119
131
  deps.changed(id);
@@ -140,12 +152,12 @@ export function createBotWorkModeRoutes(deps) {
140
152
  if (bot.busy)
141
153
  return json(res, 409, { error: "Stop planning before approving the plan." });
142
154
  if (typeof body.nonce !== "string")
143
- return json(res, 200, { ...status(), confirmation: deps.modes.request(id, body.mode, auth.session.id, bot.revision) });
144
- if (body.mode === "ask" && !deps.modes.confirm(body.nonce, id, "ask", auth.session.id, bot.revision))
155
+ return json(res, 200, { ...status(), confirmation: deps.modes.request(id, body.mode, owner, bot.revision) });
156
+ if (body.mode === "ask" && !deps.modes.confirm(body.nonce, id, "ask", owner, bot.revision))
145
157
  return json(res, 409, { error: "Plan confirmation expired or changed." });
146
158
  }
147
159
  if (body.mode === "ask") {
148
- deps.modes.set(id, "ask", auth.session.id);
160
+ deps.modes.set(id, "ask", owner);
149
161
  deps.apply(id, "ask");
150
162
  await deps.stop(id);
151
163
  deps.changed(id);
@@ -156,14 +168,14 @@ export function createBotWorkModeRoutes(deps) {
156
168
  if (!deps.modes.availability(bot.drivers).includes(body.mode))
157
169
  return json(res, 409, { error: "This mode is unavailable in Settings or on one of this bot's engines." });
158
170
  if (body.mode === "plan") {
159
- deps.modes.set(id, "plan", auth.session.id);
171
+ deps.modes.set(id, "plan", owner);
160
172
  deps.apply(id, "plan");
161
173
  deps.changed(id);
162
174
  return json(res, 200, status());
163
175
  }
164
176
  if (typeof body.nonce !== "string")
165
- return json(res, 200, { ...status(), confirmation: deps.modes.request(id, body.mode, auth.session.id, bot.revision) });
166
- if (!deps.modes.confirm(body.nonce, id, body.mode, auth.session.id, bot.revision))
177
+ return json(res, 200, { ...status(), confirmation: deps.modes.request(id, body.mode, owner, bot.revision) });
178
+ if (!deps.modes.confirm(body.nonce, id, body.mode, owner, bot.revision))
167
179
  return json(res, 409, { error: "This confirmation expired or the bot changed. Choose the mode again." });
168
180
  deps.apply(id, body.mode);
169
181
  deps.changed(id);
@@ -0,0 +1,207 @@
1
+ // Atomic's Chibitek (Stiki) sign-in as the credential of Chibitek's own MCP
2
+ // servers, Nexus and Mochii (server/company-mcp-tenancy.ts).
3
+ //
4
+ // Both servers accept the person's Stiki access token as their bearer. So
5
+ // once someone signs in to Atomic with Chibitek (first-run setup or Settings,
6
+ // the same Electron-held session, electron/stiki-signin.mjs), every start of
7
+ // those two servers carries that token: no second browser OAuth, and no way
8
+ // for the MCP sign-in to drift onto a different or expired Stiki account.
9
+ //
10
+ // - A bridged entry (mcp-remote, the default) gets
11
+ // `--header Authorization:Bearer ${ATOMIC_STIKI_ACCESS_TOKEN}` on argv and
12
+ // the token itself only in its environment (mcp-remote expands the
13
+ // placeholder), plus ATOMIC_MCP_NO_BROWSER=1: a refused token exits 77
14
+ // instead of opening a sign-in page.
15
+ // - A remote (url) entry gets an Authorization header.
16
+ // - An entry that brings its own Authorization is the person's: untouched.
17
+ //
18
+ // The token is held in memory only, refreshed before it expires, and a turn
19
+ // reads it synchronously (`current()`). A token a server refuses asks Electron
20
+ // main for a refresh right away (`refreshAfterRejection()`); only when that
21
+ // yields nothing new does the usual sign-in back-off apply.
22
+ import { isChibitekMochii, isChibitekNexus, CHIBITEK_DEFAULT_MCP_SERVERS } from "./company-mcp-tenancy.js";
23
+ import { MCP_NO_BROWSER_ENV, mcpRemoteTarget } from "./mcp-remote-bridge.js";
24
+ import { onStikiSessionChange } from "./stiki-session.js";
25
+ /** The bridge's environment variable that holds the token. */
26
+ export const STIKI_BEARER_ENV = "ATOMIC_STIKI_ACCESS_TOKEN";
27
+ /** The `--header` value: a placeholder, never the token itself. */
28
+ export const STIKI_BEARER_HEADER_ARG = `Authorization:Bearer \${${STIKI_BEARER_ENV}}`;
29
+ /** A token with less than this left is not handed to a new start. */
30
+ const MIN_VALID_MS = 60_000;
31
+ /** Look again this long before the held token expires. */
32
+ const RESYNC_BEFORE_MS = 6 * 60_000;
33
+ /** And at least this often, so a refresh main did on its own is picked up. */
34
+ const MAX_RESYNC_MS = 15 * 60_000;
35
+ const MIN_RESYNC_MS = 30_000;
36
+ /** One forced refresh per this long, however many starts were refused. */
37
+ const REJECTION_REFRESH_MS = 60_000;
38
+ /** Without a readable `exp`, treat a token as good for this long. */
39
+ const UNKNOWN_EXPIRY_MS = 10 * 60_000;
40
+ function isAuthorizationHeaderArg(value) {
41
+ return typeof value === "string" && /^\s*authorization\s*:/i.test(value);
42
+ }
43
+ /** Does this bridge's own argv already carry an Authorization header? */
44
+ function bridgeHasOwnAuthorization(extraArgs) {
45
+ return extraArgs.some((arg, index) => arg === "--header-file" || (arg === "--header" && isAuthorizationHeaderArg(extraArgs[index + 1]) && extraArgs[index + 1] !== STIKI_BEARER_HEADER_ARG));
46
+ }
47
+ /** Is this one of Chibitek's MCP servers with no credential of its own, so
48
+ * the Chibitek sign-in should sign it in? */
49
+ export function takesStikiCredential(spec) {
50
+ if (!spec || !(isChibitekNexus(spec) || isChibitekMochii(spec)))
51
+ return false;
52
+ if ("url" in spec)
53
+ return !Object.keys(spec.headers ?? {}).some((name) => name.toLowerCase() === "authorization");
54
+ const target = mcpRemoteTarget(spec);
55
+ // Some other program that happens to reach the URL: not ours to sign in.
56
+ if (!target)
57
+ return false;
58
+ return !bridgeHasOwnAuthorization(target.extraArgs);
59
+ }
60
+ /** The spec to start with the person's Stiki token; anything that does not
61
+ * take it comes back unchanged (the same object). */
62
+ export function withStikiCredential(spec, token) {
63
+ if (!token || !takesStikiCredential(spec))
64
+ return spec;
65
+ if ("url" in spec)
66
+ return { ...spec, headers: { ...spec.headers, Authorization: `Bearer ${token}` } };
67
+ const args = spec.args.includes(STIKI_BEARER_HEADER_ARG) ? [...spec.args] : [...spec.args, "--header", STIKI_BEARER_HEADER_ARG];
68
+ return { ...spec, args, env: { ...spec.env, [STIKI_BEARER_ENV]: token, [MCP_NO_BROWSER_ENV]: "1" } };
69
+ }
70
+ /** The token's own `exp`, in ms, read only to know when to look again.
71
+ * Nothing is decided from it: the servers verify the token. */
72
+ export function stikiTokenExpiry(token) {
73
+ const payload = token.split(".")[1];
74
+ if (!payload)
75
+ return null;
76
+ try {
77
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
78
+ return typeof claims.exp === "number" && Number.isFinite(claims.exp) ? Math.floor(claims.exp * 1000) : null;
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
84
+ /** The Chibitek MCP defaults a config lacks (by name or by URL). */
85
+ export function missingChibitekMcpDefaults(servers) {
86
+ const entries = Object.entries(servers ?? {});
87
+ return CHIBITEK_DEFAULT_MCP_SERVERS.filter((server) => {
88
+ if (entries.some(([name]) => name === server.name))
89
+ return false;
90
+ return !entries.some(([, entry]) => (server.name === "nexus" ? isChibitekNexus(entry) : isChibitekMochii(entry)));
91
+ });
92
+ }
93
+ const sameCredential = (a, b) => a === b || (!!a && !!b && a.token === b.token && a.identity.userId === b.identity.userId);
94
+ export class ChibitekMcpCredentials {
95
+ held = null;
96
+ syncing = null;
97
+ syncAgain = null;
98
+ timer;
99
+ lastRejectionRefresh = Number.NEGATIVE_INFINITY;
100
+ stopListening = null;
101
+ deps;
102
+ now;
103
+ constructor(deps) {
104
+ this.deps = deps;
105
+ this.now = deps.now ?? Date.now;
106
+ }
107
+ /** Follow the sign-in: look now, on every sign-in change, and before the
108
+ * held token expires. */
109
+ start() {
110
+ if (this.stopListening)
111
+ return;
112
+ this.stopListening = onStikiSessionChange(() => void this.sync());
113
+ void this.sync();
114
+ }
115
+ stop() {
116
+ this.stopListening?.();
117
+ this.stopListening = null;
118
+ if (this.timer)
119
+ clearTimeout(this.timer);
120
+ this.timer = undefined;
121
+ }
122
+ /** The credential a start may use now, or null (signed out, or no token
123
+ * with time left). Synchronous: turns are assembled without waiting. */
124
+ current() {
125
+ const held = this.held;
126
+ if (!held)
127
+ return null;
128
+ if (held.expiresAt - this.now() <= MIN_VALID_MS) {
129
+ void this.sync();
130
+ return null;
131
+ }
132
+ const signedIn = this.deps.session().identity();
133
+ if (!signedIn || signedIn.userId !== held.identity.userId) {
134
+ void this.sync();
135
+ return null;
136
+ }
137
+ return held;
138
+ }
139
+ /** Read the session again (it refreshes a token close to expiry). A call
140
+ * while a read is running reads once more after it, so a sign-in change
141
+ * that lands mid-read is never answered with what was read before it. */
142
+ sync() {
143
+ if (this.syncing) {
144
+ this.syncAgain ??= this.syncing.then(() => {
145
+ this.syncAgain = null;
146
+ return this.sync();
147
+ });
148
+ return this.syncAgain;
149
+ }
150
+ this.syncing = this.read(false).finally(() => {
151
+ this.syncing = null;
152
+ });
153
+ return this.syncing;
154
+ }
155
+ /** A server refused the held token: ask for a fresh one now. True when a
156
+ * different token came back, so the refused start is worth retrying at
157
+ * once; false means the usual back-off should apply. */
158
+ async refreshAfterRejection() {
159
+ const before = this.held?.token ?? null;
160
+ if (this.now() - this.lastRejectionRefresh < REJECTION_REFRESH_MS) {
161
+ await this.syncing;
162
+ return Boolean(this.held && this.held.token !== before);
163
+ }
164
+ this.lastRejectionRefresh = this.now();
165
+ this.deps.log?.("a Chibitek MCP server refused the Chibitek sign-in; refreshing it");
166
+ const next = await this.read(true);
167
+ return Boolean(next && next.token !== before);
168
+ }
169
+ async read(force) {
170
+ const session = this.deps.session();
171
+ let token = null;
172
+ try {
173
+ token = force && session.refresh ? await session.refresh() : await session.accessToken();
174
+ }
175
+ catch {
176
+ token = null;
177
+ }
178
+ const identity = session.identity();
179
+ const next = token && identity
180
+ ? { token, identity, expiresAt: stikiTokenExpiry(token) ?? this.now() + UNKNOWN_EXPIRY_MS }
181
+ : null;
182
+ const before = this.held;
183
+ this.held = next;
184
+ this.schedule();
185
+ if (!sameCredential(before, next)) {
186
+ const switched = (before?.identity.userId ?? null) !== (next?.identity.userId ?? null);
187
+ try {
188
+ this.deps.onChange?.(next, switched);
189
+ }
190
+ catch (error) {
191
+ this.deps.log?.(`Chibitek MCP sign-in listener failed: ${error instanceof Error ? error.message : String(error)}`);
192
+ }
193
+ }
194
+ return next;
195
+ }
196
+ schedule() {
197
+ if (this.timer)
198
+ clearTimeout(this.timer);
199
+ this.timer = undefined;
200
+ if (!this.held || !this.stopListening)
201
+ return;
202
+ const untilResync = this.held.expiresAt - RESYNC_BEFORE_MS - this.now();
203
+ const wait = Math.min(MAX_RESYNC_MS, Math.max(MIN_RESYNC_MS, untilResync));
204
+ this.timer = setTimeout(() => void this.sync(), wait);
205
+ this.timer.unref?.();
206
+ }
207
+ }
@@ -0,0 +1,124 @@
1
+ // The server side of "signing in to Atomic with Chibitek signs Nexus and
2
+ // Mochii in" (server/chibitek-mcp-credentials.ts holds the token itself):
3
+ //
4
+ // - every start of those servers carries the Stiki token (`credentialed`);
5
+ // - a refused token is refreshed at once instead of backing off
6
+ // (`refused`, `probe`), and only a refresh with nothing new backs off;
7
+ // - signing in installs any missing Nexus/Mochii entry, once per person,
8
+ // so a server that person removes afterwards stays removed (`install`);
9
+ // - a new token or another person clears what the old one was told
10
+ // (a stale "sign in again", or "not enabled for your organization").
11
+ //
12
+ // index.ts wires it; every dependency is read lazily because the sign-in is
13
+ // created before the stores it updates.
14
+ import { readFileSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { writeFileAtomic } from "./atomic.js";
17
+ import { ChibitekMcpCredentials, missingChibitekMcpDefaults, takesStikiCredential, withStikiCredential } from "./chibitek-mcp-credentials.js";
18
+ import { CHIBITEK_DEFAULT_MCP_SERVERS, mcpServerTarget } from "./company-mcp-tenancy.js";
19
+ import { MCP_REMOTE_PACKAGE } from "./mcp-featured-add.js";
20
+ const MARKER = "chibitek-mcp-signin.json";
21
+ export function createChibitekMcpSignIn(deps) {
22
+ const credentials = new ChibitekMcpCredentials({
23
+ session: deps.session,
24
+ now: deps.now,
25
+ log: deps.log,
26
+ onChange: (credential, switched) => {
27
+ for (const server of CHIBITEK_DEFAULT_MCP_SERVERS) {
28
+ const name = Object.entries(deps.servers() ?? {}).find(([key, entry]) => key === server.name || mcpServerTarget(entry) === server.url)?.[0] ?? server.name;
29
+ if (credential)
30
+ deps.authState().noteOk(name);
31
+ if (switched)
32
+ deps.notices().clear(name);
33
+ }
34
+ if (credential && switched)
35
+ void install();
36
+ deps.changed();
37
+ },
38
+ });
39
+ const markerPath = join(deps.dataDir, MARKER);
40
+ const installedFor = () => {
41
+ try {
42
+ const parsed = JSON.parse(readFileSync(markerPath, "utf8"));
43
+ return Array.isArray(parsed.installedFor) ? parsed.installedFor.filter((id) => typeof id === "string") : [];
44
+ }
45
+ catch {
46
+ return [];
47
+ }
48
+ };
49
+ /** The entry a Chibitek default starts with: the bundled bridge, the same
50
+ * shape the desktop seeds (electron/chibitek-defaults.mjs). */
51
+ const entryFor = (name, url) => {
52
+ const bridge = deps.bridge();
53
+ return bridge
54
+ ? { command: "node", args: [bridge, url], env: { CHIBITEK_MCP_BRAND: name }, enabled: true }
55
+ : { command: "npx", args: ["-y", MCP_REMOTE_PACKAGE, url], env: { CHIBITEK_MCP_BRAND: name }, enabled: true };
56
+ };
57
+ /** Install the missing Nexus/Mochii entries for whoever is signed in. */
58
+ async function install(attempt = 0) {
59
+ const identity = deps.session().identity();
60
+ if (!identity)
61
+ return [];
62
+ const already = installedFor();
63
+ if (already.includes(identity.userId))
64
+ return [];
65
+ const missing = missingChibitekMcpDefaults(deps.servers()).filter((server) => deps.mayInstall(server.name, server.url));
66
+ if (missing.length) {
67
+ const next = { ...deps.servers() };
68
+ for (const server of missing)
69
+ next[server.name] = entryFor(server.name, server.url);
70
+ try {
71
+ await deps.persist(next);
72
+ }
73
+ catch (error) {
74
+ // Another MCP change is being saved: try again shortly.
75
+ if (attempt < 5)
76
+ setTimeout(() => void install(attempt + 1), 5_000).unref?.();
77
+ else
78
+ deps.log(`could not install the Chibitek MCP servers: ${error instanceof Error ? error.message : String(error)}`);
79
+ return [];
80
+ }
81
+ deps.log(`signed in with Chibitek: installed ${missing.map((server) => server.name).join(", ")}`);
82
+ }
83
+ writeFileAtomic(markerPath, `${JSON.stringify({ installedFor: [...already, identity.userId] }, null, 2)}\n`);
84
+ if (missing.length)
85
+ deps.changed();
86
+ return missing.map((server) => server.name);
87
+ }
88
+ const signedIn = (spec) => Boolean(spec && credentials.current() && takesStikiCredential(spec));
89
+ return {
90
+ credentials,
91
+ install,
92
+ start: () => credentials.start(),
93
+ /** A start of `spec`, signed in with the Chibitek session when it takes one. */
94
+ credentialed(spec) {
95
+ const credential = credentials.current();
96
+ return credential ? withStikiCredential(spec, credential.token) : spec;
97
+ },
98
+ signedIn,
99
+ /** Who Settings says the server is signed in as, or undefined. */
100
+ signedInAs(spec) {
101
+ const credential = signedIn(spec) ? credentials.current() : null;
102
+ return credential ? { name: credential.identity.name } : undefined;
103
+ },
104
+ /** A signed-in start needed a sign-in: refresh the token now. True when
105
+ * this took over; a refresh with nothing new falls back to the back-off. */
106
+ refused(name, spec) {
107
+ if (!signedIn(spec))
108
+ return false;
109
+ void credentials.refreshAfterRejection().then((renewed) => {
110
+ if (!renewed)
111
+ deps.authState().noteSignInRequired(name, spec);
112
+ });
113
+ return true;
114
+ },
115
+ /** Settings' Test and Reconnect: a refused token is refreshed and the
116
+ * probe tried once more, never a browser. `start` builds the start. */
117
+ async probe(spec, run) {
118
+ const first = await run();
119
+ if (first.ok || first.signInRequired !== true || !signedIn(spec))
120
+ return first;
121
+ return (await credentials.refreshAfterRejection()) ? run() : first;
122
+ },
123
+ };
124
+ }
@@ -13,8 +13,8 @@
13
13
  // error: "<a calm sentence for the person>" }`.
14
14
  //
15
15
  // So Atomic never sends an organization of its own: it connects as the person.
16
- // What it does here is recognise these two servers (they need a one-time
17
- // sign-in in the browser) and turn Nexus's "not enabled" answer into a calm
16
+ // What it does here is recognise these two servers (Atomic's Chibitek sign-in
17
+ // signs them in: server/chibitek-mcp-signin.ts) and turn Nexus's "not enabled" answer into a calm
18
18
  // notice that is shown as-is, instead of a failure.
19
19
  /** Kept equal to CHIBITEK_MCP_SERVERS in electron/chibitek-defaults.mjs
20
20
  * (company-mcp-tenancy.test.ts checks it). */
@@ -1,9 +1,6 @@
1
- // The agents tools' only way to the harness: JSON over HTTP to the
2
- // loopback-only /api/internal/* routes, carrying the capability token the
3
- // harness minted for this turn (or the standing one of an external runtime).
4
- // The harness authenticates and scopes every call; nothing here decides what
5
- // a bot may do.
1
+ import { readFileSync } from "node:fs";
6
2
  export function createHarnessClient(baseUrl, token) {
3
+ const bearer = typeof token === "function" ? token : () => token;
7
4
  async function api(path, init) {
8
5
  const { ok, status, body } = await apiResponse(path, init);
9
6
  if (!ok)
@@ -13,7 +10,7 @@ export function createHarnessClient(baseUrl, token) {
13
10
  async function apiResponse(path, init) {
14
11
  const res = await fetch(baseUrl + path, {
15
12
  ...init,
16
- headers: { "content-type": "application/json", authorization: `Bearer ${token}`, ...init?.headers },
13
+ headers: { "content-type": "application/json", authorization: `Bearer ${bearer()}`, ...init?.headers },
17
14
  });
18
15
  const body = (await res.json().catch(() => ({})));
19
16
  return { ok: res.ok, status: res.status, body };
@@ -21,8 +18,25 @@ export function createHarnessClient(baseUrl, token) {
21
18
  return { api, apiResponse };
22
19
  }
23
20
  /** The client a spawned proxy was given:
24
- * OMB_HARNESS_URL base URL of the harness (http://127.0.0.1:8799)
25
- * OMB_COMMS_TOKEN the capability token for the internal endpoints */
21
+ * OMB_HARNESS_URL base URL of the harness (http://127.0.0.1:8799)
22
+ * OMB_COMMS_TOKEN_FILE per-thread file the harness rewrites with each turn's
23
+ * capability token. Read per call: an ACP engine keeps
24
+ * this proxy process across turns, so the token it was
25
+ * spawned with is revoked by its second turn.
26
+ * OMB_COMMS_TOKEN the spawn-time token, for runtimes with no file
27
+ * (cloud boxes, external runtimes, tests) */
26
28
  export function harnessClientFromEnv(env) {
27
- return createHarnessClient(env.OMB_HARNESS_URL ?? "http://127.0.0.1:8799", env.OMB_COMMS_TOKEN ?? "");
29
+ const file = env.OMB_COMMS_TOKEN_FILE;
30
+ const fallback = env.OMB_COMMS_TOKEN ?? "";
31
+ const token = () => {
32
+ if (!file)
33
+ return fallback;
34
+ try {
35
+ return readFileSync(file, "utf8").trim() || fallback;
36
+ }
37
+ catch {
38
+ return fallback;
39
+ }
40
+ };
41
+ return createHarnessClient(env.OMB_HARNESS_URL ?? "http://127.0.0.1:8799", token);
28
42
  }