@chibitek/chibi 0.1.209 → 0.1.210

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/assets/{TerminalPanel-CHGq3udb.js → TerminalPanel-DxQoOfkY.js} +1 -1
  2. package/dist/assets/{abnfDiagram-O67JEVCF-BMaKhJ-b.js → abnfDiagram-O67JEVCF-Ds2qYdjS.js} +1 -1
  3. package/dist/assets/{arc-CYAiNWN8.js → arc-1O9tchZk.js} +1 -1
  4. package/dist/assets/{architectureDiagram-NJMV4G6O-CxJFFlbO.js → architectureDiagram-NJMV4G6O-CWuQ1x2F.js} +1 -1
  5. package/dist/assets/{blockDiagram-BEXU5L5S-C7AbPjRB.js → blockDiagram-BEXU5L5S-CNcEkXEx.js} +1 -1
  6. package/dist/assets/{c4Diagram-YGBWAQC7-DfVnCJmT.js → c4Diagram-YGBWAQC7-BKI_wi9I.js} +1 -1
  7. package/dist/assets/channel-CT5xRPK0.js +1 -0
  8. package/dist/assets/{chunk-2Q5K7J3B-CzAUFkgv.js → chunk-2Q5K7J3B-gO88emfN.js} +1 -1
  9. package/dist/assets/{chunk-3FUC2YCW-BgeBXphm.js → chunk-3FUC2YCW-DbKNT_-r.js} +2 -2
  10. package/dist/assets/{chunk-5VM5RSS4-DPRdTAXc.js → chunk-5VM5RSS4-BbJCoZVg.js} +1 -1
  11. package/dist/assets/{chunk-GTNCS2PH-BS-_dIVl.js → chunk-GTNCS2PH-DXurSCcp.js} +1 -1
  12. package/dist/assets/{chunk-GWA4HPMP-D6I7xMmd.js → chunk-GWA4HPMP-BWyt0I_m.js} +1 -1
  13. package/dist/assets/{chunk-JWPE2WC7-BKSKe7C9.js → chunk-JWPE2WC7-6iWSsogl.js} +1 -1
  14. package/dist/assets/{chunk-NETBCI7D-R48UYTRN.js → chunk-NETBCI7D-CFoqO9Hw.js} +1 -1
  15. package/dist/assets/{chunk-WEXAMYUT-C8z4mL-2.js → chunk-WEXAMYUT-BZEzAlNi.js} +1 -1
  16. package/dist/assets/{chunk-XXDRQBXY-Bml3ZRJ5.js → chunk-XXDRQBXY-W4hfC50f.js} +1 -1
  17. package/dist/assets/{classDiagram-v2-NBCMYWYE-w5wo22FO.js → classDiagram-v2-NBCMYWYE-BsGmL9e7.js} +1 -1
  18. package/dist/assets/{cose-bilkent-JH36ORCC-Cum9v--4.js → cose-bilkent-JH36ORCC-CYtTgIzk.js} +1 -1
  19. package/dist/assets/{cynefin-OW5HDTMX-BzN0-KsP.js → cynefin-OW5HDTMX-DLOi2Q2V.js} +1 -1
  20. package/dist/assets/{cynefinDiagram-VND7K2PF-CkOpm32D.js → cynefinDiagram-VND7K2PF-BXcXJ3hv.js} +1 -1
  21. package/dist/assets/{dagre-6A5THRUB-BItQkKZD.js → dagre-6A5THRUB-BdBOiuzt.js} +1 -1
  22. package/dist/assets/{diagram-22UHCM2B-BI0zDn7c.js → diagram-22UHCM2B-DCf3M4WE.js} +1 -1
  23. package/dist/assets/{diagram-3UASUU5V-jwcDxsu6.js → diagram-3UASUU5V-CzdF-UXi.js} +1 -1
  24. package/dist/assets/{diagram-ATOU4E4O-2RnY9egJ.js → diagram-ATOU4E4O-_UmmlMOD.js} +1 -1
  25. package/dist/assets/{diagram-CDSNMT55-eVdEZmEF.js → diagram-CDSNMT55-DrQODVuX.js} +1 -1
  26. package/dist/assets/{diagram-MLGK6HIB-BCDGCJJ0.js → diagram-MLGK6HIB-CE16iJlJ.js} +1 -1
  27. package/dist/assets/{diagram-MPIPVDR6-DtN5uO5w.js → diagram-MPIPVDR6-DJuTbhbP.js} +1 -1
  28. package/dist/assets/{ebnfDiagram-ZINNZB2B-B9GpXSEs.js → ebnfDiagram-ZINNZB2B-f1VEI2Po.js} +1 -1
  29. package/dist/assets/{elk-276RUBZZ-Bk_eaK4T.js → elk-276RUBZZ-BRbs9WzY.js} +1 -1
  30. package/dist/assets/{erDiagram-OPXOYQCR-BiGoW6C6.js → erDiagram-OPXOYQCR-DvMp_cQr.js} +1 -1
  31. package/dist/assets/{flowDiagram-KWPJA3E3-ZW5w0BaJ.js → flowDiagram-KWPJA3E3-CYS1A0fu.js} +1 -1
  32. package/dist/assets/{ganttDiagram-FUAMR5RP-yyrKgsx1.js → ganttDiagram-FUAMR5RP-qya_JE9x.js} +1 -1
  33. package/dist/assets/{gitGraphDiagram-X574FWY7-CeiDikzD.js → gitGraphDiagram-X574FWY7-ChMUJ3hH.js} +1 -1
  34. package/dist/assets/{index-CZGnshrJ.js → index-COH7BlyH.js} +196 -196
  35. package/dist/assets/index-H8vkXbLq.css +1 -0
  36. package/dist/assets/{index-DUFlRZuA.js → index-xE4Li_H2.js} +1 -1
  37. package/dist/assets/{infoDiagram-VRGFBTTK-q2B-KJFm.js → infoDiagram-VRGFBTTK-B2VudqsE.js} +1 -1
  38. package/dist/assets/{ishikawaDiagram-OU5B5YK6-D8gXFuc0.js → ishikawaDiagram-OU5B5YK6-Bdk47y0t.js} +1 -1
  39. package/dist/assets/{journeyDiagram-ZHPQQLJL-BmHL2mbq.js → journeyDiagram-ZHPQQLJL-A4StgNQ9.js} +1 -1
  40. package/dist/assets/{kanban-definition-PNTS6WVX-B9Ll2WkA.js → kanban-definition-PNTS6WVX-DZo45dQw.js} +1 -1
  41. package/dist/assets/{linear-CMVGYrKx.js → linear-D_rK-Ord.js} +1 -1
  42. package/dist/assets/{mermaid.core-qO11n1kV.js → mermaid.core-C7CvDDvz.js} +5 -5
  43. package/dist/assets/{mindmap-definition-NLK3R4M7-CxLGFX45.js → mindmap-definition-NLK3R4M7-6fmVPMyc.js} +1 -1
  44. package/dist/assets/{pegDiagram-GJSIUBJH-CxK1MJG4.js → pegDiagram-GJSIUBJH-CD4Qg24h.js} +1 -1
  45. package/dist/assets/{pieDiagram-5QR66LMP-H5jiF5Eu.js → pieDiagram-5QR66LMP-DmzQ883B.js} +1 -1
  46. package/dist/assets/{quadrantDiagram-O4NWA36T-CKaqCruv.js → quadrantDiagram-O4NWA36T-BW37utPZ.js} +1 -1
  47. package/dist/assets/{railroadDiagram-XR7U4H2S-BCzKiQOd.js → railroadDiagram-XR7U4H2S-CWXiMlAb.js} +1 -1
  48. package/dist/assets/{requirementDiagram-PLB6GJNP-Cqtr43DT.js → requirementDiagram-PLB6GJNP-DHSfr9U3.js} +1 -1
  49. package/dist/assets/{sankeyDiagram-IPEJSGJF-B2tQewX8.js → sankeyDiagram-IPEJSGJF-PebTt4eq.js} +1 -1
  50. package/dist/assets/{sequenceDiagram-PO4LG4MO-nggwQyrw.js → sequenceDiagram-PO4LG4MO-DPwp8fia.js} +1 -1
  51. package/dist/assets/{sizeCapture-INFHLROL-qSPXJBv2.js → sizeCapture-INFHLROL-BX_46o3S.js} +1 -1
  52. package/dist/assets/{stateDiagram-v2-GCMORJYK-DraPbL2T.js → stateDiagram-v2-GCMORJYK-W2e0RRrZ.js} +1 -1
  53. package/dist/assets/{swimlanes-2SLR337P-C6HVkIDA.js → swimlanes-2SLR337P-CkyXpQX9.js} +1 -1
  54. package/dist/assets/swimlanesDiagram-TC7HE7FX-BH9Yry0J.js +8 -0
  55. package/dist/assets/{timeline-definition-EJHVYXUP-DZmPRTsx.js → timeline-definition-EJHVYXUP-BS-sCjlN.js} +1 -1
  56. package/dist/assets/{usecaseDiagram-POWQR4AR-CsVuROW_.js → usecaseDiagram-POWQR4AR-BQre-k6x.js} +1 -1
  57. package/dist/assets/{vennDiagram-UO4OBE2U-B9IRbuhp.js → vennDiagram-UO4OBE2U-CEWCsi_s.js} +1 -1
  58. package/dist/assets/{wardleyDiagram-VNRHLVJA-CGmVK53n.js → wardleyDiagram-VNRHLVJA-CXUxqghG.js} +1 -1
  59. package/dist/assets/{xychartDiagram-PMCCYNJV-BAw-x9Y1.js → xychartDiagram-PMCCYNJV-DBgVMpwp.js} +1 -1
  60. package/dist/index.html +4 -2
  61. package/dist-server/accounts-proxy.js +19 -12
  62. package/dist-server/browser-proxy.js +19 -14
  63. package/dist-server/container-mcp.js +84 -12
  64. package/dist-server/drivers/agents-proxy.js +28 -13
  65. package/dist-server/drivers/phone-proxy.js +21 -13
  66. package/dist-server/index.js +3990 -2815
  67. package/dist-server/local-computer-proxy.js +77 -11
  68. package/dist-server/local-computer.js +2 -1
  69. package/dist-server/mcp-gate.js +53 -4
  70. package/dist-server/mcp-server.js +1 -1
  71. package/dist-server/openmausbot.js +443 -74
  72. package/dist-server/pair-cli.js +443 -74
  73. package/dist-server/server/accounts-proxy.js +3 -17
  74. package/dist-server/server/atomic-engine-release.js +7 -0
  75. package/dist-server/server/browser-proxy.js +3 -17
  76. package/dist-server/server/child-env.js +79 -0
  77. package/dist-server/server/config.js +11 -5
  78. package/dist-server/server/container-computer.js +1 -1
  79. package/dist-server/server/container-mcp.js +3 -2
  80. package/dist-server/server/control-client.js +7 -6
  81. package/dist-server/server/delegated-full-access.js +98 -0
  82. package/dist-server/server/desktop-loopback-gate.js +57 -0
  83. package/dist-server/server/drivers/acp/core.js +4 -4
  84. package/dist-server/server/drivers/acp/session-key.js +8 -0
  85. package/dist-server/server/drivers/agents-client.js +2 -14
  86. package/dist-server/server/drivers/gcloud-token.js +28 -0
  87. package/dist-server/server/drivers/github-copilot.js +152 -0
  88. package/dist-server/server/drivers/openai-chat-protocol.js +8 -0
  89. package/dist-server/server/drivers/openai-chat.js +10 -8
  90. package/dist-server/server/drivers/openai-compat.js +44 -9
  91. package/dist-server/server/drivers/phone-proxy.js +5 -18
  92. package/dist-server/server/engine-tiers.js +9 -9
  93. package/dist-server/server/harness/http.js +47 -1
  94. package/dist-server/server/index.js +54 -54
  95. package/dist-server/server/ladder-pick.js +18 -0
  96. package/dist-server/server/local-computer-proxy.js +3 -2
  97. package/dist-server/server/local-computer.js +1 -0
  98. package/dist-server/server/mcp-bridge.js +3 -2
  99. package/dist-server/server/mcp-gate.js +2 -1
  100. package/dist-server/server/mcp-registry.js +5 -1
  101. package/dist-server/server/model-gateway/failover.js +4 -1
  102. package/dist-server/server/model-gateway/route.js +64 -14
  103. package/dist-server/server/model-gateway/usage.js +66 -0
  104. package/dist-server/server/model-levels/aa-scale.js +42 -0
  105. package/dist-server/server/model-levels/aliases.js +16 -3
  106. package/dist-server/server/model-levels/index.js +8 -3
  107. package/dist-server/server/model-levels/rankings-build.js +76 -0
  108. package/dist-server/server/model-prices.js +6 -0
  109. package/dist-server/server/nexus-memory/index.js +5 -13
  110. package/dist-server/server/nexus-memory/policy.js +5 -17
  111. package/dist-server/server/oauth-account-vault.js +7 -2
  112. package/dist-server/server/provider-accounts.js +20 -1
  113. package/dist-server/server/provider-key-check.js +31 -1
  114. package/dist-server/server/registry-load.js +88 -0
  115. package/dist-server/server/request-auth.js +6 -28
  116. package/dist-server/server/routes/provider-accounts.js +124 -6
  117. package/dist-server/server/routine-daily-schedule.js +20 -0
  118. package/dist-server/server/routine-prompt-escape.js +18 -0
  119. package/dist-server/server/routine-tick-guard.js +16 -0
  120. package/dist-server/server/routine-tool-problems.js +36 -0
  121. package/dist-server/server/routines.js +36 -38
  122. package/dist-server/server/shutdown-triggers.js +18 -0
  123. package/dist-server/server/spend.js +23 -13
  124. package/dist-server/server/store.js +4 -13
  125. package/dist-server/server/terminal.js +2 -1
  126. package/dist-server/server/turn-token-file.js +79 -0
  127. package/dist-server/server/turn-token.js +23 -0
  128. package/dist-server/server/vps-container-mcp.js +3 -2
  129. package/dist-server/server/webhook-ingress.js +11 -1
  130. package/dist-server/server/webhook-prompt.js +82 -0
  131. package/dist-server/server/webhooks.js +8 -65
  132. package/dist-server/server/workspace-backup-policy.js +3 -3
  133. package/dist-server/server/workspace-backup.js +1 -1
  134. package/dist-server/server/workspace-time-zone.js +47 -0
  135. package/dist-server/shared/engine-choices.js +12 -1
  136. package/dist-server/shared/provider-accounts.js +114 -2
  137. package/dist-server/shared/zoned-time.js +55 -0
  138. package/dist-server/vps-container-mcp.js +84 -12
  139. package/package.json +1 -1
  140. package/dist/assets/channel-DxL_mLhm.js +0 -1
  141. package/dist/assets/index-Bi3hprmz.css +0 -1
  142. package/dist/assets/swimlanesDiagram-TC7HE7FX-gQUGsELo.js +0 -8
