@chibitek/chibi 0.1.191 → 0.1.193
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{TerminalPanel-D8Eovq0F.js → TerminalPanel-BtDirrJJ.js} +1 -1
- package/dist/assets/{abnfDiagram-O67JEVCF-CPvuUneJ.js → abnfDiagram-O67JEVCF-C37-IeyR.js} +1 -1
- package/dist/assets/{arc-aMP_0t5b.js → arc-glzbadrM.js} +1 -1
- package/dist/assets/{architectureDiagram-NJMV4G6O-yyXrFi66.js → architectureDiagram-NJMV4G6O-Bcx1rmTd.js} +1 -1
- package/dist/assets/{blockDiagram-BEXU5L5S-BQN3ZvRc.js → blockDiagram-BEXU5L5S-B6KUNaLE.js} +1 -1
- package/dist/assets/{c4Diagram-YGBWAQC7-BieilTo4.js → c4Diagram-YGBWAQC7-DZ__tNnZ.js} +1 -1
- package/dist/assets/channel-C2UiHr1q.js +1 -0
- package/dist/assets/{chunk-2Q5K7J3B-Df4lxXIM.js → chunk-2Q5K7J3B-Dn-yLeEA.js} +1 -1
- package/dist/assets/{chunk-3FUC2YCW-su_KXf5y.js → chunk-3FUC2YCW-BB0MhLD8.js} +2 -2
- package/dist/assets/{chunk-5VM5RSS4-DL3rM5tY.js → chunk-5VM5RSS4-B0MU1Lq4.js} +1 -1
- package/dist/assets/{chunk-GTNCS2PH-53Ovfw1t.js → chunk-GTNCS2PH-BmT88VI9.js} +1 -1
- package/dist/assets/{chunk-GWA4HPMP-BkeiDfwS.js → chunk-GWA4HPMP-hgdMCsOk.js} +1 -1
- package/dist/assets/{chunk-JWPE2WC7-CvsdGjCO.js → chunk-JWPE2WC7-zlkz0m7Z.js} +1 -1
- package/dist/assets/{chunk-NETBCI7D-BngSjMee.js → chunk-NETBCI7D-Dz15-399.js} +1 -1
- package/dist/assets/{chunk-WEXAMYUT-DitKn6fq.js → chunk-WEXAMYUT-CrWvQLTH.js} +1 -1
- package/dist/assets/{chunk-XXDRQBXY-Czjvl52d.js → chunk-XXDRQBXY-BRuLbyd6.js} +1 -1
- package/dist/assets/{classDiagram-v2-NBCMYWYE-COr4Qzpk.js → classDiagram-v2-NBCMYWYE-BoexnyNG.js} +1 -1
- package/dist/assets/{cose-bilkent-JH36ORCC-Eg0tlzqp.js → cose-bilkent-JH36ORCC-CPTjVRUh.js} +1 -1
- package/dist/assets/{cynefin-OW5HDTMX-BjtG84WL.js → cynefin-OW5HDTMX-DtqtEAnC.js} +1 -1
- package/dist/assets/{cynefinDiagram-VND7K2PF-BzZtwDD4.js → cynefinDiagram-VND7K2PF-BVP8JLg8.js} +1 -1
- package/dist/assets/{dagre-6A5THRUB-TrLQ507j.js → dagre-6A5THRUB-BBDMxGXp.js} +1 -1
- package/dist/assets/{diagram-22UHCM2B-BDQDC-33.js → diagram-22UHCM2B-BRZ8cAsI.js} +1 -1
- package/dist/assets/{diagram-3UASUU5V-Cm_mzSfE.js → diagram-3UASUU5V-D3lhs7ty.js} +1 -1
- package/dist/assets/{diagram-ATOU4E4O-CAI_i4oy.js → diagram-ATOU4E4O-n8v1YvKt.js} +1 -1
- package/dist/assets/{diagram-CDSNMT55-9GjNyQXn.js → diagram-CDSNMT55-B6jeaO-z.js} +1 -1
- package/dist/assets/{diagram-MLGK6HIB-ETDg4UN-.js → diagram-MLGK6HIB-BLmKtNgD.js} +1 -1
- package/dist/assets/{diagram-MPIPVDR6-8_8dZKgW.js → diagram-MPIPVDR6-CNWlEkJQ.js} +1 -1
- package/dist/assets/{ebnfDiagram-ZINNZB2B-BiYh2ZYM.js → ebnfDiagram-ZINNZB2B-C0uBXIgJ.js} +1 -1
- package/dist/assets/{elk-276RUBZZ-5u6sMYIg.js → elk-276RUBZZ-DCjvJpgP.js} +1 -1
- package/dist/assets/{erDiagram-OPXOYQCR-Dm6semJ3.js → erDiagram-OPXOYQCR-BryVWOsq.js} +1 -1
- package/dist/assets/{flowDiagram-KWPJA3E3-DbQ12CeV.js → flowDiagram-KWPJA3E3-Cq-t83b3.js} +1 -1
- package/dist/assets/{ganttDiagram-FUAMR5RP-C12s51S6.js → ganttDiagram-FUAMR5RP-4vyfI4a8.js} +1 -1
- package/dist/assets/{gitGraphDiagram-X574FWY7-BhkwBL2T.js → gitGraphDiagram-X574FWY7-DxZIWlPq.js} +1 -1
- package/dist/assets/{index-D4BfC2Zf.js → index-C2Rnf5Lg.js} +1 -1
- package/dist/assets/{index-WT8Xwc4G.js → index-DtMmBnv1.js} +163 -163
- package/dist/assets/{infoDiagram-VRGFBTTK-IvWqyiSM.js → infoDiagram-VRGFBTTK-CdS4oDZm.js} +1 -1
- package/dist/assets/{ishikawaDiagram-OU5B5YK6-N2ZxLyoE.js → ishikawaDiagram-OU5B5YK6-7FJ6XPAt.js} +1 -1
- package/dist/assets/{journeyDiagram-ZHPQQLJL-UWy3ala_.js → journeyDiagram-ZHPQQLJL-DK5jSuP5.js} +1 -1
- package/dist/assets/{kanban-definition-PNTS6WVX-Cutk-kDA.js → kanban-definition-PNTS6WVX-LSLVTPp1.js} +1 -1
- package/dist/assets/{linear-dPnV_-aA.js → linear-C8T48PcW.js} +1 -1
- package/dist/assets/{mermaid.core-QdldWb2L.js → mermaid.core-CajU6Pki.js} +5 -5
- package/dist/assets/{mindmap-definition-NLK3R4M7-pkXW8CYn.js → mindmap-definition-NLK3R4M7-26gQ6jip.js} +1 -1
- package/dist/assets/{pegDiagram-GJSIUBJH-DhKkEQzV.js → pegDiagram-GJSIUBJH-rvhqKdDP.js} +1 -1
- package/dist/assets/{pieDiagram-5QR66LMP-DMehGrxw.js → pieDiagram-5QR66LMP-BOFsvwEp.js} +1 -1
- package/dist/assets/{quadrantDiagram-O4NWA36T-oNzYf4fg.js → quadrantDiagram-O4NWA36T-BGd_kb8s.js} +1 -1
- package/dist/assets/{railroadDiagram-XR7U4H2S-pkMOwYja.js → railroadDiagram-XR7U4H2S-DROi1ea2.js} +1 -1
- package/dist/assets/{requirementDiagram-PLB6GJNP-J29GrlJj.js → requirementDiagram-PLB6GJNP-BLFC_C4R.js} +1 -1
- package/dist/assets/{sankeyDiagram-IPEJSGJF-YuyCeGY6.js → sankeyDiagram-IPEJSGJF-bCdrWFYF.js} +1 -1
- package/dist/assets/{sequenceDiagram-PO4LG4MO-BjxLu0JW.js → sequenceDiagram-PO4LG4MO-CaCPCA52.js} +1 -1
- package/dist/assets/{sizeCapture-INFHLROL-BESOD3ec.js → sizeCapture-INFHLROL-DZr2YdGO.js} +1 -1
- package/dist/assets/{stateDiagram-v2-GCMORJYK-DF2yvbZA.js → stateDiagram-v2-GCMORJYK-BymY8iLv.js} +1 -1
- package/dist/assets/{swimlanes-2SLR337P-Bzp4ze7n.js → swimlanes-2SLR337P-NumTJ1tl.js} +1 -1
- package/dist/assets/swimlanesDiagram-TC7HE7FX-CjJ-nT3Z.js +8 -0
- package/dist/assets/{timeline-definition-EJHVYXUP-CnLbXs4R.js → timeline-definition-EJHVYXUP-d9-CUPKk.js} +1 -1
- package/dist/assets/{usecaseDiagram-POWQR4AR-nuJhbhCv.js → usecaseDiagram-POWQR4AR-CGvoockc.js} +1 -1
- package/dist/assets/{vennDiagram-UO4OBE2U-D_hzVg9h.js → vennDiagram-UO4OBE2U-CUkwrnK7.js} +1 -1
- package/dist/assets/{wardleyDiagram-VNRHLVJA-hgmpI4iu.js → wardleyDiagram-VNRHLVJA-DALQej81.js} +1 -1
- package/dist/assets/{xychartDiagram-PMCCYNJV-DwnJWdDn.js → xychartDiagram-PMCCYNJV-2oukzPo1.js} +1 -1
- package/dist/index.html +1 -1
- package/dist-server/container-mcp.js +2 -1
- package/dist-server/index.js +642 -207
- package/dist-server/mcp-server.js +36 -1
- package/dist-server/openmausbot.js +257 -66
- package/dist-server/pair-cli.js +257 -66
- package/dist-server/server/atomic-engine-accounts.js +64 -12
- package/dist-server/server/atomic-engine-classes.js +30 -0
- package/dist-server/server/atomic-engine-local.js +41 -0
- package/dist-server/server/chibi-defaults.js +14 -8
- package/dist-server/server/config.js +1 -1
- package/dist-server/server/default-model-selection.js +7 -0
- package/dist-server/server/drivers/acp/custom.js +7 -2
- package/dist-server/server/editor-connect.js +39 -2
- package/dist-server/server/engine-tiers.js +19 -19
- package/dist-server/server/harness-import/engine-policy.js +4 -3
- package/dist-server/server/index.js +13 -13
- package/dist-server/server/model-gateway/failover.js +44 -0
- package/dist-server/server/model-gateway/ladder.js +29 -0
- package/dist-server/server/model-gateway/route.js +104 -0
- package/dist-server/server/nexus-memory/backoff.js +41 -0
- package/dist-server/server/nexus-memory/client.js +55 -11
- package/dist-server/server/nexus-memory/index.js +4 -23
- package/dist-server/server/plan-credit.js +67 -0
- package/dist-server/server/provider-accounts.js +3 -0
- package/dist-server/server/request-auth.js +3 -0
- package/dist-server/server/routes/provider-accounts.js +46 -5
- package/dist-server/server/vault/store.js +8 -4
- package/dist-server/shared/atomic-auto.js +10 -0
- package/dist-server/shared/engine-tiers.js +24 -8
- package/dist-server/shared/harness-weights.js +3 -1
- package/dist-server/shared/provider-accounts.js +42 -5
- package/dist-server/shared/vault-api-providers.js +23 -2
- package/dist-server/shared/vault.js +3 -2
- package/dist-server/vps-container-mcp.js +2 -1
- package/package.json +1 -1
- package/dist/assets/channel-Bw54wjTR.js +0 -1
- package/dist/assets/swimlanesDiagram-TC7HE7FX-B6y4ZZ5q.js +0 -8
- package/dist-server/server/session-fallback.js +0 -76
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Local model servers on Atomic Engine's automatic chain (Erick, 2026-11-15):
|
|
2
|
+
// when Ollama, LM Studio, oMLX, EXO or Unsloth is running on this computer,
|
|
3
|
+
// Atomic Engine may use it after every subscription and before Atomic's
|
|
4
|
+
// pay-per-use notice. Atomic already probes those hosts for the engine's
|
|
5
|
+
// model list (customAcpModels, server/drivers/local-inject.ts); the last
|
|
6
|
+
// probe is kept here, and each host that answered becomes one `local`
|
|
7
|
+
// account at the end of the engine's manifest (server/atomic-engine-accounts.ts).
|
|
8
|
+
//
|
|
9
|
+
// One model per host: one it has loaded, else the first it lists. An Ollama
|
|
10
|
+
// `:cloud` model is the Ollama Cloud plan, not a local model, and is left to
|
|
11
|
+
// that subscription.
|
|
12
|
+
import { isOllamaCloudModel } from "../shared/local-models.js";
|
|
13
|
+
import { decodeInjectId, localHost } from "./drivers/local-inject.js";
|
|
14
|
+
let remembered = [];
|
|
15
|
+
/** The local servers' best model each, from catalog rows (`host::model`). */
|
|
16
|
+
export function localPicks(options) {
|
|
17
|
+
const byHost = new Map();
|
|
18
|
+
const seenUrls = new Set();
|
|
19
|
+
for (const option of options) {
|
|
20
|
+
const inject = decodeInjectId(option.id);
|
|
21
|
+
const host = inject ? localHost(inject.host) : undefined;
|
|
22
|
+
if (!inject || !host || isOllamaCloudModel(inject.model))
|
|
23
|
+
continue;
|
|
24
|
+
const current = byHost.get(host.id);
|
|
25
|
+
if (current && (current.loaded || !option.loaded))
|
|
26
|
+
continue;
|
|
27
|
+
// Two ids for one server (ollama / local_ollama) are one host.
|
|
28
|
+
if (!current && seenUrls.has(host.baseUrl))
|
|
29
|
+
continue;
|
|
30
|
+
seenUrls.add(host.baseUrl);
|
|
31
|
+
byHost.set(host.id, { host, model: inject.model, loaded: option.loaded === true });
|
|
32
|
+
}
|
|
33
|
+
return [...byHost.values()].map(({ host, model }) => ({ host, model }));
|
|
34
|
+
}
|
|
35
|
+
/** Keep the latest probe's picks; called each time the engine's models are listed. */
|
|
36
|
+
export function rememberLocalModels(options) {
|
|
37
|
+
remembered = localPicks(options);
|
|
38
|
+
}
|
|
39
|
+
export function rememberedLocalModels() {
|
|
40
|
+
return remembered;
|
|
41
|
+
}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
// One default for Chibi on every install
|
|
2
|
-
//
|
|
1
|
+
// One default for Chibi on every install: Automatic, on Atomic Engine (Auto)
|
|
2
|
+
// (ATOMIC_AUTO_RUNG, Erick 2026-11-15), else the Plata class on Claude
|
|
3
|
+
// Opus 5 (CHIBI_DEFAULT_RUNG, Erick 2026-11-13). Installs
|
|
3
4
|
// had drifted apart, so an update puts every Chibi back on it once per
|
|
4
5
|
// CHIBI_DEFAULTS_VERSION, whatever it was set to. What a person changes
|
|
5
6
|
// afterwards holds until the version is raised.
|
|
6
7
|
import { existsSync, readFileSync } from "node:fs";
|
|
7
8
|
import { join } from "node:path";
|
|
8
|
-
import { CHIBI_DEFAULTS_VERSION, CHIBI_DEFAULT_RUNG } from "../shared/engine-tiers.js";
|
|
9
|
+
import { ATOMIC_AUTO_RUNG, CHIBI_DEFAULTS_VERSION, CHIBI_DEFAULT_RUNG } from "../shared/engine-tiers.js";
|
|
9
10
|
import { writeFileAtomic } from "./atomic.js";
|
|
10
11
|
/** Where the version last applied on this install is kept. */
|
|
11
12
|
export const CHIBI_DEFAULTS_FILE = "chibi-defaults.json";
|
|
@@ -13,15 +14,20 @@ export const CHIBI_DEFAULTS_FILE = "chibi-defaults.json";
|
|
|
13
14
|
* class first, then the class below (the nearest score), then above, then
|
|
14
15
|
* the lowest, where graded local models sit. */
|
|
15
16
|
const NEAREST_CLASSES = ["Plata", "Reposado", "Mezcal", "Añejo"];
|
|
16
|
-
/** The model Chibi is put on.
|
|
17
|
-
* allowed
|
|
17
|
+
/** The model Chibi is put on. Atomic Engine (Auto) when that engine is
|
|
18
|
+
* ready, allowed and lists it; else CHIBI_DEFAULT_RUNG on a ready, allowed
|
|
19
|
+
* account that lists it. An install without one (Gemini through
|
|
18
20
|
* Google Workspace only, ChatGPT only, one API key, a local model) gets the
|
|
19
21
|
* model it does have that grades nearest: `models` in ladder order, class
|
|
20
22
|
* by class. Undefined only when nothing graded is ready; the caller then
|
|
21
23
|
* keeps or picks any working engine, so a bot is never without a model. */
|
|
22
24
|
export function chibiDefaultSelection(engines, refused, models = []) {
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
+
const usable = engines.filter((engine) => engine.snapshot.state === "available" && engine.snapshot.authenticated !== false && refused(engine) === undefined);
|
|
26
|
+
const atomic = usable.find((engine) => engine.instanceId === ATOMIC_AUTO_RUNG.engine && engine.models.options.some((option) => option.id === ATOMIC_AUTO_RUNG.model));
|
|
27
|
+
if (atomic)
|
|
28
|
+
return { instanceId: atomic.instanceId, model: ATOMIC_AUTO_RUNG.model };
|
|
29
|
+
// Atomic Engine's other models are not Chibi's fallback: they are the engine's own chain.
|
|
30
|
+
const ready = usable.filter((engine) => engine.instanceId !== ATOMIC_AUTO_RUNG.engine);
|
|
25
31
|
const on = (driverKind, model) => {
|
|
26
32
|
for (const engine of ready) {
|
|
27
33
|
if (engine.driverKind !== driverKind)
|
|
@@ -91,6 +97,6 @@ export async function applyChibiDefaults(deps) {
|
|
|
91
97
|
for (const task of chibi.tasks ?? [])
|
|
92
98
|
deps.store.setThreadEngineClass(chibi.id, task.threadId, "tier");
|
|
93
99
|
writeFileAtomic(join(deps.dataDir, CHIBI_DEFAULTS_FILE), `${JSON.stringify({ version: CHIBI_DEFAULTS_VERSION, appliedAt: new Date().toISOString() })}\n`);
|
|
94
|
-
console.log(`[chibi] put on its default: Automatic, ${CHIBI_DEFAULT_RUNG.modelClass}, ${selection ? `${selection.instanceId}/${selection.model}` : "the model it had (no graded model is ready here)"}`);
|
|
100
|
+
console.log(`[chibi] put on its default: Automatic, ${selection?.model === ATOMIC_AUTO_RUNG.model ? "Atomic Engine (Auto)" : CHIBI_DEFAULT_RUNG.modelClass}, ${selection ? `${selection.instanceId}/${selection.model}` : "the model it had (no graded model is ready here)"}`);
|
|
95
101
|
return true;
|
|
96
102
|
}
|
|
@@ -325,7 +325,7 @@ const instanceConfigSchema = z.object({
|
|
|
325
325
|
environment: z.record(z.string(), z.string()).optional(),
|
|
326
326
|
enabled: z.boolean().optional(),
|
|
327
327
|
config: z.json().optional(),
|
|
328
|
-
account: z.string().trim().min(1).max(64).optional(),
|
|
328
|
+
account: z.string().trim().min(1).max(64).optional(), planCreditUsd: z.number().positive().max(1_000_000).optional(),
|
|
329
329
|
});
|
|
330
330
|
const instanceConfigMapSchema = z.record(z.string(), instanceConfigSchema);
|
|
331
331
|
const defaultModelSelectionSchema = z.object({
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
const claudeFirst = (instances) => instances.find((instance) => instance.driverKind === "claudeAgent") ?? instances[0];
|
|
2
|
+
/** New bots are made on Atomic Engine (Auto) when that engine is installed,
|
|
3
|
+
* signed in, allowed and lists it (Erick, 2026-11-15). */
|
|
4
|
+
const ATOMIC_AUTO = { instanceId: "atomic-engine", model: "atomic/auto" };
|
|
5
|
+
const atomicAuto = (instances) => instances.find((instance) => instance.instanceId === ATOMIC_AUTO.instanceId &&
|
|
6
|
+
instance.snapshot.authenticated !== false && instance.models.options.some((model) => model.id === ATOMIC_AUTO.model));
|
|
2
7
|
/** A saved choice is intentional: an unavailable provider or removed model
|
|
3
8
|
* sends new bots to setup instead of silently changing their provider. */
|
|
4
9
|
export function selectDefaultModelSelection(instances, preferred, context = {}) {
|
|
@@ -23,6 +28,8 @@ export function selectDefaultModelSelection(instances, preferred, context = {})
|
|
|
23
28
|
// The organisation's policy is inert (no refusal) unless this desktop is enrolled.
|
|
24
29
|
const available = instances.filter((instance) => instance.snapshot.state === "available" && instance.capabilities?.chatOnly !== true &&
|
|
25
30
|
context.refusal?.(instance) === undefined);
|
|
31
|
+
if (atomicAuto(available))
|
|
32
|
+
return { ...ATOMIC_AUTO };
|
|
26
33
|
const company = context.company;
|
|
27
34
|
let pick;
|
|
28
35
|
if (company && instances.some((instance) => company(instance.instanceId))) {
|
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
import { homedir } from "node:os";
|
|
18
18
|
import { basename, join } from "node:path";
|
|
19
19
|
import { currentAtomicEngineAccounts, writeAtomicEngineAccountsFile } from "../../atomic-engine-accounts.js";
|
|
20
|
+
import { rememberLocalModels } from "../../atomic-engine-local.js";
|
|
21
|
+
import { ATOMIC_AUTO_MODEL } from "../../../shared/atomic-auto.js";
|
|
20
22
|
import { atomicEngineAsset } from "../../atomic-engine-release.js";
|
|
21
23
|
import { ATOMIC_ENGINE_MODULE_ARGS, installAtomicEngine, managedAtomicEngine } from "../../atomic-engine-runtime.js";
|
|
22
24
|
import { findCliCandidates } from "../../env-path.js";
|
|
@@ -98,8 +100,11 @@ export function lockAtomicEngineMemory(env, instanceId, cli) {
|
|
|
98
100
|
export async function customAcpModels(env, config, instanceId, fetchImpl = fetch) {
|
|
99
101
|
if (!isAtomicEngine(instanceId, config?.cli))
|
|
100
102
|
return PASSTHROUGH;
|
|
101
|
-
|
|
102
|
-
|
|
103
|
+
// One choice with Automatic (shared/atomic-auto.ts): picking it puts the bot on its tier's ladder.
|
|
104
|
+
const own = { default: ATOMIC_AUTO_MODEL, options: [{ id: ATOMIC_AUTO_MODEL, label: "Atomic Engine (Auto)", custom: true }] };
|
|
105
|
+
const catalog = await mergeLocalInject(own, env, fetchImpl);
|
|
106
|
+
rememberLocalModels(catalog.options); // the engine's local fallbacks (server/atomic-engine-local.ts)
|
|
107
|
+
return catalog;
|
|
103
108
|
}
|
|
104
109
|
/** A turn's model on a custom engine: a `host::model` id (only Atomic
|
|
105
110
|
* Engine lists them) registers the host in Atomic Engine's config.yaml. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Adds (and removes) Atomic as an MCP server in the code editors people use
|
|
2
|
-
// beside it: VS Code, Cursor, Windsurf, Antigravity and
|
|
2
|
+
// beside it: VS Code, Cursor, Windsurf, Antigravity, OpenCode and Codex. Each gets
|
|
3
3
|
// its own connected-assistant token, named after the editor, so it can be
|
|
4
4
|
// revoked on its own; the config names the token FILE, never the token.
|
|
5
5
|
//
|
|
@@ -27,6 +27,8 @@ export function editorTargets(home = homedir(), platform = process.platform, env
|
|
|
27
27
|
// Xcode 26.3+ shares one MCP server list with all of its coding agents (Claude, Codex, Gemini). macOS only.
|
|
28
28
|
...(platform === "darwin" ? [{ id: "xcode", label: "Xcode", configPath: join(home, "Library", "Developer", "Xcode", "CodingAssistant", "mcp-servers.json"), format: "mcp-servers", installedAt: [...apps("Xcode"), join(home, "Library", "Developer", "Xcode", "CodingAssistant")] }] : []),
|
|
29
29
|
{ id: "opencode", label: "OpenCode", configPath: join(xdgConfig, "opencode", "opencode.json"), format: "opencode", installedAt: [join(home, ".opencode"), join(xdgConfig, "opencode")] },
|
|
30
|
+
// Codex (CLI and app) reads [mcp_servers.*] from its TOML config; with it, Codex can hand work to Atomic Engine (atomic_engine).
|
|
31
|
+
{ id: "codex", label: "Codex", configPath: join(env.CODEX_HOME || join(home, ".codex"), "config.toml"), format: "codex-toml", installedAt: [...apps("Codex"), env.CODEX_HOME || join(home, ".codex")] },
|
|
30
32
|
];
|
|
31
33
|
}
|
|
32
34
|
export function editorTarget(id, targets = editorTargets()) {
|
|
@@ -53,6 +55,30 @@ function readConfig(path) {
|
|
|
53
55
|
throw new Error(`${path} is not a JSON object`);
|
|
54
56
|
return parsed;
|
|
55
57
|
}
|
|
58
|
+
// Codex's config is TOML. Only Atomic's own tables are written or removed
|
|
59
|
+
// ([mcp_servers.atomic] and its sub-tables); every other line stays as it
|
|
60
|
+
// was. JSON string escapes are valid TOML basic strings.
|
|
61
|
+
const CODEX_TABLE = new RegExp(`^\\s*\\[mcp_servers\\.${CLAUDE_CODE_SERVER_NAME}(\\.[^\\]]+)?\\]\\s*$`);
|
|
62
|
+
export function withoutCodexEntry(toml) {
|
|
63
|
+
const out = [];
|
|
64
|
+
let skipping = false;
|
|
65
|
+
for (const line of toml.split("\n")) {
|
|
66
|
+
if (/^\s*\[/.test(line))
|
|
67
|
+
skipping = CODEX_TABLE.test(line);
|
|
68
|
+
if (!skipping)
|
|
69
|
+
out.push(line);
|
|
70
|
+
}
|
|
71
|
+
return out.join("\n").replace(/\s+$/, "");
|
|
72
|
+
}
|
|
73
|
+
export function withCodexEntry(toml, entry) {
|
|
74
|
+
const table = [`[mcp_servers.${CLAUDE_CODE_SERVER_NAME}]`, `command = ${JSON.stringify(entry.command)}`, `args = ${JSON.stringify(entry.args)}`];
|
|
75
|
+
const env = Object.entries(entry.env ?? {});
|
|
76
|
+
if (env.length)
|
|
77
|
+
table.push("", `[mcp_servers.${CLAUDE_CODE_SERVER_NAME}.env]`, ...env.map(([key, value]) => `${JSON.stringify(key)} = ${JSON.stringify(value)}`));
|
|
78
|
+
const rest = withoutCodexEntry(toml);
|
|
79
|
+
return `${rest ? `${rest}\n\n` : ""}${table.join("\n")}\n`;
|
|
80
|
+
}
|
|
81
|
+
const codexHasEntry = (toml) => toml.split("\n").some((line) => CODEX_TABLE.test(line) && !line.includes(`${CLAUDE_CODE_SERVER_NAME}.`));
|
|
56
82
|
function writeConfig(path, config, now) {
|
|
57
83
|
let mode = 0o600;
|
|
58
84
|
if (existsSync(path)) {
|
|
@@ -62,9 +88,12 @@ function writeConfig(path, config, now) {
|
|
|
62
88
|
else {
|
|
63
89
|
mkdirSync(dirname(path), { recursive: true });
|
|
64
90
|
}
|
|
65
|
-
writeFileAtomic(path, `${JSON.stringify(config, null, 2)}\n`, { mode });
|
|
91
|
+
writeFileAtomic(path, typeof config === "string" ? config : `${JSON.stringify(config, null, 2)}\n`, { mode });
|
|
66
92
|
}
|
|
93
|
+
const readText = (path) => (existsSync(path) ? readFileSync(path, "utf8") : "");
|
|
67
94
|
export function registerWithEditor(target, entry, now = new Date()) {
|
|
95
|
+
if (target.format === "codex-toml")
|
|
96
|
+
return writeConfig(target.configPath, withCodexEntry(readText(target.configPath), entry), now);
|
|
68
97
|
const config = readConfig(target.configPath);
|
|
69
98
|
const key = serversKey(target.format);
|
|
70
99
|
const servers = (config[key] && typeof config[key] === "object" && !Array.isArray(config[key]) ? config[key] : {});
|
|
@@ -73,6 +102,12 @@ export function registerWithEditor(target, entry, now = new Date()) {
|
|
|
73
102
|
export function unregisterFromEditor(target, now = new Date()) {
|
|
74
103
|
if (!existsSync(target.configPath))
|
|
75
104
|
return;
|
|
105
|
+
if (target.format === "codex-toml") {
|
|
106
|
+
const toml = readText(target.configPath);
|
|
107
|
+
if (codexHasEntry(toml))
|
|
108
|
+
writeConfig(target.configPath, `${withoutCodexEntry(toml)}\n`, now);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
76
111
|
const config = readConfig(target.configPath);
|
|
77
112
|
const key = serversKey(target.format);
|
|
78
113
|
const servers = config[key];
|
|
@@ -83,6 +118,8 @@ export function unregisterFromEditor(target, now = new Date()) {
|
|
|
83
118
|
}
|
|
84
119
|
export function editorHasEntry(target) {
|
|
85
120
|
try {
|
|
121
|
+
if (target.format === "codex-toml")
|
|
122
|
+
return codexHasEntry(readText(target.configPath));
|
|
86
123
|
const servers = readConfig(target.configPath)[serversKey(target.format)];
|
|
87
124
|
return Boolean(servers && typeof servers === "object" && CLAUDE_CODE_SERVER_NAME in servers);
|
|
88
125
|
}
|
|
@@ -3,21 +3,21 @@
|
|
|
3
3
|
// engine of its ladder that is ready. Everything here is pure except the
|
|
4
4
|
// snapshot cache, so the server wires it to the live registry and the tests
|
|
5
5
|
// drive it with plain candidates.
|
|
6
|
-
import { BOT_TIERS, CHIBI_DEFAULT_RUNG, DEFAULT_LADDERS, DEFAULT_TIER_CLASSES, MODEL_CLASSES, classBelow, isBotTier, rungAccounts, toModelClass } from "../shared/engine-tiers.js";
|
|
6
|
+
import { ATOMIC_AUTO_RUNG, BOT_TIERS, CHIBI_DEFAULT_RUNG, DEFAULT_LADDERS, DEFAULT_TIER_CLASSES, MODEL_CLASSES, classBelow, isBotTier, rungAccounts, toModelClass } from "../shared/engine-tiers.js";
|
|
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
|
-
/** Engines a tier tries first
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
10
|
+
/** Engines a tier tries first after Atomic Engine (Auto), whatever the
|
|
11
|
+
* class catalog order says. Without Atomic Engine, Chibi runs on Claude:
|
|
12
|
+
* Claude's best model graded in its class, then Claude's next (or Claude's
|
|
13
|
+
* own default should the catalog grade only one there); other providers
|
|
14
|
+
* follow only for when no Claude account is free (Erick, 2026-10-13, now
|
|
15
|
+
* the fallback under Atomic Engine (Auto), 2026-11-15). */
|
|
16
16
|
const TIER_PREFERRED_DRIVERS = {
|
|
17
17
|
orchestrator: ["claudeAgent"],
|
|
18
18
|
};
|
|
19
|
-
/** How many of a tier's preferred rungs keep the top of its generated ladder. */
|
|
20
|
-
const PREFERRED_RUNGS =
|
|
19
|
+
/** How many of a tier's preferred rungs keep the top of its generated ladder: Atomic Engine (Auto) and two more. */
|
|
20
|
+
const PREFERRED_RUNGS = 3;
|
|
21
21
|
/** Every engine that runs a model of the class, the models in the order
|
|
22
22
|
* given (cheapest per task, then per token, then fastest), each model's
|
|
23
23
|
* engines in catalog order. */
|
|
@@ -43,7 +43,7 @@ export function classLadder(models, modelClass) {
|
|
|
43
43
|
}
|
|
44
44
|
/** The ladders a refresh generates: each tier asks for its class, and its
|
|
45
45
|
* ladder is every model in that class in harness-aware order (orderRungs)
|
|
46
|
-
* after the tier's first PREFERRED_RUNGS preferred rungs. Subscriptions still
|
|
46
|
+
* after the tier's first PREFERRED_RUNGS preferred rungs (Atomic Engine (Auto) first). Subscriptions still
|
|
47
47
|
* come before API keys when it is walked (resolveLadder). Falls back to the
|
|
48
48
|
* hand-written ladder for a tier whose class has no model. */
|
|
49
49
|
export function generateLadders(models, classes) {
|
|
@@ -51,7 +51,7 @@ export function generateLadders(models, classes) {
|
|
|
51
51
|
const seen = new Set();
|
|
52
52
|
const rungs = classRungs(models, classes[tier]);
|
|
53
53
|
const drivers = TIER_PREFERRED_DRIVERS[tier] ?? [];
|
|
54
|
-
const preferred = [...(tier === "orchestrator" && classes[tier] === CHIBI_DEFAULT_RUNG.modelClass ? [{ ...CHIBI_DEFAULT_RUNG }] : []), ...rungs.filter((entry) => drivers.includes(entry.engine)), ...drivers.map((engine) => ({ engine }))];
|
|
54
|
+
const preferred = [{ ...ATOMIC_AUTO_RUNG }, ...(tier === "orchestrator" && classes[tier] === CHIBI_DEFAULT_RUNG.modelClass ? [{ ...CHIBI_DEFAULT_RUNG }] : []), ...rungs.filter((entry) => drivers.includes(entry.engine)), ...drivers.map((engine) => ({ engine }))];
|
|
55
55
|
const pinned = Math.min(PREFERRED_RUNGS, preferred.length);
|
|
56
56
|
const ordered = [...preferred, ...rungs].filter((entry) => {
|
|
57
57
|
const key = entryKey(entry);
|
|
@@ -287,7 +287,7 @@ export function resolveLadder(ladder, stored, context) {
|
|
|
287
287
|
subscription.sort((a, b) => atomicFirst(a.candidate) - atomicFirst(b.candidate) || a.step - b.step);
|
|
288
288
|
key.sort((a, b) => a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
|
|
289
289
|
free.sort((a, b) => a.step - b.step || storedFirst(a.candidate, b.candidate) || a.index - b.index);
|
|
290
|
-
for (const { step, entry, candidate, band } of [...subscription, ...
|
|
290
|
+
for (const { step, entry, candidate, band } of [...subscription, ...free, ...key]) { // free before pay-per-use (Erick, 2026-11-15)
|
|
291
291
|
// "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.
|
|
292
292
|
const reason = band === "free" && !context.includeFree ? "free-off"
|
|
293
293
|
: band === "free" && context.clientData ? "client-data"
|
|
@@ -338,8 +338,8 @@ export function failoverClassOrder(modelClass) {
|
|
|
338
338
|
* 1. subscriptions in the required class (its ladder, then any other
|
|
339
339
|
* subscription engine whose model is graded in it);
|
|
340
340
|
* 2. subscriptions in each class below it, closest first, then above it;
|
|
341
|
-
* 3. pay-per-use keys in the
|
|
342
|
-
* the same order.
|
|
341
|
+
* 3. free models when allowed, then 4. pay-per-use keys: each in the
|
|
342
|
+
* required class, then the other classes in the same order.
|
|
343
343
|
*
|
|
344
344
|
* A rung's class is the one written on it, else the model's graded class,
|
|
345
345
|
* else, for an engine the required class's ladder names, the class the turn
|
|
@@ -381,16 +381,16 @@ export function resolveFailover(request) {
|
|
|
381
381
|
const ladders = new Map(classes.map((modelClass) => [modelClass, ladderOf(modelClass)]));
|
|
382
382
|
const all = [];
|
|
383
383
|
let lastPassSkipped;
|
|
384
|
-
for (const stage of ["subscription", "
|
|
384
|
+
for (const stage of ["subscription", "free", "key"]) {
|
|
385
385
|
for (const modelClass of classes) {
|
|
386
386
|
const { ladder, vouched } = ladders.get(modelClass);
|
|
387
387
|
const effective = (candidate, model, entry, step) => entry?.modelClass ?? request.classOf(candidate, model) ?? (step < vouched ? modelClass : "Añejo");
|
|
388
388
|
const accept = (candidate, model, entry, named) => {
|
|
389
389
|
if (request.tried.has(candidate.instanceId))
|
|
390
390
|
return "tried";
|
|
391
|
-
// Free
|
|
392
|
-
// in every class,
|
|
393
|
-
if (
|
|
391
|
+
// Free models have their own pass, after subscriptions and before
|
|
392
|
+
// pay-per-use keys in every class (Erick, 2026-11-15).
|
|
393
|
+
if (freeCandidate(candidate) !== (stage === "free"))
|
|
394
394
|
return "key-later";
|
|
395
395
|
if (stage === "subscription" && (keyBased(candidate) || perTokenModel(candidate, model)))
|
|
396
396
|
return "key-later";
|
|
@@ -402,7 +402,7 @@ export function resolveFailover(request) {
|
|
|
402
402
|
};
|
|
403
403
|
const resolution = resolveLadder(ladder, request.failed, { ...request.context, accept });
|
|
404
404
|
all.push(...resolution.skipped);
|
|
405
|
-
if (stage === "
|
|
405
|
+
if (stage === "key" && modelClass === request.modelClass)
|
|
406
406
|
lastPassSkipped = resolution.skipped;
|
|
407
407
|
if (resolution.choice) {
|
|
408
408
|
const { choice } = resolution;
|
|
@@ -73,13 +73,14 @@ export const freeCandidate = (candidate) => candidate.billing === "free";
|
|
|
73
73
|
// they are configured for, as `<provider>:<model>` ("deepinfra:XiaomiMiMo/
|
|
74
74
|
// MiMo-V2.6-Pro", "nous:xiaomi/mimo-v2.6-pro"). The engine is not paid one
|
|
75
75
|
// way: each model is paid as its provider is.
|
|
76
|
-
/** Providers on such engines that are flat plans: Nous Portal
|
|
76
|
+
/** Providers on such engines that are flat plans: Nous Portal (its login and
|
|
77
|
+
* its API key, `nous-api`: Erick, 2026-11-15), the Kimi,
|
|
77
78
|
* Z.ai GLM and OpenCode Go coding plans, and the subscription sign-ins (ChatGPT, GitHub
|
|
78
79
|
* Copilot, Qwen). */
|
|
79
|
-
const FLAT_PLAN_PROVIDERS = new Set(["nous", "kimi-coding", "opencode-go", "openai-codex", "copilot", "qwen-oauth", "zai-coding-plan"]);
|
|
80
|
+
const FLAT_PLAN_PROVIDERS = new Set(["nous", "nous-api", "kimi-coding", "opencode-go", "openai-codex", "copilot", "qwen-oauth", "zai-coding-plan"]);
|
|
80
81
|
/** Providers that run on this machine: free, and never a stand-in for a
|
|
81
82
|
* frontier model (resolveFailover). */
|
|
82
|
-
const LOCAL_PROVIDERS = new Set(["custom", "lmstudio", "ollama", "vllm", "llamacpp"]);
|
|
83
|
+
const LOCAL_PROVIDERS = new Set(["custom", "lmstudio", "ollama", "vllm", "llamacpp", "omlx", "exo", "unsloth"]);
|
|
83
84
|
export const multiProviderEngine = (candidate) => candidate.driverKind === "hermesAgent" || candidate.instanceId === ATOMIC_ENGINE_INSTANCE;
|
|
84
85
|
/** The provider a model runs on, on an engine that runs many; undefined
|
|
85
86
|
* elsewhere, and for an id with no provider (Hermes' own config default).
|
|
@@ -85,6 +85,7 @@ import { augmentedPath, findCliCandidates, resetPathCache, splitCliString } from
|
|
|
85
85
|
import { registerEnginesBinDir } from "./engine-install.js";
|
|
86
86
|
import { setupLog } from "./setup-log.js";
|
|
87
87
|
import { bundledNpmCli, ensureNodeShim, nodeRuntimeStatus } from "./node-runtime.js";
|
|
88
|
+
import { accountBilling } from "./plan-credit.js";
|
|
88
89
|
import { appendUsage, isUsageOwnerFilter, parseUsageRange, readUsage, summarizeUsage, usageCsv, usageForOwner, USAGE_GROUPINGS, flushUsageLedger } from "./usage-ledger.js";
|
|
89
90
|
import { GroupUsageReader } from "./group-thread-usage.js";
|
|
90
91
|
import { ledgerCost } from "./model-prices.js";
|
|
@@ -292,9 +293,10 @@ import { compareWithinClass } from "./model-levels/classes.js";
|
|
|
292
293
|
import { HISTORY_RECEIPT_KIND, historyAttachmentStore } from "./harness-import/history.js";
|
|
293
294
|
import { chooseEngine, engineIntent, freeCandidate, harnessForName, localModel, newBotSelection, paidCandidate, perTokenModel } from "./harness-import/engine-policy.js";
|
|
294
295
|
import { createEngineTierRoutes } from "./routes/engine-tiers.js";
|
|
296
|
+
import { createModelGatewayRoutes } from "./model-gateway/route.js";
|
|
295
297
|
import { applyChibiDefaults, chibiDefaultSelection } from "./chibi-defaults.js";
|
|
296
298
|
import { createPrimaryBotRoutes } from "./routes/primary-bot.js";
|
|
297
|
-
import { EngineSnapshotCache, botTier, canDriveComputer, classLadder, engineAccount, engineHealth, engineLabel, engineTierClasses, engineTierLadders, engineTiersIncludeFree, generateLadders, handlesClientData, ladderForClass, keyBased, needsDelegation, resolveFailover, resolveLadder } from "./engine-tiers.js";
|
|
299
|
+
import { EngineSnapshotCache, botTier, canDriveComputer, classLadder, engineAccount, engineHealth, engineLabel, engineTierClasses, engineTierLadders, failoverClassOrder, engineTiersIncludeFree, generateLadders, handlesClientData, ladderForClass, keyBased, needsDelegation, resolveFailover, resolveLadder } from "./engine-tiers.js";
|
|
298
300
|
import { PRIMARY_BOT_THREAD_TITLE, PRIMARY_BOT_TRIGGER, PrimaryBotStore, routesAsSweep, PrimaryBotSweeper } from "./primary-bot.js";
|
|
299
301
|
import { PRIMARY_BOT_LOCKED, primaryBotChoiceField } from "../shared/primary-bot.js";
|
|
300
302
|
import { moveIntoChibi } from "./move-into-chibi.js";
|
|
@@ -2297,9 +2299,9 @@ async function defaultSelection() {
|
|
|
2297
2299
|
refusal: (instance) => policyModelRefusal(instance),
|
|
2298
2300
|
});
|
|
2299
2301
|
}
|
|
2300
|
-
/** Chibi is made on
|
|
2301
|
-
* on
|
|
2302
|
-
*
|
|
2302
|
+
/** Chibi is made on Atomic Engine (Auto), else its Claude default, when
|
|
2303
|
+
* here (chibiDefaultSelection); otherwise on Atomic Engine's own default when
|
|
2304
|
+
* its CLI is installed and allowed; otherwise on the workspace default. */
|
|
2303
2305
|
async function builtinChibiSelection() {
|
|
2304
2306
|
if (hostedModels)
|
|
2305
2307
|
return defaultSelection();
|
|
@@ -2331,8 +2333,8 @@ const tierCandidates = (described) => {
|
|
|
2331
2333
|
return described.filter((instance) => policyModelRefusal(instance) === undefined).map((instance) => {
|
|
2332
2334
|
// An engine added as a provider account is paid as that account is: a
|
|
2333
2335
|
// flat plan used through a key (the Qwen Coding Plan) is a subscription.
|
|
2334
|
-
|
|
2335
|
-
const billing =
|
|
2336
|
+
// Ollama Team's included credit decides while it lasts (server/plan-credit.ts).
|
|
2337
|
+
const billing = accountBilling(instance.instanceId, configs[instance.instanceId], DATA_DIR);
|
|
2336
2338
|
return billing ? { ...instance, billing } : instance;
|
|
2337
2339
|
});
|
|
2338
2340
|
};
|
|
@@ -2616,8 +2618,7 @@ function subscriptionCandidate(instanceId) {
|
|
|
2616
2618
|
const described = engineSnapshots.current()?.find((candidate) => candidate.instanceId === instanceId);
|
|
2617
2619
|
if (described)
|
|
2618
2620
|
return described;
|
|
2619
|
-
const
|
|
2620
|
-
const billing = account === undefined ? undefined : accountProvider(account)?.billing;
|
|
2621
|
+
const billing = accountBilling(instanceId, providerConfigs()[instanceId], DATA_DIR);
|
|
2621
2622
|
return {
|
|
2622
2623
|
instanceId, driverKind: registry.get(instanceId)?.driverKind ?? "", displayName: instanceId,
|
|
2623
2624
|
snapshot: { state: "available" }, models: { default: "", options: [] }, ...(billing ? { billing } : {}),
|
|
@@ -3387,7 +3388,7 @@ const engineRests = new EngineRestStore(DATA_DIR, undefined, { probeBaseMs: prob
|
|
|
3387
3388
|
// engine's own trouble, not the account's.
|
|
3388
3389
|
bindAtomicEngineAccountSource(() => ({
|
|
3389
3390
|
instances: providerConfigs(),
|
|
3390
|
-
engineInstanceId: "atomic-engine",
|
|
3391
|
+
engineInstanceId: "atomic-engine", classModels: classedModels(), classOrder: failoverClassOrder(engineTierClasses(cfg.engineTiers).orchestrator), // class Auto (server/atomic-engine-classes.ts)
|
|
3391
3392
|
owner: instanceOwner,
|
|
3392
3393
|
restingUntil: (instanceId) => engineRests.active()
|
|
3393
3394
|
.filter((entry) => entry.instanceId === instanceId && !entry.scope && entry.reason !== "stalled")
|
|
@@ -3518,7 +3519,7 @@ function classSelection(profile, projected, candidates, modelClass) {
|
|
|
3518
3519
|
function botClassChoices(profile, threadId) {
|
|
3519
3520
|
const tier = botTier(profile);
|
|
3520
3521
|
const task = store.taskByThread(profile.id, threadId);
|
|
3521
|
-
const base = { tier, tierClass: engineTierClasses(cfg.engineTiers)[tier], bot: botEngineMode(profile),
|
|
3522
|
+
const base = { tier, tierClass: engineTierClasses(cfg.engineTiers)[tier], bot: botEngineMode(profile), includeFree: engineTiersIncludeFree(cfg.engineTiers),
|
|
3522
3523
|
...(task ? { thread: threadEngineMode(profile, task) } : {}) };
|
|
3523
3524
|
const projected = store.projectBotForTask(profile.id, threadId);
|
|
3524
3525
|
if (hostedModels || !projected)
|
|
@@ -16181,7 +16182,7 @@ const deliverableAccess = (senderId, auth) => sharedDeliverableAccess(sharedDeli
|
|
|
16181
16182
|
canSeeGroup: auth ? (id) => visibleTo(viewerFor(auth)).group(id) : () => true,
|
|
16182
16183
|
});
|
|
16183
16184
|
ROUTES.push(createSharedDeliverablesRoutes(sharedDeliverables, () => deliverableAccess(undefined).sharedBlockedRoots ?? []));
|
|
16184
|
-
ROUTES.push(createMessageFileRoutes({ store, attachments: ATTACHMENTS_DIR, workspaceDir, access: deliverableAccess }));
|
|
16185
|
+
ROUTES.push(createMessageFileRoutes({ store, attachments: ATTACHMENTS_DIR, workspaceDir, access: deliverableAccess }), createModelGatewayRoutes());
|
|
16185
16186
|
ROUTES.push(createPinOrderRoutes({ store, visible: (auth) => visibleTo(viewerFor(auth)), personalHidden: personalBotHidden, fromBot: (req) => authorizedInternalCapability(req.headers.authorization) !== null }));
|
|
16186
16187
|
// Linked repos: Settings > Repos, per-thread links and worktrees. See
|
|
16187
16188
|
// server/routes/repos.ts for the routes and docs/chibitek/README.md.
|
|
@@ -16464,8 +16465,7 @@ const handleRequest = async (req, res) => {
|
|
|
16464
16465
|
if (path.startsWith("/api/") && path !== "/api/events" && path !== "/api/health" && !path.startsWith("/api/shared-computers/") && !isWorkspaceBackupSessionControl(method, path)) {
|
|
16465
16466
|
releaseWorkspaceRequest = workspaceMaintenance.request();
|
|
16466
16467
|
}
|
|
16467
|
-
// New routes live in modules registered in server/routes/table.ts and
|
|
16468
|
-
// are tried here, behind the gate above; do not add route `if`s below.
|
|
16468
|
+
// New routes live in modules registered in server/routes/table.ts and are tried here, behind the gate above; no route `if`s below.
|
|
16469
16469
|
if (await dispatchRoutes(ROUTES, { req, res, url, path, method, auth, json, readBody }))
|
|
16470
16470
|
return;
|
|
16471
16471
|
// ── sessions: who am I, tickets, pairing and revocation ─────────────
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Try the next model before the first byte reaches the harness, never after
|
|
2
|
+
// (docs/specs/atomic-model-source, Testing strategy). Pure apart from the
|
|
3
|
+
// `send` it is handed, so tests drive it with a fake upstream.
|
|
4
|
+
import { classifyEngineFailure } from "../engine-failure.js";
|
|
5
|
+
const REST_MS = 10 * 60_000;
|
|
6
|
+
/** Statuses that mean "this model cannot answer right now", worth the next one. */
|
|
7
|
+
export function failsOver(status, body) {
|
|
8
|
+
if (status === 401 || status === 402 || status === 403 || status === 404 || status === 408 || status === 429 || status >= 500)
|
|
9
|
+
return true;
|
|
10
|
+
return status >= 400 && classifyEngineFailure(body) !== null;
|
|
11
|
+
}
|
|
12
|
+
/** A model that hit a limit rests a while, so the next request starts lower. */
|
|
13
|
+
export class GatewayRests {
|
|
14
|
+
until = new Map();
|
|
15
|
+
now;
|
|
16
|
+
constructor(now = Date.now) { this.now = now; }
|
|
17
|
+
rest(model, ms = REST_MS) { this.until.set(model, this.now() + ms); }
|
|
18
|
+
resting = (model) => (this.until.get(model) ?? 0) > this.now();
|
|
19
|
+
}
|
|
20
|
+
export async function firstAnswer(models, send, rests) {
|
|
21
|
+
const failovers = [];
|
|
22
|
+
let last = { status: 404, error: "No model is available behind Atomic right now. Start Ollama, or sign in to Ollama for its cloud models." };
|
|
23
|
+
for (const model of models) {
|
|
24
|
+
let response;
|
|
25
|
+
try {
|
|
26
|
+
response = await send(model);
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
failovers.push(model);
|
|
30
|
+
last = { status: 502, error: `Ollama did not answer (${error.message}).` };
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (response.ok)
|
|
34
|
+
return { ok: true, model, response, failovers };
|
|
35
|
+
const body = await response.text().catch(() => "");
|
|
36
|
+
if (!failsOver(response.status, body))
|
|
37
|
+
return { ok: true, model, response: new Response(body, { status: response.status, headers: response.headers }), failovers };
|
|
38
|
+
if (response.status === 429 || response.status === 402)
|
|
39
|
+
rests?.rest(model);
|
|
40
|
+
failovers.push(model);
|
|
41
|
+
last = { status: response.status, error: `${model} could not answer (${response.status}).` };
|
|
42
|
+
}
|
|
43
|
+
return { ok: false, ...last, failovers };
|
|
44
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The order `atomic/auto` walks when Claude Code or Codex use Atomic as a
|
|
2
|
+
// model source (docs/specs/atomic-model-source). Pure, so it tests without a
|
|
3
|
+
// server. Only models the local Ollama daemon serves are here: its `:cloud`
|
|
4
|
+
// models run on the Ollama Teams subscription, the rest run on this computer.
|
|
5
|
+
// Claude and ChatGPT sign-ins are never behind the gateway (spec, Boundaries).
|
|
6
|
+
export const ATOMIC_AUTO_GATEWAY_MODEL = "atomic/auto";
|
|
7
|
+
/** Erick's locked backup order (spec, Open questions): first when served. */
|
|
8
|
+
export const LOCKED_CLOUD_ORDER = ["glm-5.3:cloud", "deepseek-v4-pro:cloud", "qwen3.5:cloud"];
|
|
9
|
+
const isCloud = (model) => /(^|[:-])cloud$/.test(model);
|
|
10
|
+
/** Subscription first (the locked cloud order, then every other `:cloud`
|
|
11
|
+
* model in the order Ollama lists them), then local models. A model that is
|
|
12
|
+
* resting after a usage or rate limit is skipped; when every model rests the
|
|
13
|
+
* whole list is tried anyway, since a rest is only an estimate. */
|
|
14
|
+
export function autoLadder(available, resting = () => false, locked = LOCKED_CLOUD_ORDER) {
|
|
15
|
+
const unique = [...new Set(available.filter((model) => model && model !== ATOMIC_AUTO_GATEWAY_MODEL))];
|
|
16
|
+
const ordered = [
|
|
17
|
+
...locked.filter((model) => unique.includes(model)),
|
|
18
|
+
...unique.filter((model) => isCloud(model) && !locked.includes(model)),
|
|
19
|
+
...unique.filter((model) => !isCloud(model)),
|
|
20
|
+
];
|
|
21
|
+
const awake = ordered.filter((model) => !resting(model));
|
|
22
|
+
return awake.length ? awake : ordered;
|
|
23
|
+
}
|
|
24
|
+
/** What one request walks: the ladder for `atomic/auto`, else the one model asked for. */
|
|
25
|
+
export function modelsFor(asked, available, resting) {
|
|
26
|
+
if (asked === ATOMIC_AUTO_GATEWAY_MODEL)
|
|
27
|
+
return autoLadder(available, resting);
|
|
28
|
+
return available.includes(asked) ? [asked] : [];
|
|
29
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Atomic as a model source for Claude Code and Codex: the model id
|
|
2
|
+
// `atomic/auto` (docs/chibitek/model-source.md, docs/specs/atomic-model-source).
|
|
3
|
+
// GET /api/v1/models atomic/auto, then every model Ollama serves
|
|
4
|
+
// POST /api/v1/responses OpenAI Responses (Codex)
|
|
5
|
+
// POST /api/v1/chat/completions OpenAI Chat Completions (OpenCode, Cline)
|
|
6
|
+
// POST /api/v1/messages Anthropic Messages (Claude Code, ANTHROPIC_BASE_URL)
|
|
7
|
+
// Each call is passed through to the local Ollama daemon unchanged except for
|
|
8
|
+
// the model, walking the `atomic/auto` ladder until one model answers; the
|
|
9
|
+
// caller's token never leaves Atomic. Loopback only, and only with a
|
|
10
|
+
// connected assistant's token (request-auth.ts ASSISTANT_ALLOW). Prompt and
|
|
11
|
+
// completion text are never logged. Under /api/ because the static app
|
|
12
|
+
// answers every other GET path.
|
|
13
|
+
import { Readable } from "node:stream";
|
|
14
|
+
import { hostApiKey, localHost } from "../drivers/local-inject.js";
|
|
15
|
+
import { PASS } from "../routes/table.js";
|
|
16
|
+
import { firstAnswer, GatewayRests } from "./failover.js";
|
|
17
|
+
import { ATOMIC_AUTO_GATEWAY_MODEL, modelsFor } from "./ladder.js";
|
|
18
|
+
const PREFIX = "/api/v1/";
|
|
19
|
+
const PASS_THROUGH = new Set(["responses", "chat/completions", "messages"]);
|
|
20
|
+
const MAX_BODY = 32 * 1024 * 1024;
|
|
21
|
+
const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1", "localhost"]);
|
|
22
|
+
/** The socket and the Host header both name this computer. */
|
|
23
|
+
export function fromLoopback(remoteAddress, host) {
|
|
24
|
+
if (!remoteAddress || !LOOPBACK.has(remoteAddress))
|
|
25
|
+
return false;
|
|
26
|
+
if (!host)
|
|
27
|
+
return true;
|
|
28
|
+
const name = host.startsWith("[") ? host.slice(1, host.indexOf("]")) : host.replace(/:\d+$/, "");
|
|
29
|
+
return LOOPBACK.has(name.toLowerCase());
|
|
30
|
+
}
|
|
31
|
+
function ollama() {
|
|
32
|
+
const host = localHost("ollama");
|
|
33
|
+
return host ? { baseUrl: host.baseUrl.replace(/\/+$/, ""), apiKey: hostApiKey(host) } : null;
|
|
34
|
+
}
|
|
35
|
+
export function createModelGatewayRoutes(deps = {}) {
|
|
36
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
37
|
+
const rests = deps.rests ?? new GatewayRests();
|
|
38
|
+
const log = deps.log ?? ((line) => console.info(line));
|
|
39
|
+
const upstream = () => (deps.upstream ?? ollama)();
|
|
40
|
+
async function served() {
|
|
41
|
+
const base = upstream();
|
|
42
|
+
if (!base)
|
|
43
|
+
return [];
|
|
44
|
+
try {
|
|
45
|
+
const res = await fetchImpl(`${base.baseUrl}/models`, { headers: base.apiKey ? { authorization: `Bearer ${base.apiKey}` } : {}, signal: AbortSignal.timeout(5_000) });
|
|
46
|
+
const body = res.ok ? await res.json() : {};
|
|
47
|
+
return (body.data ?? []).map((row) => row.id).filter((id) => typeof id === "string" && id.length > 0);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return async ({ req, res, path, method, auth, json, readBody }) => {
|
|
54
|
+
if (!path.startsWith(PREFIX))
|
|
55
|
+
return PASS;
|
|
56
|
+
const tail = path.slice(PREFIX.length);
|
|
57
|
+
if (!(tail === "models" && method === "GET") && !(PASS_THROUGH.has(tail) && method === "POST"))
|
|
58
|
+
return PASS;
|
|
59
|
+
if (!fromLoopback(req.socket.remoteAddress, req.headers.host))
|
|
60
|
+
return json(res, 403, { error: "Atomic's model source answers only on this computer." });
|
|
61
|
+
if (auth.kind !== "assistant")
|
|
62
|
+
return json(res, 401, { error: "Send a connected assistant's token from Atomic Settings → Connected assistants." });
|
|
63
|
+
const available = await served();
|
|
64
|
+
if (tail === "models") {
|
|
65
|
+
const ids = [ATOMIC_AUTO_GATEWAY_MODEL, ...available];
|
|
66
|
+
return json(res, 200, { object: "list", data: ids.map((id) => ({ id, object: "model", owned_by: id === ATOMIC_AUTO_GATEWAY_MODEL ? "atomic" : "ollama", ...(id === ATOMIC_AUTO_GATEWAY_MODEL ? { display_name: "Atomic Engine (Auto)" } : {}) })) });
|
|
67
|
+
}
|
|
68
|
+
let body;
|
|
69
|
+
try {
|
|
70
|
+
body = await readBody(req, MAX_BODY);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
return json(res, error.status ?? 400, { error: error.message });
|
|
74
|
+
}
|
|
75
|
+
const asked = typeof body.model === "string" ? body.model : "";
|
|
76
|
+
const models = modelsFor(asked, available, rests.resting);
|
|
77
|
+
if (!models.length) {
|
|
78
|
+
return json(res, 404, { error: available.length ? `Atomic does not serve "${asked}". Use ${ATOMIC_AUTO_GATEWAY_MODEL} or a model from /api/v1/models.` : "No model is available behind Atomic right now. Start Ollama, or sign in to Ollama for its cloud models." });
|
|
79
|
+
}
|
|
80
|
+
const base = upstream();
|
|
81
|
+
const headers = { "content-type": "application/json" };
|
|
82
|
+
if (base.apiKey)
|
|
83
|
+
headers.authorization = `Bearer ${base.apiKey}`;
|
|
84
|
+
if (tail === "messages") {
|
|
85
|
+
headers["x-api-key"] = base.apiKey ?? "ollama";
|
|
86
|
+
headers["anthropic-version"] = String(req.headers["anthropic-version"] ?? "2023-06-01");
|
|
87
|
+
}
|
|
88
|
+
const answer = await firstAnswer(models, (model) => fetchImpl(`${base.baseUrl}/${tail}`, { method: "POST", headers, body: JSON.stringify({ ...body, model }) }), rests);
|
|
89
|
+
log(`[model-gateway] ${tail} asked=${asked} used=${answer.ok ? answer.model : "none"} failovers=${answer.failovers.join(",") || "none"}`);
|
|
90
|
+
if (!answer.ok)
|
|
91
|
+
return json(res, answer.status === 404 ? 503 : answer.status, { error: answer.error });
|
|
92
|
+
const type = answer.response.headers.get("content-type") ?? "application/json";
|
|
93
|
+
res.writeHead(answer.response.status, { "content-type": type, "cache-control": "no-cache", "x-atomic-model": answer.model });
|
|
94
|
+
if (!answer.response.body)
|
|
95
|
+
return void res.end();
|
|
96
|
+
// Past the first byte there is no failing over: the harness has started reading.
|
|
97
|
+
await new Promise((resolve) => {
|
|
98
|
+
const stream = Readable.fromWeb(answer.response.body);
|
|
99
|
+
stream.on("error", () => { res.destroy(); resolve(); });
|
|
100
|
+
res.on("close", () => { stream.destroy(); resolve(); });
|
|
101
|
+
stream.pipe(res).on("finish", () => resolve());
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
}
|