@@ -0,0 +1,152 @@
1
+ export const COPILOT_CLIENT_ID_ENV = "ATOMIC_GITHUB_COPILOT_CLIENT_ID";
2
+ const DEFAULT_CLIENT_ID = "Iv1.b507a08c87ecfe98";
3
+ export const COPILOT_DEFAULT_API = "https://api.githubcopilot.com";
4
+ const GITHUB = "https://github.com";
5
+ const GITHUB_API = "https://api.github.com";
6
+ /** A Copilot token is renewed this long before GitHub says it expires. */
7
+ const RENEW_EARLY_MS = 5 * 60_000;
8
+ /** The integration headers the Copilot API requires on every request; a
9
+ * Copilot token is scoped to the integration it was minted for. */
10
+ export const COPILOT_HEADERS = Object.freeze({
11
+ "editor-version": "vscode/1.99.0",
12
+ "editor-plugin-version": "copilot-chat/0.26.0",
13
+ "copilot-integration-id": "vscode-chat",
14
+ "user-agent": "GitHubCopilotChat/0.26.0",
15
+ "openai-intent": "conversation-panel",
16
+ });
17
+ export function copilotClientId(env = process.env) {
18
+ return env[COPILOT_CLIENT_ID_ENV]?.trim() || DEFAULT_CLIENT_ID;
19
+ }
20
+ export async function startCopilotDeviceSignIn(fetchImpl = fetch, env = process.env) {
21
+ const response = await fetchImpl(`${GITHUB}/login/device/code`, {
22
+ method: "POST",
23
+ headers: { accept: "application/json", "content-type": "application/json" },
24
+ body: JSON.stringify({ client_id: copilotClientId(env), scope: "read:user" }),
25
+ redirect: "error",
26
+ signal: AbortSignal.timeout(10_000),
27
+ });
28
+ if (!response.ok)
29
+ throw new Error(`GitHub did not start the sign-in (HTTP ${response.status}).`);
30
+ const body = await response.json();
31
+ const deviceCode = typeof body.device_code === "string" ? body.device_code : "";
32
+ const userCode = typeof body.user_code === "string" ? body.user_code : "";
33
+ const verificationUri = typeof body.verification_uri === "string" ? body.verification_uri : "";
34
+ if (!deviceCode || !userCode || !verificationUri.startsWith("https://github.com/")) {
35
+ throw new Error("GitHub gave an unexpected answer when starting the sign-in.");
36
+ }
37
+ return {
38
+ deviceCode, userCode, verificationUri,
39
+ interval: typeof body.interval === "number" && body.interval > 0 ? body.interval : 5,
40
+ expiresIn: typeof body.expires_in === "number" && body.expires_in > 0 ? body.expires_in : 900,
41
+ };
42
+ }
43
+ /** One poll of the device code (RFC 8628). */
44
+ export async function pollCopilotDeviceSignIn(deviceCode, fetchImpl = fetch, env = process.env) {
45
+ let response;
46
+ try {
47
+ response = await fetchImpl(`${GITHUB}/login/oauth/access_token`, {
48
+ method: "POST",
49
+ headers: { accept: "application/json", "content-type": "application/json" },
50
+ body: JSON.stringify({ client_id: copilotClientId(env), device_code: deviceCode, grant_type: "urn:ietf:params:oauth:grant-type:device_code" }),
51
+ redirect: "error",
52
+ signal: AbortSignal.timeout(10_000),
53
+ });
54
+ }
55
+ catch {
56
+ return { state: "pending" }; // a dropped poll is retried on the next tick
57
+ }
58
+ if (!response.ok)
59
+ return { state: "failed", reason: "unexpected" };
60
+ const body = await response.json().catch(() => null);
61
+ if (typeof body?.access_token === "string" && body.access_token)
62
+ return { state: "done", token: body.access_token };
63
+ switch (body?.error) {
64
+ case "authorization_pending": return { state: "pending" };
65
+ case "slow_down": return { state: "pending", interval: typeof body.interval === "number" ? body.interval : undefined };
66
+ case "access_denied": return { state: "failed", reason: "denied" };
67
+ case "expired_token": return { state: "failed", reason: "expired" };
68
+ default: return { state: "failed", reason: "unexpected" };
69
+ }
70
+ }
71
+ export class CopilotAuthError extends Error {
72
+ status;
73
+ constructor(message, status) {
74
+ super(message);
75
+ this.status = status;
76
+ }
77
+ }
78
+ export const COPILOT_NO_PLAN = "This GitHub account has no active Copilot plan. Check github.com/settings/copilot, then sign in again.";
79
+ export const COPILOT_SIGNED_OUT = "GitHub Copilot is signed out. Sign in again in Settings > AI & accounts > Subscriptions.";
80
+ /** Trade a GitHub token for a Copilot token. */
81
+ export async function exchangeCopilotToken(githubToken, fetchImpl = fetch, now = Date.now()) {
82
+ let response;
83
+ try {
84
+ response = await fetchImpl(`${GITHUB_API}/copilot_internal/v2/token`, {
85
+ headers: { ...COPILOT_HEADERS, accept: "application/json", authorization: `token ${githubToken}` },
86
+ redirect: "error",
87
+ signal: AbortSignal.timeout(10_000),
88
+ });
89
+ }
90
+ catch {
91
+ throw new CopilotAuthError("Could not reach GitHub to renew the Copilot sign-in.");
92
+ }
93
+ if (response.status === 401)
94
+ throw new CopilotAuthError(COPILOT_SIGNED_OUT, 401);
95
+ if (response.status === 403 || response.status === 404)
96
+ throw new CopilotAuthError(COPILOT_NO_PLAN, response.status);
97
+ if (!response.ok)
98
+ throw new CopilotAuthError(`GitHub could not renew the Copilot sign-in (HTTP ${response.status}).`, response.status);
99
+ const body = await response.json().catch(() => null);
100
+ const token = typeof body?.token === "string" ? body.token : "";
101
+ if (!token)
102
+ throw new CopilotAuthError("GitHub gave an unexpected answer when renewing the Copilot sign-in.");
103
+ const endpoints = body?.endpoints && typeof body.endpoints === "object" ? body.endpoints : {};
104
+ const api = typeof endpoints.api === "string" && /^https:\/\/[a-z0-9.-]+\.githubcopilot\.com\/?$/i.test(endpoints.api)
105
+ ? endpoints.api.replace(/\/+$/, "") : COPILOT_DEFAULT_API;
106
+ const expiresAt = typeof body?.expires_at === "number" ? body.expires_at * 1000 : now + 25 * 60_000;
107
+ return { token, apiUrl: api, expiresAt };
108
+ }
109
+ /** One account's Copilot token, renewed only when it is close to expiring;
110
+ * concurrent turns share one renewal. */
111
+ export function copilotSessionCache(githubToken, fetchImpl = fetch, clock = Date.now) {
112
+ let current;
113
+ let pending;
114
+ return async () => {
115
+ if (current && current.expiresAt - RENEW_EARLY_MS > clock())
116
+ return current;
117
+ pending ??= exchangeCopilotToken(githubToken, fetchImpl, clock()).then((session) => {
118
+ current = session;
119
+ return session;
120
+ }).finally(() => { pending = undefined; });
121
+ return pending;
122
+ };
123
+ }
124
+ /** The chat models a Copilot plan offers (GET <api>/models): those the
125
+ * Copilot model picker shows and the plan has not switched off. */
126
+ export async function fetchCopilotModels(session, fetchImpl = fetch) {
127
+ const response = await fetchImpl(`${session.apiUrl}/models`, {
128
+ headers: { ...COPILOT_HEADERS, authorization: `Bearer ${session.token}` },
129
+ redirect: "error",
130
+ signal: AbortSignal.timeout(8_000),
131
+ });
132
+ if (!response.ok)
133
+ return [];
134
+ const json = await response.json().catch(() => null);
135
+ const rows = Array.isArray(json?.data) ? json.data : [];
136
+ const seen = new Set();
137
+ const options = [];
138
+ for (const row of rows) {
139
+ const id = typeof row.id === "string" ? row.id : "";
140
+ const capabilities = row.capabilities && typeof row.capabilities === "object" ? row.capabilities : {};
141
+ const policy = row.policy && typeof row.policy === "object" ? row.policy : {};
142
+ if (!id || seen.has(id))
143
+ continue;
144
+ if (capabilities.type !== undefined && capabilities.type !== "chat")
145
+ continue;
146
+ if (row.model_picker_enabled === false || policy.state === "disabled")
147
+ continue;
148
+ seen.add(id);
149
+ options.push({ id, label: typeof row.name === "string" && row.name.trim() ? row.name : id, custom: true });
150
+ }
151
+ return options;
152
+ }
@@ -105,3 +105,11 @@ export class ChatToolCalls {
105
105
  return calls;
106
106
  }
107
107
  }
108
+ /** Token totals from an OpenAI-style `usage` block, with the request's price
109
+ * in US dollars when the provider reports one (OpenRouter's `usage.cost`). */
110
+ export function chatUsage(usage) {
111
+ if (!usage)
112
+ return null;
113
+ const cost = typeof usage.cost === "number" && Number.isFinite(usage.cost) && usage.cost >= 0 ? usage.cost : undefined;
114
+ return { input: usage.prompt_tokens ?? 0, output: usage.completion_tokens ?? 0, ...(cost !== undefined ? { cost } : {}) };
115
+ }
@@ -5,13 +5,11 @@ import { toolDetailPreview } from "../tool-summary.js";
5
5
  import { ChatToolSessionError, mountChatTools } from "./chat-mcp-tools.js";
6
6
  import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent } from "./chat-images.js";
7
7
  import { createChatToolApproval } from "./chat-tool-approval.js";
8
- import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, MAX_CHAT_TOOL_CALLS, object, providerError } from "./openai-chat-protocol.js";
8
+ import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, MAX_CHAT_TOOL_CALLS, chatUsage, object, providerError } from "./openai-chat-protocol.js";
9
9
  import { hasImageParts, learnTextOnly, sendableMessages } from "./chat-text-only.js";
10
10
  import { appendNative } from "./native.js";
11
11
  import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.js";
12
- const usageFrom = (usage) => usage
13
- ? { input: usage.prompt_tokens ?? 0, output: usage.completion_tokens ?? 0 }
14
- : null;
12
+ const usageFrom = (usage) => chatUsage(usage);
15
13
  const asError = (value) => value instanceof Error ? value : new Error(String(value));
16
14
  /** Shared runtime for the three providers that speak OpenAI chat completions. */
17
15
  export function createOpenAIChatRuntime(options) {
@@ -45,11 +43,12 @@ export function createOpenAIChatRuntime(options) {
45
43
  const activeSignal = signal
46
44
  ? AbortSignal.any([signal, timeoutController.signal])
47
45
  : timeoutController.signal;
48
- const sendable = sendableMessages(options.apiUrl, model, messages);
49
- const response = await fetch(`${options.apiUrl}/chat/completions`, {
46
+ const auth = await options.authorize?.();
47
+ const sendable = sendableMessages(auth?.apiUrl ?? options.apiUrl, model, messages);
48
+ const response = await fetch(`${auth?.apiUrl ?? options.apiUrl}/chat/completions`, {
50
49
  method: "POST",
51
50
  ...(hasImageParts(sendable) ? { redirect: "error" } : {}),
52
- headers: { ...options.extraHeaders, authorization: `Bearer ${options.apiKey}`, "content-type": "application/json" },
51
+ headers: { ...options.extraHeaders, ...auth?.headers, authorization: `Bearer ${auth?.apiKey ?? options.apiKey}`, "content-type": "application/json" },
53
52
  body: JSON.stringify({
54
53
  ...options.requestBody(model, sendable, stream),
55
54
  ...(tools.length ? { tools } : {}),
@@ -281,6 +280,7 @@ export function createOpenAIChatRuntime(options) {
281
280
  let tools;
282
281
  const usage = { input: 0, output: 0 };
283
282
  let hasUsage = false;
283
+ let cost = null; // the provider's own price, when it reports one
284
284
  let ok = false;
285
285
  let stopReason = null;
286
286
  let failure;
@@ -354,6 +354,8 @@ export function createOpenAIChatRuntime(options) {
354
354
  }
355
355
  native("in", options.nativeLog.incoming(completion));
356
356
  if (completion.usage) {
357
+ if (completion.usage.cost !== undefined)
358
+ cost = (cost ?? 0) + completion.usage.cost;
357
359
  usage.input += completion.usage.input;
358
360
  usage.output += completion.usage.output;
359
361
  hasUsage = true;
@@ -488,7 +490,7 @@ export function createOpenAIChatRuntime(options) {
488
490
  emit({ ...base(turn.threadId, turnId), type: "runtime.error", message: failure, terminal: !abort.signal.aborted });
489
491
  }
490
492
  active.delete(turn.threadId);
491
- emit({ ...base(turn.threadId, turnId), type: "turn.completed", ok, stopReason, cost: null,
493
+ emit({ ...base(turn.threadId, turnId), type: "turn.completed", ok, stopReason, cost,
492
494
  ...(hasUsage && (options.includeUsageInCompleted || seenCalls.size) ? { usage } : {}),
493
495
  ...(denials.length ? { denials } : {}),
494
496
  });
@@ -1,8 +1,10 @@
1
1
  import { OLLAMA_CLOUD_PREFERRED_MODEL, OLLAMA_CLOUD_URL } from "./ollama-cloud.js";
2
2
  import { createOpenAIChatRuntime } from "./openai-chat.js";
3
3
  import { openAiTeamHeaders } from "../provider-key-check.js";
4
+ import { COPILOT_HEADERS, copilotSessionCache, fetchCopilotModels } from "./github-copilot.js";
5
+ import { gcloudTokenCache } from "./gcloud-token.js";
4
6
  const DRIVER_KIND = "openai-compat";
5
- const DEFAULT_IDLE_TIMEOUT_MS = 180_000;
7
+ export const DEFAULT_IDLE_TIMEOUT_MS = 180_000;
6
8
  const idleTimeoutMs = () => {
7
9
  const raw = process.env.OPENMAUS_OPENAI_COMPAT_IDLE_TIMEOUT_MS;
8
10
  if (!raw)
@@ -14,6 +16,10 @@ const DEFAULT_MODELS = {
14
16
  default: OLLAMA_CLOUD_PREFERRED_MODEL,
15
17
  options: [{ id: OLLAMA_CLOUD_PREFERRED_MODEL, label: `${OLLAMA_CLOUD_PREFERRED_MODEL} (Ollama)`, custom: true }],
16
18
  };
19
+ /** OpenRouter's free models: `:free` ids and the `openrouter/free` router. */
20
+ export function isFreeOpenRouterModel(id) {
21
+ return id.endsWith(":free") || id === "openrouter/free";
22
+ }
17
23
  function isOpenRouterUrl(url) {
18
24
  try {
19
25
  const host = new URL(url).hostname.toLowerCase();
@@ -48,6 +54,10 @@ function decodeConfig(raw) {
48
54
  ? config.provider || undefined
49
55
  : process.env.OPENAI_COMPAT_PROVIDER || undefined,
50
56
  ...(typeof config.organization === "string" && config.organization ? { organization: config.organization } : {}),
57
+ // Accounts added as "OpenRouter (free models)" before the filter existed
58
+ // are known by their key's variable.
59
+ ...(config.modelFilter === "free" || config.apiKeyEnv === "OPENROUTER_FREE_API_KEY" ? { modelFilter: "free" } : {}),
60
+ ...(config.auth === "githubCopilot" || config.auth === "gcloud" ? { auth: config.auth } : {}),
51
61
  ...(typeof config.project === "string" && config.project ? { project: config.project } : {}),
52
62
  };
53
63
  }
@@ -93,11 +103,29 @@ export const OpenAICompatDriver = {
93
103
  : [{ id: config.model, label: config.model, custom: true }, ...DEFAULT_MODELS.options],
94
104
  }
95
105
  : DEFAULT_MODELS;
106
+ const copilot = config.auth === "githubCopilot" && apiKey ? copilotSessionCache(apiKey) : undefined;
107
+ // Vertex AI: the token comes from the person's own gcloud sign-in.
108
+ const gcloud = config.auth === "gcloud" ? gcloudTokenCache() : undefined;
109
+ const useOptions = (options) => {
110
+ if (!options.length)
111
+ return;
112
+ if (config.model && !options.some((model) => model.id === config.model)) {
113
+ options.unshift({ id: config.model, label: config.model, custom: true });
114
+ }
115
+ catalog = { default: config.model || options[0].id, options };
116
+ };
96
117
  const fetchModels = async () => {
97
- if (config.managedModels)
118
+ if (config.managedModels || gcloud)
98
119
  return;
99
120
  if (!apiKey)
100
121
  return;
122
+ if (copilot) {
123
+ try {
124
+ useOptions(await fetchCopilotModels(await copilot()));
125
+ }
126
+ catch { /* the turn reports a sign-in problem */ }
127
+ return;
128
+ }
101
129
  try {
102
130
  const response = await fetch(`${config.url}/models`, {
103
131
  headers: { ...teamHeaders, authorization: `Bearer ${apiKey}` },
@@ -113,6 +141,8 @@ export const OpenAICompatDriver = {
113
141
  const id = typeof row.id === "string" ? row.id : "";
114
142
  if (!id || seen.has(id))
115
143
  continue;
144
+ if (config.modelFilter === "free" && !isFreeOpenRouterModel(id))
145
+ continue;
116
146
  seen.add(id);
117
147
  options.push({
118
148
  id,
@@ -120,12 +150,7 @@ export const OpenAICompatDriver = {
120
150
  custom: true,
121
151
  });
122
152
  }
123
- if (!options.length)
124
- return;
125
- if (config.model && !options.some((model) => model.id === config.model)) {
126
- options.unshift({ id: config.model, label: config.model, custom: true });
127
- }
128
- catalog = { default: config.model ?? options[0].id, options };
153
+ useOptions(options);
129
154
  }
130
155
  catch {
131
156
  // Catalog refresh is opportunistic; keep the seeded options.
@@ -139,6 +164,12 @@ export const OpenAICompatDriver = {
139
164
  apiKey,
140
165
  apiUrl: config.url,
141
166
  extraHeaders: teamHeaders,
167
+ ...(copilot ? {
168
+ authorize: async () => {
169
+ const session = await copilot();
170
+ return { apiKey: session.token, apiUrl: session.apiUrl, headers: { ...COPILOT_HEADERS } };
171
+ },
172
+ } : gcloud ? { authorize: async () => ({ apiKey: await gcloud() }) } : {}),
142
173
  tools: config.tools,
143
174
  computerUse: true,
144
175
  models: () => catalog,
@@ -151,13 +182,17 @@ export const OpenAICompatDriver = {
151
182
  ...(config.provider && isOpenRouterUrl(config.url)
152
183
  ? { provider: { order: [config.provider], allow_fallbacks: false } }
153
184
  : {}),
185
+ // OpenRouter then reports each request's price, which the ledger and
186
+ // the monthly spend limit use instead of an estimate.
187
+ ...(isOpenRouterUrl(config.url) ? { usage: { include: true } } : {}),
154
188
  }),
155
189
  httpErrorLabel: "upstream",
156
190
  missingKeyError: OPENAI_COMPAT_NO_KEY,
157
191
  unavailableReason: OPENAI_COMPAT_NO_KEY,
158
192
  timeoutMs: idleTimeoutMs(),
159
193
  reasoning: true,
160
- billing: "metered",
194
+ // A Copilot plan is a subscription, not metered by the token.
195
+ ...(copilot ? {} : { billing: "metered" }),
161
196
  includeUsageInCompleted: true,
162
197
  nativeLog: {
163
198
  source: "openai-compat.chat.completions",
@@ -1,10 +1,11 @@
1
1
  // First-party Android phone MCP server. It deliberately accepts physical USB
2
2
  // devices only: no emulators, wireless debugging, network ADB, or Tailscale.
3
3
  import { spawn } from "node:child_process";
4
- import { accessSync, constants, existsSync, readFileSync } from "node:fs";
4
+ import { accessSync, constants, existsSync } from "node:fs";
5
5
  import { createInterface } from "node:readline";
6
6
  import { delimiter, join } from "node:path";
7
7
  import { homedir } from "node:os";
8
+ import { turnTokenReader } from "../turn-token.js";
8
9
  const MAX_ADB_OUTPUT = 16 * 1024 * 1024;
9
10
  // Mirrors the shared-computer blockedReason shape: name the holder's
10
11
  // situation, say the call did not happen, and tell the model what beats a
@@ -252,32 +253,18 @@ const textResult = (text, isError = false) => ({ content: [{ type: "text", text
252
253
  // is idempotent; a blocked caller can retry once the holding turn settles.
253
254
  export function createPhoneClaim(env = process.env, fetchImpl = fetch) {
254
255
  const url = env.OMB_HARNESS_URL?.trim();
255
- const spawnToken = env.OMB_PHONE_TOKEN?.trim() ?? "";
256
- const tokenFile = env.OMB_PHONE_TOKEN_FILE?.trim() ?? "";
257
- if (!url || (!spawnToken && !tokenFile)) {
256
+ const currentToken = turnTokenReader(env, "OMB_PHONE_TOKEN");
257
+ if (!url || !currentToken()) {
258
258
  // Spawned outside the harness (development, direct debugging): no
259
259
  // exclusivity to enforce, exactly the behavior this proxy always had.
260
260
  return async () => ({ ok: true });
261
261
  }
262
- // Read per call: the harness rewrites the file each turn, and a pooled
263
- // engine keeps this process across turns, so the spawn-time token is
264
- // revoked by turn two.
265
- const token = () => {
266
- if (!tokenFile)
267
- return spawnToken;
268
- try {
269
- return readFileSync(tokenFile, "utf8").trim() || spawnToken;
270
- }
271
- catch {
272
- return spawnToken;
273
- }
274
- };
275
262
  return async () => {
276
263
  try {
277
264
  const response = await fetchImpl(new URL("/api/internal/phone/claim", url), {
278
265
  method: "POST",
279
266
  redirect: "error",
280
- headers: { authorization: `Bearer ${token()}`, "content-type": "application/json" },
267
+ headers: { authorization: `Bearer ${currentToken()}`, "content-type": "application/json" },
281
268
  body: "{}",
282
269
  signal: AbortSignal.timeout(10_000),
283
270
  });
@@ -7,6 +7,7 @@ import { ATOMIC_AUTO_RUNG, BOT_TIERS, CHIBI_DEFAULT_RUNG, DEFAULT_LADDERS, DEFAU
7
7
  export { DEFAULT_LADDERS };
8
8
  import { expandAnySubscription, orderRungs } from "./ladder-order.js";
9
9
  import { ATOMIC_ENGINE_INSTANCE, engineIntent, freeCandidate, localModel, modelBilling, modelProvider, paidCandidate, perTokenModel } from "./harness-import/engine-policy.js";
10
+ export { needsWiderWalk, takeWider } from "./ladder-pick.js";
10
11
  /** Engines a tier tries first after Atomic Engine (Auto), whatever the
11
12
  * class catalog order says. Without Atomic Engine, Chibi runs on Claude:
12
13
  * Claude's best model graded in its class, then Claude's next (or Claude's
@@ -237,10 +238,9 @@ export function canDriveComputer(candidate, computer) {
237
238
  return candidate.capabilities?.localComputerMcp === true;
238
239
  return candidate.driverKind !== "boxAgent" && candidate.capabilities?.computerMcp === true;
239
240
  }
240
- /** Walk a ladder in two bands. First the subscription engines its rungs
241
- * name, in rung order, and Ollama Cloud whether named or not (after them
242
- * when no rung names it); then, automatically, every key-based engine
243
- * (those the rungs name first, then the rest). A rung on an engine that runs
241
+ /** Walk a ladder in three bands. First the subscription engines its rungs
242
+ * name, in rung order, and flat plans (Ollama Cloud) named or not; then free
243
+ * models; then every key-based engine (named first, then the rest). A rung on an engine that runs
244
244
  * many providers is in the band its model is paid in: a DeepInfra model on
245
245
  * Hermes is a key, a Nous Portal one a subscription. An engine is taken when
246
246
  * it is available, signed in, has a model, can delegate when the bot must,
@@ -263,15 +263,15 @@ export function resolveLadder(ladder, stored, context) {
263
263
  }
264
264
  }
265
265
  const rungOf = (candidate) => {
266
- const step = ladder.findIndex((entry) => matchesEngine(entry, candidate));
266
+ const step = ladder.findIndex((entry) => matchesEngine(entry, candidate) && entryModel(entry, candidate) !== undefined); // only a rung whose model it serves (a catalog run such as gpt-oss-120b must not leave a free account with no model)
267
267
  return step < 0 ? ladder.length : step;
268
268
  };
269
269
  const ownRung = (entry, candidate) => // a same-driver rung naming a model this account lacks: its own default
270
270
  (entry && entryModel(entry, candidate) ? entry : { engine: candidate.instanceId });
271
271
  for (const [index, candidate] of context.candidates.entries()) {
272
- // Ollama Cloud joins every ladder by itself, as it always has: now as the
273
- // flat plan it is, in the subscription band.
274
- if (candidate.driverKind === "ollamaCloud" && !keyBased(candidate) && !subscription.some((attempt) => attempt.candidate === candidate)) {
272
+ // Ollama Cloud and plans on OpenAI-compatible accounts (GitHub Copilot, coding plans) join every ladder's subscription band.
273
+ const planAccount = candidate.driverKind === "openai-compat" && candidate.billing === "subscription";
274
+ if ((candidate.driverKind === "ollamaCloud" || planAccount) && !keyBased(candidate) && !subscription.some((attempt) => attempt.candidate === candidate)) {
275
275
  subscription.push({ step: ladder.length, entry: { engine: candidate.instanceId }, candidate, band: "subscription", index });
276
276
  }
277
277
  // A free-tier account joins every ladder by itself, in its own
@@ -289,7 +289,7 @@ export function resolveLadder(ladder, stored, context) {
289
289
  }
290
290
  subscription.sort((a, b) => atomicFirst(a.candidate) - atomicFirst(b.candidate) || a.step - b.step);
291
291
  key.sort((a, b) => a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
292
- free.sort((a, b) => a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
292
+ free.sort((a, b) => Number(Boolean(a.candidate.keyless)) - Number(Boolean(b.candidate.keyless)) || a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
293
293
  for (const { step, entry, candidate, band } of [...subscription, ...free, ...key]) { // free before pay-per-use (Erick, 2026-11-15)
294
294
  // "paused" names a key kept off this turn by policy alone: a key that could not take it anyway (signed out, resting, refused) keeps its real reason.
295
295
  const reason = band === "free" && !context.includeFree ? "free-off"
@@ -15,9 +15,51 @@ export function parsedBodyOf(req) {
15
15
  export function json(res, status, body) {
16
16
  const hook = jsonHooks.get(res);
17
17
  const data = JSON.stringify(hook ? hook(body) : body);
18
- res.writeHead(status, { "content-type": "application/json" });
18
+ res.writeHead(status, { "content-type": "application/json", "x-content-type-options": "nosniff" });
19
19
  res.end(data);
20
20
  }
21
+ /** Headers for a file of the built UI. SAMEORIGIN rather than DENY because
22
+ * the app frames its own handbook page; no other site may frame it. */
23
+ export function staticHeaders(contentType) {
24
+ return {
25
+ "content-type": contentType,
26
+ "x-content-type-options": "nosniff",
27
+ "x-frame-options": "SAMEORIGIN",
28
+ "referrer-policy": "no-referrer",
29
+ };
30
+ }
31
+ function firstHeader(value) {
32
+ return Array.isArray(value) ? value[0] : value;
33
+ }
34
+ function isJsonContentType(value) {
35
+ const type = firstHeader(value)?.split(";")[0]?.trim().toLowerCase() ?? "";
36
+ return type === "application/json" || /^application\/[\w.-]+\+json$/.test(type);
37
+ }
38
+ /** The port an authority names, with the scheme defaults folded to "". */
39
+ function explicitPort(authority) {
40
+ const port = new URL(authority.includes("://") ? authority : `http://${authority}`).port;
41
+ return port === "80" || port === "443" ? "" : port;
42
+ }
43
+ /** True when a browser says this state-changing request was started by a
44
+ * page of another site, or of this site on another port (an unrelated dev
45
+ * server on localhost). Browsers always send Sec-Fetch-Site and a page
46
+ * cannot forge it; CLIs and native clients send none and are unaffected.
47
+ * The app itself is always same-origin, whichever port or proxy serves it. */
48
+ export function crossSiteMutation(req) {
49
+ if (!["POST", "PUT", "PATCH", "DELETE"].includes((req.method ?? "GET").toUpperCase()))
50
+ return false;
51
+ const site = firstHeader(req.headers["sec-fetch-site"])?.trim().toLowerCase();
52
+ if (site === "cross-site")
53
+ return true;
54
+ if (site !== "same-site")
55
+ return false;
56
+ try {
57
+ return explicitPort(firstHeader(req.headers.origin) ?? "") !== explicitPort(firstHeader(req.headers.host) ?? "");
58
+ }
59
+ catch {
60
+ return true;
61
+ }
62
+ }
21
63
  export function readBody(req, limit = 1_000_000) {
22
64
  return new Promise((resolve, reject) => {
23
65
  let data = "";
@@ -45,6 +87,10 @@ export function readBody(req, limit = 1_000_000) {
45
87
  req.on("end", () => {
46
88
  if (done)
47
89
  return;
90
+ // A page on another origin can send text/plain or form bodies with no
91
+ // preflight; JSON needs one, so only JSON may carry a body in.
92
+ if (data && !isJsonContentType(req.headers?.["content-type"]))
93
+ return fail(415, "content-type must be application/json");
48
94
  let body;
49
95
  try {
50
96
  body = data ? JSON.parse(data) : {};