mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-14 18:39:33 +01:00
Merge branch 'feat/local-model-recommendation' into test/desktop-macbook
# Conflicts: # config/test-suites.ts
This commit is contained in:
commit
1e097bc368
74 files changed
+25355
-2118
No files matched your search
@@ -0,0 +1,311 @@
|
||||
/**
|
||||
* @fileoverview The shared runner of a STOCK CLI's install command: the one place Codeman
|
||||
* executes an install one-liner, used by `POST /api/clis/:id/install`
|
||||
* (src/web/routes/cli-registry-routes.ts) and by the local model install job.
|
||||
*
|
||||
* The code was moved here from cli-registry-routes.ts, and that route keeps its behaviour
|
||||
* byte for byte (same answers, same audit entry, same 409 for a second install of one id,
|
||||
* same environment).
|
||||
*
|
||||
* What lives here:
|
||||
* - `installEnv()` and `npmGlobalPrefixWritable()`: the installer's environment is the
|
||||
* server's minus every `CODEMAN_*` variable, with npm's global prefix pointed at a place
|
||||
* the server user can write. test/routes/cli-registry-routes.test.ts imports both from the
|
||||
* route module, which re-exports them from here.
|
||||
* - `runInstallCommand()`: `shell: true`, its own process group, output capped, the whole
|
||||
* group killed on timeout. New: an abort signal that kills the group the same way, so the
|
||||
* install job's Cancel has something to stop.
|
||||
* - `forgetResolvedCli()`: after an install, successful or not, every cached lookup of the
|
||||
* CLI's binaries is dropped, or a pre-install miss is replayed for up to five minutes.
|
||||
* - The set of ids with an install running. ONE set for both callers
|
||||
* (`tryBeginCliInstall()`), so the route and the job can never run two installers of one
|
||||
* CLI over the same prefix.
|
||||
*
|
||||
* Rules:
|
||||
* - Which command runs is the CALLER's choice, and the two callers choose differently. The
|
||||
* local model job passes `stockInstallCommand()`, which reads the compiled `STOCK_CLIS`
|
||||
* and never the registry merged with `clis.json`, so an override file cannot change what
|
||||
* that job runs. The CLI management route passes the merged entry's command
|
||||
* (`resolveInstallCommandForPlatform(listClis()...)`), as it did before this module
|
||||
* existed: a `clis.json` override of a stock entry's install command IS what that route
|
||||
* runs (behind `cliManagementEnabled`, after a confirm that shows the exact text). A custom
|
||||
* entry's install text is never executed by either. Switching the route to
|
||||
* `stockInstallCommand()` would close that gap at the cost of a behaviour change the route
|
||||
* tests pin; it is an owner decision, not made here.
|
||||
* - Who may call it is the caller's rule, not this module's: the route keeps its
|
||||
* `cliManagementEnabled` gate; the install job runs it only for a harness row of the local
|
||||
* model catalogue, after the person's consent click on a screen that showed the literal
|
||||
* command, admin only in multi-user mode, and writes the admin audit entry itself.
|
||||
*/
|
||||
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import { constants as fsConstants } from 'node:fs';
|
||||
import { access } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { resolveInstallCommandForPlatform } from './config/cli-registry/registry.js';
|
||||
import { STOCK_CLIS } from './config/cli-registry/stock.js';
|
||||
import { getErrorMessage } from './types.js';
|
||||
import { invalidateCliExecutableResolvers } from './utils/cli-executable-resolver.js';
|
||||
import { invalidateCliResolverCache } from './utils/cli-resolver.js';
|
||||
|
||||
/** How long an install command may run before its process group is killed. */
|
||||
export const CLI_INSTALL_TIMEOUT_MS = 300_000;
|
||||
|
||||
/** How an install command ended. */
|
||||
export interface CliInstallResult {
|
||||
/** The exit code, `null` when the command was killed or could not be started. */
|
||||
code: number | null;
|
||||
/** stdout and stderr together, capped. */
|
||||
output: string;
|
||||
/** The timeout killed it. */
|
||||
timedOut: boolean;
|
||||
/** The abort signal killed it. */
|
||||
aborted: boolean;
|
||||
}
|
||||
|
||||
export interface RunInstallCommandOptions {
|
||||
/** Kills the installer's whole process group (SIGTERM, then SIGKILL). */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ids with an install running right now. A second request for the same id gets 409 rather
|
||||
* than a second `curl | bash` or `npm install -g` racing the first over the same prefix.
|
||||
*/
|
||||
const installsInFlight = new Set<string>();
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/**
|
||||
* True when `npm install -g` can write to this process's npm global prefix, or when that cannot
|
||||
* be determined (then nothing is redirected: a wrong guess would move installs somewhere the
|
||||
* user did not choose). `npm config get prefix` is asked rather than guessed from `process.execPath`
|
||||
* because a user `.npmrc` / `NPM_CONFIG_PREFIX` can point it anywhere.
|
||||
*
|
||||
* Async so the server keeps serving while npm boots (130 to 240 ms), and killed with SIGKILL on
|
||||
* timeout because `SIGTERM` alone leaves the wait running. A prefix that does not exist yet is
|
||||
* judged by the nearest ancestor that does: npm creates the missing directories, so a user
|
||||
* `.npmrc` pointing at `~/.npm-global` before it was made is not moved.
|
||||
*/
|
||||
export async function npmGlobalPrefixWritable(source: NodeJS.ProcessEnv): Promise<boolean> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('npm', ['config', 'get', 'prefix'], {
|
||||
env: source,
|
||||
encoding: 'utf8',
|
||||
timeout: 5_000,
|
||||
killSignal: 'SIGKILL',
|
||||
});
|
||||
const prefix = stdout.trim();
|
||||
if (!prefix) return true;
|
||||
// npm creates lib/node_modules under the prefix; walk up to the first directory that exists.
|
||||
let dir = join(prefix, 'lib', 'node_modules');
|
||||
for (;;) {
|
||||
try {
|
||||
await access(dir, fsConstants.W_OK);
|
||||
return true;
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return false;
|
||||
const parent = dirname(dir);
|
||||
if (parent === dir) return false;
|
||||
dir = parent;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The server's environment minus every `CODEMAN_*` variable. An install script is third-party
|
||||
* code, and those variables carry Codeman's own secrets and wiring (`CODEMAN_PASSWORD`, the
|
||||
* data dir, the tmux socket), none of which an installer needs.
|
||||
*
|
||||
* It also points `NPM_CONFIG_PREFIX` at `$HOME/.local` so an `npm install -g` lands somewhere the
|
||||
* server user can write and Codeman's resolvers already search (`~/.local/bin`):
|
||||
* - inside the Docker Compose container (`CODEMAN_IN_CONTAINER=1`), so installs survive an image
|
||||
* update (the image's own prefix is image content);
|
||||
* - on a native install whose npm global prefix is not writable by the server user (a system node
|
||||
* under `/usr`, installed by root). Without this `npm install -g` died with EACCES (exit 243),
|
||||
* e.g. DeepSeek's `npm install -g @deepseek-ai/dsh`. An explicit `NPM_CONFIG_PREFIX` the
|
||||
* operator set is respected, and so is a prefix that is writable (nvm, `~/.npm-global`, ...).
|
||||
*/
|
||||
export function installEnv(
|
||||
source: NodeJS.ProcessEnv = process.env,
|
||||
prefixWritable: (env: NodeJS.ProcessEnv) => boolean = () => true
|
||||
): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {};
|
||||
for (const [key, value] of Object.entries(source)) {
|
||||
if (!key.startsWith('CODEMAN_')) env[key] = value;
|
||||
}
|
||||
// ⚠️ In the Docker Compose deployment the image sets NPM_CONFIG_PREFIX=/opt/codeman-cli, which is IMAGE
|
||||
// content: `Update-Codeman.sh` recreates the container and every CLI installed there (dsh, pi, ...)
|
||||
// vanishes. HOME is the persistent bind mount and `~/.local/bin` is already on every resolver's search
|
||||
// list, so npm-based installs are redirected there. curl|bash installers already target HOME.
|
||||
if (source.CODEMAN_IN_CONTAINER === '1' && source.HOME) {
|
||||
redirectNpmPrefix(env, source.HOME);
|
||||
} else if (process.platform !== 'win32' && source.HOME && !source.NPM_CONFIG_PREFIX && !prefixWritable(env)) {
|
||||
redirectNpmPrefix(env, source.HOME);
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
/**
|
||||
* Point npm at `$HOME/.local`, dropping every spelling of the prefix key first. `npm run` exports a
|
||||
* lowercase `npm_config_prefix`, npm reads `npm_config_*` case-insensitively, and when both spellings
|
||||
* are present a `/bin/sh` that sorts its environment (bash) lets the older value win. The explicit
|
||||
* operator guard in `installEnv` stays on the uppercase key only: npm always injects the lowercase one.
|
||||
*/
|
||||
function redirectNpmPrefix(env: NodeJS.ProcessEnv, home: string): void {
|
||||
for (const key of Object.keys(env)) if (/^npm_config_prefix$/i.test(key)) delete env[key];
|
||||
env.NPM_CONFIG_PREFIX = `${home}/.local`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `installEnv` for this process, with the (async) npm prefix probe done first and only when the
|
||||
* command runs npm at all: a `curl | bash` installer never pays for it.
|
||||
*/
|
||||
async function installEnvFor(command: string, source: NodeJS.ProcessEnv = process.env): Promise<NodeJS.ProcessEnv> {
|
||||
const usesNpm = /\bnpm\b/.test(command);
|
||||
const probeNeeded =
|
||||
usesNpm &&
|
||||
source.CODEMAN_IN_CONTAINER !== '1' &&
|
||||
process.platform !== 'win32' &&
|
||||
!!source.HOME &&
|
||||
!source.NPM_CONFIG_PREFIX;
|
||||
const writable = probeNeeded ? await npmGlobalPrefixWritable(installEnv(source)) : true;
|
||||
return installEnv(source, () => writable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a STOCK entry's already-vetted install command. `shell: true` is unavoidable here:
|
||||
* the shipped commands are genuinely `curl | bash` / `npm install -g` one-liners. This is NOT
|
||||
* a reopening of the config-shell-text concern the registry's `shellToken` pattern exists to
|
||||
* prevent: the string executed here is NEVER user input, only ever what is already hardcoded
|
||||
* and reviewed in `stock.ts`, and a CUSTOM entry can never reach this function at all (see the
|
||||
* guard of each caller).
|
||||
*
|
||||
* Never throws: a spawn that fails is a result with `code: null`.
|
||||
*/
|
||||
export async function runInstallCommand(
|
||||
command: string,
|
||||
options: RunInstallCommandOptions = {}
|
||||
): Promise<CliInstallResult> {
|
||||
const { signal } = options;
|
||||
if (signal?.aborted) return { code: null, output: '', timedOut: false, aborted: true };
|
||||
const env = await installEnvFor(command);
|
||||
// The environment probe above can take a moment (npm boots): an abort during it starts nothing.
|
||||
if (signal?.aborted) return { code: null, output: '', timedOut: false, aborted: true };
|
||||
return new Promise((resolve) => {
|
||||
let child: ReturnType<typeof spawn>;
|
||||
try {
|
||||
child = spawn(command, {
|
||||
shell: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
// Own process group; the timeout below kills the whole tree by hand, mirroring
|
||||
// the DeepSeek profile-install endpoint's own reasoning: an install command fans
|
||||
// out into package-manager children, and spawn's own `timeout` option signals
|
||||
// only the direct child, leaving survivors holding the pipes open forever.
|
||||
detached: true,
|
||||
env,
|
||||
});
|
||||
} catch (err) {
|
||||
resolve({ code: null, output: `spawn failed: ${getErrorMessage(err)}`, timedOut: false, aborted: false });
|
||||
return;
|
||||
}
|
||||
|
||||
let output = '';
|
||||
let timedOut = false;
|
||||
let aborted = false;
|
||||
let settled = false;
|
||||
let killTimer: NodeJS.Timeout | undefined;
|
||||
let reapTimer: NodeJS.Timeout | undefined;
|
||||
|
||||
const capture = (chunk: Buffer) => {
|
||||
if (output.length < 16_384) output += chunk.toString('utf-8');
|
||||
};
|
||||
child.stdout?.on('data', capture);
|
||||
child.stderr?.on('data', capture);
|
||||
|
||||
const killTree = (killSignal: NodeJS.Signals) => {
|
||||
try {
|
||||
if (child.pid) process.kill(-child.pid, killSignal);
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
};
|
||||
|
||||
/** SIGTERM to the group, SIGKILL three seconds later, and give up waiting after eight. */
|
||||
const stopTree = () => {
|
||||
if (killTimer) return;
|
||||
killTree('SIGTERM');
|
||||
killTimer = setTimeout(() => killTree('SIGKILL'), 3_000);
|
||||
reapTimer = setTimeout(() => finish(null), 8_000);
|
||||
};
|
||||
|
||||
const onAbort = () => {
|
||||
aborted = true;
|
||||
stopTree();
|
||||
};
|
||||
|
||||
const finish = (code: number | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (killTimer) clearTimeout(killTimer);
|
||||
if (reapTimer) clearTimeout(reapTimer);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
resolve({ code, output, timedOut, aborted });
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
stopTree();
|
||||
}, CLI_INSTALL_TIMEOUT_MS);
|
||||
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
child.on('error', (err) => {
|
||||
output = `${output}\n${err.message}`;
|
||||
finish(null);
|
||||
});
|
||||
child.on('close', (code) => finish(code));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The install command of the STOCK CLI `id` for this platform, read from the compiled
|
||||
* `STOCK_CLIS`. `undefined` for an id that is not a stock CLI or has no command here.
|
||||
*/
|
||||
export function stockInstallCommand(id: string): string | undefined {
|
||||
const entry = STOCK_CLIS.find((candidate) => (candidate.id as string) === id);
|
||||
if (!entry) return undefined;
|
||||
const command = resolveInstallCommandForPlatform(entry);
|
||||
return command !== undefined && command.trim() !== '' ? command : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Claims the one install slot of `id`. Returns the function that releases it, or `null` when
|
||||
* an install of that CLI is already running (the caller answers 409 or waits).
|
||||
*/
|
||||
export function tryBeginCliInstall(id: string): (() => void) | null {
|
||||
if (installsInFlight.has(id)) return null;
|
||||
installsInFlight.add(id);
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
installsInFlight.delete(id);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Forgets every cached binary lookup of a CLI: the generic per-id resolver (which captures
|
||||
* the entry's binaries when first built) and every per-binary cache, hits and negative-cache
|
||||
* backoff alike. Called after anything that changes what is on disk or what the CLI's binary
|
||||
* IS; see `invalidateCliExecutableResolvers`.
|
||||
*/
|
||||
export function forgetResolvedCli(id: string, binaries: readonly string[]): void {
|
||||
invalidateCliExecutableResolvers(binaries);
|
||||
invalidateCliResolverCache(id);
|
||||
}
|
||||
@@ -3,8 +3,9 @@
|
||||
* knows, as a compiled constant validated by a Zod schema.
|
||||
*
|
||||
* Rules:
|
||||
* - There is NO override file and no runtime download data in this stage: nothing here reads
|
||||
* the data dir, and a data file can never decide what gets recommended.
|
||||
* - There is NO override file and no runtime download data here: nothing in this file reads
|
||||
* the data dir, and a data file can never decide what gets recommended. Which runtime build
|
||||
* is downloaded is a compiled constant of its own (src/local-model/runtime.ts).
|
||||
* - A model id is `name:tag` in lowercase with no slash (`LOCAL_MODEL_ID_PATTERN`), so it can
|
||||
* only ever name a model of the default registry and namespace.
|
||||
* - A harness is a ROW (`{ cli, minContext, rank, gated?, slowFirstTurn? }`). The `cli` is a CLI
|
||||
@@ -13,7 +14,7 @@
|
||||
* src/local-model/harness-facts.ts, never here.
|
||||
* - The schema checks more than fields. Across rows it requires: unique model ids and ranks,
|
||||
* unique harness `cli`s and ranks, `contexts` largest first, a `tested` entry naming a harness
|
||||
* row, `chips` most specific first, and `promptCacheTiers` ascending from 0.
|
||||
* row, and `chips` most specific first.
|
||||
* - `getLocalModelCatalog()` parses the constant once, on first use and never at import, and
|
||||
* throws on a bad row. test/local-model-catalog.test.ts pins that the stock constant parses,
|
||||
* so a bad row fails the gate and never reaches the route.
|
||||
@@ -22,26 +23,44 @@
|
||||
*
|
||||
* | Figure | Source | Checked |
|
||||
* |----------------------|-----------------------------------------------------------|--------------------------------------|
|
||||
* | `id`, `bytes` | registry manifest of the tag, sum of its layer sizes | yes, to the byte, by the facts review |
|
||||
* | `id` | the registry's tag | yes, by the facts review |
|
||||
* | `bytes` | `qwen3.6:35b-a3b`: the total of a real pull on a Mac | that row: measured. It is an MLX |
|
||||
* | | (23,105,798,956). Every other row: the sum of the layer | build on a Mac, 2% above its |
|
||||
* | | sizes of the tag's registry manifest | manifest. The others: not on a Mac |
|
||||
* | `heldBytesPerToken`, | measured for `qwen3.6:35b-a3b` on an Apple M5 Pro with | that row: measured. The others carry |
|
||||
* | `overheadBytes`, | 48 GB: 36,000 to 38,000 bytes held per token of context, | the SAME three figures, not their |
|
||||
* | `peakExtraBytes` | 2.5 to 3 GB beside the weights, and about 5 GB more for a | own: nobody ran them. `figures` says |
|
||||
* | | moment while a long prompt is processed | which row is which |
|
||||
* | `license` | the model card (all Apache-2.0) | read by the research, not re-checked |
|
||||
* | `paramsB` | 27.8 from the model card; the others are the count in the | no. Only the 12 billion line reads |
|
||||
* | | model's name | it, and no row is near that line |
|
||||
* | `kvBytesPerToken` | COMPUTED from each model's config: 2 x full-attention | no. Not measured in a running |
|
||||
* | | layers x KV heads x head size x 2 bytes | runtime. The review called the |
|
||||
* | | | gpt-oss figure plausible, no more |
|
||||
* | `contexts`, `rank` | a judgement of the design | no |
|
||||
* | `speedPer100Gbps` | one published run on an M1 Max (400 GB/s): generation | the run was read. It stands for less |
|
||||
* | | only, short prompt. The two q8_0 rows are SCALED by file | than a session: no long prompt, no |
|
||||
* | | size, not measured | thinking tokens |
|
||||
* | `tested` | our own run of the model with a harness on a real Mac | one entry, with its measured speed |
|
||||
* | `minMacosMajor` | the runtime's documentation (macOS 14) | yes, by the facts review |
|
||||
* | `promptCacheTiers` | a decision of the design, not a measurement | no |
|
||||
* | harness `minContext` | 65536: the runtime's documentation for both harnesses. | 65536 yes. 32768 no, which is why |
|
||||
* | | 32768: recalled | that row is gated |
|
||||
* | `chips` | the bandwidth column of | yes, read at the source for this |
|
||||
* | | https://github.com/ggml-org/llama.cpp/discussions/4167 | file |
|
||||
*
|
||||
* `tested` is empty on every row: nobody has run any of these models with a harness on a Mac
|
||||
* yet. Until a row has an entry, the recommendation never says "Recommended".
|
||||
* The memory figures decide a lot and rest on ONE measured model, so for every other row they
|
||||
* can be wrong in either direction:
|
||||
* - For the 9B rows they may be too HIGH (the 5 GB for a moment was seen with a prompt of
|
||||
* 89,000 tokens on the 35B model). That errs on the careful side: a small Mac is told
|
||||
* "none" before it is told to download something that may not fit.
|
||||
* - For the two dense `qwen3.8:27b` rows the per-token figure may be too LOW: computed from
|
||||
* its config alone that model holds 64 KiB per token, more than the 37,000 bytes measured
|
||||
* on the 35B (whose own computed figure was 20 KiB). Their need at a large context is
|
||||
* therefore the least certain figure of the catalogue.
|
||||
* A row gets its own figures when somebody measures it. Until then the check after the
|
||||
* download (the runtime must report the whole model on the GPU) is what catches a row that
|
||||
* was judged too kindly.
|
||||
*
|
||||
* `tested` has one entry: `qwen3.6:35b-a3b` with OpenCode on an Apple M5 Pro with 48 GB,
|
||||
* 2026-11-06, 67.7 tokens per second. Only a Mac of exactly that chip and memory size is told
|
||||
* "Recommended" and shown that speed in place of the estimate.
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
@@ -85,6 +104,7 @@ const TestedOnSchema = z
|
||||
memGb: positiveInt,
|
||||
cli: z.string().min(1).max(24),
|
||||
date: isoDate,
|
||||
tokensPerSecond: z.number().positive().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
@@ -95,7 +115,10 @@ const LocalModelEntrySchema = z
|
||||
license: z.string().min(1).max(40),
|
||||
paramsB: z.number().positive(),
|
||||
bytes: positiveInt,
|
||||
kvBytesPerToken: positiveInt,
|
||||
heldBytesPerToken: positiveInt,
|
||||
overheadBytes: z.number().int().nonnegative(),
|
||||
peakExtraBytes: z.number().int().nonnegative(),
|
||||
figures: z.enum(['measured', 'estimated']),
|
||||
contexts: z.array(positiveInt).min(1),
|
||||
rank: z.number().int(),
|
||||
speedPer100Gbps: z.number().positive().optional(),
|
||||
@@ -120,13 +143,6 @@ const ChipEntrySchema = z
|
||||
})
|
||||
.strict();
|
||||
|
||||
const PromptCacheTierSchema = z
|
||||
.object({
|
||||
minMemGb: z.number().int().nonnegative(),
|
||||
bytes: z.number().int().nonnegative(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** The index of the first value that already occurred earlier in the list, or -1. */
|
||||
function firstRepeat<T>(values: readonly T[]): number {
|
||||
const seen = new Set<T>();
|
||||
@@ -146,7 +162,6 @@ export const LocalModelCatalogSchema: z.ZodType<LocalModelCatalog> = z
|
||||
schema: z.literal(1),
|
||||
updated: isoDate,
|
||||
minMacosMajor: positiveInt,
|
||||
promptCacheTiers: z.array(PromptCacheTierSchema).min(1),
|
||||
models: z.array(LocalModelEntrySchema),
|
||||
harnesses: z.array(LocalHarnessEntrySchema),
|
||||
chips: z.array(ChipEntrySchema),
|
||||
@@ -199,23 +214,21 @@ export const LocalModelCatalogSchema: z.ZodType<LocalModelCatalog> = z
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// The tiers are read as "the last one whose minimum is not above this Mac's memory", so they
|
||||
// must start at 0 (every Mac has a tier) and ascend.
|
||||
if (catalog.promptCacheTiers[0].minMemGb !== 0) {
|
||||
issue(['promptCacheTiers', 0, 'minMemGb'], 'the first prompt cache tier must start at 0');
|
||||
}
|
||||
for (let i = 1; i < catalog.promptCacheTiers.length; i++) {
|
||||
if (catalog.promptCacheTiers[i].minMemGb <= catalog.promptCacheTiers[i - 1].minMemGb) {
|
||||
issue(['promptCacheTiers', i, 'minMemGb'], 'prompt cache tiers must ascend by minMemGb');
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const KIB = 1024;
|
||||
const MIB = 1024 ** 2;
|
||||
const GIB = 1024 ** 3;
|
||||
/**
|
||||
* The memory figures measured for `qwen3.6:35b-a3b` on an Apple M5 Pro with 48 GB (2026-11-06,
|
||||
* the MLX runner), in decimal bytes. That row carries them as `measured`; every other row
|
||||
* carries the same three as `estimated`, see the file header.
|
||||
*/
|
||||
const MEASURED_MEMORY = {
|
||||
/** 36,000 to 38,000 bytes stayed held per token of context after a prompt of 89,000 and one of 167,000 tokens. */
|
||||
heldBytesPerToken: 37_000,
|
||||
/** The runner held 2.5 to 3 GB beside the weights. */
|
||||
overheadBytes: 3_000_000_000,
|
||||
/** While a long prompt was processed the peak stood about 5 GB above what stayed held. */
|
||||
peakExtraBytes: 5_000_000_000,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* The catalogue that ships with Codeman. Never read directly outside this file and its test:
|
||||
@@ -226,12 +239,6 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
updated: '2026-11-06',
|
||||
// The oldest macOS the model runtime supports.
|
||||
minMacosMajor: 14,
|
||||
// Host memory the runtime's prompt cache may take beside the model: 512 MiB on a Mac below
|
||||
// 32 GB, 2 GiB from 32 GB. Part of the need of every candidate.
|
||||
promptCacheTiers: [
|
||||
{ minMemGb: 0, bytes: 512 * MIB },
|
||||
{ minMemGb: 32, bytes: 2 * GIB },
|
||||
],
|
||||
// Ordered by rank. The higher rank wins among models that fit equally well and are equally
|
||||
// fast. `flint:40b` is left out on purpose: its plain tag is the slow build on a Mac and it
|
||||
// has an open bug with tool arguments.
|
||||
@@ -242,7 +249,8 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
license: 'Apache-2.0',
|
||||
paramsB: 9,
|
||||
bytes: 6_550_825_373,
|
||||
kvBytesPerToken: 32 * KIB,
|
||||
...MEASURED_MEMORY,
|
||||
figures: 'estimated',
|
||||
contexts: [65536, 32768],
|
||||
rank: 1,
|
||||
// 37.1 tokens per second measured on 400 GB/s.
|
||||
@@ -255,7 +263,8 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
license: 'Apache-2.0',
|
||||
paramsB: 9,
|
||||
bytes: 10_449_217_949,
|
||||
kvBytesPerToken: 32 * KIB,
|
||||
...MEASURED_MEMORY,
|
||||
figures: 'estimated',
|
||||
contexts: [65536, 32768],
|
||||
rank: 2,
|
||||
// Not measured: the 9.3 of the row above scaled by file size.
|
||||
@@ -268,7 +277,8 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
license: 'Apache-2.0',
|
||||
paramsB: 20,
|
||||
bytes: 13_793_441_427,
|
||||
kvBytesPerToken: 24 * KIB,
|
||||
...MEASURED_MEMORY,
|
||||
figures: 'estimated',
|
||||
contexts: [131072, 65536],
|
||||
rank: 3,
|
||||
// No speed figure: its speed is unknown on every chip.
|
||||
@@ -279,13 +289,18 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
label: 'Qwen3.6 35B-A3B',
|
||||
license: 'Apache-2.0',
|
||||
paramsB: 35,
|
||||
bytes: 22_621_314_161,
|
||||
kvBytesPerToken: 20 * KIB,
|
||||
// What a Mac really downloads: an MLX build, 2% above the 22,621,314,161 of the manifest.
|
||||
bytes: 23_105_798_956,
|
||||
...MEASURED_MEMORY,
|
||||
figures: 'measured',
|
||||
contexts: [131072, 65536],
|
||||
rank: 4,
|
||||
// 54.5 tokens per second measured on 400 GB/s (3 billion parameters are active per token).
|
||||
// The MLX build ran faster than this figure predicts on the one Mac we tested (67.7
|
||||
// against 41.8), so on other chips the estimate is on the low side.
|
||||
speedPer100Gbps: 13.6,
|
||||
tested: [],
|
||||
// Run by us with OpenCode on the MacBook Pro (Mac17,13): a four-step task with tool calls.
|
||||
tested: [{ chip: 'Apple M5 Pro', memGb: 48, cli: 'opencode', date: '2026-11-06', tokensPerSecond: 67.7 }],
|
||||
},
|
||||
{
|
||||
id: 'qwen3.8:27b',
|
||||
@@ -293,7 +308,8 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
license: 'Apache-2.0',
|
||||
paramsB: 27.8,
|
||||
bytes: 17_741_871_939,
|
||||
kvBytesPerToken: 64 * KIB,
|
||||
...MEASURED_MEMORY,
|
||||
figures: 'estimated',
|
||||
contexts: [131072, 65536, 32768],
|
||||
rank: 5,
|
||||
// 11.8 tokens per second measured on 400 GB/s.
|
||||
@@ -306,7 +322,8 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
license: 'Apache-2.0',
|
||||
paramsB: 27.8,
|
||||
bytes: 29_978_241_837,
|
||||
kvBytesPerToken: 64 * KIB,
|
||||
...MEASURED_MEMORY,
|
||||
figures: 'estimated',
|
||||
contexts: [262144, 131072],
|
||||
rank: 6,
|
||||
// Not measured: the 2.95 of the row above scaled by file size.
|
||||
@@ -319,7 +336,8 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
license: 'Apache-2.0',
|
||||
paramsB: 122,
|
||||
bytes: 81_370_035_877,
|
||||
kvBytesPerToken: 24 * KIB,
|
||||
...MEASURED_MEMORY,
|
||||
figures: 'estimated',
|
||||
contexts: [131072],
|
||||
rank: 7,
|
||||
// No speed figure: its speed is unknown on every chip.
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* @fileoverview The serialized writer of `custom-model-hosts.json`, the store of the saved
|
||||
* custom model endpoints (src/custom-model-hosts.ts).
|
||||
*
|
||||
* Why it exists: `writeCustomModelHosts()` writes through ONE temp file name per process and
|
||||
* has no queue, and `readCustomModelHosts()` reads a file that does not parse as an empty
|
||||
* list. Two overlapping writers (an endpoint route and the 5-minute discovery sweep) can
|
||||
* leave one body over the tail of a longer one, and the next writer then saves a file that
|
||||
* holds only its own record: every other endpoint and its API key is gone. The same fault
|
||||
* `mutateSettingsFile()` ended for `settings.json`.
|
||||
*
|
||||
* The shape of `mutateSettingsFile()` (src/web/settings-writer.ts):
|
||||
* - Serialized: mutations run one at a time on one promise chain. The check a route makes
|
||||
* (the id is free, the record still exists) runs INSIDE `fn`, in the same step as the write.
|
||||
* - Atomic: each write goes to a temp file with a random name beside the target and is
|
||||
* renamed over it. The file is mode 0600 (it holds API keys).
|
||||
* - Refuses a file it must not trust: only a missing or empty file starts from an empty
|
||||
* list. A file that cannot be read, does not parse or is not an array is left alone and
|
||||
* the write rejects with `CustomModelHostsWriteRefusedError`. The message never repeats
|
||||
* the parser's own text, which can quote an API key.
|
||||
*
|
||||
* EVERY writer goes through it: the four endpoint routes of
|
||||
* src/web/routes/custom-model-routes.ts (create, update, delete, discover-models), the
|
||||
* discovery sweep `refreshAllCustomModelHosts()`, and the local model's connect step. The one
|
||||
* direct writer left is config-backup restore, which must work on a file that does not parse.
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import { getDataDir } from './config/instance.js';
|
||||
import { customModelHostsPath, type CustomModelHost } from './custom-model-hosts.js';
|
||||
import { ApiErrorCode, createErrorResponse, getErrorMessage, type ApiResponse } from './types.js';
|
||||
|
||||
/** A write refused because the existing `custom-model-hosts.json` must not be overwritten. The message is user-facing. */
|
||||
export class CustomModelHostsWriteRefusedError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'CustomModelHostsWriteRefusedError';
|
||||
}
|
||||
}
|
||||
|
||||
/** The list a write starts from. Only a missing or empty file is an empty list; anything else that is not an array is refused. */
|
||||
async function readHostsForWrite(path: string): Promise<CustomModelHost[]> {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await fs.readFile(path, 'utf-8');
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];
|
||||
throw new CustomModelHostsWriteRefusedError(
|
||||
`Cannot read ${path} (${(err as Error).message}), so this change was not saved.`
|
||||
);
|
||||
}
|
||||
// An empty file holds no endpoint to lose.
|
||||
if (raw.trim() === '') return [];
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
parsed = undefined;
|
||||
}
|
||||
if (!Array.isArray(parsed)) {
|
||||
throw new CustomModelHostsWriteRefusedError(
|
||||
`${path} is not a valid JSON list, so this change was not saved (saving would have replaced every other model endpoint in it, with its API key). Fix or delete the file, or restore it from a config backup, then try again.`
|
||||
);
|
||||
}
|
||||
return parsed as CustomModelHost[];
|
||||
}
|
||||
|
||||
async function writeHostsFile(path: string, hosts: CustomModelHost[]): Promise<void> {
|
||||
// Through a symlink: the rename lands on the real file.
|
||||
const target = await fs.realpath(path).catch(() => path);
|
||||
await fs.mkdir(dirname(target), { recursive: true });
|
||||
const tmp = `${target}.${process.pid}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await fs.writeFile(tmp, JSON.stringify(hosts, null, 2), { mode: 0o600 });
|
||||
await fs.rename(tmp, target);
|
||||
} catch (err) {
|
||||
await fs.rm(tmp, { force: true }).catch(() => {});
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
let mutationChain: Promise<unknown> = Promise.resolve();
|
||||
|
||||
/** What a mutation returns: the list to write (absent: write nothing) and what the caller gets back. */
|
||||
export interface CustomModelHostsMutation<T> {
|
||||
/** The whole list to store. Absent: the file is left as it is. */
|
||||
hosts?: CustomModelHost[];
|
||||
/** Handed back to the caller of `mutateCustomModelHosts()`. */
|
||||
result: T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one change to the endpoint store. `fn` receives the current list (a copy it may change)
|
||||
* and returns what to write and what to hand back. Resolves with `result`. A refused or failed
|
||||
* mutation rejects its own caller only; the chain keeps going.
|
||||
*
|
||||
* `configDir` is the folder of the file, as for `readCustomModelHosts()`. Default: the data dir.
|
||||
*/
|
||||
export function mutateCustomModelHosts<T>(
|
||||
fn: (hosts: CustomModelHost[]) => CustomModelHostsMutation<T>,
|
||||
configDir?: string
|
||||
): Promise<T> {
|
||||
const run = mutationChain.then(async () => {
|
||||
// Resolved inside the chain: the data dir is read when the mutation runs, like the file.
|
||||
const path = customModelHostsPath(configDir ?? getDataDir());
|
||||
const current = await readHostsForWrite(path).catch((err: unknown) => {
|
||||
console.warn(`[custom-model] write refused: ${getErrorMessage(err)}`);
|
||||
throw err;
|
||||
});
|
||||
const mutation = fn(current);
|
||||
if (mutation.hosts) await writeHostsFile(path, mutation.hosts);
|
||||
return mutation.result;
|
||||
});
|
||||
mutationChain = run.catch(() => {});
|
||||
return run;
|
||||
}
|
||||
|
||||
/** A refused write answers 409 CONFLICT with the fix; any other failure stays OPERATION_FAILED. Like `settingsWriteErrorResponse()`. */
|
||||
export function customModelHostsWriteErrorResponse(err: unknown): ApiResponse<never> {
|
||||
if (err instanceof CustomModelHostsWriteRefusedError) return createErrorResponse(ApiErrorCode.CONFLICT, err.message);
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
/**
|
||||
* @fileoverview Connecting the installed local model to Codeman, and undoing it: the endpoint
|
||||
* record, the settings flag, and the checks around them.
|
||||
*
|
||||
* These are the ONLY two writes of the local model outside its own folder:
|
||||
* 1. One record in `custom-model-hosts.json`, through `mutateCustomModelHosts()`:
|
||||
* `{ id: 'local-ollama', label: 'This Mac', baseUrl: 'http://127.0.0.1:<port>',
|
||||
* authStyle: 'bearer', models: [<id as /v1/models lists it>], defaultModelId,
|
||||
* defaultContextLength: <the chosen context> }`, validated by `CustomModelHostSchema`
|
||||
* before it is written. No `apiKey`. `defaultContextLength` is what reaches the coding
|
||||
* agent as its context limit, because the runtime's model listing states none.
|
||||
* 2. `customModelEndpointsEnabled: true` in `settings.json`, through `mutateSettingsFile()`.
|
||||
* The value it had before is returned and kept in the state file.
|
||||
*
|
||||
* Rules:
|
||||
* - The id is reserved. A record with it that this feature did not write is never
|
||||
* overwritten: the connect step fails with `endpoint-id-taken`.
|
||||
* - The connection is CLAIMED before it is written: the install job records `connection` in
|
||||
* the state file first (`inspectLocalEndpoint()` tells it what is there and what the flag
|
||||
* is), then calls `connectLocalModel()` with `ours: true`. A state write that fails, or a
|
||||
* server that is killed between the two, therefore never leaves a record of ours that the
|
||||
* state file does not know: the worst case is a claim with nothing behind it, which a
|
||||
* resumed job fills in and Remove undoes.
|
||||
* - Second net: a record with the reserved id that already says exactly what ours would say
|
||||
* (`isSameLocalEndpoint()`) is ours whatever `ours` says. Nobody else can have made it: the
|
||||
* endpoint routes refuse the reserved id.
|
||||
* - Both writes are idempotent, so a resumed job writes them again.
|
||||
* - Undoing removes our record, and switches the flag off again only when this feature
|
||||
* switched it on AND no other endpoint is saved.
|
||||
* - The model's digest is compared again before a session starts and at boot
|
||||
* (`compareModelDigest()`): a model that changed under the same name is not launched.
|
||||
* - The record is MANAGED while the state file records it as ours (`isManagedLocalEndpoint()`):
|
||||
* the endpoint routes then refuse to edit or delete it and the discovery sweep leaves it
|
||||
* alone, so its `models` stays the one model the install job checked.
|
||||
*/
|
||||
|
||||
import { mutateCustomModelHosts } from '../custom-model-hosts-writer.js';
|
||||
import type { CustomModelHost } from '../custom-model-hosts.js';
|
||||
import { getDataDir } from '../config/instance.js';
|
||||
import { readCustomModelHosts } from '../custom-model-hosts.js';
|
||||
import { getErrorMessage, type LocalModelErrorCode } from '../types.js';
|
||||
import { readJsonConfig, SETTINGS_PATH } from '../web/route-helpers.js';
|
||||
import { CustomModelHostSchema } from '../web/schemas.js';
|
||||
import { mutateSettingsFile } from '../web/settings-writer.js';
|
||||
import { readLocalModelState } from './state-store.js';
|
||||
|
||||
/** The key of the settings flag that shows saved endpoints in the Run menu and runs the discovery sweep. */
|
||||
const ENDPOINTS_FLAG = 'customModelEndpointsEnabled';
|
||||
|
||||
/** The id of the endpoint record this feature writes. Reserved: nobody else may use it. */
|
||||
export const LOCAL_MODEL_ENDPOINT_ID = 'local-ollama';
|
||||
/** The label of that record, what the Run menu shows in brackets. */
|
||||
export const LOCAL_MODEL_ENDPOINT_LABEL = 'This Mac';
|
||||
|
||||
/** What the endpoint record is built from. */
|
||||
export interface LocalEndpointInput {
|
||||
/** The runtime's loopback port. */
|
||||
port: number;
|
||||
/** The model id exactly as the runtime's `/v1/models` lists it. */
|
||||
modelId: string;
|
||||
/** The chosen context length in tokens. */
|
||||
context: number;
|
||||
}
|
||||
|
||||
/** The endpoint record of the file header. Pure; the caller validates it with `CustomModelHostSchema`. */
|
||||
export function buildLocalEndpointRecord(input: LocalEndpointInput): CustomModelHost {
|
||||
return {
|
||||
id: LOCAL_MODEL_ENDPOINT_ID,
|
||||
label: LOCAL_MODEL_ENDPOINT_LABEL,
|
||||
baseUrl: `http://127.0.0.1:${input.port}`,
|
||||
authStyle: 'bearer',
|
||||
models: [input.modelId],
|
||||
defaultModelId: input.modelId,
|
||||
defaultContextLength: input.context,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a saved record says exactly what our record for `input` says: the same address, the
|
||||
* one model, its context, no key. What discovery may have added to it (context lengths, a
|
||||
* time stamp) does not count. Pure.
|
||||
*/
|
||||
export function isSameLocalEndpoint(host: CustomModelHost, input: LocalEndpointInput): boolean {
|
||||
const ours = buildLocalEndpointRecord(input);
|
||||
return (
|
||||
host.id === ours.id &&
|
||||
host.label === ours.label &&
|
||||
host.baseUrl === ours.baseUrl &&
|
||||
host.authStyle === ours.authStyle &&
|
||||
host.apiKey === undefined &&
|
||||
Array.isArray(host.models) &&
|
||||
host.models.length === 1 &&
|
||||
host.models[0] === input.modelId &&
|
||||
host.defaultModelId === ours.defaultModelId &&
|
||||
host.defaultContextLength === ours.defaultContextLength
|
||||
);
|
||||
}
|
||||
|
||||
/** What the connect step finds before it claims the connection. */
|
||||
export interface LocalEndpointInspection {
|
||||
/**
|
||||
* The saved record with the reserved id: there is none, it says what ours would say, or it
|
||||
* says something else (somebody else's: `endpoint-id-taken`).
|
||||
*/
|
||||
record: 'absent' | 'same' | 'other';
|
||||
/** `customModelEndpointsEnabled` right now: what the claim keeps as the value before this feature. */
|
||||
flagEnabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks at the endpoint store and the settings flag WITHOUT writing either. The install job
|
||||
* calls it before it claims the connection in the state file. Rejects when the endpoint store
|
||||
* cannot be read; a settings file that cannot be read counts as "the flag is off".
|
||||
*/
|
||||
export async function inspectLocalEndpoint(input: LocalEndpointInput): Promise<LocalEndpointInspection> {
|
||||
const hosts = await readCustomModelHosts(getDataDir());
|
||||
const existing = hosts.find((host) => host.id === LOCAL_MODEL_ENDPOINT_ID);
|
||||
const settings = await readJsonConfig<Record<string, unknown>>(SETTINGS_PATH, 'settings.json', {});
|
||||
return {
|
||||
record: !existing ? 'absent' : isSameLocalEndpoint(existing, input) ? 'same' : 'other',
|
||||
flagEnabled: settings[ENDPOINTS_FLAG] === true,
|
||||
};
|
||||
}
|
||||
|
||||
export interface ConnectLocalModelInput extends LocalEndpointInput {
|
||||
/**
|
||||
* True when the state file already records a connection of ours: an existing record with
|
||||
* our id is then ours and is replaced. False: such a record is somebody else's, unless it
|
||||
* says exactly what ours would say (`isSameLocalEndpoint()`).
|
||||
*/
|
||||
ours: boolean;
|
||||
/**
|
||||
* The flag's value before this feature first switched it on, when the state file already
|
||||
* holds one. It is handed back unchanged, so a second connect cannot overwrite it with `true`.
|
||||
*/
|
||||
flagWasEnabled?: boolean;
|
||||
}
|
||||
|
||||
/** How the connect step ended. */
|
||||
export type ConnectResult =
|
||||
| {
|
||||
ok: true;
|
||||
/** The value `customModelEndpointsEnabled` had before this feature switched it on. */
|
||||
flagWasEnabled: boolean;
|
||||
}
|
||||
| { ok: false; code: Extract<LocalModelErrorCode, 'endpoint-id-taken' | 'connect-failed'>; detail?: string };
|
||||
|
||||
/**
|
||||
* Writes the record and the flag. Idempotent. Never throws: a refused write is `connect-failed`
|
||||
* with its message as `detail`.
|
||||
*
|
||||
* The record goes first, with the "is the id free" check in the same serialized step as the
|
||||
* write, so a record that is somebody else's is found before anything is changed. Should the
|
||||
* flag then fail to save, a record this call ADDED is taken out again: the pair is never left
|
||||
* half done, and a later attempt starts from the same place.
|
||||
*/
|
||||
export async function connectLocalModel(input: ConnectLocalModelInput): Promise<ConnectResult> {
|
||||
const parsed = CustomModelHostSchema.safeParse(buildLocalEndpointRecord(input));
|
||||
if (!parsed.success) {
|
||||
return { ok: false, code: 'connect-failed', detail: `The endpoint record is not valid: ${parsed.error.message}` };
|
||||
}
|
||||
const record: CustomModelHost = parsed.data;
|
||||
|
||||
let outcome: 'added' | 'replaced' | 'taken';
|
||||
try {
|
||||
outcome = await mutateCustomModelHosts<'added' | 'replaced' | 'taken'>((hosts) => {
|
||||
const index = hosts.findIndex((host) => host.id === record.id);
|
||||
if (index === -1) return { hosts: [...hosts, record], result: 'added' };
|
||||
if (!input.ours && !isSameLocalEndpoint(hosts[index], input)) return { result: 'taken' };
|
||||
const next = [...hosts];
|
||||
next[index] = record;
|
||||
return { hosts: next, result: 'replaced' };
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, code: 'connect-failed', detail: getErrorMessage(err) };
|
||||
}
|
||||
if (outcome === 'taken') return { ok: false, code: 'endpoint-id-taken' };
|
||||
|
||||
let flagBefore: boolean;
|
||||
try {
|
||||
const { before } = await mutateSettingsFile((current) =>
|
||||
current[ENDPOINTS_FLAG] === true ? undefined : { ...current, [ENDPOINTS_FLAG]: true }
|
||||
);
|
||||
flagBefore = before[ENDPOINTS_FLAG] === true;
|
||||
} catch (err) {
|
||||
if (outcome === 'added') await removeLocalEndpoint().catch(() => {});
|
||||
return { ok: false, code: 'connect-failed', detail: getErrorMessage(err) };
|
||||
}
|
||||
return { ok: true, flagWasEnabled: input.flagWasEnabled ?? flagBefore };
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts our record back when it is gone, and does nothing when a record with our id exists
|
||||
* (it is never replaced here). For the start of the server while a model is installed: a
|
||||
* config-backup restore can bring back an older endpoint store without our record while the
|
||||
* model, the runtime and the state file stay. The settings flag is NOT touched: a person who
|
||||
* switched it off meant to. Resolves true when the record was added. Never throws.
|
||||
*/
|
||||
export async function ensureLocalEndpoint(input: LocalEndpointInput): Promise<boolean> {
|
||||
const parsed = CustomModelHostSchema.safeParse(buildLocalEndpointRecord(input));
|
||||
if (!parsed.success) return false;
|
||||
const record: CustomModelHost = parsed.data;
|
||||
try {
|
||||
return await mutateCustomModelHosts<boolean>((hosts) =>
|
||||
hosts.some((host) => host.id === record.id) ? { result: false } : { hosts: [...hosts, record], result: true }
|
||||
);
|
||||
} catch {
|
||||
// A store that must not be overwritten stays as it is; a session start then says what is wrong.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes our record out of the store. Resolves with how many OTHER endpoints are saved. */
|
||||
async function removeLocalEndpoint(): Promise<number> {
|
||||
return mutateCustomModelHosts<number>((hosts) => {
|
||||
const others = hosts.filter((host) => host.id !== LOCAL_MODEL_ENDPOINT_ID);
|
||||
return others.length === hosts.length ? { result: others.length } : { hosts: others, result: others.length };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves our record to another port (the answer to "Use another port" once connected). A
|
||||
* missing record is not an error, and a record that is already there is not written again.
|
||||
*/
|
||||
export async function moveLocalEndpoint(port: number): Promise<void> {
|
||||
const baseUrl = `http://127.0.0.1:${port}`;
|
||||
await mutateCustomModelHosts<void>((hosts) => {
|
||||
const index = hosts.findIndex((host) => host.id === LOCAL_MODEL_ENDPOINT_ID);
|
||||
if (index === -1 || hosts[index].baseUrl === baseUrl) return { result: undefined };
|
||||
const next = [...hosts];
|
||||
next[index] = { ...next[index], baseUrl };
|
||||
return { hosts: next, result: undefined };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes our record, and restores the settings flag when this feature switched it on
|
||||
* (`flagWasEnabled` is false) and no other endpoint is left. Idempotent.
|
||||
*/
|
||||
export async function disconnectLocalModel(input: { flagWasEnabled: boolean }): Promise<void> {
|
||||
const othersLeft = await removeLocalEndpoint();
|
||||
if (input.flagWasEnabled || othersLeft > 0) return;
|
||||
await mutateSettingsFile((current) =>
|
||||
current[ENDPOINTS_FLAG] === true ? { ...current, [ENDPOINTS_FLAG]: false } : undefined
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether `id` is the reserved endpoint id. For the endpoint routes and the discovery sweep, which leave that record alone. */
|
||||
export function isLocalModelEndpointId(id: string): boolean {
|
||||
return id === LOCAL_MODEL_ENDPOINT_ID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the saved endpoint `id` is the record THIS feature wrote and still owns: the id is
|
||||
* the reserved one and the state file records a connection under it. A record with the
|
||||
* reserved id that somebody made by hand (before this feature, or while nothing is installed)
|
||||
* is not managed, so its owner can still edit and delete it. Never throws.
|
||||
*/
|
||||
export async function isManagedLocalEndpoint(id: string): Promise<boolean> {
|
||||
if (!isLocalModelEndpointId(id)) return false;
|
||||
const state = await readLocalModelState();
|
||||
return state.connection?.endpointId === id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The names of the live sessions that use the endpoint `endpointId`, in the order given.
|
||||
* Pure. What `DELETE /api/local-model` answers its 409 with.
|
||||
*/
|
||||
export function sessionNamesUsingEndpoint(
|
||||
sessions: Iterable<{ name: string; customModel?: { endpointId: string } }>,
|
||||
endpointId: string = LOCAL_MODEL_ENDPOINT_ID
|
||||
): string[] {
|
||||
const names: string[] = [];
|
||||
for (const session of sessions) {
|
||||
if (session.customModel?.endpointId === endpointId) names.push(session.name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares the digest stored at install time with the one the runtime reports now. Pure.
|
||||
* - `same`: launch.
|
||||
* - `changed`: refuse (`model-changed`): the name now stands for other weights or another template.
|
||||
* - `unknown`: one of the two is absent (the runtime does not answer, the model is gone).
|
||||
* The caller refuses as well, with the reason it knows.
|
||||
*/
|
||||
export function compareModelDigest(
|
||||
stored: string | undefined,
|
||||
current: string | undefined
|
||||
): 'same' | 'changed' | 'unknown' {
|
||||
const a = normalizeDigest(stored);
|
||||
const b = normalizeDigest(current);
|
||||
if (!a || !b) return 'unknown';
|
||||
return a === b ? 'same' : 'changed';
|
||||
}
|
||||
|
||||
/** A digest as it is compared: lowercase hex, without the `sha256:` some listings put in front. */
|
||||
function normalizeDigest(digest: string | undefined): string | undefined {
|
||||
if (typeof digest !== 'string') return undefined;
|
||||
const hex = digest
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^sha256:/, '');
|
||||
return hex === '' ? undefined : hex;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* @fileoverview Whether this Mac has the developer tools a coding agent calls (git, Python).
|
||||
*
|
||||
* Why it exists: on a Mac without Xcode or the Command Line Tools, `git` and `python3` are
|
||||
* stubs that open macOS's "install the command line developer tools" window. A coding agent
|
||||
* runs both, so the install window says one honest sentence when the tools are missing
|
||||
* (`LOCAL_MODEL_INSTALL_LABELS.developerToolsMissing`).
|
||||
*
|
||||
* Rules:
|
||||
* - The ONLY command ever run is `/usr/bin/xcode-select -p`, bounded by a timeout. Never
|
||||
* `git`, `python3`, `xcrun` or anything else that would open that window itself.
|
||||
* - macOS only. Anywhere else, and when the command does not answer in time, the answer is
|
||||
* `unknown`, and nothing is said.
|
||||
* - Never throws. The answer is cached for a short while, so a window that polls once a
|
||||
* second does not spawn once a second. Only `present` and `missing` are cached: an
|
||||
* `unknown` is asked again, because it says the check itself did not work.
|
||||
* - Under vitest the default `run` spawns nothing and answers "did not start", so a test
|
||||
* that wants an answer injects its own.
|
||||
*/
|
||||
|
||||
import { execFile } from 'node:child_process';
|
||||
import type { LocalModelDeveloperTools } from '../types.js';
|
||||
|
||||
/** How long `/usr/bin/xcode-select -p` may take. */
|
||||
export const DEVELOPER_TOOLS_TIMEOUT_MS = 2_000;
|
||||
|
||||
/** How long an answer is reused. Installing the tools takes minutes, so a minute of staleness is not seen. */
|
||||
const DEVELOPER_TOOLS_CACHE_MS = 60_000;
|
||||
|
||||
/** The one command this module runs. It prints the active developer directory and exits 0, or exits with an error when there is none. */
|
||||
const XCODE_SELECT = '/usr/bin/xcode-select';
|
||||
|
||||
/** What the check calls. Each member defaults to the real thing; a test injects its own. */
|
||||
export interface DeveloperToolsDeps {
|
||||
/** Default `process.platform`. */
|
||||
platform: string;
|
||||
/** Runs `file` with `args` and resolves with its exit code (`null` when it timed out or could not be started). */
|
||||
run: (file: string, args: readonly string[], timeoutMs: number) => Promise<number | null>;
|
||||
}
|
||||
|
||||
/** The default `run`: one bounded `execFile`, no shell. Spawns nothing under vitest. */
|
||||
function runBounded(file: string, args: readonly string[], timeoutMs: number): Promise<number | null> {
|
||||
return new Promise((resolve) => {
|
||||
if (process.env.VITEST) return resolve(null);
|
||||
try {
|
||||
execFile(file, [...args], { timeout: timeoutMs }, (err) => {
|
||||
if (!err) return resolve(0);
|
||||
// A number is the exit code of a command that ran. Anything else (ENOENT, a timeout
|
||||
// that killed it) is "it did not answer".
|
||||
const code = (err as { code?: unknown }).code;
|
||||
resolve(typeof code === 'number' && !(err as { killed?: boolean }).killed ? code : null);
|
||||
});
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function check(deps: DeveloperToolsDeps): Promise<LocalModelDeveloperTools> {
|
||||
if (deps.platform !== 'darwin') return 'unknown';
|
||||
let code: number | null;
|
||||
try {
|
||||
code = await deps.run(XCODE_SELECT, ['-p'], DEVELOPER_TOOLS_TIMEOUT_MS);
|
||||
} catch {
|
||||
code = null;
|
||||
}
|
||||
if (code === null || !Number.isInteger(code)) return 'unknown';
|
||||
return code === 0 ? 'present' : 'missing';
|
||||
}
|
||||
|
||||
/**
|
||||
* A check that remembers its answer for a minute and shares one run among callers that ask at
|
||||
* the same time. `now` is the clock of the cache; a test injects its own.
|
||||
*/
|
||||
export function createDeveloperToolsCheck(
|
||||
deps: Partial<DeveloperToolsDeps> & { now?: () => number } = {}
|
||||
): () => Promise<LocalModelDeveloperTools> {
|
||||
const resolved: DeveloperToolsDeps = {
|
||||
platform: deps.platform ?? process.platform,
|
||||
run: deps.run ?? runBounded,
|
||||
};
|
||||
const now = deps.now ?? Date.now;
|
||||
let cached: { answer: LocalModelDeveloperTools; at: number } | undefined;
|
||||
let inFlight: Promise<LocalModelDeveloperTools> | undefined;
|
||||
return () => {
|
||||
if (cached && now() - cached.at < DEVELOPER_TOOLS_CACHE_MS) return Promise.resolve(cached.answer);
|
||||
inFlight ??= check(resolved)
|
||||
.then((answer) => {
|
||||
if (answer !== 'unknown') cached = { answer, at: now() };
|
||||
return answer;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlight = undefined;
|
||||
});
|
||||
return inFlight;
|
||||
};
|
||||
}
|
||||
|
||||
/** The check of this server's own Mac. */
|
||||
let shared = createDeveloperToolsCheck();
|
||||
|
||||
/** Forgets the cached answer of this server's own Mac. For tests. */
|
||||
export function resetDeveloperToolsCache(): void {
|
||||
shared = createDeveloperToolsCheck();
|
||||
}
|
||||
|
||||
/**
|
||||
* `present` when `/usr/bin/xcode-select -p` exits 0, `missing` when it exits with anything
|
||||
* else, `unknown` otherwise. Without `deps` it is the cached check of this server's Mac; with
|
||||
* a platform or a runner of the caller's it asks once and remembers nothing.
|
||||
*/
|
||||
export async function checkDeveloperTools(deps: Partial<DeveloperToolsDeps> = {}): Promise<LocalModelDeveloperTools> {
|
||||
if (deps.platform !== undefined || deps.run !== undefined) {
|
||||
return check({ platform: deps.platform ?? process.platform, run: deps.run ?? runBounded });
|
||||
}
|
||||
return shared();
|
||||
}
|
||||
@@ -7,12 +7,12 @@
|
||||
* `budgetGb`, and the size slots of a `LocalModelMessage`). Nothing else may turn bytes into a
|
||||
* size for display, the browser included: it prints the text it was sent.
|
||||
*
|
||||
* GiB and MiB exist only for the budget math (reserves, the wired limit, the prompt cache) and
|
||||
* never reach a person, with one exception: `memClassGb()`, the memory size a Mac is sold as,
|
||||
* is how the card names the installed memory ("48 GB memory", what About This Mac shows). It
|
||||
* is a name of the machine, not a computed size: `formatGb()` of the same bytes reads 51.5,
|
||||
* which no owner recognises. Every computed size (need, budget, download, free disk) is
|
||||
* `formatGb()`.
|
||||
* GiB and MiB exist only for the budget math (reserves, the wired limit, the device total the
|
||||
* runtime reports) and never reach a person, with one exception: `memClassGb()`, the memory
|
||||
* size a Mac is sold as, is how the card names the installed memory ("48 GB memory", what
|
||||
* About This Mac shows). It is a name of the machine, not a computed size: `formatGb()` of the
|
||||
* same bytes reads 51.5, which no owner recognises. Every computed size (need, budget,
|
||||
* download, free disk) is `formatGb()`.
|
||||
*
|
||||
* Pure: no IO, no state.
|
||||
*/
|
||||
|
||||
@@ -10,8 +10,11 @@
|
||||
* - reports `label` from the registry entry and `installed` from the same probe the page
|
||||
* render and `GET /api/clis` use (`utils/cli-installed-probes.ts`), asked once per build;
|
||||
* - reports `installable` only for a STOCK CLI that is not installed and whose install
|
||||
* command for this platform needs no administrator rights (`installCommandNeedsAdmin()`).
|
||||
* Stock only, because the install runner never executes a custom entry's command;
|
||||
* command for this platform needs no administrator rights (`installCommandNeedsAdmin()`),
|
||||
* and then carries that command as `installCommand`, so the consent screen can print the
|
||||
* literal text. The command is the COMPILED stock one (`stockInstallCommand()`), never the
|
||||
* one a `clis.json` override supplies: it is exactly what the install job would run, and
|
||||
* an override file must not be able to change that;
|
||||
* - supplies `acceptsModelId` (`cliAcceptsCustomModelId()`), the test a custom model launch
|
||||
* applies to the model id before anything is written.
|
||||
*
|
||||
@@ -33,7 +36,8 @@
|
||||
|
||||
import type { CliEntry } from '../config/cli-registry/types.js';
|
||||
import { matchesPattern } from '../config/cli-registry/patterns.js';
|
||||
import { getCli, resolveInstallCommandForPlatform } from '../config/cli-registry/registry.js';
|
||||
import { stockInstallCommand } from '../cli-install-runner.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { buildCustomModelInjection, type CustomModelEndpoint } from '../custom-model-injection.js';
|
||||
import { isCliEntryInstalled, probeStockCliAvailability } from '../utils/cli-installed-probes.js';
|
||||
import { getErrorMessage, type HarnessFact, type LocalModelCatalog } from '../types.js';
|
||||
@@ -48,7 +52,11 @@ export interface HarnessFactsDeps {
|
||||
* `installed` passes its own.
|
||||
*/
|
||||
probeInstalled: () => Promise<(entry: CliEntry) => boolean>;
|
||||
/** The install command the registry holds for this platform. Read as text, never run. */
|
||||
/**
|
||||
* The install command the install job would run for this CLI on this platform: the compiled
|
||||
* stock command, `undefined` for a CLI that is not stock or has none here. Read as text,
|
||||
* never run.
|
||||
*/
|
||||
installCommandFor: (entry: CliEntry) => string | undefined;
|
||||
}
|
||||
|
||||
@@ -58,7 +66,7 @@ export const defaultHarnessFactsDeps: HarnessFactsDeps = {
|
||||
const stockAvailability = await probeStockCliAvailability();
|
||||
return (entry) => isCliEntryInstalled(entry, stockAvailability);
|
||||
},
|
||||
installCommandFor: resolveInstallCommandForPlatform,
|
||||
installCommandFor: (entry) => stockInstallCommand(entry.id as string),
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -147,17 +155,20 @@ export async function buildHarnessFacts(
|
||||
console.warn(`[local-model] Probing ${entry.label} failed, reading it as not installed: ${getErrorMessage(err)}`);
|
||||
}
|
||||
|
||||
let installable = false;
|
||||
let installCommand: string | undefined;
|
||||
if (!installed && entry.stock) {
|
||||
const command = resolved.installCommandFor(entry);
|
||||
installable = command !== undefined && command.trim() !== '' && !installCommandNeedsAdmin(command);
|
||||
if (command !== undefined && command.trim() !== '' && !installCommandNeedsAdmin(command)) {
|
||||
installCommand = command;
|
||||
}
|
||||
}
|
||||
|
||||
facts.push({
|
||||
cli: row.cli,
|
||||
label: entry.label,
|
||||
installed,
|
||||
installable,
|
||||
installable: installCommand !== undefined,
|
||||
...(installCommand !== undefined ? { installCommand } : {}),
|
||||
acceptsModelId: (modelId: string) => cliAcceptsCustomModelId(entry, modelId),
|
||||
});
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,810 @@
|
||||
/**
|
||||
* @fileoverview The HTTP client of the model runtime: what Codeman asks its own runtime on
|
||||
* the loopback port, and the pure functions that read the answers.
|
||||
*
|
||||
* What it asks:
|
||||
* - `GET /api/version`, `GET /api/tags`, `GET /api/ps`, `GET /v1/models`, `DELETE /api/delete`.
|
||||
* - `POST /api/pull` with `stream: true`. The answer is one JSON object per line, and a
|
||||
* 23 GB pull sends about 1.4 million of them, so the stream is parsed INCREMENTALLY
|
||||
* (`createPullParser()`, pure): only the unfinished last line and the running totals are
|
||||
* kept, never the body. Aborting the request stops the download; pulling again continues
|
||||
* it. An error line or a stream that ends without `success` is retried, at most
|
||||
* `PULL_RETRIES` times.
|
||||
* - The check after the pull (`verifyModel()`), in this order: one tiny chat with
|
||||
* `reasoning_effort: "none"` (it loads the model), then `GET /api/ps` must show the whole
|
||||
* model on the GPU (`size_vram` equal to `size`) at the chosen context
|
||||
* (`judgeLoaded()`, pure), then one tool probe on `/v1/chat/completions` with a `tools`
|
||||
* array, `reasoning_effort: "none"` and `max_tokens` of `TOOL_PROBE_MAX_TOKENS`, which
|
||||
* passes on a tool call whose arguments parse as JSON (`judgeToolProbe()`, pure).
|
||||
*
|
||||
* Rules:
|
||||
* - Nothing here throws for something a runtime can answer: every outcome is a result with
|
||||
* the job's error code. An abort signal is the result `cancelled`.
|
||||
* - Every request is bounded: a listing by seconds, the two probes by minutes (the first
|
||||
* chat loads the model). Only the pull has no deadline of its own, because its length is
|
||||
* the download; it ends with the stream, and the caller's signal cancels it.
|
||||
* - The runtime does not enforce the context length (a prompt of 167,012 tokens was accepted
|
||||
* at 131072), so nothing here relies on it to.
|
||||
* - Every function takes its `fetch` from the target, so a test passes the fake runtime's
|
||||
* address and spawns nothing. The target is always a loopback address the caller built from
|
||||
* the stored port: no function here takes a URL from a file or a request.
|
||||
*/
|
||||
|
||||
import type { LocalModelErrorCode } from '../types.js';
|
||||
import { formatGb } from './format.js';
|
||||
|
||||
/** How often a pull that ended on an error line or a cut stream is started again. */
|
||||
export const PULL_RETRIES = 5;
|
||||
/** `max_tokens` of the tool probe. */
|
||||
export const TOOL_PROBE_MAX_TOKENS = 1024;
|
||||
|
||||
/** How long `/api/version` may take: it is asked while a runtime starts, many times. */
|
||||
const VERSION_TIMEOUT_MS = 2_000;
|
||||
/** How long a listing or a delete may take. */
|
||||
const LIST_TIMEOUT_MS = 10_000;
|
||||
/** How long the chat that loads the model may take. A 23 GB model loaded in 5.9 s on the test Mac; a cold disk is slower. */
|
||||
const CHAT_PROBE_TIMEOUT_MS = 180_000;
|
||||
/** How long the tool probe may take. The model is loaded by then. */
|
||||
const TOOL_PROBE_TIMEOUT_MS = 120_000;
|
||||
/** `max_tokens` of the chat that loads the model: its answer is not read. */
|
||||
const CHAT_PROBE_MAX_TOKENS = 16;
|
||||
/** The least time between two progress reports of a pull. */
|
||||
const PULL_PROGRESS_INTERVAL_MS = 250;
|
||||
/** The window the download speed is averaged over. */
|
||||
const PULL_SPEED_WINDOW_MS = 5_000;
|
||||
/** The first wait before a pull is started again; it doubles with every retry. */
|
||||
const PULL_RETRY_DELAY_MS = 1_000;
|
||||
/** A pull line longer than this is not a pull line. It is dropped, so a stream without line breaks cannot grow the buffer. */
|
||||
const MAX_PULL_LINE_CHARS = 1024 * 1024;
|
||||
/** More layers than any model has. Lines for further ones are counted and not added up, so the layer table cannot grow without bound. */
|
||||
const MAX_PULL_LAYERS = 1024;
|
||||
/** How much of a runtime's error text is kept as `detail`. */
|
||||
const MAX_DETAIL_CHARS = 400;
|
||||
|
||||
/** Which runtime to ask. */
|
||||
export interface OllamaTarget {
|
||||
/** `http://127.0.0.1:<port>`, without a trailing slash. */
|
||||
baseUrl: string;
|
||||
/** Default: the global `fetch`. */
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
// ---------- Plumbing ----------
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value !== '' ? value : undefined;
|
||||
}
|
||||
|
||||
/** A byte count or a token count as the runtime reports it: a finite number that is not negative. */
|
||||
function asCount(value: unknown): number | undefined {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
|
||||
}
|
||||
|
||||
function clip(text: string): string {
|
||||
const trimmed = text.trim();
|
||||
return trimmed.length > MAX_DETAIL_CHARS ? `${trimmed.slice(0, MAX_DETAIL_CHARS)}...` : trimmed;
|
||||
}
|
||||
|
||||
function errorText(err: unknown): string {
|
||||
if (err instanceof Error) {
|
||||
// undici wraps the reason ("fetch failed") and keeps the useful part in `cause`.
|
||||
const cause = (err as { cause?: unknown }).cause;
|
||||
return clip(cause instanceof Error && cause.message ? `${err.message}: ${cause.message}` : err.message);
|
||||
}
|
||||
return clip(String(err));
|
||||
}
|
||||
|
||||
/** The error text of a runtime answer: `{"error":"..."}` (its own routes) or `{"error":{"message":"..."}}` (the OpenAI routes). */
|
||||
function errorOfBody(body: unknown): string | undefined {
|
||||
if (!isRecord(body)) return undefined;
|
||||
const { error } = body;
|
||||
if (typeof error === 'string') return asString(error);
|
||||
if (isRecord(error)) return asString(error.message);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The caller's signal joined with a deadline. */
|
||||
function bounded(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
|
||||
const deadline = AbortSignal.timeout(timeoutMs);
|
||||
return signal ? AbortSignal.any([signal, deadline]) : deadline;
|
||||
}
|
||||
|
||||
/** An answer of the runtime: its status and its body as JSON (`undefined` when it is not JSON). */
|
||||
interface Answer {
|
||||
status: number;
|
||||
body: unknown;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One bounded request. `undefined` when nothing answered (refused, timed out, aborted): the
|
||||
* caller looks at its own signal to tell an abort from the rest.
|
||||
*/
|
||||
async function ask(
|
||||
target: OllamaTarget,
|
||||
path: string,
|
||||
init: { method?: string; json?: unknown },
|
||||
timeoutMs: number,
|
||||
signal?: AbortSignal
|
||||
): Promise<Answer | undefined> {
|
||||
const fetchFn = target.fetch ?? fetch;
|
||||
try {
|
||||
const res = await fetchFn(`${target.baseUrl}${path}`, {
|
||||
method: init.method ?? 'GET',
|
||||
...(init.json !== undefined
|
||||
? { headers: { 'content-type': 'application/json' }, body: JSON.stringify(init.json) }
|
||||
: {}),
|
||||
signal: bounded(signal, timeoutMs),
|
||||
});
|
||||
const text = await res.text();
|
||||
let body: unknown;
|
||||
try {
|
||||
body = text === '' ? undefined : JSON.parse(text);
|
||||
} catch {
|
||||
body = undefined;
|
||||
}
|
||||
return { status: res.status, body, text };
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** A digest as it is stored and compared: lowercase hex without the `sha256:` prefix. */
|
||||
function normalizeDigest(value: unknown): string {
|
||||
return typeof value === 'string'
|
||||
? value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^sha256:/, '')
|
||||
: '';
|
||||
}
|
||||
|
||||
// ---------- Listings ----------
|
||||
|
||||
/** One model of `GET /api/tags`: what is on disk. */
|
||||
export interface OllamaTagModel {
|
||||
/** `name:tag`. */
|
||||
name: string;
|
||||
/** Size on disk in bytes. */
|
||||
size: number;
|
||||
/** The model's digest, lowercase hex without a prefix. What is stored and compared again before a session starts. */
|
||||
digest: string;
|
||||
/** `details.format` ('safetensors' for an MLX build, 'gguf'). */
|
||||
format?: string;
|
||||
/** `details.runner` ('mlx', 'ggml'). */
|
||||
runner?: string;
|
||||
/** `capabilities` ('completion', 'tools', 'thinking', 'vision'). */
|
||||
capabilities?: string[];
|
||||
}
|
||||
|
||||
/** One model of `GET /api/ps`: what is loaded. */
|
||||
export interface OllamaPsModel {
|
||||
name: string;
|
||||
/** Memory the loaded model takes, in bytes. */
|
||||
size: number;
|
||||
/** The part of `size` that is on the GPU. Equal to `size` when all of it is. */
|
||||
sizeVram: number;
|
||||
/** The context length the model was loaded with. */
|
||||
contextLength: number;
|
||||
digest?: string;
|
||||
}
|
||||
|
||||
/** The `models` array of a listing, or an empty one. */
|
||||
function modelsOf(answer: Answer | undefined): Record<string, unknown>[] {
|
||||
if (!answer || answer.status !== 200 || !isRecord(answer.body)) return [];
|
||||
const { models } = answer.body;
|
||||
return Array.isArray(models) ? models.filter(isRecord) : [];
|
||||
}
|
||||
|
||||
/** The runtime's version ('0.40.15'), or `undefined` when nothing answers there or the answer is not a runtime's. */
|
||||
export async function getRuntimeVersion(target: OllamaTarget, signal?: AbortSignal): Promise<string | undefined> {
|
||||
const answer = await ask(target, '/api/version', {}, VERSION_TIMEOUT_MS, signal);
|
||||
if (!answer || answer.status !== 200 || !isRecord(answer.body)) return undefined;
|
||||
return asString(answer.body.version);
|
||||
}
|
||||
|
||||
/** The models on disk. An empty list when the runtime has none or does not answer. */
|
||||
export async function listTags(target: OllamaTarget, signal?: AbortSignal): Promise<OllamaTagModel[]> {
|
||||
const listed: OllamaTagModel[] = [];
|
||||
for (const row of modelsOf(await ask(target, '/api/tags', {}, LIST_TIMEOUT_MS, signal))) {
|
||||
const name = asString(row.name) ?? asString(row.model);
|
||||
if (!name) continue;
|
||||
const details = isRecord(row.details) ? row.details : {};
|
||||
const format = asString(details.format);
|
||||
const runner = asString(details.runner) ?? asString(row.runner);
|
||||
const capabilities = Array.isArray(row.capabilities)
|
||||
? row.capabilities.filter((entry): entry is string => typeof entry === 'string')
|
||||
: undefined;
|
||||
listed.push({
|
||||
name,
|
||||
size: asCount(row.size) ?? 0,
|
||||
digest: normalizeDigest(row.digest),
|
||||
...(format ? { format } : {}),
|
||||
...(runner ? { runner } : {}),
|
||||
...(capabilities ? { capabilities } : {}),
|
||||
});
|
||||
}
|
||||
return listed;
|
||||
}
|
||||
|
||||
/** The models loaded right now. An empty list when none is or the runtime does not answer. */
|
||||
export async function listRunning(target: OllamaTarget, signal?: AbortSignal): Promise<OllamaPsModel[]> {
|
||||
const listed: OllamaPsModel[] = [];
|
||||
for (const row of modelsOf(await ask(target, '/api/ps', {}, LIST_TIMEOUT_MS, signal))) {
|
||||
const name = asString(row.name) ?? asString(row.model);
|
||||
if (!name) continue;
|
||||
const digest = normalizeDigest(row.digest);
|
||||
listed.push({
|
||||
name,
|
||||
size: asCount(row.size) ?? 0,
|
||||
sizeVram: asCount(row.size_vram) ?? 0,
|
||||
contextLength: asCount(row.context_length) ?? 0,
|
||||
...(digest ? { digest } : {}),
|
||||
});
|
||||
}
|
||||
return listed;
|
||||
}
|
||||
|
||||
/** The model ids `GET /v1/models` lists, exactly as listed (the runtime answers `data: null` for none). */
|
||||
export async function listOpenAiModels(target: OllamaTarget, signal?: AbortSignal): Promise<string[]> {
|
||||
const answer = await ask(target, '/v1/models', {}, LIST_TIMEOUT_MS, signal);
|
||||
if (!answer || answer.status !== 200 || !isRecord(answer.body)) return [];
|
||||
const { data } = answer.body;
|
||||
if (!Array.isArray(data)) return [];
|
||||
return data.flatMap((row) => (isRecord(row) && typeof row.id === 'string' && row.id !== '' ? [row.id] : []));
|
||||
}
|
||||
|
||||
/** The digest `GET /api/tags` reports for `modelId`, or `undefined` when the model is not on disk. */
|
||||
export async function readModelDigest(
|
||||
target: OllamaTarget,
|
||||
modelId: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<string | undefined> {
|
||||
const found = (await listTags(target, signal)).find((model) => model.name === modelId);
|
||||
return found && found.digest !== '' ? found.digest : undefined;
|
||||
}
|
||||
|
||||
/** Deletes a model from the runtime's store. True when it is gone afterwards (also when it never was there). */
|
||||
export async function deleteModel(target: OllamaTarget, modelId: string, signal?: AbortSignal): Promise<boolean> {
|
||||
const answer = await ask(
|
||||
target,
|
||||
'/api/delete',
|
||||
{ method: 'DELETE', json: { model: modelId } },
|
||||
LIST_TIMEOUT_MS,
|
||||
signal
|
||||
);
|
||||
// 404 is the runtime's answer for a model it does not have.
|
||||
return answer !== undefined && (answer.status === 200 || answer.status === 404);
|
||||
}
|
||||
|
||||
// ---------- Pull ----------
|
||||
|
||||
/** What the pull's lines add up to so far. */
|
||||
export interface PullSnapshot {
|
||||
/** Sum of the last `completed` of every layer seen. */
|
||||
completedBytes: number;
|
||||
/** Sum of the `total` of every layer seen. Grows while new layers appear; 0 before the first. */
|
||||
totalBytes: number;
|
||||
/** The `status` text of the last line that had one ('pulling manifest', 'writing manifest'). */
|
||||
status?: string;
|
||||
/** A line `{"status":"success"}` was seen. */
|
||||
succeeded: boolean;
|
||||
/** The text of the first `{"error":"..."}` line. */
|
||||
error?: string;
|
||||
/** How many complete lines were parsed. */
|
||||
lines: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a pull stream piece by piece. It keeps the unfinished last line and the totals per
|
||||
* layer, never the lines themselves, so its memory does not grow with the stream.
|
||||
*/
|
||||
export interface PullParser {
|
||||
/** Feed the next piece of the body. A line may be split anywhere across pieces, a multi-byte character too. */
|
||||
push(chunk: string | Uint8Array): void;
|
||||
/** The body ended: reads a last line that had no line break. */
|
||||
end(): void;
|
||||
snapshot(): PullSnapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* A parser for one pull stream. Pure: no IO, no clock. Lines it understands (both real):
|
||||
*
|
||||
* - an MLX build: `{"status":"pulling model","digest":"sha256:model","total":23105798956,"completed":N}`
|
||||
* - a GGUF build, one layer after the other:
|
||||
* `{"status":"pulling c5396e06af29","digest":"sha256:c539...","total":397807936,"completed":N}`
|
||||
* (`completed` is absent until the layer's first bytes arrived)
|
||||
* - `{"status":"pulling manifest"}`, `{"status":"verifying sha256 digest"}`,
|
||||
* `{"status":"writing manifest"}`, `{"status":"success"}`
|
||||
* - `{"error":"max retries exceeded: local error: tls: bad record MAC"}`
|
||||
*
|
||||
* A line that is not JSON is skipped and still counted. A blank line is not a line.
|
||||
*/
|
||||
export function createPullParser(): PullParser {
|
||||
const decoder = new TextDecoder();
|
||||
// One entry per layer: what the layer's last line said. A model has a handful of layers.
|
||||
const layers = new Map<string, { total: number; completed: number }>();
|
||||
let pending = '';
|
||||
// True while a line longer than the limit is being skipped up to its line break.
|
||||
let skipping = false;
|
||||
let status: string | undefined;
|
||||
let succeeded = false;
|
||||
let error: string | undefined;
|
||||
let lines = 0;
|
||||
|
||||
function line(text: string): void {
|
||||
const trimmed = text.trim();
|
||||
if (trimmed === '') return;
|
||||
lines += 1;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(trimmed);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!isRecord(parsed)) return;
|
||||
const failure = errorOfBody(parsed);
|
||||
if (failure !== undefined) {
|
||||
error ??= clip(failure);
|
||||
return;
|
||||
}
|
||||
const lineStatus = asString(parsed.status);
|
||||
if (lineStatus !== undefined) {
|
||||
status = lineStatus;
|
||||
if (lineStatus === 'success') succeeded = true;
|
||||
}
|
||||
const total = asCount(parsed.total);
|
||||
if (total === undefined) return;
|
||||
// A layer is named by its digest; a line without one by its status text.
|
||||
const key = asString(parsed.digest) ?? lineStatus;
|
||||
if (key === undefined) return;
|
||||
const known = layers.get(key);
|
||||
if (!known && layers.size >= MAX_PULL_LAYERS) return;
|
||||
// `completed` is absent until the layer's first bytes arrived: what was seen before stays.
|
||||
const completed = asCount(parsed.completed) ?? known?.completed ?? 0;
|
||||
layers.set(key, { total, completed: Math.min(completed, total) });
|
||||
}
|
||||
|
||||
function feed(text: string): void {
|
||||
let rest = text;
|
||||
for (;;) {
|
||||
const breakAt = rest.indexOf('\n');
|
||||
if (breakAt < 0) break;
|
||||
const head = rest.slice(0, breakAt);
|
||||
rest = rest.slice(breakAt + 1);
|
||||
if (skipping) {
|
||||
// The end of the line that was too long: it was counted when it was dropped.
|
||||
skipping = false;
|
||||
} else {
|
||||
line(pending + head);
|
||||
}
|
||||
pending = '';
|
||||
}
|
||||
if (skipping) return;
|
||||
pending += rest;
|
||||
if (pending.length > MAX_PULL_LINE_CHARS) {
|
||||
pending = '';
|
||||
skipping = true;
|
||||
lines += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
push(chunk) {
|
||||
feed(typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true }));
|
||||
},
|
||||
end() {
|
||||
feed(decoder.decode());
|
||||
if (!skipping && pending !== '') line(pending);
|
||||
pending = '';
|
||||
skipping = false;
|
||||
},
|
||||
snapshot() {
|
||||
let completedBytes = 0;
|
||||
let totalBytes = 0;
|
||||
for (const layer of layers.values()) {
|
||||
completedBytes += layer.completed;
|
||||
totalBytes += layer.total;
|
||||
}
|
||||
return {
|
||||
completedBytes,
|
||||
totalBytes,
|
||||
...(status !== undefined ? { status } : {}),
|
||||
succeeded,
|
||||
...(error !== undefined ? { error } : {}),
|
||||
lines,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** How far a pull is, for the caller's progress display. */
|
||||
export interface PullProgress {
|
||||
completedBytes: number;
|
||||
totalBytes: number;
|
||||
/** Over the last few seconds. Absent until it can be told. */
|
||||
bytesPerSecond?: number;
|
||||
}
|
||||
|
||||
export interface PullOptions {
|
||||
/** Aborts the request, which stops the download. The result is `cancelled`. */
|
||||
signal?: AbortSignal;
|
||||
/** Called at most a few times a second, and once more when the pull ends. */
|
||||
onProgress?: (progress: PullProgress) => void;
|
||||
/** Default `PULL_RETRIES`. */
|
||||
retries?: number;
|
||||
/** Waits between retries. A test injects its own. */
|
||||
sleep?: (ms: number) => Promise<void>;
|
||||
/** The clock of the speed figure, in milliseconds. A test injects its own. */
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
/** How a pull ended. */
|
||||
export type PullResult =
|
||||
| {
|
||||
ok: true;
|
||||
/** The pull's own total: what every size shown for the model comes from once it is known. */
|
||||
totalBytes: number;
|
||||
}
|
||||
| {
|
||||
ok: false;
|
||||
code: Extract<LocalModelErrorCode, 'pull-failed' | 'model-not-found' | 'disk-full'>;
|
||||
/** The runtime's last error text. */
|
||||
detail?: string;
|
||||
}
|
||||
| { ok: false; code: 'cancelled' };
|
||||
|
||||
/** How one request of a pull ended. */
|
||||
type PullAttempt =
|
||||
| { kind: 'success'; totalBytes: number }
|
||||
| { kind: 'cancelled' }
|
||||
| { kind: 'fatal'; code: 'model-not-found' | 'disk-full'; detail: string }
|
||||
| { kind: 'retry'; detail: string };
|
||||
|
||||
/**
|
||||
* What an error text of the runtime means for the pull. A model the registry does not have and
|
||||
* a full disk do not get better by asking again; everything else (a damaged download, a
|
||||
* dropped connection) may.
|
||||
*/
|
||||
function classifyPullError(text: string): PullAttempt {
|
||||
const detail = clip(text);
|
||||
if (/file does not exist|manifest unknown|manifest\b.*\bnot found|model\b.*\bnot found/i.test(text)) {
|
||||
return { kind: 'fatal', code: 'model-not-found', detail };
|
||||
}
|
||||
if (/no space left on device|disk (is )?full|not enough (free )?(disk )?space/i.test(text)) {
|
||||
return { kind: 'fatal', code: 'disk-full', detail };
|
||||
}
|
||||
return { kind: 'retry', detail };
|
||||
}
|
||||
|
||||
/** A wait that ends early when the signal aborts. */
|
||||
function waitFor(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (signal?.aborted) return resolve();
|
||||
const done = (): void => {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener('abort', done);
|
||||
resolve();
|
||||
};
|
||||
const timer = setTimeout(done, ms);
|
||||
signal?.addEventListener('abort', done, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
/** One `POST /api/pull`, read to its end. */
|
||||
async function pullOnce(target: OllamaTarget, modelId: string, options: PullOptions): Promise<PullAttempt> {
|
||||
const { signal, onProgress } = options;
|
||||
const now = options.now ?? Date.now;
|
||||
const fetchFn = target.fetch ?? fetch;
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchFn(`${target.baseUrl}/api/pull`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ model: modelId, stream: true }),
|
||||
...(signal ? { signal } : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
return signal?.aborted ? { kind: 'cancelled' } : { kind: 'retry', detail: errorText(err) };
|
||||
}
|
||||
|
||||
const parser = createPullParser();
|
||||
// The speed is the bytes of the last few seconds: (when, how far) pairs, the oldest first.
|
||||
const samples: { at: number; completed: number }[] = [];
|
||||
let lastReport = Number.NEGATIVE_INFINITY;
|
||||
const report = (force: boolean): void => {
|
||||
if (!onProgress) return;
|
||||
const at = now();
|
||||
if (!force && at - lastReport < PULL_PROGRESS_INTERVAL_MS) return;
|
||||
const snap = parser.snapshot();
|
||||
// Before the first layer line there is no size to show.
|
||||
if (snap.totalBytes <= 0) return;
|
||||
lastReport = at;
|
||||
samples.push({ at, completed: snap.completedBytes });
|
||||
while (samples.length > 2 && at - samples[1].at >= PULL_SPEED_WINDOW_MS) samples.shift();
|
||||
const first = samples[0];
|
||||
const seconds = (at - first.at) / 1000;
|
||||
const moved = snap.completedBytes - first.completed;
|
||||
try {
|
||||
onProgress({
|
||||
completedBytes: snap.completedBytes,
|
||||
totalBytes: snap.totalBytes,
|
||||
...(seconds > 0 && moved >= 0 ? { bytesPerSecond: Math.round(moved / seconds) } : {}),
|
||||
});
|
||||
} catch {
|
||||
// A display that fails must not fail the download.
|
||||
}
|
||||
};
|
||||
|
||||
let streamError: string | undefined;
|
||||
try {
|
||||
if (res.body) {
|
||||
for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
|
||||
parser.push(chunk);
|
||||
report(false);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
streamError = errorText(err);
|
||||
}
|
||||
// An abort ends the stream with an error too: it is a cancel, not a cut.
|
||||
if (signal?.aborted) return { kind: 'cancelled' };
|
||||
parser.end();
|
||||
const snap = parser.snapshot();
|
||||
|
||||
if (snap.error !== undefined) return classifyPullError(snap.error);
|
||||
if (res.status !== 200) return classifyPullError(`The runtime answered ${res.status} to the pull`);
|
||||
if (!snap.succeeded) {
|
||||
return { kind: 'retry', detail: streamError ?? 'The download ended before the runtime reported success' };
|
||||
}
|
||||
report(true);
|
||||
if (snap.totalBytes > 0) return { kind: 'success', totalBytes: snap.totalBytes };
|
||||
// A pull of a model that was already complete may name no layer. The size is then what the
|
||||
// runtime lists for the model, which is the same figure a full pull reports as its total.
|
||||
const listed = (await listTags(target, signal)).find((model) => model.name === modelId);
|
||||
return { kind: 'success', totalBytes: listed?.size ?? 0 };
|
||||
}
|
||||
|
||||
/** Pulls `modelId` and waits for the end. Resuming is calling it again. Never throws. */
|
||||
export async function pullModel(target: OllamaTarget, modelId: string, options: PullOptions = {}): Promise<PullResult> {
|
||||
const { signal } = options;
|
||||
const retries =
|
||||
options.retries !== undefined && Number.isInteger(options.retries) && options.retries >= 0
|
||||
? options.retries
|
||||
: PULL_RETRIES;
|
||||
const sleep = options.sleep ?? ((ms: number) => waitFor(ms, signal));
|
||||
let lastDetail: string | undefined;
|
||||
for (let attempt = 0; attempt <= retries; attempt++) {
|
||||
if (signal?.aborted) return { ok: false, code: 'cancelled' };
|
||||
if (attempt > 0) {
|
||||
await sleep(PULL_RETRY_DELAY_MS * 2 ** (attempt - 1));
|
||||
if (signal?.aborted) return { ok: false, code: 'cancelled' };
|
||||
}
|
||||
let outcome: PullAttempt;
|
||||
try {
|
||||
outcome = await pullOnce(target, modelId, options);
|
||||
} catch (err) {
|
||||
// Only an injected `fetch` or clock can throw here. It must not end the pull as a crash.
|
||||
outcome = { kind: 'retry', detail: errorText(err) };
|
||||
}
|
||||
if (outcome.kind === 'success') return { ok: true, totalBytes: outcome.totalBytes };
|
||||
if (outcome.kind === 'cancelled') return { ok: false, code: 'cancelled' };
|
||||
if (outcome.kind === 'fatal') return { ok: false, code: outcome.code, detail: outcome.detail };
|
||||
lastDetail = outcome.detail;
|
||||
}
|
||||
return { ok: false, code: 'pull-failed', ...(lastDetail !== undefined ? { detail: lastDetail } : {}) };
|
||||
}
|
||||
|
||||
// ---------- The check after the pull ----------
|
||||
|
||||
/** The codes the check can end on. */
|
||||
export type VerifyFailureCode = Extract<
|
||||
LocalModelErrorCode,
|
||||
'load-failed' | 'does-not-fit' | 'context-not-applied' | 'no-tool-call' | 'probe-unfinished'
|
||||
>;
|
||||
|
||||
/** What the runtime reported about the loaded model. */
|
||||
export interface LoadedModel {
|
||||
context: number;
|
||||
sizeBytes: number;
|
||||
sizeVramBytes: number;
|
||||
}
|
||||
|
||||
/** The body of the tiny chat that loads the model: one short user message, `reasoning_effort: "none"`, a small `max_tokens`. Pure. */
|
||||
export function buildChatProbeRequest(modelId: string): Record<string, unknown> {
|
||||
return {
|
||||
model: modelId,
|
||||
messages: [{ role: 'user', content: 'Reply with the single word: ready' }],
|
||||
reasoning_effort: 'none',
|
||||
max_tokens: CHAT_PROBE_MAX_TOKENS,
|
||||
temperature: 0,
|
||||
stream: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** A function tool of the tool probe, in the shape `/v1/chat/completions` takes. */
|
||||
function probeTool(name: string, description: string, properties: Record<string, string>): Record<string, unknown> {
|
||||
return {
|
||||
type: 'function',
|
||||
function: {
|
||||
name,
|
||||
description,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: Object.fromEntries(
|
||||
Object.entries(properties).map(([key, about]) => [key, { type: 'string', description: about }])
|
||||
),
|
||||
required: Object.keys(properties),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The body of the tool probe: a `tools` array, `reasoning_effort: "none"`, `max_tokens: TOOL_PROBE_MAX_TOKENS`. Pure. */
|
||||
export function buildToolProbeRequest(modelId: string): Record<string, unknown> {
|
||||
return {
|
||||
model: modelId,
|
||||
messages: [
|
||||
{ role: 'system', content: 'You are a coding agent. Use the tools you are given to do what the user asks.' },
|
||||
{ role: 'user', content: 'Read the file README.md and tell me what it says.' },
|
||||
],
|
||||
// The three tools a coding agent always has. The task needs the first.
|
||||
tools: [
|
||||
probeTool('read_file', 'Read a file and return its content.', { path: 'The path of the file.' }),
|
||||
probeTool('write_file', 'Write a file.', { path: 'The path of the file.', content: 'The new content.' }),
|
||||
probeTool('run_command', 'Run a shell command and return its output.', { command: 'The command line.' }),
|
||||
],
|
||||
reasoning_effort: 'none',
|
||||
max_tokens: TOOL_PROBE_MAX_TOKENS,
|
||||
temperature: 0,
|
||||
stream: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Judges the process list after the chat. Pure.
|
||||
* - the model is not listed: `load-failed`;
|
||||
* - `sizeVram` is not `size`: `does-not-fit` (part of the model is not on the GPU);
|
||||
* - `contextLength` is not `context`: `context-not-applied`.
|
||||
*/
|
||||
export function judgeLoaded(
|
||||
models: readonly OllamaPsModel[],
|
||||
modelId: string,
|
||||
context: number
|
||||
): { ok: true; loaded: LoadedModel } | { ok: false; code: VerifyFailureCode; detail?: string } {
|
||||
const model = models.find((entry) => entry.name === modelId);
|
||||
if (!model) return { ok: false, code: 'load-failed', detail: 'The runtime does not list the model as loaded' };
|
||||
if (model.size <= 0)
|
||||
return { ok: false, code: 'load-failed', detail: 'The runtime reports no size for the loaded model' };
|
||||
if (model.sizeVram !== model.size) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'does-not-fit',
|
||||
// A size a person reads: decimal GB, like every other size of this feature.
|
||||
detail: `${formatGb(model.sizeVram)} of ${formatGb(model.size)} GB of the model are on the GPU`,
|
||||
};
|
||||
}
|
||||
if (model.contextLength !== context) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'context-not-applied',
|
||||
detail: `The runtime reports a context of ${model.contextLength} tokens, not ${context}`,
|
||||
};
|
||||
}
|
||||
return { ok: true, loaded: { context: model.contextLength, sizeBytes: model.size, sizeVramBytes: model.sizeVram } };
|
||||
}
|
||||
|
||||
/** Whether the arguments of a tool call are a JSON object: as text that parses to one, or already as one. */
|
||||
function argumentsAreObject(value: unknown): boolean {
|
||||
if (isRecord(value)) return true;
|
||||
if (typeof value !== 'string') return false;
|
||||
try {
|
||||
return isRecord(JSON.parse(value));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Judges the answer of the tool probe. Pure. `status` is the HTTP status, `body` the parsed
|
||||
* JSON (or `undefined` when it did not parse).
|
||||
* - a tool call whose `arguments` parse as a JSON object: passed (when the answer holds
|
||||
* several calls, every one must have a name and such arguments);
|
||||
* - `finish_reason` is `length`: `probe-unfinished` (the token limit ended it, so it proves nothing);
|
||||
* - any other answer of status 200: `no-tool-call`;
|
||||
* - another status: `load-failed`.
|
||||
*/
|
||||
export function judgeToolProbe(
|
||||
status: number,
|
||||
body: unknown
|
||||
): { ok: true } | { ok: false; code: VerifyFailureCode; detail?: string } {
|
||||
if (status !== 200) {
|
||||
const said = errorOfBody(body);
|
||||
return { ok: false, code: 'load-failed', detail: clip(said ?? `The runtime answered ${status}`) };
|
||||
}
|
||||
const choice = isRecord(body) && Array.isArray(body.choices) ? body.choices[0] : undefined;
|
||||
const message = isRecord(choice) && isRecord(choice.message) ? choice.message : undefined;
|
||||
const calls = message && Array.isArray(message.tool_calls) ? message.tool_calls : [];
|
||||
if (calls.length > 0) {
|
||||
const wellFormed = calls.every(
|
||||
(call) =>
|
||||
isRecord(call) &&
|
||||
isRecord(call.function) &&
|
||||
asString(call.function.name) !== undefined &&
|
||||
argumentsAreObject(call.function.arguments)
|
||||
);
|
||||
if (wellFormed) return { ok: true };
|
||||
return { ok: false, code: 'no-tool-call', detail: 'The model called a tool with arguments that are not JSON' };
|
||||
}
|
||||
if (isRecord(choice) && choice.finish_reason === 'length') {
|
||||
return { ok: false, code: 'probe-unfinished', detail: `The answer ended at ${TOOL_PROBE_MAX_TOKENS} tokens` };
|
||||
}
|
||||
const said = message ? asString(message.content) : undefined;
|
||||
return {
|
||||
ok: false,
|
||||
code: 'no-tool-call',
|
||||
detail: said ? clip(`The model answered in text: ${said}`) : 'The answer holds no tool call',
|
||||
};
|
||||
}
|
||||
|
||||
/** How the check ended. */
|
||||
export type VerifyResult =
|
||||
| { ok: true; loaded: LoadedModel }
|
||||
| { ok: false; code: VerifyFailureCode; detail?: string }
|
||||
| { ok: false; code: 'cancelled' };
|
||||
|
||||
/**
|
||||
* The whole check, in order: the chat, the process list, the tool probe. Stops at the first
|
||||
* failure. Never throws.
|
||||
*/
|
||||
export async function verifyModel(
|
||||
target: OllamaTarget,
|
||||
modelId: string,
|
||||
context: number,
|
||||
signal?: AbortSignal
|
||||
): Promise<VerifyResult> {
|
||||
const cancelled: VerifyResult = { ok: false, code: 'cancelled' };
|
||||
if (signal?.aborted) return cancelled;
|
||||
|
||||
// 1. The chat that loads the model. Its text is not read: only that it was answered.
|
||||
const chat = await ask(
|
||||
target,
|
||||
'/v1/chat/completions',
|
||||
{ method: 'POST', json: buildChatProbeRequest(modelId) },
|
||||
CHAT_PROBE_TIMEOUT_MS,
|
||||
signal
|
||||
);
|
||||
if (signal?.aborted) return cancelled;
|
||||
if (!chat) return { ok: false, code: 'load-failed', detail: 'The runtime did not answer the first request' };
|
||||
if (chat.status !== 200) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'load-failed',
|
||||
detail: clip(errorOfBody(chat.body) ?? `The runtime answered ${chat.status}`),
|
||||
};
|
||||
}
|
||||
|
||||
// 2. What the runtime says it loaded.
|
||||
const judged = judgeLoaded(await listRunning(target, signal), modelId, context);
|
||||
if (signal?.aborted) return cancelled;
|
||||
if (!judged.ok) return judged;
|
||||
|
||||
// 3. One tool call.
|
||||
const probe = await ask(
|
||||
target,
|
||||
'/v1/chat/completions',
|
||||
{ method: 'POST', json: buildToolProbeRequest(modelId) },
|
||||
TOOL_PROBE_TIMEOUT_MS,
|
||||
signal
|
||||
);
|
||||
if (signal?.aborted) return cancelled;
|
||||
if (!probe)
|
||||
return { ok: false, code: 'probe-unfinished', detail: 'The runtime did not answer the tool request in time' };
|
||||
const tool = judgeToolProbe(probe.status, probe.body);
|
||||
if (!tool.ok) return tool;
|
||||
return { ok: true, loaded: judged.loaded };
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* @fileoverview Where everything of the local model lives on disk. One pure function, so the
|
||||
* runtime, the install job and uninstall all name the same folders.
|
||||
*
|
||||
* Layout, all under the data dir (`dataPath()`, so a second Codeman instance has its own):
|
||||
*
|
||||
* ```
|
||||
* local-model.json the state file (mode 0600)
|
||||
* local-model/
|
||||
* runtime/ollama-<version>.tgz.partial the runtime archive while it downloads
|
||||
* runtime/ollama-<version>.unpack/ where the archive is unpacked, before the rename
|
||||
* runtime/ollama-<version>/ the unpacked runtime; its binary is `ollama`
|
||||
* models/ the runtime's model store
|
||||
* home/ the runtime's private HOME (its key pair lands here)
|
||||
* ```
|
||||
*
|
||||
* Rules:
|
||||
* - `root` is the ONE folder this feature owns. Nothing is written or deleted outside it,
|
||||
* except the state file beside it and the two writes of the connect step (the endpoint
|
||||
* record and the settings flag), which have their own writers.
|
||||
* - Every path comes from here. None is ever read back from the state file, so a state file
|
||||
* cannot point a delete anywhere else. `isInsideLocalModelRoot()` is the check a delete
|
||||
* makes before it runs.
|
||||
* - Pure apart from `dataPath()`, which resolves (and creates) the data dir.
|
||||
*/
|
||||
|
||||
import { join, resolve, sep } from 'node:path';
|
||||
import { dataPath } from '../config/instance.js';
|
||||
|
||||
/** A runtime version as it may appear in a folder name: digits and dots only ('0.40.15'). */
|
||||
const VERSION_PATTERN = /^\d+(?:\.\d+){1,3}$/;
|
||||
|
||||
export interface LocalModelPaths {
|
||||
/** `<data dir>/local-model`: the one folder this feature owns. */
|
||||
root: string;
|
||||
/** `<root>/runtime`: the archive and every unpacked version. */
|
||||
runtimeRoot: string;
|
||||
/** `<root>/runtime/ollama-<version>`: the unpacked runtime. */
|
||||
runtimeDir: string;
|
||||
/** The runtime's binary: `<runtimeDir>/ollama`. */
|
||||
binary: string;
|
||||
/** `<root>/runtime/ollama-<version>.tgz.partial`: the archive while it downloads. */
|
||||
archivePartial: string;
|
||||
/** `<root>/runtime/ollama-<version>.unpack`: the temporary folder the archive is unpacked into. */
|
||||
unpackDir: string;
|
||||
/** `<root>/models`: the runtime's model store. */
|
||||
modelsDir: string;
|
||||
/** `<root>/home`: the runtime's private HOME. */
|
||||
homeDir: string;
|
||||
/** `<data dir>/local-model.json`: the state file. */
|
||||
stateFile: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The paths of the local model for one runtime version. Throws on a version that is not
|
||||
* digits and dots, so a version string can never add a path segment.
|
||||
*/
|
||||
export function localModelPaths(version: string): LocalModelPaths {
|
||||
if (!VERSION_PATTERN.test(version)) {
|
||||
throw new Error(`Not a runtime version: ${JSON.stringify(version)}`);
|
||||
}
|
||||
const root = dataPath('local-model');
|
||||
const runtimeRoot = join(root, 'runtime');
|
||||
const runtimeDir = join(runtimeRoot, `ollama-${version}`);
|
||||
return {
|
||||
root,
|
||||
runtimeRoot,
|
||||
runtimeDir,
|
||||
binary: join(runtimeDir, 'ollama'),
|
||||
archivePartial: join(runtimeRoot, `ollama-${version}.tgz.partial`),
|
||||
unpackDir: join(runtimeRoot, `ollama-${version}.unpack`),
|
||||
modelsDir: join(root, 'models'),
|
||||
homeDir: join(root, 'home'),
|
||||
stateFile: dataPath('local-model.json'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The binary of another unpacked runtime version beside the pinned one: `<runtimeRoot>/
|
||||
* ollama-<version>/ollama`. For an installed model whose runtime was unpacked by an earlier
|
||||
* build with another pin: it keeps running the version it was installed with. Throws on a
|
||||
* version that is not digits and dots, like `localModelPaths()`. Pure.
|
||||
*/
|
||||
export function runtimeBinaryForVersion(paths: LocalModelPaths, version: string): string {
|
||||
if (!VERSION_PATTERN.test(version)) {
|
||||
throw new Error(`Not a runtime version: ${JSON.stringify(version)}`);
|
||||
}
|
||||
return join(paths.runtimeRoot, `ollama-${version}`, 'ollama');
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `path` is the local model folder itself or lies inside it, judged on the resolved
|
||||
* text (no filesystem access, so a symlink is not followed: a caller that deletes checks the
|
||||
* real path first). `..` segments are resolved before the comparison.
|
||||
*/
|
||||
export function isInsideLocalModelRoot(path: string, root: string = dataPath('local-model')): boolean {
|
||||
const base = resolve(root);
|
||||
const target = resolve(path);
|
||||
return target === base || target.startsWith(base + sep);
|
||||
}
|
||||
+176
-64
@@ -3,21 +3,33 @@
|
||||
* fits this Mac. Pure: no IO, no clock, no CLI registry, no data dir.
|
||||
*
|
||||
* The math, in the order it runs:
|
||||
* - `deviceBudget()`: L is the wired limit when it is above 0, else 2/3 of memory below 36 GB
|
||||
* and 3/4 from 36 GB. B = min(L - 1 GiB, memory - reserve), with a reserve of 6 GiB up to
|
||||
* 18 GB, 8 GiB up to 48 GB and 12 GiB above.
|
||||
* - `needBytes()`: F = weights + kvBytesPerToken * ctx + 1 GiB + the prompt cache tier of the
|
||||
* catalogue for this Mac's memory.
|
||||
* - Fit: F/B up to 0.85 is good, up to 0.98 is tight, above is out.
|
||||
* - Speed: tokens per second = the model's `speedPer100Gbps` x the chip's bandwidth / 100.
|
||||
* Below 10 is slow, decided on the unrounded product (9.96 is slow although it prints as
|
||||
* 10). A chip that is in no chips row, or a model without a speed figure, is UNKNOWN: a
|
||||
* - `deviceBudget()`. ESTIMATED (all there is before the runtime ran): L is the wired limit
|
||||
* when it is above 0, else 2/3 of memory below 36 GB and 3/4 from 36 GB, and
|
||||
* B = min(L - 1 GiB, memory - reserve), with a reserve of 6 GiB up to 18 GB, 8 GiB up to
|
||||
* 48 GB and 12 GiB above. MEASURED (`RecommendOptions.measuredTotalBytes`, the device total
|
||||
* the runtime printed when it started): L is that total and B = min(L, memory - reserve),
|
||||
* without the 1 GiB, because the figure is already what the runtime will really use.
|
||||
* - `needBytes()`: the PEAK, `bytes + heldBytesPerToken * ctx + overheadBytes +
|
||||
* peakExtraBytes` of the catalogue row: the weights, what stays held per token of context,
|
||||
* what the runner holds beside both, and what it takes for a moment while a long prompt is
|
||||
* processed. Measured for one model on one Mac (see the catalogue header); every other row
|
||||
* carries the same figures and says `estimated`.
|
||||
* - Fit: need over budget up to 0.85 is good, up to 0.98 is tight, above is out. The grade
|
||||
* decides whether a model is offered at all and what its row says. It does NOT sort: the
|
||||
* need is the worst moment at the full context, so a tight fit is a model that runs, and a
|
||||
* Mac whose best model is tight should be offered that model, not a smaller one.
|
||||
* - Speed: a candidate that matches a `tested` entry with a measured speed reports that
|
||||
* speed. Every other one is estimated: the model's `speedPer100Gbps` x the chip's bandwidth
|
||||
* / 100. Below 10 is slow, decided on the unrounded figure (9.96 is slow although it prints
|
||||
* as 10). A chip that is in no chips row, or a model without a speed figure, is UNKNOWN: a
|
||||
* bandwidth is never guessed.
|
||||
* - Candidates: (model, context, harness) with `ctx >= harness.minContext`, the harness not
|
||||
* gated, installed or installable, and accepting the model id.
|
||||
* - Ranking, lexicographic: good before tight; ok before unknown before slow; the higher model
|
||||
* rank; the higher harness rank; the larger context. The pick is the first candidate, the
|
||||
* alternatives are the next four MODELS, each at its own best context and harness.
|
||||
* - Ranking, lexicographic: tested on a Mac like this before not tested (a measurement beats
|
||||
* a formula); ok before unknown before slow; the higher model rank; the higher harness
|
||||
* rank; the larger context. The pick is the first candidate, the alternatives are the next
|
||||
* four MODELS, each at its own best context and harness, so a model is always offered at
|
||||
* the largest context it fits at.
|
||||
* - Disk: a model whose download would leave less than 10 GiB free is not offered. It is not
|
||||
* dropped in silence: the best-ranked model left out that way is named in `noteDiskDropped`
|
||||
* with what is missing.
|
||||
@@ -32,8 +44,8 @@
|
||||
* installable).
|
||||
* 6. `memory`: models fit, but none at a context a usable harness needs. Its own sentence
|
||||
* (`noneMemoryContext`) with the budget and the smallest need at such a context, because
|
||||
* this Mac can miss by a hair (the 16 GB Mac mini: 10.3 of 10.4 GB) and "too little
|
||||
* memory" would hide that the answer rests on an estimate.
|
||||
* "too little memory" would hide that a model does fit at a smaller context and that the
|
||||
* answer rests on estimates.
|
||||
* 7. `no-harness`: models fit at such a context, but no usable harness accepts their id.
|
||||
* 8. `disk`: for every remaining model, free disk minus the download is below 10 GiB (an
|
||||
* unknown free disk does not block).
|
||||
@@ -42,16 +54,20 @@
|
||||
* - Verdict `limited` when NO model with 12 billion parameters or more fits this Mac's memory
|
||||
* at a context a usable harness works at. It is a statement about the Mac ("This Mac can run
|
||||
* a small model"), so it is judged on everything that fits, BEFORE the disk filter and
|
||||
* whatever the pick is: a 36 GB Mac whose pick is a 9B model while a 20B, a 27B and a 35B
|
||||
* are listed under it is not a small-model Mac, and a 48 GB Mac does not become one because
|
||||
* its disk is full. A small pick under verdict `ok` carries `noteSmallPick` instead.
|
||||
* whatever the pick is: a 36 GB Mac whose pick is a 9B model while a 20B is listed under it
|
||||
* is not a small-model Mac, and a 48 GB Mac does not become one because its disk is full. A
|
||||
* small pick under verdict `ok` carries `noteSmallPick` instead.
|
||||
* - The word "Recommended" (`LOCAL_MODEL_LABELS.headlineTested`) only for verdict `ok` with a
|
||||
* pick whose model has a `tested` entry for exactly this chip, this memory size and this
|
||||
* harness. Otherwise `headlineOk` (or `headlineLimited`) plus `noteUntested`.
|
||||
* - Every label in the result comes from `LOCAL_MODEL_LABELS`, every computed size text from
|
||||
* `formatGb()`. The one size that is not decimal GB is the installed memory in `noneMemory`:
|
||||
* `HardwareFacts.memClassGb`, the size the Mac is sold as. No number is spliced into a
|
||||
* sentence here.
|
||||
* - Every row carries what the chooser needs and nothing the browser must work out: its one
|
||||
* tag (`tagFor()`), every harness it can run with (`Candidate.harnesses`, the flat harness
|
||||
* fields first), and the whole download of an install (`installBytes`: the model plus
|
||||
* `RecommendOptions.runtimeDownloadBytes`).
|
||||
* - Every label in the result comes from `LOCAL_MODEL_LABELS` or `LOCAL_MODEL_TAG_LABELS`,
|
||||
* every computed size text from `formatGb()`. The one size that is not decimal GB is the
|
||||
* installed memory in `noneMemory`: `HardwareFacts.memClassGb`, the size the Mac is sold
|
||||
* as. No number is spliced into a sentence here.
|
||||
* - No CLI id is ever compared with a literal: a harness is a catalogue row plus a
|
||||
* `HarnessFact`.
|
||||
*/
|
||||
@@ -59,7 +75,11 @@
|
||||
import {
|
||||
LOCAL_MODEL_LABELS,
|
||||
LOCAL_MODEL_NONE_LABELS,
|
||||
LOCAL_MODEL_TAG_LABELS,
|
||||
type Candidate,
|
||||
type CandidateHarness,
|
||||
type CandidateTag,
|
||||
type CandidateTagKind,
|
||||
type DeviceBudget,
|
||||
type FitGrade,
|
||||
type HardwareFacts,
|
||||
@@ -71,7 +91,9 @@ import {
|
||||
type LocalModelMessage,
|
||||
type NoneReason,
|
||||
type Recommendation,
|
||||
type RecommendOptions,
|
||||
type SpeedGrade,
|
||||
type TestedOn,
|
||||
} from '../types.js';
|
||||
import { chipBandwidthGbps } from '../config/local-model-catalog.js';
|
||||
import { formatGb, GIB, MIB } from './format.js';
|
||||
@@ -80,14 +102,12 @@ import { formatGb, GIB, MIB } from './format.js';
|
||||
export const FIT_GOOD_MAX_SHARE = 0.85;
|
||||
/** Need over budget up to this share is a `tight` fit; above it the model is out. */
|
||||
export const FIT_TIGHT_MAX_SHARE = 0.98;
|
||||
/** An estimated speed below this many tokens per second is `slow`. */
|
||||
/** A speed below this many tokens per second is `slow`. */
|
||||
export const SLOW_BELOW_TOKENS_PER_SECOND = 10;
|
||||
/** When no model that fits has at least this many billion parameters, the verdict is `limited`. A pick below it is a "small model". */
|
||||
export const LIMITED_BELOW_PARAMS_B = 12;
|
||||
/** What must stay free on the disk after the model download. */
|
||||
export const DISK_HEADROOM_BYTES = 10 * GIB;
|
||||
/** What the runtime needs beside the weights, the KV cache and the prompt cache (compute buffers). */
|
||||
export const RUNTIME_OVERHEAD_BYTES = GIB;
|
||||
/** How many other models are listed under the pick. */
|
||||
export const MAX_ALTERNATIVES = 4;
|
||||
|
||||
@@ -101,30 +121,39 @@ function reserveBytes(memClassGb: number): number {
|
||||
return 12 * GIB;
|
||||
}
|
||||
|
||||
/** The memory a model may use on this Mac: the device limit L, the budget B and where L came from. */
|
||||
export function deviceBudget(hw: HardwareFacts): DeviceBudget {
|
||||
/** A byte count a caller supplied, when it is one: finite and above 0. */
|
||||
function positiveBytes(value: number | undefined): number | undefined {
|
||||
return value !== undefined && Number.isFinite(value) && value > 0 ? Math.floor(value) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The memory a model may use on this Mac: the device limit L, the budget B and where L came
|
||||
* from. With `options.measuredTotalBytes` the limit is what the runtime itself reported and
|
||||
* the 1 GiB the estimate keeps back is not subtracted; the reserve bounds both.
|
||||
*/
|
||||
export function deviceBudget(hw: HardwareFacts, options: RecommendOptions = {}): DeviceBudget {
|
||||
const memBytes = Number.isFinite(hw.memBytes) && hw.memBytes > 0 ? hw.memBytes : 0;
|
||||
const afterReserve = memBytes - reserveBytes(hw.memClassGb);
|
||||
const measured = positiveBytes(options.measuredTotalBytes);
|
||||
if (measured !== undefined) {
|
||||
return { limitBytes: measured, budgetBytes: Math.max(0, Math.min(measured, afterReserve)), source: 'measured' };
|
||||
}
|
||||
// 0 means "not set" (both test Macs report 0): only a value above 0 is a limit.
|
||||
const wired = hw.wiredLimitMb !== undefined && Number.isFinite(hw.wiredLimitMb) && hw.wiredLimitMb > 0;
|
||||
const limitBytes = wired
|
||||
? Math.floor((hw.wiredLimitMb as number) * MIB)
|
||||
: Math.floor(memBytes * (hw.memClassGb < LARGE_LIMIT_FROM_GB ? 2 / 3 : 3 / 4));
|
||||
const budgetBytes = Math.max(0, Math.min(limitBytes - GIB, memBytes - reserveBytes(hw.memClassGb)));
|
||||
const budgetBytes = Math.max(0, Math.min(limitBytes - GIB, afterReserve));
|
||||
return { limitBytes, budgetBytes, source: wired ? 'wired-limit' : 'estimated' };
|
||||
}
|
||||
|
||||
/** The prompt cache of the last tier whose minimum is not above this Mac's memory size. */
|
||||
function promptCacheBytes(catalog: LocalModelCatalog, memClassGb: number): number {
|
||||
let bytes = 0;
|
||||
for (const tier of catalog.promptCacheTiers) {
|
||||
if (tier.minMemGb <= memClassGb) bytes = tier.bytes;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** F: the bytes `model` needs in memory at a context of `ctx` tokens on this Mac. */
|
||||
export function needBytes(model: LocalModelEntry, ctx: number, catalog: LocalModelCatalog, hw: HardwareFacts): number {
|
||||
return model.bytes + model.kvBytesPerToken * ctx + RUNTIME_OVERHEAD_BYTES + promptCacheBytes(catalog, hw.memClassGb);
|
||||
/**
|
||||
* The bytes `model` needs in memory at a context of `ctx` tokens, at its PEAK: the weights,
|
||||
* what stays held for the context, what the runner holds beside them, and what it takes for a
|
||||
* moment while a long prompt is processed. It does not depend on the Mac.
|
||||
*/
|
||||
export function needBytes(model: LocalModelEntry, ctx: number): number {
|
||||
return model.bytes + model.heldBytesPerToken * ctx + model.overheadBytes + model.peakExtraBytes;
|
||||
}
|
||||
|
||||
function fitGrade(need: number, budgetBytes: number): FitGrade {
|
||||
@@ -135,6 +164,26 @@ function fitGrade(need: number, budgetBytes: number): FitGrade {
|
||||
return 'out';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the catalogue model `modelId` at `context` tokens fits this Mac's budget (a `good`
|
||||
* or a `tight` fit). The install job asks this right after the runtime started, with the
|
||||
* budget the runtime measured (`options.measuredTotalBytes`), BEFORE it downloads the model: a
|
||||
* `false` ends the job with `does-not-fit`. It is the same judgement `recommend()` makes for a
|
||||
* candidate, without the ranking, so a model that fits is never ruled out for being listed
|
||||
* sixth. False for a model the catalogue does not have.
|
||||
*/
|
||||
export function modelFitsBudget(
|
||||
hw: HardwareFacts,
|
||||
catalog: LocalModelCatalog,
|
||||
modelId: string,
|
||||
context: number,
|
||||
options: RecommendOptions = {}
|
||||
): boolean {
|
||||
const model = catalog.models.find((entry) => entry.id === modelId);
|
||||
if (!model || !Number.isFinite(context) || context <= 0) return false;
|
||||
return fitGrade(needBytes(model, context), deviceBudget(hw, options).budgetBytes) !== 'out';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the MACHINE is Apple silicon. `hw.optional.arm64` decides when it was read. Without
|
||||
* it: a process under Rosetta, an arm64 process or an Apple chip name each prove Apple silicon
|
||||
@@ -165,13 +214,12 @@ interface UsableHarness {
|
||||
fact: HarnessFact;
|
||||
}
|
||||
|
||||
const FIT_ORDER: Record<Candidate['fit'], number> = { good: 0, tight: 1 };
|
||||
const SPEED_ORDER: Record<SpeedGrade, number> = { ok: 0, unknown: 1, slow: 2 };
|
||||
|
||||
/** Best first. */
|
||||
/** Best first. The fit grade is not a key: every candidate here fits, see the file header. */
|
||||
function compareRanked(a: Ranked, b: Ranked): number {
|
||||
return (
|
||||
FIT_ORDER[a.candidate.fit] - FIT_ORDER[b.candidate.fit] ||
|
||||
Number(b.candidate.tested) - Number(a.candidate.tested) ||
|
||||
SPEED_ORDER[a.candidate.speed] - SPEED_ORDER[b.candidate.speed] ||
|
||||
b.modelRank - a.modelRank ||
|
||||
b.harnessRank - a.harnessRank ||
|
||||
@@ -188,27 +236,53 @@ function accepts(fact: HarnessFact, modelId: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/** What the chooser's "Runs with" select needs to know about one harness. */
|
||||
function candidateHarness(harness: UsableHarness): CandidateHarness {
|
||||
const { row, fact } = harness;
|
||||
return {
|
||||
cli: row.cli,
|
||||
cliLabel: fact.label,
|
||||
installed: fact.installed,
|
||||
// Only a harness that still has to be installed has a command to show.
|
||||
...(!fact.installed && fact.installCommand ? { installCommand: fact.installCommand } : {}),
|
||||
...(row.slowFirstTurn ? { slowFirstTurn: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry that makes this model "tested on a Mac like this": exactly the same chip string,
|
||||
* the same memory size as sold, the same harness.
|
||||
*/
|
||||
function testedEntry(model: LocalModelEntry, hw: HardwareFacts, cli: string): TestedOn | undefined {
|
||||
return model.tested.find((entry) => entry.chip === hw.chip && entry.memGb === hw.memClassGb && entry.cli === cli);
|
||||
}
|
||||
|
||||
function buildCandidate(
|
||||
model: LocalModelEntry,
|
||||
ctx: number,
|
||||
harness: UsableHarness,
|
||||
/** Every usable harness that can run this model at this context, `harness` among them. */
|
||||
runsWith: readonly UsableHarness[],
|
||||
need: number,
|
||||
fit: Candidate['fit'],
|
||||
hw: HardwareFacts,
|
||||
catalog: LocalModelCatalog,
|
||||
budgetBytes: number
|
||||
budgetBytes: number,
|
||||
runtimeDownloadBytes: number
|
||||
): Candidate {
|
||||
const testedOn = testedEntry(model, hw, harness.row.cli);
|
||||
const gbps = chipBandwidthGbps(catalog.chips, hw.chip);
|
||||
// A speed measured on a Mac like this one beats the estimate from the chip's bandwidth.
|
||||
const rawSpeed =
|
||||
gbps !== undefined && model.speedPer100Gbps !== undefined ? (model.speedPer100Gbps * gbps) / 100 : undefined;
|
||||
testedOn?.tokensPerSecond ??
|
||||
(gbps !== undefined && model.speedPer100Gbps !== undefined ? (model.speedPer100Gbps * gbps) / 100 : undefined);
|
||||
// Graded on the unrounded figure: 9.96 rounds to 10.0 for the payload and is still slow.
|
||||
const speed: SpeedGrade =
|
||||
rawSpeed === undefined ? 'unknown' : rawSpeed < SLOW_BELOW_TOKENS_PER_SECOND ? 'slow' : 'ok';
|
||||
const tokensPerSecond = rawSpeed === undefined ? undefined : round(rawSpeed, 1);
|
||||
// "A Mac like this" is exact: the same chip string, the same memory size as sold, the same harness.
|
||||
const tested = model.tested.some(
|
||||
(entry) => entry.chip === hw.chip && entry.memGb === hw.memClassGb && entry.cli === harness.row.cli
|
||||
);
|
||||
// The harness of the flat fields first, then the others, best first.
|
||||
const others = runsWith.filter((other) => other !== harness).sort((a, b) => b.row.rank - a.row.rank);
|
||||
const installBytes = model.bytes + runtimeDownloadBytes;
|
||||
return {
|
||||
modelId: model.id,
|
||||
modelLabel: model.label,
|
||||
@@ -230,10 +304,41 @@ function buildCandidate(
|
||||
...(speed === 'slow' ? { speedLabel: LOCAL_MODEL_LABELS.speedSlow } : {}),
|
||||
...(speed === 'unknown' ? { speedLabel: LOCAL_MODEL_LABELS.speedUnknown } : {}),
|
||||
...(tokensPerSecond !== undefined ? { tokensPerSecond } : {}),
|
||||
tested,
|
||||
tested: testedOn !== undefined,
|
||||
needSource: model.figures,
|
||||
harnesses: [harness, ...others].map(candidateHarness),
|
||||
installBytes,
|
||||
installGb: formatGb(installBytes),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The one tag of a row: the first kind that applies, in the order tested, the pick (which
|
||||
* says so when it only just fits), tight, slow, small. `undefined` when none does.
|
||||
*/
|
||||
function tagFor(candidate: Candidate, isPick: boolean): CandidateTag | undefined {
|
||||
const kind: CandidateTagKind | undefined = candidate.tested
|
||||
? 'tested'
|
||||
: isPick
|
||||
? candidate.fit === 'tight'
|
||||
? 'best-tight'
|
||||
: 'best'
|
||||
: candidate.fit === 'tight'
|
||||
? 'tight'
|
||||
: candidate.speed === 'slow'
|
||||
? 'slow'
|
||||
: candidate.paramsB < LIMITED_BELOW_PARAMS_B
|
||||
? 'small'
|
||||
: undefined;
|
||||
return kind === undefined ? undefined : { kind, label: LOCAL_MODEL_TAG_LABELS[kind] };
|
||||
}
|
||||
|
||||
/** `candidate` with its tag, when it has one. */
|
||||
function withTag(candidate: Candidate, isPick: boolean): Candidate {
|
||||
const tag = tagFor(candidate, isPick);
|
||||
return tag ? { ...candidate, tag } : candidate;
|
||||
}
|
||||
|
||||
/** A `none` answer. `text` replaces the reason's default sentence (the `memory` reason has three). */
|
||||
function none(
|
||||
reason: NoneReason,
|
||||
@@ -256,18 +361,24 @@ function none(
|
||||
/**
|
||||
* The recommendation for this Mac. `harnessFacts` holds one fact per catalogue harness the
|
||||
* caller could resolve; a catalogue harness without a fact is not offered.
|
||||
*
|
||||
* `options` is what the caller knows beyond the probe: the budget the runtime measured (the
|
||||
* answer then says `budgetSource: 'measured'`), and the runtime download an install still
|
||||
* needs (it is added to every row's `installBytes`).
|
||||
*/
|
||||
export function recommend(
|
||||
hw: HardwareFacts,
|
||||
catalog: LocalModelCatalog,
|
||||
harnessFacts: readonly HarnessFact[]
|
||||
harnessFacts: readonly HarnessFact[],
|
||||
options: RecommendOptions = {}
|
||||
): Recommendation {
|
||||
// Off macOS and on an Intel Mac there is no budget to compute: a model has no memory to run in.
|
||||
const noBudget: DeviceBudget = { limitBytes: 0, budgetBytes: 0, source: 'estimated' };
|
||||
if (hw.platform !== 'darwin') return none('not-macos', noBudget);
|
||||
if (!isAppleSilicon(hw)) return none('intel', noBudget);
|
||||
|
||||
const budget = deviceBudget(hw);
|
||||
const budget = deviceBudget(hw, options);
|
||||
const runtimeDownloadBytes = positiveBytes(options.runtimeDownloadBytes) ?? 0;
|
||||
if (hw.macosMajor !== undefined && hw.macosMajor < catalog.minMacosMajor) {
|
||||
return none('macos', budget, {
|
||||
version: hw.macosVersion ?? String(hw.macosMajor),
|
||||
@@ -279,7 +390,7 @@ export function recommend(
|
||||
const fitting: { model: LocalModelEntry; ctx: number; need: number; fit: Candidate['fit'] }[] = [];
|
||||
for (const model of catalog.models) {
|
||||
for (const ctx of model.contexts) {
|
||||
const need = needBytes(model, ctx, catalog, hw);
|
||||
const need = needBytes(model, ctx);
|
||||
const fit = fitGrade(need, budget.budgetBytes);
|
||||
if (fit !== 'out') fitting.push({ model, ctx, need, fit });
|
||||
}
|
||||
@@ -305,14 +416,14 @@ export function recommend(
|
||||
usable.filter((harness) => entry.ctx >= harness.row.minContext).map((harness) => ({ ...entry, harness }))
|
||||
);
|
||||
if (atHarnessContext.length === 0) {
|
||||
// Models fit, but only below the context a harness needs. Say both numbers: the smallest
|
||||
// need at such a context can sit a hair over the line, and the budget is an estimate.
|
||||
// Models fit, but only below the context a harness needs. Say both numbers: the reader
|
||||
// sees how far apart they are, and that both are estimates.
|
||||
const smallestContext = Math.min(...usable.map((harness) => harness.row.minContext));
|
||||
let smallestNeed: number | undefined;
|
||||
for (const model of catalog.models) {
|
||||
for (const ctx of model.contexts) {
|
||||
if (ctx < smallestContext) continue;
|
||||
const need = needBytes(model, ctx, catalog, hw);
|
||||
const need = needBytes(model, ctx);
|
||||
if (smallestNeed === undefined || need < smallestNeed) smallestNeed = need;
|
||||
}
|
||||
}
|
||||
@@ -333,12 +444,8 @@ export function recommend(
|
||||
const hasRoom = (model: LocalModelEntry): boolean => free === undefined || free - model.bytes >= DISK_HEADROOM_BYTES;
|
||||
if (free !== undefined && !accepted.some((entry) => hasRoom(entry.model))) {
|
||||
const smallest = Math.min(...accepted.map((entry) => entry.model.bytes));
|
||||
return none('disk', budget, {
|
||||
download: formatGb(smallest),
|
||||
reserve: formatGb(DISK_HEADROOM_BYTES),
|
||||
free: hw.freeDiskGb ?? formatGb(free),
|
||||
missing: formatGb(smallest + DISK_HEADROOM_BYTES - free),
|
||||
});
|
||||
// One number, the one that says what to do: what must be freed for the smallest model.
|
||||
return none('disk', budget, { missing: formatGb(smallest + DISK_HEADROOM_BYTES - free) });
|
||||
}
|
||||
|
||||
// Everything that fits is ranked, the models without room on the disk included: the best of
|
||||
@@ -349,11 +456,15 @@ export function recommend(
|
||||
entry.model,
|
||||
entry.ctx,
|
||||
entry.harness,
|
||||
accepted
|
||||
.filter((other) => other.model === entry.model && other.ctx === entry.ctx)
|
||||
.map((other) => other.harness),
|
||||
entry.need,
|
||||
entry.fit,
|
||||
hw,
|
||||
catalog,
|
||||
budget.budgetBytes
|
||||
budget.budgetBytes,
|
||||
runtimeDownloadBytes
|
||||
),
|
||||
model: entry.model,
|
||||
modelRank: entry.model.rank,
|
||||
@@ -368,7 +479,8 @@ export function recommend(
|
||||
}
|
||||
const offered = bestPerModel.filter((entry) => hasRoom(entry.model)).map((entry) => entry.candidate);
|
||||
const leftOutForDisk = bestPerModel.find((entry) => !hasRoom(entry.model));
|
||||
const [pick, ...others] = offered;
|
||||
const pick = withTag(offered[0], true);
|
||||
const alternatives = offered.slice(1, 1 + MAX_ALTERNATIVES).map((candidate) => withTag(candidate, false));
|
||||
|
||||
// About the Mac, not the pick, and judged before the disk filter (see the file header).
|
||||
const limited = !accepted.some((entry) => entry.model.paramsB >= LIMITED_BELOW_PARAMS_B);
|
||||
@@ -397,7 +509,7 @@ export function recommend(
|
||||
headline: { text: headline },
|
||||
notes,
|
||||
pick,
|
||||
alternatives: others.slice(0, MAX_ALTERNATIVES),
|
||||
alternatives,
|
||||
budgetBytes: budget.budgetBytes,
|
||||
budgetGb: formatGb(budget.budgetBytes),
|
||||
budgetSource: budget.source,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,276 @@
|
||||
/**
|
||||
* @fileoverview The ONE reader and writer of `local-model.json`, the state file of the local
|
||||
* model install (`LocalModelStateFile`).
|
||||
*
|
||||
* Why one module: the install job writes the state, the step and the digest, and the caller
|
||||
* of the runtime supervisor writes the pid and the port. Two writers with their own temp file
|
||||
* and rename would lose each other's change, which is the fault `mutateCustomModelHosts()`
|
||||
* exists to end for the endpoint store. So every write goes through `mutateLocalModelState()`.
|
||||
*
|
||||
* The shape of `mutateSettingsFile()` (src/web/settings-writer.ts):
|
||||
* - Serialized: mutations run one at a time on one promise chain.
|
||||
* - Atomic: each write goes to a temp file with a random name beside the target and is
|
||||
* renamed over it. The file is mode 0600.
|
||||
* - Reading is TOTAL, unlike the settings writer: the file holds no setting of the user, only
|
||||
* what this feature recorded, so a missing file, one that does not parse or one with
|
||||
* another `schema` reads as `IDLE_LOCAL_MODEL_STATE` and the next write replaces it.
|
||||
* - The path is `localModelPaths().stateFile`. The file itself holds no path.
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import {
|
||||
LOCAL_MODEL_ERROR_LABELS,
|
||||
LOCAL_MODEL_INSTALL_STEPS,
|
||||
type LocalModelErrorCode,
|
||||
type LocalModelInstallState,
|
||||
type LocalModelInstallStep,
|
||||
type LocalModelStateFile,
|
||||
} from '../types.js';
|
||||
import { OLLAMA_RUNTIME_PIN } from './runtime.js';
|
||||
import { localModelPaths } from './paths.js';
|
||||
|
||||
/** The state when nothing was ever installed. What an unreadable file reads as. */
|
||||
export const IDLE_LOCAL_MODEL_STATE: LocalModelStateFile = Object.freeze({ schema: 1, state: 'idle' });
|
||||
|
||||
const STATES: readonly LocalModelInstallState[] = ['idle', 'installing', 'paused', 'failed', 'installed'];
|
||||
|
||||
// ---------- Reading one member at a time ----------
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
|
||||
const text = (value: unknown, max = 4_096): string | undefined =>
|
||||
typeof value === 'string' && value !== '' && value.length <= max ? value : undefined;
|
||||
|
||||
/** A whole number of bytes, tokens, a port or a pid: finite, not negative, and an integer. */
|
||||
const count = (value: unknown): number | undefined =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
||||
|
||||
const step = (value: unknown): LocalModelInstallStep | undefined =>
|
||||
LOCAL_MODEL_INSTALL_STEPS.find((candidate) => candidate === value);
|
||||
|
||||
function parseSteps(value: unknown): LocalModelInstallStep[] | undefined {
|
||||
if (!Array.isArray(value)) return undefined;
|
||||
const steps: LocalModelInstallStep[] = [];
|
||||
for (const item of value) {
|
||||
const parsed = step(item);
|
||||
// A list with an unknown or a repeated step is not a list this build wrote.
|
||||
if (!parsed || steps.includes(parsed)) return undefined;
|
||||
steps.push(parsed);
|
||||
}
|
||||
return steps.length > 0 ? steps : undefined;
|
||||
}
|
||||
|
||||
function parseVars(value: unknown): Record<string, string> | undefined {
|
||||
if (!isRecord(value)) return undefined;
|
||||
const vars: Record<string, string> = {};
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
if (typeof item === 'string' && item.length <= 4_096) vars[key] = item;
|
||||
}
|
||||
return Object.keys(vars).length > 0 ? vars : undefined;
|
||||
}
|
||||
|
||||
function parseError(value: unknown): LocalModelStateFile['error'] {
|
||||
if (!isRecord(value)) return undefined;
|
||||
const code = text(value.code);
|
||||
if (!code || !Object.prototype.hasOwnProperty.call(LOCAL_MODEL_ERROR_LABELS, code)) return undefined;
|
||||
const vars = parseVars(value.vars);
|
||||
const detail = text(value.detail, 16_384);
|
||||
const nextModelId = text(value.nextModelId, 200);
|
||||
return {
|
||||
code: code as LocalModelErrorCode,
|
||||
...(vars ? { vars } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
...(nextModelId ? { nextModelId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseModel(value: unknown): LocalModelStateFile['model'] {
|
||||
if (!isRecord(value)) return undefined;
|
||||
const id = text(value.id, 200);
|
||||
const label = text(value.label, 200);
|
||||
const context = count(value.context);
|
||||
if (!id || !label || !context) return undefined;
|
||||
const pullBytes = count(value.pullBytes);
|
||||
const digest = text(value.digest, 200);
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
context,
|
||||
...(pullBytes !== undefined ? { pullBytes } : {}),
|
||||
...(digest ? { digest } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseCli(value: unknown): LocalModelStateFile['cli'] {
|
||||
if (!isRecord(value)) return undefined;
|
||||
const id = text(value.id, 200);
|
||||
const label = text(value.label, 200);
|
||||
return id && label ? { id, label } : undefined;
|
||||
}
|
||||
|
||||
function parseRuntime(value: unknown): LocalModelStateFile['runtime'] {
|
||||
if (!isRecord(value)) return undefined;
|
||||
const version = text(value.version, 64);
|
||||
const port = count(value.port);
|
||||
if (!version || !port || port > 65_535) return undefined;
|
||||
const pid = count(value.pid);
|
||||
const measuredTotalBytes = count(value.measuredTotalBytes);
|
||||
return {
|
||||
version,
|
||||
port,
|
||||
...(pid ? { pid } : {}),
|
||||
// Anything but an explicit `false` reads as enabled: only Stop switches the runtime off.
|
||||
enabled: value.enabled !== false,
|
||||
...(measuredTotalBytes ? { measuredTotalBytes } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseProgress(value: unknown): LocalModelStateFile['progress'] {
|
||||
if (!isRecord(value)) return undefined;
|
||||
const completedBytes = count(value.completedBytes);
|
||||
const totalBytes = count(value.totalBytes);
|
||||
return completedBytes !== undefined && totalBytes !== undefined ? { completedBytes, totalBytes } : undefined;
|
||||
}
|
||||
|
||||
function parseLoaded(value: unknown): LocalModelStateFile['loaded'] {
|
||||
if (!isRecord(value)) return undefined;
|
||||
const context = count(value.context);
|
||||
const sizeBytes = count(value.sizeBytes);
|
||||
const sizeVramBytes = count(value.sizeVramBytes);
|
||||
return context !== undefined && sizeBytes !== undefined && sizeVramBytes !== undefined
|
||||
? { context, sizeBytes, sizeVramBytes }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function parseConnection(value: unknown): LocalModelStateFile['connection'] {
|
||||
if (!isRecord(value)) return undefined;
|
||||
const endpointId = text(value.endpointId, 200);
|
||||
return endpointId && typeof value.flagWasEnabled === 'boolean'
|
||||
? { endpointId, flagWasEnabled: value.flagWasEnabled }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The state a file's text stands for. Pure and total: text that is not a JSON object of
|
||||
* `schema: 1` with a known `state` is `IDLE_LOCAL_MODEL_STATE`. Members it does not know are
|
||||
* dropped, and a member of the wrong type is dropped rather than trusted.
|
||||
*
|
||||
* A state that needs a member it does not have is not trusted either: a job (`installing`,
|
||||
* `paused`, `failed`) without its model, its coding agent or its step, a `failed` job without
|
||||
* its error, and an `installed` state without its model or its runtime all read as idle.
|
||||
* Nothing is deleted by that: what lies in the folder stays until a Remove or a new install.
|
||||
*/
|
||||
export function parseLocalModelState(raw: string): LocalModelStateFile {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return IDLE_LOCAL_MODEL_STATE;
|
||||
}
|
||||
if (!isRecord(parsed) || parsed.schema !== 1) return IDLE_LOCAL_MODEL_STATE;
|
||||
const state = STATES.find((candidate) => candidate === parsed.state);
|
||||
if (!state || state === 'idle') return IDLE_LOCAL_MODEL_STATE;
|
||||
|
||||
const model = parseModel(parsed.model);
|
||||
const cli = parseCli(parsed.cli);
|
||||
const runtime = parseRuntime(parsed.runtime);
|
||||
const connection = parseConnection(parsed.connection);
|
||||
const updatedAt = text(parsed.updatedAt, 64);
|
||||
const replacedModelId = text(parsed.replacedModelId, 200);
|
||||
if (!model || !cli) return IDLE_LOCAL_MODEL_STATE;
|
||||
|
||||
if (state === 'installed') {
|
||||
if (!runtime) return IDLE_LOCAL_MODEL_STATE;
|
||||
const loaded = parseLoaded(parsed.loaded);
|
||||
return {
|
||||
schema: 1,
|
||||
state,
|
||||
model,
|
||||
cli,
|
||||
runtime,
|
||||
...(loaded ? { loaded } : {}),
|
||||
...(connection ? { connection } : {}),
|
||||
...(updatedAt ? { updatedAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const steps = parseSteps(parsed.steps);
|
||||
const current = step(parsed.step);
|
||||
if (!steps || !current || !steps.includes(current)) return IDLE_LOCAL_MODEL_STATE;
|
||||
const error = parseError(parsed.error);
|
||||
if (state === 'failed' && !error) return IDLE_LOCAL_MODEL_STATE;
|
||||
const progress = parseProgress(parsed.progress);
|
||||
const loaded = parseLoaded(parsed.loaded);
|
||||
return {
|
||||
schema: 1,
|
||||
state,
|
||||
step: current,
|
||||
steps,
|
||||
...(state === 'failed' && error ? { error } : {}),
|
||||
model,
|
||||
cli,
|
||||
...(runtime ? { runtime } : {}),
|
||||
...(progress ? { progress } : {}),
|
||||
...(loaded ? { loaded } : {}),
|
||||
...(connection ? { connection } : {}),
|
||||
...(replacedModelId ? { replacedModelId } : {}),
|
||||
...(updatedAt ? { updatedAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Where the state file is. Built from `dataPath()` on every call, so a test's own data dir is honoured. */
|
||||
function stateFilePath(): string {
|
||||
return localModelPaths(OLLAMA_RUNTIME_PIN.version).stateFile;
|
||||
}
|
||||
|
||||
async function readStateFrom(path: string): Promise<LocalModelStateFile> {
|
||||
try {
|
||||
return parseLocalModelState(await fs.readFile(path, 'utf-8'));
|
||||
} catch {
|
||||
return IDLE_LOCAL_MODEL_STATE;
|
||||
}
|
||||
}
|
||||
|
||||
/** The stored state. Never throws: a file that cannot be read is `IDLE_LOCAL_MODEL_STATE`. */
|
||||
export async function readLocalModelState(): Promise<LocalModelStateFile> {
|
||||
return readStateFrom(stateFilePath());
|
||||
}
|
||||
|
||||
async function writeStateFile(path: string, state: LocalModelStateFile): Promise<void> {
|
||||
await fs.mkdir(dirname(path), { recursive: true });
|
||||
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await fs.writeFile(tmp, JSON.stringify(state, null, 2), { mode: 0o600 });
|
||||
await fs.rename(tmp, path);
|
||||
} catch (err) {
|
||||
await fs.rm(tmp, { force: true }).catch(() => {});
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
let mutationChain: Promise<unknown> = Promise.resolve();
|
||||
|
||||
/**
|
||||
* Runs one change to the state file. `fn` receives the current state and returns the state to
|
||||
* write, or `undefined` to write nothing. Resolves with the state before and after the change
|
||||
* (`after` is `undefined` when nothing was written). `updatedAt` is stamped here. A failed
|
||||
* write rejects its own caller only; the chain keeps going.
|
||||
*/
|
||||
export function mutateLocalModelState(
|
||||
fn: (current: LocalModelStateFile) => LocalModelStateFile | undefined
|
||||
): Promise<{ before: LocalModelStateFile; after: LocalModelStateFile | undefined }> {
|
||||
const run = mutationChain.then(async () => {
|
||||
const path = stateFilePath();
|
||||
const before = await readStateFrom(path);
|
||||
const next = fn(before);
|
||||
if (!next) return { before, after: undefined };
|
||||
const after: LocalModelStateFile = { ...next, updatedAt: new Date().toISOString() };
|
||||
await writeStateFile(path, after);
|
||||
return { before, after };
|
||||
});
|
||||
mutationChain = run.catch(() => {});
|
||||
return run;
|
||||
}
|
||||
@@ -134,6 +134,8 @@ export interface RebootRestoreRejection {
|
||||
| 'workspace-forbidden'
|
||||
| 'already-live'
|
||||
| 'capacity-reached'
|
||||
/** The session ran on the model Codeman runs on this Mac, and that model cannot be started on right now. */
|
||||
| 'local-model-not-ready'
|
||||
| 'rebuild-failed';
|
||||
}
|
||||
|
||||
|
||||
@@ -510,6 +510,18 @@ export class GuardedInputBusyError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The session's launch guard refused the start of a new agent process
|
||||
* (`Session.setLaunchGuard()`). Its message is the sentence for the user. A typed error, so a
|
||||
* start that was refused is told apart from a tmux failure and never falls back to a direct PTY.
|
||||
*/
|
||||
export class LaunchRefusedError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'LaunchRefusedError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a programmatic write leaves the keep-alive turn running: the nudge itself, or a bare
|
||||
* Enter (which submits nothing new). Anything else carrying an Enter starts a turn of its own.
|
||||
@@ -880,6 +892,12 @@ export class Session extends EventEmitter {
|
||||
// config dir) without guessing what it once wrote. Persisted disk-only (`__customModel`).
|
||||
private _customModel: CustomModelBookkeeping | undefined;
|
||||
|
||||
// Asked right before a NEW agent process is started for this session (a fresh pane, the
|
||||
// respawn of a dead one, a restart in place), never for an attach to an agent that runs.
|
||||
// Resolves with the sentence that refuses the start, or undefined. Set by the web layer
|
||||
// (`WebServer.setupSessionListeners()`); this file does not know who asks or why.
|
||||
private _launchGuard: (() => Promise<string | undefined>) | null = null;
|
||||
|
||||
// Env keys a retired custom-model selection injected that the NEXT respawn must
|
||||
// `tmux setenv -u`. Deleting a key from `_envOverrides` alone does nothing to the
|
||||
// tmux session, which keeps every `setenv` and hands it to `respawn-pane`, so the
|
||||
@@ -2063,6 +2081,22 @@ export class Session extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets what is asked before a new agent process is started for this session (see
|
||||
* `_launchGuard`). The first user is the model Codeman runs on this Mac: an agent is not
|
||||
* started on it while its runtime is down or its model changed. `null` removes it.
|
||||
*/
|
||||
setLaunchGuard(guard: (() => Promise<string | undefined>) | null): void {
|
||||
this._launchGuard = guard;
|
||||
}
|
||||
|
||||
/** Throws the guard's sentence (`LaunchRefusedError`) when a new agent process must not be started now. */
|
||||
private async _assertLaunchAllowed(): Promise<void> {
|
||||
if (!this._launchGuard) return;
|
||||
const refusal = await this._launchGuard();
|
||||
if (refusal) throw new LaunchRefusedError(refusal);
|
||||
}
|
||||
|
||||
// Custom Model Endpoint Profiles (docs/custom-model-endpoints-plan.md) — public-safe
|
||||
// subset only (never envKeys/configDir/launchModel, the bookkeeping for setCustomModel).
|
||||
get customModel(): CustomModelSelection | undefined {
|
||||
@@ -2635,6 +2669,8 @@ export class Session extends EventEmitter {
|
||||
let respawnedResumeId: string | undefined;
|
||||
if (this._muxSession && mux.isPaneDead(this._muxSession.muxName)) {
|
||||
console.log('[Session] Dead pane detected, respawning:', this._muxSession.muxName);
|
||||
// A new agent process: asked first (see `_launchGuard`). A refusal leaves the pane as it is.
|
||||
await this._assertLaunchAllowed();
|
||||
// Confirmed dead — safe to resolve/pin now (see `_pinOmpRespawnId()`).
|
||||
// `options.respawnPaneOptions` was built eagerly before this dead-pane
|
||||
// check ran, so it still carries the pre-pin ompConfig; rebuild it.
|
||||
@@ -2689,6 +2725,8 @@ export class Session extends EventEmitter {
|
||||
this._resumeSessionId = pinned;
|
||||
}
|
||||
}
|
||||
// A new agent process: asked first (see `_launchGuard`).
|
||||
await this._assertLaunchAllowed();
|
||||
this._muxSession = await mux.createSession(options.createSessionOptions);
|
||||
console.log('[Session] Created mux session:', this._muxSession.muxName);
|
||||
// No extra sleep — createSession() already waits for tmux readiness
|
||||
@@ -2808,6 +2846,9 @@ export class Session extends EventEmitter {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A new agent process: asked first (see `_launchGuard`). A refusal rejects, and the pane
|
||||
// keeps what runs in it.
|
||||
await this._assertLaunchAllowed();
|
||||
this._pinOmpRespawnId();
|
||||
const newPid = await mux.respawnPane(await this._buildRespawnPaneOptionsWithResumePin());
|
||||
if (!newPid) {
|
||||
@@ -3461,6 +3502,9 @@ export class Session extends EventEmitter {
|
||||
this._armPaneSettle(true);
|
||||
}
|
||||
} catch (err) {
|
||||
// A refused launch is an answer, not a tmux failure: it must not fall through to
|
||||
// the direct PTY below, which would start the very process that was refused.
|
||||
if (err instanceof LaunchRefusedError) throw err;
|
||||
if (this._adopt) this._failAdoptedStart(err);
|
||||
console.error('[Session] Failed to create mux session, falling back to direct PTY:', err);
|
||||
this._useMux = false;
|
||||
@@ -3482,6 +3526,8 @@ export class Session extends EventEmitter {
|
||||
throw new Error(`${getModeLabel(this.mode)} sessions require tmux. Direct PTY fallback is not supported.`);
|
||||
}
|
||||
if (this._adopt) this._failAdoptedStart(new Error('tmux is not available'));
|
||||
// A new agent process on this path too: asked first (see `_launchGuard`).
|
||||
await this._assertLaunchAllowed();
|
||||
try {
|
||||
// Pass --session-id to use the SAME ID as the Codeman session
|
||||
// This ensures subagents can be directly matched to the correct tab.
|
||||
@@ -4485,6 +4531,8 @@ export class Session extends EventEmitter {
|
||||
}, 100);
|
||||
}
|
||||
} catch (err) {
|
||||
// As in startInteractive(): a refused launch never falls back to a direct PTY.
|
||||
if (err instanceof LaunchRefusedError) throw err;
|
||||
if (this._adopt) this._failAdoptedStart(err);
|
||||
console.error('[Session] Failed to create mux session, falling back to direct PTY:', err);
|
||||
this._useMux = false;
|
||||
|
||||
+3
-1
@@ -29,7 +29,8 @@
|
||||
* | plan | PlanItem, PlanTaskStatus, TddPhase | In-memory → `GET /api/sessions/:id/plan/tasks` |
|
||||
* | orchestrator | OrchestratorState, OrchestratorPlan, OrchestratorConfig, OrchestratorPersistState | `~/.codeman/state.json` → `GET /api/orchestrator/status` |
|
||||
* | mcp-sync | McpSyncResult, McpSyncTargetResult | Other CLIs' own config files → `GET`/`POST /api/mcp-sync` |
|
||||
* | local-model | HardwareFacts, LocalModelCatalog, Candidate, Recommendation, LocalModelStatus, LOCAL_MODEL_LABELS | In-memory only (nothing persisted) → `GET /api/local-model` |
|
||||
* | local-model | HardwareFacts, LocalModelCatalog, Candidate, Recommendation, RecommendOptions, LOCAL_MODEL_LABELS | In-memory only (nothing persisted) → `GET /api/local-model` |
|
||||
* | local-model-install | LocalModelStatus, LocalModelInstallView, LocalModelStateFile, LocalModelRuntimePin, LOCAL_MODEL_INSTALL_LABELS | `~/.codeman/local-model.json` → `GET /api/local-model` and its install verbs |
|
||||
*
|
||||
* ## Cross-domain relationship map
|
||||
*
|
||||
@@ -79,3 +80,4 @@ export * from './intent.js';
|
||||
export * from './foreign-tmux.js';
|
||||
export * from './mcp-sync.js';
|
||||
export * from './local-model.js';
|
||||
export * from './local-model-install.js';
|
||||
@@ -0,0 +1,638 @@
|
||||
/**
|
||||
* @fileoverview Types of the local model INSTALL: the runtime pin, the job's states, steps and
|
||||
* error codes, the progress, the `install` object of `GET /api/local-model`, the bodies and
|
||||
* answers of the install verbs, and the shape of the state file.
|
||||
*
|
||||
* The read side (hardware, catalogue, recommendation) is in src/types/local-model.ts. This
|
||||
* file holds `LocalModelStatus`, the whole `data` of the GET, because it joins the two.
|
||||
*
|
||||
* Who produces what:
|
||||
* - `LocalModelRuntimePin`: a compiled constant in src/local-model/runtime.ts. No file, no
|
||||
* setting and no request can change which binary is downloaded.
|
||||
* - `LocalModelStateFile`: src/local-model/state-store.ts, the ONE writer of
|
||||
* `local-model.json` (mode 0600, temp file + rename).
|
||||
* - `LocalModelInstallView`: src/local-model/install-job.ts (`buildInstallView()`, pure), from
|
||||
* the state file plus what is live (the runtime child, the developer tools check).
|
||||
* - `LocalModelStatus` and the verb answers: src/web/routes/local-model-routes.ts.
|
||||
*
|
||||
* The HTTP contract. Every route is admin only in multi-user mode (403 `FORBIDDEN`) and
|
||||
* EXPERIMENTAL like the GET (docs/versioning-policy.md). Every verb answers
|
||||
* `{ success: true, data: LocalModelInstallView }` with the view AFTER the verb.
|
||||
*
|
||||
* | Route | Body | Refusals |
|
||||
* |----------------------------------|-----------------------------|-------------------------------------------------------|
|
||||
* | `GET /api/local-model` | none | none (a failed probe is an answer) |
|
||||
* | `POST /api/local-model/install` | `LocalModelInstallRequest` | 400 not a row the server offers, or a saved endpoint |
|
||||
* | | | already has the reserved id; 409 `job-running`, |
|
||||
* | | | `already-installed`, `size-changed` |
|
||||
* | `POST /api/local-model/cancel` | none | 409 `wrong-state` (no job is running) |
|
||||
* | `POST /api/local-model/resume` | `LocalModelResumeRequest` | 409 `job-running`, `wrong-state` (not paused or |
|
||||
* | | | failed), `sessions-open` (another port while live |
|
||||
* | | | sessions use the model) |
|
||||
* | `POST /api/local-model/runtime` | `LocalModelRuntimeRequest` | 409 `wrong-state` (not installed), `job-running`, |
|
||||
* | | | `sessions-open` (stop, or another port, while live |
|
||||
* | | | sessions use the model) |
|
||||
* | `DELETE /api/local-model` | `LocalModelRemoveRequest` | 409 `job-running`, `sessions-open` |
|
||||
*
|
||||
* A 409 is the error envelope plus `data: LocalModelConflict`:
|
||||
* `{ success: false, error, errorCode: 'CONFLICT', data: { reason, message, ... } }`. A 409
|
||||
* WITHOUT `data` is a write of `settings.json` or of the endpoint store that was refused
|
||||
* because the file does not parse; `error` names the fix. A 400 the service names carries its
|
||||
* sentence the same way: `{ success: false, error, errorCode: 'INVALID_INPUT', data: {
|
||||
* message } }` (`LocalModelRefusal`), so the window can print it in its own language.
|
||||
*
|
||||
* The rules of src/types/local-model.ts hold here too:
|
||||
* 1. A size a person reads travels twice: as bytes and as decimal GB text from `formatGb()`
|
||||
* (`completedGb`, `totalGb`, `downloadGb`). The browser prints the text and adds or
|
||||
* divides nothing for display. `mbPerSecond` is the one other unit, decimal MB per second.
|
||||
* 2. Every sentence the server chooses comes from `LOCAL_MODEL_INSTALL_LABELS`, with its
|
||||
* numbers and names in `vars`. `{name}` is taken by the translator, so no slot has that name.
|
||||
* 3. A CLI id is data (`LocalModelInstallView.cli`): the browser passes it on and compares it
|
||||
* with nothing. What a person reads is `cliLabel`.
|
||||
*/
|
||||
|
||||
import type { HardwareFacts, Recommendation } from './local-model.js';
|
||||
|
||||
// ---------- The runtime pin ----------
|
||||
|
||||
/**
|
||||
* The one runtime build Codeman downloads and runs. A compiled constant
|
||||
* (`OLLAMA_RUNTIME_PIN` in src/local-model/runtime.ts): the hash is compared before anything
|
||||
* is unpacked, so the pin and the hash must come from the same reviewed source file.
|
||||
*/
|
||||
export interface LocalModelRuntimePin {
|
||||
/** The runtime's family. One value today. */
|
||||
id: 'ollama';
|
||||
/** The release ('0.40.15'). `GET /api/version` of the running runtime must answer it. */
|
||||
version: string;
|
||||
/** Where the archive is downloaded from. https, a fixed release asset. */
|
||||
url: string;
|
||||
/** Size of the archive in bytes. A body that grows past it is refused before the hash is finished. */
|
||||
bytes: number;
|
||||
/** Lowercase hex sha256 of the archive. */
|
||||
sha256: string;
|
||||
/** What the unpacked folder takes on disk, in bytes (measured: about 579 MB). */
|
||||
unpackedBytes: number;
|
||||
/** The oldest macOS major version the runtime supports. */
|
||||
minMacosMajor: number;
|
||||
}
|
||||
|
||||
// ---------- States, steps, codes ----------
|
||||
|
||||
/**
|
||||
* Where the install stands. The verb of the flow is the same throughout: install, installing,
|
||||
* installed.
|
||||
* - `idle`: nothing is installed and no job exists.
|
||||
* - `installing`: the one job is running; `step` says where.
|
||||
* - `paused`: the job stopped at `step` because of Cancel or a server restart. It never
|
||||
* continues without a click.
|
||||
* - `failed`: the job stopped at `step` with `error`.
|
||||
* - `installed`: the model is connected. Whether the runtime runs is `running`, not a state.
|
||||
* The state table (what is on disk, what a restart and Cancel do, the allowed actions) is
|
||||
* `INSTALL_STATE_TABLE` in src/local-model/install-job.ts.
|
||||
*/
|
||||
export type LocalModelInstallState = 'idle' | 'installing' | 'paused' | 'failed' | 'installed';
|
||||
|
||||
/**
|
||||
* The steps of a job, in the order they run.
|
||||
* - `runtime`: get the pinned runtime (download, compare the hash, unpack), start it, read
|
||||
* the measured memory budget and judge the chosen model against it.
|
||||
* - `model`: download the model (the runtime's pull).
|
||||
* - `verify`: load the model and check it: one tiny chat, the memory and context the runtime
|
||||
* reports, one tool call.
|
||||
* - `agent`: install the coding agent. Left out of a job whose coding agent is installed.
|
||||
* - `connect`: save the connection (the endpoint record and the settings flag).
|
||||
*/
|
||||
export type LocalModelInstallStep = 'runtime' | 'model' | 'verify' | 'agent' | 'connect';
|
||||
|
||||
/** Every step, in order. A job runs these, without `agent` when the coding agent is installed. */
|
||||
export const LOCAL_MODEL_INSTALL_STEPS: readonly LocalModelInstallStep[] = [
|
||||
'runtime',
|
||||
'model',
|
||||
'verify',
|
||||
'agent',
|
||||
'connect',
|
||||
];
|
||||
|
||||
/**
|
||||
* Why a job failed, or (in state `installed`) what blocks a session. Each code has one
|
||||
* sentence (`LOCAL_MODEL_ERROR_LABELS`) and one helpful next step (`LOCAL_MODEL_ERROR_NEXT`).
|
||||
*
|
||||
* | Code | Raised when |
|
||||
* |---------------------------|--------------------------------------------------------------------------|
|
||||
* | `runtime-download-failed` | the archive download still fails after its retries |
|
||||
* | `runtime-damaged` | the archive's sha256 is not the pinned one (the file was deleted) |
|
||||
* | `runtime-unpack-failed` | `/usr/bin/tar` failed |
|
||||
* | `runtime-start-failed` | the runtime was started and never answered `/api/version`. Installed: |
|
||||
* | | the last start failed (the detail says why), and Start tries again |
|
||||
* | `runtime-stopped` | the runtime crashed and was restarted 3 times, then given up: on an |
|
||||
* | | installed model, or during a job's download |
|
||||
* | `runtime-not-running` | installed: the runtime is not running (the person stopped it). Only a |
|
||||
* | | refused session start says it; the view shows no error for a stopped runtime |
|
||||
* | `port-in-use` | another program listens on the stored port, or no port of the span is free |
|
||||
* | `disk-full` | a write failed for lack of space |
|
||||
* | `pull-failed` | the pull still ends on an error line or a cut stream after its retries |
|
||||
* | `model-not-found` | the registry no longer has this model under this name |
|
||||
* | `does-not-fit` | the measured budget rules the model out, or the runtime did not put all of it on the GPU |
|
||||
* | `context-not-applied` | the runtime loaded the model with another context than the chosen one |
|
||||
* | `load-failed` | the tiny chat that loads the model failed |
|
||||
* | `no-tool-call` | the tool probe was answered without a tool call with parseable arguments |
|
||||
* | `probe-unfinished` | the tool probe ended on its token limit, so it proves nothing |
|
||||
* | `harness-failed` | the coding agent's install command failed, or its binary is still missing |
|
||||
* | `endpoint-id-taken` | a saved endpoint with our id exists that this feature did not write |
|
||||
* | `connect-failed` | the endpoint record or the settings flag could not be written |
|
||||
* | `model-changed` | installed: the model's digest is not the one stored at install time |
|
||||
* | `internal` | anything unexpected (the exception text is in `detail`) |
|
||||
*/
|
||||
export type LocalModelErrorCode =
|
||||
| 'runtime-download-failed'
|
||||
| 'runtime-damaged'
|
||||
| 'runtime-unpack-failed'
|
||||
| 'runtime-start-failed'
|
||||
| 'runtime-stopped'
|
||||
| 'runtime-not-running'
|
||||
| 'port-in-use'
|
||||
| 'disk-full'
|
||||
| 'pull-failed'
|
||||
| 'model-not-found'
|
||||
| 'does-not-fit'
|
||||
| 'context-not-applied'
|
||||
| 'load-failed'
|
||||
| 'no-tool-call'
|
||||
| 'probe-unfinished'
|
||||
| 'harness-failed'
|
||||
| 'endpoint-id-taken'
|
||||
| 'connect-failed'
|
||||
| 'model-changed'
|
||||
| 'internal';
|
||||
|
||||
/**
|
||||
* The ONE action that helps after an error. The window draws one button for it.
|
||||
* - `retry`: "Try again". `POST /api/local-model/resume`.
|
||||
* - `other-port`: "Use another port". `POST /api/local-model/resume` with `newPort: true`
|
||||
* (state `failed`), or `POST /api/local-model/runtime` with `action: 'start'` and
|
||||
* `newPort: true` (state `installed`).
|
||||
* - `next-model`: "Try <model>". Back to the chooser with `error.nextModel` preselected; the
|
||||
* person confirms its sizes and a new `POST /api/local-model/install` replaces the job.
|
||||
* Without a `nextModel` the window offers the chooser and Remove.
|
||||
* - `start`: "Start". `POST /api/local-model/runtime` with `action: 'start'`.
|
||||
* - `remove`: "Remove". `DELETE /api/local-model`.
|
||||
*
|
||||
* `LOCAL_MODEL_ERROR_NEXT` is the default of a code. The view adapts it to the state the
|
||||
* error is shown in, so the button is always one the server accepts there: a code whose
|
||||
* default is `start` says `retry` on a failed job (there is no Start verb for a job), and
|
||||
* `runtime-start-failed` says `start` on an installed model (there is nothing to resume).
|
||||
*/
|
||||
export type LocalModelNextStep = 'retry' | 'other-port' | 'next-model' | 'start' | 'remove';
|
||||
|
||||
/**
|
||||
* What a client may do in the current state. The view's `actions` lists exactly the ones the
|
||||
* server would accept right now, so the window shows a button only for those.
|
||||
* - `install`: `POST /api/local-model/install`.
|
||||
* - `cancel`: `POST /api/local-model/cancel`.
|
||||
* - `resume`: `POST /api/local-model/resume`.
|
||||
* - `start` and `stop`: `POST /api/local-model/runtime`.
|
||||
* - `remove`: `DELETE /api/local-model`.
|
||||
* - `start-session`: not a route of this feature: the window starts a session on the endpoint
|
||||
* `endpointId` with the coding agent `cli`. Offered only while the runtime runs and nothing
|
||||
* blocks a session.
|
||||
*/
|
||||
export type LocalModelAction = 'install' | 'cancel' | 'resume' | 'start' | 'stop' | 'remove' | 'start-session';
|
||||
|
||||
/** Whether the Mac has the developer tools (git, Python) a coding agent calls. */
|
||||
export type LocalModelDeveloperTools =
|
||||
/** `/usr/bin/xcode-select -p` succeeded. */
|
||||
| 'present'
|
||||
/** It failed: macOS will offer to install the tools the first time an agent needs one. */
|
||||
| 'missing'
|
||||
/** Not macOS, or the check did not answer in time. Nothing is said then. */
|
||||
| 'unknown';
|
||||
|
||||
// ---------- Sentences ----------
|
||||
|
||||
/**
|
||||
* Every sentence the server may put into the `install` object or a 409, in English (the i18n
|
||||
* source language). Like `LOCAL_MODEL_LABELS`: the zh-CN dictionary in src/web/public/i18n.js
|
||||
* has one entry per value, keyed by this exact text, and the i18n test lists them from here.
|
||||
* A constant of its own, so the sentences of the recommendation and of the install can be
|
||||
* listed apart.
|
||||
*
|
||||
* | Key | Slots (all text) |
|
||||
* |------------------------|----------------------------------------------------------------------|
|
||||
* | `errPortInUse` | `port`: the port number |
|
||||
* | `errModelNotFound`, `errDoesNotFit`, `errLoadFailed`, `errNoToolCall`, `errProbeUnfinished` | `model`: the model's label |
|
||||
* | `errContextNotApplied` | `model`; `actual`: the context the runtime reports; `wanted`: the chosen one |
|
||||
* | `errHarnessFailed` | `cli`: the coding agent's label |
|
||||
* | `errEndpointIdTaken` | `id`: the endpoint id this feature uses |
|
||||
* | `refusedAgentNotInstallable` | `cli`: the coding agent's label |
|
||||
* | `refusedOtherModel` | `model`: the label of the model that is installed |
|
||||
* | `conflictSizeChanged` | `size`: the server's own total as decimal GB |
|
||||
* | `conflictSessionsOpen` | `sessions`: the session names, joined with ', ' |
|
||||
*
|
||||
* `developerToolsMissing` is not sent: the view carries `developerTools` and the window prints
|
||||
* this sentence when it is `missing`. It is here so that its wording has one source.
|
||||
*
|
||||
* `endpointManaged` and `endpointIdReserved` are what the endpoint routes
|
||||
* (src/web/routes/custom-model-routes.ts) answer for the record this feature manages and for
|
||||
* its reserved id. They have no slot, so the App Settings toast that prints them translates
|
||||
* them as it translates every other whole sentence.
|
||||
*/
|
||||
export const LOCAL_MODEL_INSTALL_LABELS = {
|
||||
errRuntimeDownloadFailed:
|
||||
'The download of the runtime stopped and could not be continued. Check the network connection, then try again.',
|
||||
errRuntimeDamaged: 'The runtime download was damaged and has been deleted. Try again.',
|
||||
errRuntimeUnpackFailed: 'The runtime could not be unpacked on this Mac.',
|
||||
errRuntimeStartFailed: 'The runtime did not start on this Mac.',
|
||||
errRuntimeStopped: 'The runtime keeps stopping, so Codeman no longer restarts it.',
|
||||
errRuntimeNotRunning: 'The model on this Mac is not running. Start it first.',
|
||||
errPortInUse: 'Port {port} is in use by another program.',
|
||||
errDiskFull: 'The disk is full. Free up space, then try again.',
|
||||
errPullFailed: 'The download keeps stopping. The network may be damaging data. Try again or use another network.',
|
||||
errModelNotFound: '{model} is no longer offered under this name. Update Codeman or pick another model.',
|
||||
errDoesNotFit: '{model} does not fit in the memory of this Mac after all.',
|
||||
errContextNotApplied: '{model} loaded with a context of {actual} tokens instead of {wanted}.',
|
||||
errLoadFailed: '{model} did not load on this Mac.',
|
||||
errNoToolCall: '{model} loaded but did not call a tool, so a coding agent cannot work with it.',
|
||||
errProbeUnfinished: 'The check of {model} did not finish.',
|
||||
errHarnessFailed: '{cli} could not be installed.',
|
||||
errEndpointIdTaken:
|
||||
'A saved model connection named {id} already exists and was not created here. Rename or delete it in App Settings, then try again.',
|
||||
errConnectFailed: 'Codeman could not save the connection to the model.',
|
||||
errModelChanged: 'The model on this Mac changed since it was installed. Remove it and install it again.',
|
||||
errInternal: 'The install stopped on an unexpected error.',
|
||||
conflictJobRunning: 'An install is already running.',
|
||||
conflictAlreadyInstalled: 'A model is already installed on this Mac. Remove it first.',
|
||||
conflictSizeChanged: 'The download is {size} GB now. Check the sizes and confirm again.',
|
||||
conflictSessionsOpen: 'Sessions are still using this model: {sessions}. Close them first.',
|
||||
conflictWrongState: 'That is not possible in the current state.',
|
||||
refusedModelNotOffered: 'This model at this context is not offered for this Mac right now.',
|
||||
refusedAgentNotOffered: 'This coding agent is not offered for this model.',
|
||||
refusedAgentNotInstallable: '{cli} is not installed and cannot be installed from here.',
|
||||
refusedOtherModel: 'Only {model} is installed on this Mac. Remove it and install another model first.',
|
||||
endpointManaged:
|
||||
'This endpoint belongs to the model Codeman runs on this Mac. Change or remove it in the local model window.',
|
||||
endpointIdReserved: 'This endpoint id is reserved for the model Codeman runs on this Mac. Pick another id.',
|
||||
developerToolsMissing:
|
||||
'Coding agents use git and Python. This Mac has no developer tools yet, so macOS will offer to install them the first time an agent needs one.',
|
||||
} as const;
|
||||
|
||||
/** One of the texts in `LOCAL_MODEL_INSTALL_LABELS`. */
|
||||
export type LocalModelInstallLabel = (typeof LOCAL_MODEL_INSTALL_LABELS)[keyof typeof LOCAL_MODEL_INSTALL_LABELS];
|
||||
|
||||
/** A sentence of the install: a text from `LOCAL_MODEL_INSTALL_LABELS` plus the values of its `{placeholder}` slots. */
|
||||
export interface LocalModelInstallMessage {
|
||||
text: LocalModelInstallLabel;
|
||||
/** Slot values, already formatted as text. Absent when the text has no slot. */
|
||||
vars?: Record<string, string>;
|
||||
}
|
||||
|
||||
/** The sentence of each error code. */
|
||||
export const LOCAL_MODEL_ERROR_LABELS: Record<LocalModelErrorCode, LocalModelInstallLabel> = {
|
||||
'runtime-download-failed': LOCAL_MODEL_INSTALL_LABELS.errRuntimeDownloadFailed,
|
||||
'runtime-damaged': LOCAL_MODEL_INSTALL_LABELS.errRuntimeDamaged,
|
||||
'runtime-unpack-failed': LOCAL_MODEL_INSTALL_LABELS.errRuntimeUnpackFailed,
|
||||
'runtime-start-failed': LOCAL_MODEL_INSTALL_LABELS.errRuntimeStartFailed,
|
||||
'runtime-stopped': LOCAL_MODEL_INSTALL_LABELS.errRuntimeStopped,
|
||||
'runtime-not-running': LOCAL_MODEL_INSTALL_LABELS.errRuntimeNotRunning,
|
||||
'port-in-use': LOCAL_MODEL_INSTALL_LABELS.errPortInUse,
|
||||
'disk-full': LOCAL_MODEL_INSTALL_LABELS.errDiskFull,
|
||||
'pull-failed': LOCAL_MODEL_INSTALL_LABELS.errPullFailed,
|
||||
'model-not-found': LOCAL_MODEL_INSTALL_LABELS.errModelNotFound,
|
||||
'does-not-fit': LOCAL_MODEL_INSTALL_LABELS.errDoesNotFit,
|
||||
'context-not-applied': LOCAL_MODEL_INSTALL_LABELS.errContextNotApplied,
|
||||
'load-failed': LOCAL_MODEL_INSTALL_LABELS.errLoadFailed,
|
||||
'no-tool-call': LOCAL_MODEL_INSTALL_LABELS.errNoToolCall,
|
||||
'probe-unfinished': LOCAL_MODEL_INSTALL_LABELS.errProbeUnfinished,
|
||||
'harness-failed': LOCAL_MODEL_INSTALL_LABELS.errHarnessFailed,
|
||||
'endpoint-id-taken': LOCAL_MODEL_INSTALL_LABELS.errEndpointIdTaken,
|
||||
'connect-failed': LOCAL_MODEL_INSTALL_LABELS.errConnectFailed,
|
||||
'model-changed': LOCAL_MODEL_INSTALL_LABELS.errModelChanged,
|
||||
internal: LOCAL_MODEL_INSTALL_LABELS.errInternal,
|
||||
};
|
||||
|
||||
/** The one helpful next step of each error code. */
|
||||
export const LOCAL_MODEL_ERROR_NEXT: Record<LocalModelErrorCode, LocalModelNextStep> = {
|
||||
'runtime-download-failed': 'retry',
|
||||
'runtime-damaged': 'retry',
|
||||
'runtime-unpack-failed': 'retry',
|
||||
'runtime-start-failed': 'retry',
|
||||
'runtime-stopped': 'start',
|
||||
'runtime-not-running': 'start',
|
||||
'port-in-use': 'other-port',
|
||||
'disk-full': 'retry',
|
||||
'pull-failed': 'retry',
|
||||
'model-not-found': 'next-model',
|
||||
'does-not-fit': 'next-model',
|
||||
'context-not-applied': 'retry',
|
||||
'load-failed': 'retry',
|
||||
'no-tool-call': 'next-model',
|
||||
'probe-unfinished': 'retry',
|
||||
'harness-failed': 'retry',
|
||||
'endpoint-id-taken': 'retry',
|
||||
'connect-failed': 'retry',
|
||||
'model-changed': 'remove',
|
||||
internal: 'retry',
|
||||
};
|
||||
|
||||
// ---------- The `install` object of the GET ----------
|
||||
|
||||
/**
|
||||
* How far a download is. Present while the `runtime` step downloads the archive and while the
|
||||
* `model` step pulls, once the total is known; kept on a paused or failed job as it stood.
|
||||
* During the `model` step both byte figures come from the pull's own lines, never from the
|
||||
* catalogue.
|
||||
*/
|
||||
export interface LocalModelProgress {
|
||||
completedBytes: number;
|
||||
totalBytes: number;
|
||||
/** `completedBytes` as decimal GB text, no unit ('6.2'). */
|
||||
completedGb: string;
|
||||
/** `totalBytes` as decimal GB text, no unit ('23.1'). */
|
||||
totalGb: string;
|
||||
/** Download speed. Absent until it can be told (the first moments, a paused job). */
|
||||
bytesPerSecond?: number;
|
||||
/** `bytesPerSecond` as whole decimal megabytes per second, no unit ('58'). Present exactly when `bytesPerSecond` is. */
|
||||
mbPerSecond?: string;
|
||||
/** Seconds left at the current speed, rounded up. Absent when the speed is unknown or 0. */
|
||||
secondsLeft?: number;
|
||||
}
|
||||
|
||||
/** An error as the window shows it: the sentence, the one action that helps, and the raw detail. */
|
||||
export interface LocalModelInstallError {
|
||||
code: LocalModelErrorCode;
|
||||
/** `LOCAL_MODEL_ERROR_LABELS[code]` with its slots filled. */
|
||||
message: LocalModelInstallMessage;
|
||||
/** `LOCAL_MODEL_ERROR_NEXT[code]`, adapted to the state the error is shown in (see `LocalModelNextStep`). */
|
||||
next: LocalModelNextStep;
|
||||
/**
|
||||
* For `next-model`: the model to try instead. After `does-not-fit` it is one that needs LESS
|
||||
* memory than the one that failed; after the other codes the best other model that fits.
|
||||
* Absent when there is none.
|
||||
*/
|
||||
nextModel?: { modelId: string; modelLabel: string };
|
||||
/**
|
||||
* Raw text for the person who wants to know more: the last lines of an installer, the
|
||||
* message of a refused write, an exception. Not translated; printed with `textContent`.
|
||||
*/
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
/** The model of the job or of the installation. */
|
||||
export interface LocalModelInstalledModel {
|
||||
/** `LocalModelEntry.id`. */
|
||||
id: string;
|
||||
/** `LocalModelEntry.label`. */
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** The runtime, as the consent screen needs it. */
|
||||
export interface LocalModelRuntimeView {
|
||||
/** `LocalModelRuntimePin.version`. */
|
||||
version: string;
|
||||
/** The pinned runtime is unpacked on disk. Then an install downloads only the model. */
|
||||
installed: boolean;
|
||||
/** What an install would download for the runtime: the archive size, 0 when `installed`. */
|
||||
downloadBytes: number;
|
||||
/** `downloadBytes` as decimal GB text, no unit ('0.2'). */
|
||||
downloadGb: string;
|
||||
/** What the unpacked runtime takes on disk, as decimal GB text, no unit ('0.6'). */
|
||||
unpackedGb: string;
|
||||
}
|
||||
|
||||
/** What the runtime reported about the loaded model when the job checked it. The facts of the Done line. */
|
||||
export interface LocalModelLoadedFacts {
|
||||
/** The context length in tokens the runtime loaded the model with. */
|
||||
context: number;
|
||||
/** Memory the loaded model took, in bytes (`size` of the runtime's process list). */
|
||||
memoryBytes: number;
|
||||
/** `memoryBytes` as decimal GB text, no unit. */
|
||||
memoryGb: string;
|
||||
/** All of it is on the GPU (`size_vram` equals `size`). Always true after a job that passed. */
|
||||
onGpu: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `install` object of `GET /api/local-model`: where the install stands and what can be
|
||||
* done about it. The window polls it once a second while it is open; there is no SSE event.
|
||||
*
|
||||
* Which members are present, by state:
|
||||
*
|
||||
* | Member | idle | installing | paused | failed | installed |
|
||||
* |-----------------------------------|------|------------|--------|--------|-----------|
|
||||
* | `step`, `steps` | | yes | yes | yes | |
|
||||
* | `progress` | | during a download | as it stood, when known | as it stood, when known | |
|
||||
* | `error` | | | | yes | only when something blocks a session |
|
||||
* | `model`, `cli`, `cliLabel`, `context` | | yes | yes | yes | yes |
|
||||
* | `port` | | once chosen | once chosen | once chosen | yes |
|
||||
* | `loaded`, `endpointId` | | | | | yes |
|
||||
*
|
||||
* `running`, `developerTools`, `runtime`, `folder` and `actions` are always present.
|
||||
*/
|
||||
export interface LocalModelInstallView {
|
||||
state: LocalModelInstallState;
|
||||
/** The step the job is in, or stopped in. */
|
||||
step?: LocalModelInstallStep;
|
||||
/** The steps of THIS job in order, for the step list (`agent` is absent when the coding agent was already installed). */
|
||||
steps?: LocalModelInstallStep[];
|
||||
progress?: LocalModelProgress;
|
||||
error?: LocalModelInstallError;
|
||||
model?: LocalModelInstalledModel;
|
||||
/** The coding agent: a CLI registry id, as data. */
|
||||
cli?: string;
|
||||
/** The coding agent's display label ('OpenCode'). */
|
||||
cliLabel?: string;
|
||||
/** The context length in tokens the runtime is started with. */
|
||||
context?: number;
|
||||
/** The loopback port of the runtime. */
|
||||
port?: number;
|
||||
/** The runtime child Codeman started is alive right now. */
|
||||
running: boolean;
|
||||
developerTools: LocalModelDeveloperTools;
|
||||
runtime: LocalModelRuntimeView;
|
||||
/** The absolute folder everything of this feature is kept in, for the "where it goes" line. */
|
||||
folder: string;
|
||||
loaded?: LocalModelLoadedFacts;
|
||||
/** The id of the saved endpoint a session is started on. */
|
||||
endpointId?: string;
|
||||
/** What the server accepts right now, see `LocalModelAction`. */
|
||||
actions: LocalModelAction[];
|
||||
}
|
||||
|
||||
/** The `data` of `GET /api/local-model`. Admin only in multi-user mode. */
|
||||
export interface LocalModelStatus {
|
||||
hardware: HardwareFacts;
|
||||
recommendation: Recommendation;
|
||||
/** `LocalModelCatalog.updated`. */
|
||||
catalogUpdated: string;
|
||||
/** Where the install stands. Always present. */
|
||||
install: LocalModelInstallView;
|
||||
}
|
||||
|
||||
// ---------- Request bodies and answers ----------
|
||||
|
||||
/**
|
||||
* Body of `POST /api/local-model/install`. The three choices must name a row the server offers
|
||||
* right now: a model of `recommendation.pick` or `recommendation.alternatives`, at that
|
||||
* candidate's `context`, with one of its `harnesses`. Anything else is a 400 before any
|
||||
* download.
|
||||
*/
|
||||
export interface LocalModelInstallRequest {
|
||||
/** `Candidate.modelId`. */
|
||||
modelId: string;
|
||||
/** `CandidateHarness.cli`. */
|
||||
cli: string;
|
||||
/** `Candidate.context`. */
|
||||
context: number;
|
||||
/**
|
||||
* The total the person saw and confirmed: `Candidate.installBytes`. The server compares it
|
||||
* with its own total and answers 409 `size-changed` when they differ, so a consent is bound
|
||||
* to the size that was shown.
|
||||
*/
|
||||
acknowledgedBytes: number;
|
||||
}
|
||||
|
||||
/** Body of `POST /api/local-model/resume`. May be absent or empty. */
|
||||
export interface LocalModelResumeRequest {
|
||||
/** True: choose another port first (the answer to `port-in-use`). */
|
||||
newPort?: boolean;
|
||||
}
|
||||
|
||||
/** Body of `POST /api/local-model/runtime`. */
|
||||
export interface LocalModelRuntimeRequest {
|
||||
/** `stop` also keeps the runtime from being started at the next boot; `start` undoes that. */
|
||||
action: 'start' | 'stop';
|
||||
/** With `start`: choose another port first (the answer to `port-in-use`), and move the saved endpoint to it. */
|
||||
newPort?: boolean;
|
||||
}
|
||||
|
||||
/** Body of `DELETE /api/local-model`. May be absent or empty. */
|
||||
export interface LocalModelRemoveRequest {
|
||||
/** True: delete the downloaded model too. Default false: the model stays for a later install. */
|
||||
removeModel?: boolean;
|
||||
}
|
||||
|
||||
/** The `data` of a 400 the service names: its sentence, for the window to print in its own language. */
|
||||
export interface LocalModelRefusal {
|
||||
message: LocalModelInstallMessage;
|
||||
}
|
||||
|
||||
/** What every verb answers on success: the view after the verb. */
|
||||
export type LocalModelVerbAnswer = LocalModelInstallView;
|
||||
|
||||
/**
|
||||
* Why a verb was refused with 409.
|
||||
* - `job-running`: a job is running (a second install, a resume, a remove or a runtime action).
|
||||
* - `already-installed`: install while a model is installed. Remove it first.
|
||||
* - `size-changed`: `acknowledgedBytes` is not the server's total; `expectedBytes` and
|
||||
* `expectedGb` carry that total, so the window can show it and ask again.
|
||||
* - `sessions-open`: remove, stop or a change of port while live sessions use the endpoint;
|
||||
* `sessions` names them. Their coding agents were given the runtime's address when they
|
||||
* started, so they would go on calling a port nothing of ours holds.
|
||||
* - `wrong-state`: the verb makes no sense in the current state (see the route table above).
|
||||
*/
|
||||
export type LocalModelConflictReason =
|
||||
| 'job-running'
|
||||
| 'already-installed'
|
||||
| 'size-changed'
|
||||
| 'sessions-open'
|
||||
| 'wrong-state';
|
||||
|
||||
/** The `data` of a 409 of an install verb. */
|
||||
export interface LocalModelConflict {
|
||||
reason: LocalModelConflictReason;
|
||||
/** The sentence for the window (`conflict...` of `LOCAL_MODEL_INSTALL_LABELS`). */
|
||||
message: LocalModelInstallMessage;
|
||||
/** `size-changed`: the server's own total in bytes. */
|
||||
expectedBytes?: number;
|
||||
/** `size-changed`: `expectedBytes` as decimal GB text, no unit. */
|
||||
expectedGb?: string;
|
||||
/** `sessions-open`: the names of the live sessions that use the endpoint. */
|
||||
sessions?: string[];
|
||||
}
|
||||
|
||||
// ---------- The state file ----------
|
||||
|
||||
/**
|
||||
* `local-model.json` in the data dir: everything that must survive a restart. Mode 0600,
|
||||
* written through a temp file and a rename, by src/local-model/state-store.ts alone.
|
||||
*
|
||||
* Rules:
|
||||
* - It holds NO path. Every path of this feature is built from `dataPath()` constants
|
||||
* (`localModelPaths()`), so a state file can never point a delete somewhere else.
|
||||
* - Reading is total: a missing file, a file that does not parse or one with another `schema`
|
||||
* reads as `{ schema: 1, state: 'idle' }`.
|
||||
* - A file read at boot with state `installing` is a job a restart interrupted: it becomes
|
||||
* `paused` before anything else looks at it.
|
||||
*/
|
||||
export interface LocalModelStateFile {
|
||||
schema: 1;
|
||||
state: LocalModelInstallState;
|
||||
/** The step the job is in or stopped in. Absent in `idle` and `installed`. */
|
||||
step?: LocalModelInstallStep;
|
||||
/** The steps of the job, in order. Absent in `idle` and `installed`. */
|
||||
steps?: LocalModelInstallStep[];
|
||||
/** State `failed`: why. State `installed`: absent (a blocking problem is found live, never stored). */
|
||||
error?: {
|
||||
code: LocalModelErrorCode;
|
||||
/** The slot values of the code's sentence. */
|
||||
vars?: Record<string, string>;
|
||||
detail?: string;
|
||||
/** For a `next-model` code: the model to offer, when the job knew one. */
|
||||
nextModelId?: string;
|
||||
};
|
||||
/** The model of the job or of the installation. */
|
||||
model?: {
|
||||
id: string;
|
||||
label: string;
|
||||
/** The context length in tokens the person chose. */
|
||||
context: number;
|
||||
/** The total the pull reported, once known. */
|
||||
pullBytes?: number;
|
||||
/** The digest `/api/tags` reported after the pull. Compared again at boot and before a session starts. */
|
||||
digest?: string;
|
||||
};
|
||||
/**
|
||||
* The model of the job this one replaced, when it was another model: what that job left in
|
||||
* the model store is deleted once the runtime runs, before the new model is downloaded.
|
||||
* Absent once that was done, and in `idle` and `installed`.
|
||||
*/
|
||||
replacedModelId?: string;
|
||||
/** The coding agent of the job or of the installation. */
|
||||
cli?: { id: string; label: string };
|
||||
/** The runtime, once its port was chosen. */
|
||||
runtime?: {
|
||||
/**
|
||||
* The runtime version this installation runs. A later build with another pin keeps
|
||||
* starting this version for as long as its folder is unpacked.
|
||||
*/
|
||||
version: string;
|
||||
/** The loopback port, chosen once by binding. */
|
||||
port: number;
|
||||
/**
|
||||
* The pid of the child Codeman last started, stored the moment it is spawned. Used to
|
||||
* tell our own runtime from another program: at boot, and before the folder is deleted.
|
||||
*/
|
||||
pid?: number;
|
||||
/** False after Stop: the runtime is not started at boot. */
|
||||
enabled: boolean;
|
||||
/** The device total the runtime printed when it started, in bytes. */
|
||||
measuredTotalBytes?: number;
|
||||
};
|
||||
/** How far the last download was when the job paused or failed. A restart may leave it absent. */
|
||||
progress?: { completedBytes: number; totalBytes: number };
|
||||
/** What the runtime reported when the job checked the loaded model. */
|
||||
loaded?: { context: number; sizeBytes: number; sizeVramBytes: number };
|
||||
/**
|
||||
* Present once the `connect` step CLAIMED the connection, which it does before its two
|
||||
* writes: what uninstall must undo. A claim with nothing behind it (the step was interrupted
|
||||
* right after it) is harmless: a resumed job writes both, and uninstall removes nothing.
|
||||
*/
|
||||
connection?: {
|
||||
/** The id of the endpoint record this feature wrote. */
|
||||
endpointId: string;
|
||||
/** The value `customModelEndpointsEnabled` had before this feature switched it on. */
|
||||
flagWasEnabled: boolean;
|
||||
};
|
||||
/** ISO time of the last write. */
|
||||
updatedAt?: string;
|
||||
}
|
||||
+215
-48
@@ -1,9 +1,12 @@
|
||||
/**
|
||||
* @fileoverview Types of the hardware-aware local model recommendation: what the server sees of
|
||||
* this Mac, the catalogue of models and harnesses, and the answer of `GET /api/local-model`.
|
||||
* this Mac, the catalogue of models and harnesses, and the recommendation part of the answer of
|
||||
* `GET /api/local-model`.
|
||||
*
|
||||
* This stage is read-only: Codeman looks at the Mac and recommends. It downloads nothing,
|
||||
* installs nothing and writes no file.
|
||||
* Everything here is the READ side: Codeman looks at the Mac and recommends. The types of the
|
||||
* install (the job states, the progress, the `install` object of the GET, the request bodies,
|
||||
* the state file, the runtime pin) and `LocalModelStatus`, the whole `data` of the GET, are in
|
||||
* src/types/local-model-install.ts. Both files go out through the barrel (`../types.js`).
|
||||
*
|
||||
* Who produces what:
|
||||
* - `HardwareFacts`: src/local-model/hardware.ts (one bounded `sysctl` spawn, never throws).
|
||||
@@ -11,7 +14,11 @@
|
||||
* - `HarnessFact`: src/local-model/harness-facts.ts (server only, read from the CLI registry at
|
||||
* call time; it holds a function, so it never goes over HTTP).
|
||||
* - `Recommendation`, `Candidate`, `DeviceBudget`: src/local-model/recommend.ts (pure).
|
||||
* - `LocalModelStatus`: src/web/routes/local-model-routes.ts (the `data` of the GET).
|
||||
*
|
||||
* A field that is optional here is optional by meaning, and its comment says when it is
|
||||
* absent (a tested entry without a measured speed, a harness that needs no install command, a
|
||||
* row without a tag). Everything else is always there, so the chooser window and the install
|
||||
* job may rely on it.
|
||||
*
|
||||
* Three rules every producer and consumer follows:
|
||||
*
|
||||
@@ -90,7 +97,11 @@ export interface HardwareFacts {
|
||||
|
||||
// ---------- Catalogue ----------
|
||||
|
||||
/** One Mac a model and harness pair was really run on by us. A model row with a matching entry may be called "Recommended". */
|
||||
/**
|
||||
* One Mac a model and harness pair was really run on by us. A candidate that matches an entry
|
||||
* (the same chip string, the same memory size as sold, the same harness) is `tested`: it ranks
|
||||
* before every candidate that is not, and as the pick it may be called "Recommended".
|
||||
*/
|
||||
export interface TestedOn {
|
||||
/** The chip, as `machdep.cpu.brand_string` reports it ('Apple M4'). */
|
||||
chip: string;
|
||||
@@ -100,6 +111,13 @@ export interface TestedOn {
|
||||
cli: string;
|
||||
/** ISO date of the test ('2026-11-06'). */
|
||||
date: string;
|
||||
/**
|
||||
* The generation speed measured in that test, in tokens per second (67.7 for the
|
||||
* 2026-11-06 run on an Apple M5 Pro with 48 GB). A candidate that matches this entry reports
|
||||
* this figure as `Candidate.tokensPerSecond` in place of the estimate from the chip's memory
|
||||
* bandwidth: a measurement on the same Mac beats a formula.
|
||||
*/
|
||||
tokensPerSecond?: number;
|
||||
}
|
||||
|
||||
/** One model of the catalogue. */
|
||||
@@ -112,17 +130,44 @@ export interface LocalModelEntry {
|
||||
license: string;
|
||||
/** Parameter count in billions. When no model that fits has 12 or more, the verdict is `limited`, never `ok`. */
|
||||
paramsB: number;
|
||||
/** Size of the weights in bytes: both the download and what they take in memory. */
|
||||
/**
|
||||
* Size of the weights in bytes: both the download and what they take in memory.
|
||||
*
|
||||
* It is the size of the build the runtime really downloads ON A MAC. That is not always
|
||||
* the sum of the registry manifest: `qwen3.6:35b-a3b` is an MLX build of 23,105,798,956 bytes
|
||||
* on Apple silicon, 2% more than the manifest's 22,621,314,161. A row whose Mac size nobody
|
||||
* measured keeps the manifest sum and says so in `figures`.
|
||||
*/
|
||||
bytes: number;
|
||||
/** Bytes of KV cache one token of context costs. */
|
||||
kvBytesPerToken: number;
|
||||
/**
|
||||
* Bytes that stay HELD in memory per token of context once the token was processed (measured
|
||||
* on the MLX runner: 36,000 to 38,000, so about 37,000). A figure computed from a model's
|
||||
* config alone came out too low by almost half, so a row that was not measured carries the
|
||||
* measured row's figure and says so in `figures`.
|
||||
*/
|
||||
heldBytesPerToken: number;
|
||||
/** What the runner holds beside the weights and the context (measured: about 3 GB). */
|
||||
overheadBytes: number;
|
||||
/**
|
||||
* The TRANSIENT extra the runner takes while it processes a long prompt, on top of
|
||||
* what stays held (measured: about 5 GB). The fit is judged on the peak:
|
||||
* `bytes + heldBytesPerToken * context + overheadBytes + peakExtraBytes`. For
|
||||
* `qwen3.6:35b-a3b` at 131072 tokens that is about 36 GB, which is tight on a 48 GB Mac.
|
||||
*/
|
||||
peakExtraBytes: number;
|
||||
/**
|
||||
* Where `bytes` and the three memory figures above come from: `measured` on a Mac by
|
||||
* us, or `estimated` (the manifest size, and the per-token, overhead and peak figures of the
|
||||
* measured row applied to this one).
|
||||
*/
|
||||
figures: 'measured' | 'estimated';
|
||||
/** Context lengths (tokens) the model may be run at, largest first. */
|
||||
contexts: number[];
|
||||
/** Preference among models that fit: the HIGHER rank wins. A judgement, not a measurement. */
|
||||
rank: number;
|
||||
/** Measured tokens per second per 100 GB/s of memory bandwidth. Absent: the speed of this model is unknown. */
|
||||
speedPer100Gbps?: number;
|
||||
/** Macs this model was really run on. Empty today for every row. */
|
||||
/** Macs this model was really run on. Empty for every row but one. */
|
||||
tested: TestedOn[];
|
||||
}
|
||||
|
||||
@@ -155,16 +200,6 @@ export interface ChipEntry {
|
||||
gbps: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Host memory the runtime's prompt cache takes, by the size of the Mac. Tiers are ordered by
|
||||
* `minMemGb` ascending and the last tier with `minMemGb <= HardwareFacts.memClassGb` applies.
|
||||
*/
|
||||
export interface PromptCacheTier {
|
||||
/** Smallest memory size (as sold, binary gigabytes) this tier applies to. The first tier has 0. */
|
||||
minMemGb: number;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
/** The catalogue: a compiled constant, validated by `LocalModelCatalogSchema`. No override file, no download data. */
|
||||
export interface LocalModelCatalog {
|
||||
schema: 1;
|
||||
@@ -172,7 +207,6 @@ export interface LocalModelCatalog {
|
||||
updated: string;
|
||||
/** Oldest macOS major version a local model runs on. Below it: verdict `none`, reason `macos`. */
|
||||
minMacosMajor: number;
|
||||
promptCacheTiers: PromptCacheTier[];
|
||||
models: LocalModelEntry[];
|
||||
harnesses: LocalHarnessEntry[];
|
||||
chips: ChipEntry[];
|
||||
@@ -194,13 +228,25 @@ export interface HarnessFact {
|
||||
installed: boolean;
|
||||
/** Not installed, but the registry has an install command for this platform that needs no administrator rights. */
|
||||
installable: boolean;
|
||||
/**
|
||||
* The literal install command the install job would run for this CLI: the STOCK
|
||||
* command of the CLI registry for this platform, never one a `clis.json` override supplies.
|
||||
* Present exactly when `installable` is true. The consent screen prints it
|
||||
* (`CandidateHarness.installCommand`).
|
||||
*/
|
||||
installCommand?: string;
|
||||
/** Whether this CLI can be launched with that model id (its command-line pattern accepts it). */
|
||||
acceptsModelId: (modelId: string) => boolean;
|
||||
}
|
||||
|
||||
// ---------- Recommendation ----------
|
||||
|
||||
/** Need over budget: up to 0.85 is `good`, up to 0.98 is `tight`, above is `out`. */
|
||||
/**
|
||||
* Need over budget: up to 0.85 is `good`, up to 0.98 is `tight`, above is `out`. The need is
|
||||
* the PEAK, so the grade says how much room is left at the worst moment. It decides whether a
|
||||
* model is offered at all (`out` never is) and what its row says (`tight`). It does not sort
|
||||
* the list.
|
||||
*/
|
||||
export type FitGrade = 'good' | 'tight' | 'out';
|
||||
|
||||
/**
|
||||
@@ -223,18 +269,54 @@ export type SpeedGrade = 'ok' | 'slow' | 'unknown';
|
||||
*/
|
||||
export type NoneReason = 'not-macos' | 'intel' | 'memory' | 'disk' | 'macos' | 'no-harness';
|
||||
|
||||
/** Where the device budget came from: a formula (`estimated`) or `iogpu.wired_limit_mb` above 0 (`wired-limit`). */
|
||||
export type BudgetSource = 'estimated' | 'wired-limit';
|
||||
/**
|
||||
* Where the device budget came from.
|
||||
* - `estimated`: a formula over the installed memory. All there is before the runtime ran.
|
||||
* - `wired-limit`: `iogpu.wired_limit_mb` above 0.
|
||||
* - `measured`: the device total the runtime itself printed when it started
|
||||
* (`RecommendOptions.measuredTotalBytes`). The chooser says "estimated" next to the memory
|
||||
* bar for the first value only.
|
||||
*/
|
||||
export type BudgetSource = 'estimated' | 'wired-limit' | 'measured';
|
||||
|
||||
/** The memory a model may use on this Mac. */
|
||||
export interface DeviceBudget {
|
||||
/** L: the wired limit when above 0, else 2/3 of memory below 36 GB and 3/4 from 36 GB. */
|
||||
/**
|
||||
* L: the measured device total when there is one, else the wired limit when above 0, else
|
||||
* 2/3 of memory below 36 GB and 3/4 from 36 GB.
|
||||
*/
|
||||
limitBytes: number;
|
||||
/** B = min(L - 1 GiB, memory - reserve). What `Candidate.budgetShare` is measured against. */
|
||||
/**
|
||||
* What `Candidate.budgetShare` is measured against. Estimated or from the wired limit:
|
||||
* B = min(L - 1 GiB, memory - reserve). Measured: B = min(L, memory - reserve), without the
|
||||
* 1 GiB, because the runtime's figure is already what it will really use (37.4 GiB on the
|
||||
* 48 GB test Mac, which reads '40.2').
|
||||
*/
|
||||
budgetBytes: number;
|
||||
source: BudgetSource;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the caller of `recommend()` knows beyond the hardware probe. Both members are optional:
|
||||
* an empty object means the budget is the estimate and an install downloads the model alone.
|
||||
*/
|
||||
export interface RecommendOptions {
|
||||
/**
|
||||
* The device total the runtime reported in its log line "inference compute"
|
||||
* (`total="37.4 GiB"`), in bytes: `parseInferenceComputeTotal()` in
|
||||
* src/local-model/runtime.ts. Present: the budget is `measured`. The install job passes it
|
||||
* right after the runtime started, before the model is downloaded, and the GET passes the
|
||||
* stored figure from then on.
|
||||
*/
|
||||
measuredTotalBytes?: number;
|
||||
/**
|
||||
* What an install adds to every candidate's download beside the model: the size of the
|
||||
* pinned runtime archive while the runtime is not installed, 0 once it is. It is the
|
||||
* difference between `Candidate.installBytes` and `Candidate.downloadBytes`. Default 0.
|
||||
*/
|
||||
runtimeDownloadBytes?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every sentence and label the server may put into the payload, in English (the i18n source
|
||||
* language). The zh-CN dictionary in src/web/public/i18n.js has one entry per value, keyed by
|
||||
@@ -257,7 +339,8 @@ export interface DeviceBudget {
|
||||
* | `noneMacos` | `version`: `HardwareFacts.macosVersion`; `minimum`: the catalogue minimum |
|
||||
*
|
||||
* The word "Recommended" exists only in `headlineTested`, which may be used only when the
|
||||
* pick's `tested` is true. No catalogue row has a tested entry today, so it is never sent.
|
||||
* pick's `tested` is true: one catalogue row has a tested entry (`qwen3.6:35b-a3b` on an Apple
|
||||
* M5 Pro with 48 GB), so one kind of Mac is told so.
|
||||
*/
|
||||
export const LOCAL_MODEL_LABELS = {
|
||||
/** Verdict `ok`, pick not tested by us on a Mac like this one. */
|
||||
@@ -268,7 +351,7 @@ export const LOCAL_MODEL_LABELS = {
|
||||
headlineLimited:
|
||||
'This Mac can run a small model. It handles small edits and questions. It does not replace a cloud model.',
|
||||
/** A note under an `ok` or `limited` pick whose `tested` is false. */
|
||||
noteUntested: 'Not yet tested by us on a Mac like this.',
|
||||
noteUntested: 'Codeman has not run this on a Mac like this yet.',
|
||||
/** A note under an `ok` pick that is itself a small model: larger ones fit this Mac, but rank lower or have no room on the disk. */
|
||||
noteSmallPick:
|
||||
'The best fit is a small model. It handles small edits and questions. It does not replace a cloud model.',
|
||||
@@ -280,18 +363,17 @@ export const LOCAL_MODEL_LABELS = {
|
||||
speedSlow: 'Slow',
|
||||
speedUnknown: 'Speed unknown',
|
||||
noneNotMacos: 'Codeman recommends a local model only on a Mac with Apple silicon.',
|
||||
noneIntel: 'This Mac has an Intel processor. Local coding models need Apple silicon.',
|
||||
noneIntel: 'Local coding models need Apple silicon, and this Mac has an Intel processor.',
|
||||
/** Reason `memory`: nothing fits at any context. */
|
||||
noneMemory:
|
||||
'This Mac has {memory} GB of memory. That is too little to run a model that can drive a coding agent, so Codeman recommends none here.',
|
||||
/** Reason `memory`: a model fits, but only below the context a harness needs. Says both numbers, and that they are an estimate. */
|
||||
noneMemory: 'With {memory} GB of memory, this Mac cannot run a model that can drive a coding agent.',
|
||||
/** Reason `memory`: a model fits, but only below the context a harness needs. Says both numbers, and ("about") that they are estimates. */
|
||||
noneMemoryContext:
|
||||
'Codeman estimates that this Mac can give a model about {budget} GB of memory. The smallest model a coding agent can work with needs about {need} GB. That leaves no safe margin, so Codeman recommends none here.',
|
||||
'This Mac can give a model about {budget} GB of memory, and the smallest model a coding agent can work with needs about {need} GB.',
|
||||
/** Reason `memory`: the memory size could not be read, so no size is stated. */
|
||||
noneMemoryUnknown: 'Codeman could not read how much memory this Mac has, so it recommends no model here.',
|
||||
noneDisk:
|
||||
'Not enough free disk space. The smallest model that fits this Mac is a {download} GB download, and {reserve} GB must stay free after it. {free} GB is free now. Free up about {missing} GB.',
|
||||
noneMacos: 'This Mac runs macOS {version}. Local models need macOS {minimum} or newer.',
|
||||
/** Reason `disk`. One number: what to do. The other sizes travel in `vars` for a client that wants them. */
|
||||
noneDisk: 'Free up about {missing} GB of disk space to install the smallest model that fits this Mac.',
|
||||
noneMacos: 'Local models need macOS {minimum} or newer, and this Mac runs macOS {version}.',
|
||||
noneNoHarness: 'No coding agent that Codeman can connect to a local model is available on this Mac.',
|
||||
} as const;
|
||||
|
||||
@@ -315,6 +397,64 @@ export interface LocalModelMessage {
|
||||
vars?: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The one tag a model row of the chooser carries, by what it says.
|
||||
* - `tested`: `Candidate.tested` is true. Replaces every other tag.
|
||||
* - `best-tight`: the pick, when its `fit` is `tight`. The words must not say less than the
|
||||
* memory bar beside them, which is nearly full for such a row.
|
||||
* - `best`: the pick.
|
||||
* - `tight`: `Candidate.fit` is `tight`.
|
||||
* - `slow`: `Candidate.speed` is `slow`.
|
||||
* - `small`: the model has fewer than 12 billion parameters.
|
||||
* A row gets the FIRST kind of this list that applies and no tag when none does. `tested`,
|
||||
* `best` and `best-tight` are the tags of the row the window opens on, drawn in the accent
|
||||
* colour.
|
||||
*/
|
||||
export type CandidateTagKind = 'tested' | 'best-tight' | 'best' | 'tight' | 'slow' | 'small';
|
||||
|
||||
/**
|
||||
* The text of each tag, in English (the i18n source language), like `LOCAL_MODEL_LABELS`. A
|
||||
* constant of its own so that a consumer can list the tag texts apart from the sentences.
|
||||
*/
|
||||
export const LOCAL_MODEL_TAG_LABELS = {
|
||||
tested: 'Tested on a Mac like this',
|
||||
'best-tight': 'Best fit, tight',
|
||||
best: 'Best fit',
|
||||
tight: 'Tight',
|
||||
slow: 'Slow',
|
||||
small: 'Small model',
|
||||
} as const satisfies Record<CandidateTagKind, string>;
|
||||
|
||||
/** One of the texts in `LOCAL_MODEL_TAG_LABELS`. */
|
||||
export type LocalModelTagLabel = (typeof LOCAL_MODEL_TAG_LABELS)[CandidateTagKind];
|
||||
|
||||
/** The tag of a model row: what kind it is (for the styling) and the text to print. */
|
||||
export interface CandidateTag {
|
||||
kind: CandidateTagKind;
|
||||
/** `LOCAL_MODEL_TAG_LABELS[kind]`. */
|
||||
label: LocalModelTagLabel;
|
||||
}
|
||||
|
||||
/**
|
||||
* One coding agent a candidate's model can be run with on this Mac, for the "Runs
|
||||
* with" select of the chooser. Everything a browser needs is here, so it compares no CLI id.
|
||||
*/
|
||||
export interface CandidateHarness {
|
||||
/** The CLI registry id, as data: what `POST /api/local-model/install` is sent as `cli`. */
|
||||
cli: string;
|
||||
/** The registry's display label ('OpenCode'). */
|
||||
cliLabel: string;
|
||||
/** False: the install job installs it first (it is installable, or it would not be listed). */
|
||||
installed: boolean;
|
||||
/**
|
||||
* The literal command the install job would run to install it (`HarnessFact.installCommand`).
|
||||
* Present exactly when `installed` is false. The consent screen prints it as it is.
|
||||
*/
|
||||
installCommand?: string;
|
||||
/** The harness row's `slowFirstTurn`. */
|
||||
slowFirstTurn?: boolean;
|
||||
}
|
||||
|
||||
/** One model at one context with one harness, measured against this Mac. Plain JSON. */
|
||||
export interface Candidate {
|
||||
/** `LocalModelEntry.id`. */
|
||||
@@ -333,7 +473,11 @@ export interface Candidate {
|
||||
cliInstalled: boolean;
|
||||
/** The harness row's `slowFirstTurn`. */
|
||||
slowFirstTurn?: boolean;
|
||||
/** F = weights + kvBytesPerToken * context + 1 GiB + prompt cache. */
|
||||
/**
|
||||
* What the model needs in memory at this context: the PEAK, `bytes + heldBytesPerToken *
|
||||
* context + overheadBytes + peakExtraBytes` of the catalogue row. The memory bar of the
|
||||
* chooser is filled to `budgetShare`, which is this over the budget.
|
||||
*/
|
||||
needBytes: number;
|
||||
/** `needBytes` as decimal GB text, no unit. */
|
||||
needGb: string;
|
||||
@@ -350,10 +494,36 @@ export interface Candidate {
|
||||
speed: SpeedGrade;
|
||||
/** `speedSlow` or `speedUnknown`. Absent when `speed` is `ok`. */
|
||||
speedLabel?: LocalModelLabel;
|
||||
/** Estimated generation speed, rounded to one decimal. Present exactly when `speed` is not `unknown`. `speed` is decided on the unrounded figure. */
|
||||
/**
|
||||
* Generation speed in tokens per second, rounded to one decimal. Present exactly when `speed`
|
||||
* is not `unknown`; `speed` is decided on the unrounded figure. An estimate from the chip's
|
||||
* memory bandwidth, except for a candidate that is `tested`, which reports the
|
||||
* speed measured in that test (`TestedOn.tokensPerSecond`).
|
||||
*/
|
||||
tokensPerSecond?: number;
|
||||
/** A `TestedOn` entry of the model matches this Mac (same chip, same `memClassGb`) and this harness. */
|
||||
/**
|
||||
* A `TestedOn` entry of the model matches this Mac (same chip, same `memClassGb`) and this
|
||||
* harness. Such a candidate ranks first, and its `tag` says so in place of any other tag.
|
||||
*/
|
||||
tested: boolean;
|
||||
/** `LocalModelEntry.figures` of the model: whether `needBytes` rests on a measurement of this model. */
|
||||
needSource: 'measured' | 'estimated';
|
||||
/** The row's one tag, see `CandidateTagKind`. Absent when no kind applies. */
|
||||
tag?: CandidateTag;
|
||||
/**
|
||||
* Every coding agent this model can be run with at `context` on this Mac, best
|
||||
* first. The first entry is the one the flat fields above name (`cli`, `cliLabel`,
|
||||
* `cliInstalled`, `slowFirstTurn`). Never empty.
|
||||
*/
|
||||
harnesses: CandidateHarness[];
|
||||
/**
|
||||
* The whole download a click on Install starts for this row: `downloadBytes` plus
|
||||
* `RecommendOptions.runtimeDownloadBytes`. It is the server's own total, and exactly the
|
||||
* number `POST /api/local-model/install` must be sent as `acknowledgedBytes`.
|
||||
*/
|
||||
installBytes: number;
|
||||
/** `installBytes` as decimal GB text, no unit. */
|
||||
installGb: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -376,7 +546,12 @@ export interface Recommendation {
|
||||
notes: LocalModelMessage[];
|
||||
/** Present exactly when `verdict` is `ok` or `limited`. */
|
||||
pick?: Candidate;
|
||||
/** The next models that fit and have room on the disk (at most four, each at its best context and harness), best first. Empty when `verdict` is `none`. */
|
||||
/**
|
||||
* The next models that fit and have room on the disk (at most four), best first: tested
|
||||
* before not tested, then ok before unknown before slow speed, then the higher model rank.
|
||||
* Each is at the largest context it fits at, with the best harness that can run it there.
|
||||
* Empty when `verdict` is `none`.
|
||||
*/
|
||||
alternatives: Candidate[];
|
||||
/** `DeviceBudget.budgetBytes`. 0 when no budget is computed: not macOS, or a Mac without Apple silicon. */
|
||||
budgetBytes: number;
|
||||
@@ -385,12 +560,4 @@ export interface Recommendation {
|
||||
budgetSource: BudgetSource;
|
||||
}
|
||||
|
||||
// ---------- API ----------
|
||||
|
||||
/** The `data` of `GET /api/local-model`. Read-only; admin only in multi-user mode. */
|
||||
export interface LocalModelStatus {
|
||||
hardware: HardwareFacts;
|
||||
recommendation: Recommendation;
|
||||
/** `LocalModelCatalog.updated`. */
|
||||
catalogUpdated: string;
|
||||
}
|
||||
// `LocalModelStatus`, the `data` of `GET /api/local-model`, is in src/types/local-model-install.ts.
|
||||
+1
-1
@@ -48,7 +48,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Opened outside Codeman** (`foreign-sessions.js`, both home screens): the tmux sessions a human started, listed from `GET /api/mux/foreign` (root CLAUDE.md, Adopted tmux sessions). ONE renderer, `renderForeignSessions(container)`, fills the welcome block and the phone overview's, and every row goes through `textContent`, since a session name and a command line come from someone else's process. ⚠️ It polls only while a home screen is up (`startForeignPolling`/`stopForeignPolling` from `showWelcome()`/`hideWelcome()`) and the tab is visible (`_foreignPollTick()` is the one gate, and `visibilitychange` catches up; the cache TTL sits under the poll interval, so one tab's every tick is a full socket sweep), and the poll is local only: the docker and ssh scan costs one connection per target, so it runs once on the toggle and again on Rescan, and its rows and notes are kept apart (`_foreignWideSessions`, `_foreignWideNotes`) or the next local poll would wipe them. ⚠️ A 403 is a non-admin in multi-user mode, an answer and not a failed poll: `_foreignRefused` stops the polling and shows no block. ⚠️ `closeSession()` re-reads the list after an adopted tab's DELETE, since the home screen's own load races it and the row would say `Go to tab` until the next poll. ⚠️ An adopted tab has no kill outcome to offer, so the close dialog hides the red button and always tears the wrapper down. ⚠️ `session.remote` and `session.docker` are undefined on an adopted session, so a check that hides a row for those two usually needs `session.adopt` as well. Tests: `test/foreign-sessions-ui.test.ts`, `test/foreign-sessions-i18n.test.ts` (harvests every string from the real module).
|
||||
|
||||
**Model on this Mac** (`local-model-ui.js`; welcome card `#localModelCard` + App Settings > Models group `#localModelGroup`; server rules in the root CLAUDE.md, Local model recommendation): a READ-ONLY view of `GET /api/local-model`. ONE builder (`localModelBody`) paints both containers, so the card and the Settings row can never name a different pick; the card folds the alternatives, Settings lists them. ⚠️ Every dynamic string goes in through `textContent` (model, harness and chip names are someone else's text), both containers carry `data-i18n-skip`, and the module translates its own sentences at render time, so a language or display-name change must repaint from the module (the `<html lang>` observer). ⚠️ Labels and sentences come from the payload (`{ text, vars }` through `localModelT`); the module holds no list of models or harnesses, never compares a CLI id, and never contains the word "Recommended" (that headline is the server's to send). ⚠️ `test/local-model-i18n.test.ts` harvests every `localModelT('...')` literal: a new string is a single-quoted literal with no apostrophe and gets a zh-CN entry, and the only non-literal calls are the two payload ones. ⚠️ Sizes are printed as sent (decimal GB text), bytes are never divided here; the installed memory alone is `memClassGb`, a number or nothing (an unknown size is left out, never `0 GB`). ⚠️ The card ships `hidden` and shows only once the server answered for a Mac; the card AND the Settings group stay hidden for `not-macos` (the server is usually Linux, and "this Mac" always means the machine the server runs on), for a refusal and while the first request is in flight; a failed first request shows one sentence in Settings only. ⚠️ Refused means `403` with `errorCode: FORBIDDEN` (a non-admin in multi-user mode: stop asking); the auth layer's `403 PASSWORD_CHANGE_REQUIRED` is a failed request that is asked again on `codeman:me`. ⚠️ Each fit and speed pill carries what it measures as `title` + `aria-label` ("Good" is the memory fit, not a rating), and the line saying Codeman cannot download or install yet sits right under the pick and its notes, in `--text-dim` like every other line. The dismissal is a per-device localStorage key named for this stage (`codeman:local-model-dismissed:readonly`), never a server setting: the stage that can set a model up takes a new key so its offer shows once more. At most one request a minute (the server caches its probe for 60 s), shared while in flight, and a failed refresh keeps the answer on screen. Tests: `test/local-model-ui.test.ts`, `test/local-model-i18n.test.ts`.
|
||||
**Run a model on this Mac** (`local-model-ui.js`; welcome button `#welcomeLocalModelBtn`, chooser window `#localModelModal`, App Settings > Models row `#localModelSettings`; server rules in the root CLAUDE.md, Local model): ONE window does everything (choose, confirm, progress, paused, failed, installed, no recommendation); the button and the Settings row only open it. Which screen shows follows `install.state` of `GET /api/local-model`; the page itself holds only the selection and whether the person is on the chooser or the confirm screen. ⚠️ The window is ONE frame for the whole flow: a fixed height on desktop (`.modal-content.local-model-window`), App Settings' boxed close button, the body scrolling between the header and a foot of its own (`#localModelWindowFoot`): every screen's last part (`.lm-foot`, or the `.lm-remove` question) is moved there by `_renderLocalModelWindow()`, so a button never moves away from under the pointer and is never clipped; a test that looks for a button looks in the frame, not the body. The short screens are centred in that frame on desktop and sit above the buttons on a phone (`data-screen` on the body). ⚠️ The memory bar (`.lm-bar`, `role="meter"`) is the one strong element: filled to the selected row's `budgetShare`, the model at its PEAK (the legend says so, and the installed line uses the same words beside what the model takes now, so the two figures are never read as a contradiction), a flat `--accent` fill on a `--text-muted` track (about 3:1 against the window, so the free part can be seen; a border token is 1.5:1 and the inputs' `--bg-input` is the window's own surface on the dark skins), 10px, no gradient or glow, and its width transition is the only motion (off under `prefers-reduced-motion`); a repaint starts each bar at the last width of its kind, so keep `_settleLocalModelBars()` after every body write. The figure beside it is an estimate and says "about" in whole GB (`localModelWholeGb()` on the server's text); only the download figure keeps tabular figures. ⚠️ The rows are the server's pick first, then the other models by download size, largest first (`localModelCandidates()`): the server's alternatives are its ranking, which no column shows. ⚠️ The download bar means ONE thing, the model download: at the start while the runtime is fetched, gone once the model is in (the step list carries verify, agent and connect); the first paint after an install finished shows "Start a session" alone (`justInstalled`), an error on an installed model is the headline with a grey dot, and Remove is quiet everywhere but red in its own question, never the accent. ⚠️ The window polls the GET once a second WHILE OPEN and never otherwise (no SSE event): `closeLocalModelWindow()` clears the timer, a background tab asks nothing, an unchanged answer repaints nothing, and a tick that moved only the download replaces `.lm-meter` alone, so a button is never swapped out under a click. A read that was already under way when a verb answered is dropped (`_localModelVerbs`), or the old state flashes back. ⚠️ The consent is bound to the size shown: the install request carries the row's `installBytes` as `acknowledgedBytes`, and a 409 `size-changed` shows `expectedGb` and sends `expectedBytes` next; never compute a total here. ⚠️ A button exists only for an action in `install.actions`, and after an error exactly one helpful action (`error.next`, already adapted by the server to the state: `start` on an installed model, `retry` on a job) plus a quiet Remove; an error's text is split after its first sentence (`localModelSentences()`, which knows the ideographic full stop) and only that sentence is the headline. A refusal the server names (a 400, a full disk) carries `data.message` like a 409 and is printed from it, never from the English `error` text. ⚠️ Every dynamic string goes in through `textContent` (model, coding agent and chip names, an error's detail, session names, the folder and the install command are someone else's text); the window body, the button and the row carry `data-i18n-skip` and the module translates its own sentences at render time, so a language or display-name change repaints from the module (the `<html lang>` observer). ⚠️ Labels and sentences come from the payload (`{ text, vars }` through `localModelT`); the module holds no list of models or coding agents, compares no CLI id (the agent select's values are positions in the server's list, the id travels only as data into the install request and `selectCustomModelEntry`) and never contains the word "Recommended". ⚠️ `test/local-model-i18n.test.ts` harvests every `localModelT('...')` literal: a new string is a single-quoted literal with no apostrophe and gets a zh-CN entry, the only non-literal calls are the two payload ones, and a unit alone (`23.1 GB`) is not a translator call. ⚠️ Sizes are printed as sent (decimal GB text), bytes are never turned into a size; the installed memLine truncated
|
||||
|
||||
**Home-screen session order** (`CodemanSessionOrder` in constants.js, pure): BOTH home screens (phone overview, desktop rail) must order rows through this ONE comparator. Rank `needs` → `error` → `waiting` → `working` → `idle` → `done`. ⚠️ The tiebreak flips: states a session is still IN sort oldest-first, states it has STOPPED sort newest-first. ⚠️ The running group keys off `lastSubmitAt`, never `lastActivityAt` (a working pane repaints constantly). ⚠️ A 0 stamp means unknown and sorts last within its state. Final tiebreak is `orderIndex`, so the list never shuffles. The tab strip itself is NOT sorted by this. Test: `test/session-overview-order.test.ts`. → [architecture-invariants#home-screen-session-order](../../docs/architecture-invariants.md#home-screen-session-order)
|
||||
|
||||
|
||||
@@ -1468,6 +1468,12 @@ class CodemanApp {
|
||||
this.handleTabRailSearchKeydown(e);
|
||||
return;
|
||||
}
|
||||
// The local model window can sit on top of App Settings (it opens from a
|
||||
// row there): Escape closes the window alone and leaves Settings open.
|
||||
if (this.isLocalModelWindowOpen?.()) {
|
||||
this.closeLocalModelWindow();
|
||||
return;
|
||||
}
|
||||
this.closeAllPanels();
|
||||
this.closeHelp();
|
||||
if (this.attachmentHistoryDrawerOpen) this.closeAttachmentHistory();
|
||||
|
||||
+155
-37
@@ -1415,46 +1415,109 @@
|
||||
'该 tmux 会话在此处打开时所在的位置。它是在 Codeman 之外启动的,关闭此标签页后仍会继续运行。',
|
||||
'Git status is not available for a tmux session opened outside Codeman.':
|
||||
'在 Codeman 之外打开的 tmux 会话无法使用 Git 状态。',
|
||||
// Model on this Mac (local-model-ui.js: the welcome card and its App Settings group). The first
|
||||
// block is the module's own text; sizes and names fill the {placeholder} slots.
|
||||
// Run a model on this Mac (local-model-ui.js: the welcome button, the chooser window and its
|
||||
// App Settings group). The first block is the page's and the module's own text; sizes and
|
||||
// names fill the {placeholder} slots.
|
||||
'Model on this Mac': '此 Mac 上的模型',
|
||||
'What the Mac that Codeman runs on can run as a local coding model. Read-only: nothing is downloaded or installed from here.':
|
||||
'运行 {name} 的这台 Mac 可以运行哪种本地编程模型。只读:此处不会下载或安装任何内容。',
|
||||
'Run a coding model on the Mac that Codeman runs on. No account and no API key.':
|
||||
'在运行 {name} 的这台 Mac 上运行编程模型。无需账号,也无需 API 密钥。',
|
||||
'Run a model on this Mac': '在此 Mac 上运行模型',
|
||||
'Run a local model': '运行本地模型',
|
||||
'Local model': '本地模型',
|
||||
'The Mac that Codeman runs on, which is not always the device you are reading on.':
|
||||
'指运行 {name} 的那台 Mac,不一定是你正在使用的这台设备。',
|
||||
Hide: '隐藏',
|
||||
'Hide this card on this device. It stays in App Settings, under Models.':
|
||||
'在此设备上隐藏此卡片。它仍保留在“应用设置”的“模型”中。',
|
||||
'{chip}, {memory} GB memory, {free} GB free': '{chip},内存 {memory} GB,可用磁盘空间 {free} GB',
|
||||
'{chip}, {memory} GB memory': '{chip},内存 {memory} GB',
|
||||
'{memory} GB memory, {free} GB free': '内存 {memory} GB,可用磁盘空间 {free} GB',
|
||||
'{memory} GB memory': '内存 {memory} GB',
|
||||
'{model} ({id}) with {harness}': '{model}({id}),搭配 {harness}',
|
||||
'Context {context} tokens': '上下文 {context} 个 Token',
|
||||
'{need} GB of memory': '占用内存 {need} GB',
|
||||
'{download} GB download': '下载 {download} GB',
|
||||
'Needs about {need} GB of the {budget} GB this Mac can give a model.':
|
||||
'大约需要 {need} GB,此 Mac 可分配给模型的内存为 {budget} GB。',
|
||||
'Needs about {need} GB of the {budget} GB this Mac can give a model (estimated).':
|
||||
'大约需要 {need} GB,此 Mac 可分配给模型的内存约为 {budget} GB(估算)。',
|
||||
'About {speed} tokens per second (estimated).': '每秒约 {speed} 个 Token(估算)。',
|
||||
'{harness} is not installed on this Mac yet.': '此 Mac 上尚未安装 {harness}。',
|
||||
'With {harness}, the first answer can take minutes.': '使用 {harness} 时,第一次回答可能需要几分钟。',
|
||||
'about {speed} tokens per second': '每秒约 {speed} 个 Token',
|
||||
// What the fit and speed labels measure (their tooltip and accessible name).
|
||||
'Memory fit: needs {share}% of what this Mac can give a model':
|
||||
'内存占用:需要此 Mac 可分配给模型的内存的 {share}%',
|
||||
'No speed estimate for this model on this chip': '此芯片上没有该模型的速度估算',
|
||||
'Other models that fit': '其他装得下的模型',
|
||||
'Codeman cannot download or install this for you yet. That is the next step, and it is not built yet.':
|
||||
'{name} 目前还不能为你下载或安装它。这是下一步的功能,尚未实现。',
|
||||
// The App Settings row: where the install stands, in a few words.
|
||||
'No model installed': '尚未安装模型',
|
||||
'Installing {model}': '正在安装 {model}',
|
||||
'The install of {model} is paused': '{model} 的安装已暂停',
|
||||
'The install of {model} stopped': '{model} 的安装已中止',
|
||||
'{model} is running': '{model} 正在运行',
|
||||
'{model} is installed and stopped': '{model} 已安装,当前已停止',
|
||||
'Checking this Mac': '正在检查此 Mac',
|
||||
// The chooser: the memory bar, the list, the coding agent.
|
||||
'About {need} of {budget} GB of memory': '约需 {need} GB 内存,共 {budget} GB 可用',
|
||||
estimated: '估算',
|
||||
'The selected model needs {share}% of the memory this Mac can give a model':
|
||||
'所选模型需要此 Mac 可分配给模型的内存的 {share}%',
|
||||
'The model at its peak, with all {context} tokens of context in use':
|
||||
'模型的峰值占用({context} 个 Token 的上下文全部用满时)',
|
||||
'What stays free': '剩余可用',
|
||||
'Models that fit this Mac': '此 Mac 装得下的模型',
|
||||
Speed: '速度',
|
||||
Download: '下载',
|
||||
'speed not known': '速度未知',
|
||||
'{speed} tokens/s': '{speed} Token/秒',
|
||||
'about {speed} tokens/s': '约 {speed} Token/秒',
|
||||
'Runs with': '搭配',
|
||||
'Not on this Mac yet. Codeman installs it for you.': '此 Mac 上尚未安装,{name} 会为你一并安装。',
|
||||
'The first answer can take minutes.': '第一次回答可能需要几分钟。',
|
||||
'No account and no API key. The model runs only on this Mac.': '无需账号,也无需 API 密钥。模型只在此 Mac 上运行。',
|
||||
'Install on this Mac': '安装到此 Mac',
|
||||
// The confirm screen: the download as a table, where it goes.
|
||||
'What will be downloaded': '将下载的内容',
|
||||
'At {context} tokens of context, with {cli}': '上下文 {context} 个 Token,搭配 {cli}',
|
||||
'Ollama {version}': 'Ollama {version}',
|
||||
'The program that runs the model': '用于运行模型的程序',
|
||||
Total: '合计',
|
||||
'Not on this Mac yet. Its own installer fetches it with this command:':
|
||||
'此 Mac 上尚未安装。它自带的安装程序会用以下命令获取它:',
|
||||
'Not on this Mac yet. Its own installer fetches it.': '此 Mac 上尚未安装。它自带的安装程序会获取它。',
|
||||
'Goes into': '存放位置:',
|
||||
'No administrator password.': '无需管理员密码。',
|
||||
'Download and install': '下载并安装',
|
||||
// Progress, and the same picture paused.
|
||||
'{done} of {total} GB': '已下载 {done} GB,共 {total} GB',
|
||||
'{speed} MB per second, {left}': '每秒 {speed} MB,{left}',
|
||||
'{speed} MB per second': '每秒 {speed} MB',
|
||||
'less than a minute left': '剩余不到 1 分钟',
|
||||
'about 1 minute left': '剩余约 1 分钟',
|
||||
'about {minutes} minutes left': '剩余约 {minutes} 分钟',
|
||||
'about 1 hour left': '剩余约 1 小时',
|
||||
'about {hours} hours left': '剩余约 {hours} 小时',
|
||||
'Getting the runtime': '获取运行时',
|
||||
'Downloading the model': '下载模型',
|
||||
'Loading and checking': '加载并检查',
|
||||
'Installing {cli}': '安装 {cli}',
|
||||
Connecting: '正在连接',
|
||||
'Download of the model': '模型下载进度',
|
||||
'0 of {total} GB': '已下载 0 GB,共 {total} GB',
|
||||
'You can close this window. The download continues while Codeman is running.':
|
||||
'你可以关闭此窗口。只要 {name} 在运行,下载就会继续。',
|
||||
'You can close this window. The install continues while Codeman is running.':
|
||||
'你可以关闭此窗口。只要 {name} 在运行,安装就会继续。',
|
||||
'The download waits until you continue.': '下载会等你点击继续后再进行。',
|
||||
'The install waits until you continue.': '安装会等你点击继续后再进行。',
|
||||
Continue: '继续',
|
||||
'Choose another model': '选择其他模型',
|
||||
// After an error: the one action that helps.
|
||||
'Use another port': '改用其他端口',
|
||||
'Try {model}': '试试 {model}',
|
||||
Start: '启动',
|
||||
'The server did not accept that.': '服务器未接受该请求。',
|
||||
// Installed, and the Remove question.
|
||||
'{model} is ready on this Mac.': '{model} 已在此 Mac 上准备就绪。',
|
||||
'{model} is installed on this Mac.': '{model} 已安装在此 Mac 上。',
|
||||
'Runs with {cli}.': '搭配 {cli} 运行。',
|
||||
'Context {context} tokens.': '上下文 {context} 个 Token。',
|
||||
'Takes {memory} GB of memory now, and up to about {peak} GB at its peak, with all of the context in use.':
|
||||
'目前占用 {memory} GB 内存;上下文全部用满时,峰值约为 {peak} GB。',
|
||||
'Takes {memory} GB of memory now.': '目前占用 {memory} GB 内存。',
|
||||
'All of it is on the GPU.': '全部位于 GPU 上。',
|
||||
'Start a session': '开始会话',
|
||||
'Remove the local model from this Mac?': '要从此 Mac 移除本地模型吗?',
|
||||
'Also delete the downloaded model': '同时删除已下载的模型',
|
||||
'The coding agent stays installed.': '编程智能体会保留,不会被卸载。',
|
||||
// The sentences and labels the SERVER picks (LOCAL_MODEL_LABELS in src/types/local-model.ts), keyed
|
||||
// by their exact English text: changing a text there means changing its key here.
|
||||
'Best fit for this Mac': '最适合此 Mac 的选择',
|
||||
'Recommended for this Mac': '为此 Mac 推荐',
|
||||
'This Mac can run a small model. It handles small edits and questions. It does not replace a cloud model.':
|
||||
'此 Mac 可以运行小型模型。它能处理小幅修改和问答,但不能替代云端模型。',
|
||||
'Not yet tested by us on a Mac like this.': '我们尚未在类似的 Mac 上测试过。',
|
||||
'Codeman has not run this on a Mac like this yet.': '{name} 尚未在同类 Mac 上运行过它。',
|
||||
'The best fit is a small model. It handles small edits and questions. It does not replace a cloud model.':
|
||||
'最适合的是一个小型模型。它能处理小幅修改和问答,但不能替代云端模型。',
|
||||
'{model} fits the memory of this Mac too, but its download needs about {missing} GB more free disk space.':
|
||||
@@ -1465,20 +1528,75 @@
|
||||
'Speed unknown': '速度未知',
|
||||
'Codeman recommends a local model only on a Mac with Apple silicon.':
|
||||
'{name} 仅在搭载 Apple 芯片的 Mac 上推荐本地模型。',
|
||||
'This Mac has an Intel processor. Local coding models need Apple silicon.':
|
||||
'此 Mac 使用 Intel 处理器。本地编程模型需要 Apple 芯片。',
|
||||
'This Mac has {memory} GB of memory. That is too little to run a model that can drive a coding agent, so Codeman recommends none here.':
|
||||
'此 Mac 有 {memory} GB 内存,不足以运行能够驱动编程智能体的模型,因此 {name} 在此不推荐任何模型。',
|
||||
'Codeman estimates that this Mac can give a model about {budget} GB of memory. The smallest model a coding agent can work with needs about {need} GB. That leaves no safe margin, so Codeman recommends none here.':
|
||||
'据 {name} 估算,此 Mac 可分配给模型的内存约为 {budget} GB。编程智能体能够使用的最小模型约需 {need} GB。这样没有留出安全余量,因此 {name} 在此不推荐任何模型。',
|
||||
'Local coding models need Apple silicon, and this Mac has an Intel processor.':
|
||||
'本地编程模型需要 Apple 芯片,而此 Mac 使用的是 Intel 处理器。',
|
||||
'With {memory} GB of memory, this Mac cannot run a model that can drive a coding agent.':
|
||||
'此 Mac 只有 {memory} GB 内存,无法运行能够驱动编程智能体的模型。',
|
||||
'This Mac can give a model about {budget} GB of memory, and the smallest model a coding agent can work with needs about {need} GB.':
|
||||
'此 Mac 可分配给模型的内存约为 {budget} GB,而编程智能体能够使用的最小模型约需 {need} GB。',
|
||||
'Codeman could not read how much memory this Mac has, so it recommends no model here.':
|
||||
'{name} 无法读取此 Mac 的内存大小,因此在此不推荐任何模型。',
|
||||
'Not enough free disk space. The smallest model that fits this Mac is a {download} GB download, and {reserve} GB must stay free after it. {free} GB is free now. Free up about {missing} GB.':
|
||||
'可用磁盘空间不足。适合此 Mac 的最小模型需要下载 {download} GB,下载后还必须保留 {reserve} GB 的可用空间。当前可用空间为 {free} GB。请腾出约 {missing} GB。',
|
||||
'This Mac runs macOS {version}. Local models need macOS {minimum} or newer.':
|
||||
'此 Mac 运行的是 macOS {version}。本地模型需要 macOS {minimum} 或更高版本。',
|
||||
'Free up about {missing} GB of disk space to install the smallest model that fits this Mac.':
|
||||
'请腾出约 {missing} GB 磁盘空间,以便安装适合此 Mac 的最小模型。',
|
||||
'Local models need macOS {minimum} or newer, and this Mac runs macOS {version}.':
|
||||
'本地模型需要 macOS {minimum} 或更高版本,而此 Mac 运行的是 macOS {version}。',
|
||||
'No coding agent that Codeman can connect to a local model is available on this Mac.':
|
||||
'此 Mac 上没有 {name} 可以连接到本地模型的编程智能体。',
|
||||
// The tag of a model row (LOCAL_MODEL_TAG_LABELS in src/types/local-model.ts). Tight and Slow are
|
||||
// the entries above.
|
||||
'Tested on a Mac like this': '已在同类 Mac 上测试',
|
||||
'Best fit': '最适合',
|
||||
'Best fit, tight': '最适合,内存偏紧',
|
||||
'Small model': '小型模型',
|
||||
// The sentences of the install (LOCAL_MODEL_INSTALL_LABELS in src/types/local-model-install.ts):
|
||||
// why a job stopped, why a request was refused, and the one sentence about the developer tools.
|
||||
'The download of the runtime stopped and could not be continued. Check the network connection, then try again.':
|
||||
'运行时的下载已中断,且无法继续。请检查网络连接,然后重试。',
|
||||
'The runtime download was damaged and has been deleted. Try again.': '下载的运行时已损坏,已被删除。请重试。',
|
||||
'The runtime could not be unpacked on this Mac.': '无法在此 Mac 上解压运行时。',
|
||||
'The runtime did not start on this Mac.': '运行时未能在此 Mac 上启动。',
|
||||
'The runtime keeps stopping, so Codeman no longer restarts it.': '运行时反复停止,因此 {name} 不再重新启动它。',
|
||||
'The model on this Mac is not running. Start it first.': '此 Mac 上的模型没有在运行。请先启动它。',
|
||||
'Port {port} is in use by another program.': '端口 {port} 已被其他程序占用。',
|
||||
'The disk is full. Free up space, then try again.': '磁盘已满。请腾出空间,然后重试。',
|
||||
'The download keeps stopping. The network may be damaging data. Try again or use another network.':
|
||||
'下载反复中断。网络可能正在损坏数据。请重试,或换一个网络。',
|
||||
'{model} is no longer offered under this name. Update Codeman or pick another model.':
|
||||
'{model} 已不再以此名称提供。请更新 {name},或选择其他模型。',
|
||||
'{model} does not fit in the memory of this Mac after all.': '{model} 终究装不进此 Mac 的内存。',
|
||||
'{model} loaded with a context of {actual} tokens instead of {wanted}.':
|
||||
'{model} 加载时的上下文为 {actual} 个 Token,而不是 {wanted} 个。',
|
||||
'{model} did not load on this Mac.': '{model} 未能在此 Mac 上加载。',
|
||||
'{model} loaded but did not call a tool, so a coding agent cannot work with it.':
|
||||
'{model} 已加载,但没有调用工具,因此编程智能体无法使用它。',
|
||||
'The check of {model} did not finish.': '对 {model} 的检查没有完成。',
|
||||
'{cli} could not be installed.': '无法安装 {cli}。',
|
||||
'A saved model connection named {id} already exists and was not created here. Rename or delete it in App Settings, then try again.':
|
||||
'已存在名为 {id} 的已保存模型连接,而它不是在这里创建的。请在“应用设置”中重命名或删除它,然后重试。',
|
||||
'Codeman could not save the connection to the model.': '{name} 无法保存与模型的连接。',
|
||||
'The model on this Mac changed since it was installed. Remove it and install it again.':
|
||||
'此 Mac 上的模型在安装后发生了变化。请移除后重新安装。',
|
||||
'The install stopped on an unexpected error.': '安装因意外错误而中止。',
|
||||
'An install is already running.': '已有一个安装正在进行。',
|
||||
'A model is already installed on this Mac. Remove it first.': '此 Mac 上已安装了一个模型。请先移除它。',
|
||||
'The download is {size} GB now. Check the sizes and confirm again.':
|
||||
'现在的下载大小为 {size} GB。请核对大小后再次确认。',
|
||||
'Sessions are still using this model: {sessions}. Close them first.':
|
||||
'仍有会话在使用此模型:{sessions}。请先关闭它们。',
|
||||
'That is not possible in the current state.': '当前状态下无法执行此操作。',
|
||||
'This model at this context is not offered for this Mac right now.':
|
||||
'目前不为此 Mac 提供这一上下文大小下的该模型。',
|
||||
'This coding agent is not offered for this model.': '该模型不提供这个编程智能体。',
|
||||
'{cli} is not installed and cannot be installed from here.': '{cli} 尚未安装,也无法从这里安装。',
|
||||
'Only {model} is installed on this Mac. Remove it and install another model first.':
|
||||
'此 Mac 上只安装了 {model}。请先移除它,再安装其他模型。',
|
||||
// What the endpoint routes answer for the record of the model on this Mac (shown as a toast).
|
||||
'This endpoint belongs to the model Codeman runs on this Mac. Change or remove it in the local model window.':
|
||||
'此端点属于 {name} 在此 Mac 上运行的模型。请在本地模型窗口中更改或移除它。',
|
||||
'This endpoint id is reserved for the model Codeman runs on this Mac. Pick another id.':
|
||||
'此端点标识已保留给 {name} 在此 Mac 上运行的模型。请换一个标识。',
|
||||
'Coding agents use git and Python. This Mac has no developer tools yet, so macOS will offer to install them the first time an agent needs one.':
|
||||
'编程智能体会用到 git 和 Python。此 Mac 尚未安装开发者工具,因此在智能体首次需要时,macOS 会提示安装。',
|
||||
});
|
||||
|
||||
const ZH_CN_LOWER = new Map(Object.entries(ZH_CN).map(([key, value]) => [key.toLocaleLowerCase('en'), value]));
|
||||
|
||||
+44
-16
@@ -511,6 +511,17 @@
|
||||
contents on every state change and owns its inline display. -->
|
||||
<div class="welcome-actions">
|
||||
<div class="welcome-cli-actions" id="welcomeCliActions"></div>
|
||||
<!-- A model that runs on the Mac the server runs on (local-model-ui.js).
|
||||
One button in the chip family, a sibling of the launcher slot and
|
||||
never inside it (renderWelcomeCliActions empties that slot on every
|
||||
state change). Ships `hidden`: only that module reveals it, once the
|
||||
server has answered for a Mac. It opens the chooser window
|
||||
(#localModelModal) and the module writes its label through its own
|
||||
translator call, hence data-i18n-skip. -->
|
||||
<button type="button" class="welcome-chip welcome-local-model" id="welcomeLocalModelBtn" data-i18n-skip hidden onclick="app.openLocalModelWindow()">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9.5 2.5v3.5M14.5 2.5v3.5M9.5 18v3.5M14.5 18v3.5M2.5 9.5H6M2.5 14.5H6M18 9.5h3.5M18 14.5h3.5"/></svg>
|
||||
<span class="welcome-label" id="welcomeLocalModelLabel">Run a local model</span>
|
||||
</button>
|
||||
<button type="button" class="welcome-tunnel-link" id="welcomeTunnelBtn" style="display: none;" onclick="app.toggleTunnelFromWelcome()">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
||||
Cloudflare Tunnel
|
||||
@@ -583,14 +594,6 @@
|
||||
</div>
|
||||
<div class="history-list" id="historyList"></div>
|
||||
</div>
|
||||
<!-- What the Mac the server runs on can run as a local coding model
|
||||
(local-model-ui.js). Read-only. Ships `hidden` and only that module
|
||||
reveals it, once the server has answered for a Mac: a server on
|
||||
another system never shows it, and the user can hide it per device.
|
||||
The module writes every string through its own translator call
|
||||
(model and chip names are not ours to translate), hence
|
||||
data-i18n-skip. -->
|
||||
<section class="local-model-card" id="localModelCard" aria-labelledby="localModelCardTitle" data-i18n-skip hidden></section>
|
||||
<!-- Sessions a human started outside Codeman (foreign-sessions.js).
|
||||
Hidden until a scan finds one; never rendered empty on a fresh
|
||||
install, where an empty block reads as a broken feature. -->
|
||||
@@ -2876,20 +2879,24 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- What the Mac the server runs on can run as a local model (local-model-ui.js).
|
||||
Read-only: the module fills the row from GET /api/local-model, the same body
|
||||
the welcome card shows, through its own translator call (hence data-i18n-skip
|
||||
on the row's text). The module shows the group only once the server has
|
||||
<!-- The model that runs on the Mac the server runs on (local-model-ui.js). One row:
|
||||
the state in a few words, written by the module from GET /api/local-model
|
||||
through its own translator call (hence data-i18n-skip on the text and on the
|
||||
button), and a button that opens the chooser window (#localModelModal), where
|
||||
everything happens. The module shows the group only once the server has
|
||||
answered for a Mac: it hides it for a server on another system (the title
|
||||
and hint are about "this Mac"), while the first request is in flight, and
|
||||
for a non-admin in multi-user mode (the route is admin-only). Not gated on
|
||||
the endpoints toggle above: the answer does not depend on it. -->
|
||||
for a non-admin in multi-user mode (the routes are admin-only). Not gated on
|
||||
the endpoints toggle above: an install switches that on itself. -->
|
||||
<div class="set-group" id="localModelGroup">
|
||||
<div class="set-group-head"><h4>Model on this Mac</h4></div>
|
||||
<p class="set-group-hint">What the Mac that Codeman runs on can run as a local coding model. Read-only: nothing is downloaded or installed from here.</p>
|
||||
<p class="set-group-hint">Run a coding model on the Mac that Codeman runs on. No account and no API key.</p>
|
||||
<div class="set-group-body">
|
||||
<div class="set-row" data-search="local model mac apple silicon memory llm recommendation offline">
|
||||
<div class="set-row" data-search="local model mac apple silicon memory llm offline install download ollama">
|
||||
<div class="set-row-text" id="localModelSettings" data-i18n-skip aria-live="polite"></div>
|
||||
<div class="set-row-actions">
|
||||
<button type="button" class="btn-toolbar btn-sm" id="localModelSettingsOpen" data-i18n-skip onclick="app.openLocalModelWindow()">Open</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -3671,6 +3678,27 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- The local model window (local-model-ui.js): choose a model, confirm the sizes,
|
||||
watch the download, start a session. Opened by the welcome button and by the
|
||||
row in App Settings > Models; placed AFTER #appSettingsModal so it stacks above
|
||||
it when opened from there. The module fills the body from GET /api/local-model
|
||||
through its own translator call (model, agent and chip names are someone
|
||||
else's text), hence data-i18n-skip on the body; the title and the close button
|
||||
are static and go through the page translator. -->
|
||||
<div class="modal" id="localModelModal" role="dialog" aria-modal="true" aria-labelledby="localModelModalTitle">
|
||||
<div class="modal-backdrop" onclick="app.closeLocalModelWindow()"></div>
|
||||
<div class="modal-content local-model-window">
|
||||
<div class="modal-header">
|
||||
<h3 id="localModelModalTitle">Run a model on this Mac</h3>
|
||||
<button class="modal-close" onclick="app.closeLocalModelWindow()" aria-label="Close">×</button>
|
||||
</div>
|
||||
<div class="modal-body lm-body" id="localModelWindowBody" data-i18n-skip></div>
|
||||
<!-- The buttons of the current screen. Outside the body, so they keep their
|
||||
place while the body changes and scrolls. -->
|
||||
<div class="lm-foot-slot" id="localModelWindowFoot" data-i18n-skip></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Shortcut Overlay Modal -->
|
||||
<div class="modal shortcut-overlay-modal" id="shortcutOverlayModal" tabindex="-1">
|
||||
<div class="modal-backdrop" onclick="app.closeShortcutOverlay()"></div>
|
||||
|
||||
+1478
-271
File diff suppressed because it is too large.
Load diff
+96
-17
@@ -1857,15 +1857,39 @@ html.mobile-init .file-browser-panel {
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
/* Model on this Mac (local-model-ui.js). Only reached with the phone overview
|
||||
switched off. The card has no fixed width and every line in it wraps, so
|
||||
the narrow column only takes some of the spacing back. */
|
||||
.local-model-card {
|
||||
margin-top: 0.6rem;
|
||||
/* Run a model on this Mac (local-model-ui.js). The welcome button is only
|
||||
reached with the phone overview switched off; it takes the chips' finger
|
||||
size from `.welcome-chip` above. The window is full-screen like every
|
||||
modal here: its own width rule in styles.css is more specific than the
|
||||
full-screen `.modal-content` rule above, so the size is restated. */
|
||||
.modal-content.local-model-window {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
height: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.local-model-box {
|
||||
padding: 0.5rem 0.55rem;
|
||||
.local-model-window > .lm-body {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
/* The window fills the screen, so its actions sit at the bottom, under the thumb. */
|
||||
.local-model-window > .lm-foot-slot {
|
||||
padding: 0 1rem calc(1rem + var(--safe-area-bottom));
|
||||
}
|
||||
|
||||
/* The short screens (progress, paused, a failure, installed, nothing fits)
|
||||
hold a few lines. On a screen this tall they sit right above the buttons,
|
||||
where the eye and the thumb already are, not at the top with half a
|
||||
screen of nothing between the two. */
|
||||
.local-model-window > .lm-body:is(
|
||||
[data-screen='progress'],
|
||||
[data-screen='paused'],
|
||||
[data-screen='failed'],
|
||||
[data-screen='installed'],
|
||||
[data-screen='none']
|
||||
) {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* Ralph wizard responsive */
|
||||
@@ -3980,16 +4004,6 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
/* Model on this Mac (local-model-ui.js): its row follows the label size above. */
|
||||
#localModelSettings .local-model-headline,
|
||||
#localModelSettings .local-model-name {
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
#localModelSettings .local-model-alt .local-model-name {
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
/* Fields go full width under their label instead of fighting for the row */
|
||||
:is(#appSettingsModal, #sessionOptionsModal, #createCaseModal) .set-row.has-field {
|
||||
flex-direction: column;
|
||||
@@ -4282,3 +4296,68 @@ html[data-session-list="sidebar"] .session-sidebar .session-tab .tab-close {
|
||||
touch-action: pan-x pan-y;
|
||||
}
|
||||
}
|
||||
|
||||
/* Run a model on this Mac (local-model-ui.js), under 560px: each model row
|
||||
becomes two lines (name and tag, then speed and download size), the bar
|
||||
stays full width and the buttons go full width under the foot's sentence. */
|
||||
@media (max-width: 559px) {
|
||||
.lm-list {
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
column-gap: 0.7rem;
|
||||
}
|
||||
|
||||
.lm-caption-speed,
|
||||
.lm-caption-size {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.lm-model {
|
||||
row-gap: 0.1rem;
|
||||
padding-top: 0.5rem;
|
||||
padding-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.lm-radio {
|
||||
grid-row: 1;
|
||||
grid-column: 1;
|
||||
}
|
||||
|
||||
.lm-model-name {
|
||||
grid-row: 1;
|
||||
grid-column: 2;
|
||||
}
|
||||
|
||||
.lm-model-tag {
|
||||
grid-row: 1;
|
||||
grid-column: 3;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.lm-model-speed {
|
||||
grid-row: 2;
|
||||
grid-column: 2;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.lm-model-size {
|
||||
grid-row: 2;
|
||||
grid-column: 3;
|
||||
}
|
||||
|
||||
.lm-foot {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
/* The main action on top, the way back under it. */
|
||||
.lm-buttons {
|
||||
flex-direction: column-reverse;
|
||||
margin-inline-start: 0;
|
||||
}
|
||||
|
||||
.local-model-window .wt-btn.lm-btn {
|
||||
min-height: 44px;
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,8 @@ function rebootSkipReason(reason) {
|
||||
return 'already open';
|
||||
case 'capacity-reached':
|
||||
return 'session limit reached';
|
||||
case 'local-model-not-ready':
|
||||
return 'the local model is not ready';
|
||||
case 'rebuild-failed':
|
||||
return 'the agent would not start';
|
||||
default:
|
||||
|
||||
@@ -550,8 +550,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Assigning .checked above does not fire onchange, so the body's visibility
|
||||
// (and its lazy load) needs an explicit sync on every open, not just a save.
|
||||
this.applyCustomModelEndpointsVisibility();
|
||||
// Model on this Mac (local-model-ui.js): a read-only row, not a setting. Server state,
|
||||
// asked for at most once a minute; nothing here is loaded or saved by id.
|
||||
// Model on this Mac (local-model-ui.js): a row that says where the local model stands and
|
||||
// opens its window, not a setting. Server state, asked for at most once a minute; nothing
|
||||
// here is loaded or saved by id.
|
||||
this.loadLocalModel?.();
|
||||
// CLI management (docs/cli-enable-disable-plan.md): synced, default OFF.
|
||||
document.getElementById('appSettingsCliManagement').checked = settings.cliManagementEnabled === true;
|
||||
|
||||
+764
-136
@@ -22304,192 +22304,820 @@ html[data-tile-anim="soft"] .tile-grid-ghosts.tile-grid-ghosts--release:not(.til
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════
|
||||
Model on this Mac (local-model-ui.js): what the server's Mac can run as
|
||||
a local coding model. One body (`.local-model-body`), drawn in two places:
|
||||
the welcome card and a row of App Settings > Models.
|
||||
Run a model on this Mac (local-model-ui.js): the welcome button and the
|
||||
chooser window (#localModelModal). The App Settings row is ordinary
|
||||
`.set-row` markup and needs nothing here.
|
||||
|
||||
Same vocabulary as the two blocks above it on the welcome screen: a dim
|
||||
heading row, then one bordered surface with a name over dim meta lines.
|
||||
Theme tokens only (`--control-bg`, never a white alpha: that fill is
|
||||
invisible on the light skins), and the fit and speed labels are neutral
|
||||
pills: the words carry the meaning, so no skin needs a colour of its own.
|
||||
Nothing here is keyed on a CLI or a model id, and nothing animates.
|
||||
The subject is this Mac's memory, so the window has ONE strong element:
|
||||
the bar (`.lm-bar`), the memory this Mac can give a model, filled to what
|
||||
the selected model needs. Everything around it is quiet: hierarchy by size
|
||||
and weight, no box inside the window, no border around a row. The selected
|
||||
row carries the accent on its reading edge and a faint fill.
|
||||
|
||||
Theme tokens only, never a black or white alpha (those vanish on the light
|
||||
skins). The bar's track is `--text-muted`: the part of the bar that stays
|
||||
FREE is half of what the bar says, so it must be seen against the window
|
||||
(about 3:1 or better on every skin; the fill of the app's inputs,
|
||||
`--bg-input`, is the window's own surface on the dark skins, and a border
|
||||
token is 1.5:1). Nothing here is keyed on a CLI or a model id. The only
|
||||
motion is the bar's width, and it stops under prefers-reduced-motion.
|
||||
|
||||
The window is ONE frame for the whole flow: a fixed height on desktop, the
|
||||
header on top, the buttons in a foot of their own (`.lm-foot-slot`) and the
|
||||
body scrolling between them. A click never moves the next button away.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
.local-model-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
width: 100%;
|
||||
margin-top: 0.75rem;
|
||||
text-align: left;
|
||||
/* The welcome button: a second large button under the launchers, in the size
|
||||
of the primary one, so a model on this Mac is offered as a main way in and
|
||||
not as a footnote (the owner asked for it big and in the middle). It keeps
|
||||
the chip's markup and the chip family's rules for everything it does not
|
||||
restate here. */
|
||||
.welcome-local-model {
|
||||
margin-top: 1.1rem;
|
||||
height: 46px;
|
||||
gap: 0.65rem;
|
||||
padding: 0 1.4rem 0 0.45rem;
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 23px;
|
||||
background: var(--control-bg);
|
||||
color: var(--accent);
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.005em;
|
||||
box-shadow: 0 8px 24px -14px rgba(var(--accent-rgb), 0.5);
|
||||
}
|
||||
|
||||
/* A flex container, so `[hidden]` needs re-asserting or the module's only
|
||||
visibility lever does nothing (same trap as .foreign-sessions). */
|
||||
.local-model-card[hidden] {
|
||||
.welcome-local-model:hover,
|
||||
.welcome-local-model:focus-visible {
|
||||
background: rgba(var(--accent-rgb), 0.12);
|
||||
color: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
/* `.welcome-chip` is inline-flex, so `[hidden]` needs re-asserting or the
|
||||
module's only visibility lever does nothing. */
|
||||
.welcome-local-model[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.local-model-head {
|
||||
/* The chip's 14 px glyph sits in a 34 px disc, the primary button's logo size. */
|
||||
.welcome-local-model svg {
|
||||
flex-shrink: 0;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
padding: 8px;
|
||||
box-sizing: border-box;
|
||||
border-radius: 50%;
|
||||
background: rgba(var(--accent-rgb), 0.16);
|
||||
}
|
||||
|
||||
/* The window: App Settings' chrome (`.modal`, `.modal-header`, the boxed
|
||||
close button) at a width of its own. One frame for every screen: the height
|
||||
is fixed, so the header, the close button and the main button stay where
|
||||
they are from the chooser to "Start a session". */
|
||||
.modal-content.local-model-window {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(640px, 94vw);
|
||||
max-width: min(640px, 94vw);
|
||||
height: min(600px, 88vh);
|
||||
max-height: 88vh;
|
||||
}
|
||||
|
||||
.local-model-window > .modal-header {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* App Settings' close button: a 30px box, not the bare glyph of a plain modal. */
|
||||
.local-model-window > .modal-header .modal-close {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
padding: 0;
|
||||
border-radius: 9px;
|
||||
font-size: 1.2rem;
|
||||
color: var(--text-dim);
|
||||
background: transparent;
|
||||
transition:
|
||||
background 0.15s ease,
|
||||
color 0.15s ease,
|
||||
transform 0.1s ease;
|
||||
}
|
||||
|
||||
.local-model-window > .modal-header .modal-close:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.local-model-window > .modal-header .modal-close:active {
|
||||
transform: scale(0.94);
|
||||
}
|
||||
|
||||
.local-model-window > .lm-body {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
gap: 1.05rem;
|
||||
min-height: 0;
|
||||
padding: 1.15rem 1.25rem 1.2rem;
|
||||
overflow-y: auto;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
/* The short screens (progress, paused, a failure, installed, nothing fits)
|
||||
hold a few lines in a frame sized for the chooser: they sit in the middle of
|
||||
it, a status in its own room, not a heading with a void under it. */
|
||||
.local-model-window
|
||||
> .lm-body:is(
|
||||
[data-screen='progress'],
|
||||
[data-screen='paused'],
|
||||
[data-screen='failed'],
|
||||
[data-screen='installed'],
|
||||
[data-screen='none']
|
||||
) {
|
||||
justify-content: center;
|
||||
padding-bottom: 2.2rem;
|
||||
}
|
||||
|
||||
/* The foot of the frame: the buttons of the screen (or the Remove question),
|
||||
outside the part that scrolls. */
|
||||
.local-model-window > .lm-foot-slot {
|
||||
flex-shrink: 0;
|
||||
padding: 0 1.25rem 1.15rem;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.local-model-window > .lm-foot-slot:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.lm-foot-slot p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.lm-body p,
|
||||
.lm-body h4 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* ── type: four sizes, nothing in capitals ─────────────────────────── */
|
||||
.lm-hw {
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.45;
|
||||
color: var(--text-dim);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.lm-title {
|
||||
font-size: 1rem;
|
||||
font-weight: 650;
|
||||
line-height: 1.4;
|
||||
letter-spacing: -0.01em;
|
||||
color: var(--text);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.lm-lead {
|
||||
font-size: 0.84rem;
|
||||
line-height: 1.5;
|
||||
color: var(--text);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Why no model fits: one sentence, read as a sentence and not as a headline. */
|
||||
.lm-reason {
|
||||
font-size: 0.92rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.55;
|
||||
color: var(--text);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.lm-notes {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
|
||||
.lm-aside {
|
||||
font-size: 0.74rem;
|
||||
line-height: 1.5;
|
||||
color: var(--text-dim);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.lm-heading {
|
||||
font-size: 0.74rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
/* ── the bar ───────────────────────────────────────────────────────── */
|
||||
.lm-meter {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.local-model-title {
|
||||
margin: 0;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-dim);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.local-model-hide {
|
||||
margin-left: auto;
|
||||
font: inherit;
|
||||
font-size: 0.68rem;
|
||||
color: var(--text-dim);
|
||||
background: transparent;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
padding: 0.12rem 0.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.local-model-hide:hover {
|
||||
color: var(--text);
|
||||
background: var(--control-bg-hover);
|
||||
}
|
||||
|
||||
.local-model-box {
|
||||
padding: 0.55rem 0.65rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--control-bg);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.local-model-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* The line that says nothing can be set up from here yet (.local-model-next) is
|
||||
the one a reader must not miss, so it reads like every other line: same size,
|
||||
same --text-dim. --text-muted on this surface was 3.9:1. */
|
||||
.local-model-hw,
|
||||
.local-model-line,
|
||||
.local-model-note,
|
||||
.local-model-next {
|
||||
font-size: 0.68rem;
|
||||
line-height: 1.45;
|
||||
color: var(--text-dim);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.local-model-headline {
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.45;
|
||||
color: var(--text);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* The pick is the one thing in the card set apart: a rule in the accent, on the
|
||||
reading side (logical, so it follows a right-to-left page). */
|
||||
.local-model-pick {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.12rem;
|
||||
padding-inline-start: 0.55rem;
|
||||
border-inline-start: 2px solid var(--accent);
|
||||
}
|
||||
|
||||
.local-model-name-row {
|
||||
.lm-meter-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.2rem 0.4rem;
|
||||
min-width: 0;
|
||||
align-items: baseline;
|
||||
gap: 0.15rem 0.6rem;
|
||||
}
|
||||
|
||||
.local-model-name {
|
||||
font-size: 0.82rem;
|
||||
.lm-figure {
|
||||
font-size: 1.06rem;
|
||||
font-weight: 680;
|
||||
letter-spacing: -0.012em;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* Only the figure that ticks (the download) holds its digits in fixed cells.
|
||||
In a sentence fixed cells leave a hole around every 1. */
|
||||
.lm-figure-count {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.lm-figure-aside {
|
||||
font-size: 0.74rem;
|
||||
color: var(--text-dim);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.lm-bar {
|
||||
height: 10px;
|
||||
border-radius: 999px;
|
||||
background: var(--text-muted);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.lm-bar-fill {
|
||||
height: 100%;
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
transition: width 0.32s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.lm-legend {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
font-size: 0.7rem;
|
||||
line-height: 1.4;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.lm-legend > :last-child {
|
||||
text-align: end;
|
||||
}
|
||||
|
||||
/* ── the models: one grid, so the numbers line up down the list ──── */
|
||||
/* Radio, name, tag, speed, download. The tag sits next to the name and takes
|
||||
the room that is left, which pushes the two numbers to the right edge. */
|
||||
.lm-list {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, max-content) minmax(0, 1fr) auto auto;
|
||||
column-gap: 0.9rem;
|
||||
row-gap: 0.1rem;
|
||||
/* A row's fill reaches into the window's padding, so what is IN a row lines
|
||||
up with every other line of the window on both edges. */
|
||||
margin-inline: calc(-0.7rem - 2px) -0.7rem;
|
||||
}
|
||||
|
||||
.lm-caption,
|
||||
.lm-models,
|
||||
.lm-model {
|
||||
display: grid;
|
||||
grid-column: 1 / -1;
|
||||
grid-template-columns: subgrid;
|
||||
}
|
||||
|
||||
.lm-models {
|
||||
row-gap: 0.1rem;
|
||||
}
|
||||
|
||||
.lm-caption,
|
||||
.lm-model {
|
||||
align-items: center;
|
||||
padding: 0 0.7rem;
|
||||
border-inline-start: 2px solid transparent;
|
||||
}
|
||||
|
||||
.lm-caption {
|
||||
padding-bottom: 0.3rem;
|
||||
font-size: 0.7rem;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.lm-caption-label {
|
||||
grid-column: 1 / span 3;
|
||||
}
|
||||
|
||||
/* The server's word for a pick it has run on a Mac like this one stands where
|
||||
the list's label does, in the text colour. */
|
||||
.lm-caption-strong {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.lm-caption-speed,
|
||||
.lm-caption-size {
|
||||
text-align: end;
|
||||
}
|
||||
|
||||
.lm-model {
|
||||
min-height: 2.35rem;
|
||||
border-radius: 7px;
|
||||
cursor: pointer;
|
||||
transition: background var(--transition-smooth);
|
||||
}
|
||||
|
||||
.lm-model:hover {
|
||||
background: var(--control-bg);
|
||||
}
|
||||
|
||||
.lm-model:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
/* Selected: the accent on the reading edge and a faint fill. Nothing else. */
|
||||
.lm-model-on,
|
||||
.lm-model-on:hover {
|
||||
border-inline-start-color: var(--accent);
|
||||
background: rgba(var(--accent-rgb), 0.075);
|
||||
}
|
||||
|
||||
.lm-radio {
|
||||
box-sizing: border-box;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 1.5px solid var(--text-muted);
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.lm-model-on .lm-radio {
|
||||
border-color: var(--accent);
|
||||
background: radial-gradient(circle, var(--accent) 0 3px, transparent 3.5px);
|
||||
}
|
||||
|
||||
.lm-model-name {
|
||||
min-width: 0;
|
||||
font-size: 0.86rem;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
overflow-wrap: anywhere;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* Each pill carries what it measures as its tooltip (a title), hence the cursor. */
|
||||
.local-model-pill {
|
||||
flex: 0 0 auto;
|
||||
font-size: 0.62rem;
|
||||
.lm-model-tag {
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
/* A tag is text with a hairline, not a coloured pill. The accent is for the
|
||||
pick (and for a row that was run on a Mac like this one). */
|
||||
.lm-tag {
|
||||
padding: 0.05rem 0.42rem;
|
||||
border: 1px solid var(--border-light);
|
||||
border-radius: 5px;
|
||||
font-size: 0.66rem;
|
||||
line-height: 1.5;
|
||||
color: var(--text-dim);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
padding: 0 0.42rem;
|
||||
white-space: nowrap;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.local-model-alts-title {
|
||||
font-size: 0.72rem;
|
||||
.lm-tag-accent {
|
||||
border-color: rgba(var(--accent-rgb), 0.5);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.lm-model-speed,
|
||||
.lm-model-size {
|
||||
text-align: end;
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.lm-model-speed {
|
||||
font-size: 0.76rem;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
/* The welcome card folds the list behind a native disclosure (keyboard and
|
||||
screen-reader behaviour for free); the summary keeps `display: list-item`
|
||||
so its marker stays. */
|
||||
.local-model-alts > summary {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.local-model-alts > summary:hover {
|
||||
.lm-model-size {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 560;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.local-model-alt {
|
||||
/* A browser without subgrid: fixed tracks keep the columns in line. */
|
||||
@supports not (grid-template-columns: subgrid) {
|
||||
.lm-list,
|
||||
.lm-models {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.lm-caption,
|
||||
.lm-model {
|
||||
grid-template-columns: 14px 10.5rem minmax(0, 1fr) 8.6rem 4.4rem;
|
||||
column-gap: 0.9rem;
|
||||
}
|
||||
|
||||
.lm-model {
|
||||
margin-top: 0.1rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── the coding agent ─────────────────────────────────────────────── */
|
||||
.lm-runs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.4rem 0.6rem;
|
||||
font-size: 0.78rem;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.lm-runs-label {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.lm-select {
|
||||
max-width: 100%;
|
||||
padding: 5px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 7px;
|
||||
background: var(--bg-input);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 0.78rem;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.lm-select:focus-visible {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.lm-runs-hint {
|
||||
min-width: 0;
|
||||
font-size: 0.74rem;
|
||||
}
|
||||
|
||||
/* ── the confirm screen: the download as a table ──────────────────── */
|
||||
/* One row per thing that is fetched: its name in the text colour with what it
|
||||
is underneath, its size at the right edge, and the total under a rule in the
|
||||
strong weight. The table is the screen; nothing else on it competes. */
|
||||
.lm-sizes {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.1rem;
|
||||
margin-top: 0.3rem;
|
||||
padding-top: 0.3rem;
|
||||
}
|
||||
|
||||
.lm-sizes .lm-heading {
|
||||
margin-bottom: 0.35rem;
|
||||
font-size: 0.84rem;
|
||||
font-weight: 650;
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.lm-size-row {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 1.2rem;
|
||||
padding: 0.6rem 0;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.local-model-alt .local-model-name {
|
||||
font-size: 0.76rem;
|
||||
font-weight: 500;
|
||||
.lm-size-what {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.18rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* In App Settings the body sits inside an ordinary .set-row, so it takes that
|
||||
surface's type scale (label 0.76rem over a muted description) and the row
|
||||
supplies the border. */
|
||||
#localModelSettings {
|
||||
padding: 3px 0;
|
||||
.lm-size-name {
|
||||
font-size: 0.86rem;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
#localModelSettings .local-model-headline,
|
||||
#localModelSettings .local-model-name {
|
||||
font-size: 0.76rem;
|
||||
.lm-size-note {
|
||||
font-size: 0.74rem;
|
||||
line-height: 1.45;
|
||||
color: var(--text-dim);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
#localModelSettings .local-model-alt .local-model-name {
|
||||
.lm-size-gb {
|
||||
flex-shrink: 0;
|
||||
font-size: 0.86rem;
|
||||
font-weight: 560;
|
||||
color: var(--text);
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.lm-size-total {
|
||||
padding-top: 0.75rem;
|
||||
border-top-color: var(--text-muted);
|
||||
}
|
||||
|
||||
.lm-size-total .lm-size-name,
|
||||
.lm-size-total .lm-size-gb {
|
||||
font-size: 1.06rem;
|
||||
font-weight: 680;
|
||||
letter-spacing: -0.012em;
|
||||
}
|
||||
|
||||
/* A literal command: text to read and to copy, so it is set in the mono face
|
||||
and selects whole. It sits in its row, under the sentence that names it. */
|
||||
.lm-command {
|
||||
display: block;
|
||||
margin-top: 0.15rem;
|
||||
color: var(--text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
user-select: all;
|
||||
}
|
||||
|
||||
/* Touch: the two things in the card that take a press get a finger's height. */
|
||||
/* Where it goes: one quiet line under the table. */
|
||||
.lm-where {
|
||||
font-size: 0.74rem;
|
||||
line-height: 1.5;
|
||||
color: var(--text-dim);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.lm-path {
|
||||
color: var(--text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.72rem;
|
||||
user-select: all;
|
||||
}
|
||||
|
||||
/* ── progress: the steps ARE a sequence, so they are a list ───────── */
|
||||
.lm-steps {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.lm-step {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.65rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.lm-step-mark {
|
||||
position: relative;
|
||||
box-sizing: border-box;
|
||||
flex-shrink: 0;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 1.5px solid var(--border-light);
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.lm-step-done {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.lm-step-done .lm-step-mark {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
/* The check of a finished step, drawn from two borders in the page colour. */
|
||||
.lm-step-done .lm-step-mark::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 3.5px;
|
||||
top: 1px;
|
||||
width: 3px;
|
||||
height: 6px;
|
||||
border: solid var(--accent-ink);
|
||||
border-width: 0 1.5px 1.5px 0;
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
|
||||
.lm-step-now,
|
||||
.lm-step-stopped {
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.lm-step-now .lm-step-mark {
|
||||
border-color: var(--accent);
|
||||
background: radial-gradient(circle, var(--accent) 0 3px, transparent 3.5px);
|
||||
}
|
||||
|
||||
.lm-step-stopped .lm-step-mark {
|
||||
border-color: var(--text-dim);
|
||||
background: radial-gradient(circle, var(--text-dim) 0 3px, transparent 3.5px);
|
||||
}
|
||||
|
||||
/* ── installed ────────────────────────────────────────────────────── */
|
||||
.lm-state {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.3rem 0.5rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.lm-dot {
|
||||
flex-shrink: 0;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-muted);
|
||||
}
|
||||
|
||||
.lm-dot-on {
|
||||
background: var(--green);
|
||||
}
|
||||
|
||||
.lm-state-text {
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* ── a refused verb, an error's raw detail, the Remove question ──── */
|
||||
.lm-notice {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
padding-inline-start: 0.7rem;
|
||||
border-inline-start: 2px solid var(--yellow);
|
||||
}
|
||||
|
||||
.lm-notice-text {
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.5;
|
||||
color: var(--text);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.lm-notice-detail {
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.45;
|
||||
color: var(--text-dim);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.lm-details {
|
||||
margin-top: 0.2rem;
|
||||
font-size: 0.74rem;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.lm-details > summary {
|
||||
width: fit-content;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.lm-details > summary:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.lm-detail-text {
|
||||
max-height: 9rem;
|
||||
margin: 0.45rem 0 0;
|
||||
padding: 0.5rem 0.6rem;
|
||||
border-radius: 6px;
|
||||
background: var(--bg-input);
|
||||
color: var(--text-dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.68rem;
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
overflow: auto;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* An error: its first sentence as the headline, the rest in the body size. */
|
||||
.lm-error {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.lm-remove {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
padding-top: 0.95rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.lm-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: fit-content;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.lm-check input {
|
||||
margin: 0;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
/* ── the foot: one promise on the left, the action on the right ──── */
|
||||
.lm-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding-top: 0.95rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.lm-remove .lm-foot {
|
||||
padding-top: 0.2rem;
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.lm-foot-note {
|
||||
min-width: 0;
|
||||
font-size: 0.74rem;
|
||||
line-height: 1.45;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.lm-buttons {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
gap: 0.5rem;
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
|
||||
/* The buttons are the Git worktrees dialog's set (`.wt-btn`): a main action
|
||||
that reads as one on every skin (the skin block greys
|
||||
`.btn-toolbar.btn-primary`) and that the phone toolbar's !important sizing
|
||||
does not reach. Only the size is the window's own. */
|
||||
.local-model-window .wt-btn.lm-btn {
|
||||
padding: 0.5rem 0.95rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.local-model-window .wt-btn-primary.lm-btn {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* OG has no designed --accent-ink: the main action takes the deeper blue and
|
||||
light text of that skin's own Run button, as `.welcome-primary` does. Keep
|
||||
the two in step. */
|
||||
html[data-skin='og'] .local-model-window .wt-btn-primary.lm-btn {
|
||||
border-color: rgba(96, 165, 250, 0.5);
|
||||
background: linear-gradient(135deg, #1e4fb8 0%, #2563eb 100%);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
html[data-skin='og'] .local-model-window .wt-btn-primary.lm-btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #2454a8 0%, #2d6cf0 100%);
|
||||
}
|
||||
|
||||
.local-model-window .wt-btn.lm-btn:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.lm-bar-fill,
|
||||
.lm-model {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Touch: rows and the select get a finger's height. */
|
||||
@media (pointer: coarse) {
|
||||
.local-model-hide {
|
||||
min-height: 32px;
|
||||
padding: 0.3rem 0.8rem;
|
||||
.lm-model {
|
||||
min-height: 2.9rem;
|
||||
}
|
||||
|
||||
.local-model-alts > summary {
|
||||
padding: 0.4rem 0;
|
||||
.lm-select {
|
||||
min-height: 36px;
|
||||
}
|
||||
|
||||
.local-model-window .wt-btn.lm-btn {
|
||||
min-height: 40px;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2964,8 +2964,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
// up (stopped in hideWelcome), see foreign-sessions.js.
|
||||
this.wireForeignSessions?.();
|
||||
this.startForeignPolling?.();
|
||||
// What this Mac can run as a local model (local-model-ui.js). One request,
|
||||
// at most once a minute, no timer: nothing to stop in hideWelcome.
|
||||
// The "Run a local model" button (local-model-ui.js). One request, at most
|
||||
// once a minute, no timer here: only its open window polls, and closing
|
||||
// that window stops it, so there is nothing to stop in hideWelcome.
|
||||
this.loadLocalModel?.();
|
||||
}
|
||||
// Home screen has no input target — hide the CJK textarea (activeSessionId
|
||||
|
||||
@@ -29,13 +29,8 @@
|
||||
* write path (`registry-writer.ts` mirrors `custom-model-hosts.ts`).
|
||||
*/
|
||||
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import { constants as fsConstants } from 'node:fs';
|
||||
import { access } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import { ApiErrorCode, createErrorResponse, getErrorMessage, type ApiResponse } from '../../types.js';
|
||||
import { ApiErrorCode, createErrorResponse, type ApiResponse } from '../../types.js';
|
||||
import { getAuthUser, isAdmin, parseBody, readJsonConfig, SETTINGS_PATH } from '../route-helpers.js';
|
||||
import { isMultiUserMode } from '../../config/multiuser.js';
|
||||
import { listClis, resolveInstallCommandForPlatform } from '../../config/cli-registry/registry.js';
|
||||
@@ -45,9 +40,18 @@ import { STOCK_CLIS } from '../../config/cli-registry/stock.js';
|
||||
import type { CliEntry } from '../../config/cli-registry/types.js';
|
||||
import { CliCustomEntrySchema, CliEnableSchema } from '../schemas.js';
|
||||
import { appendAdminAudit } from '../admin-audit.js';
|
||||
import { invalidateCliExecutableResolvers } from '../../utils/cli-executable-resolver.js';
|
||||
import { invalidateCliResolverCache } from '../../utils/cli-resolver.js';
|
||||
import { isCliEntryInstalled, probeStockCliAvailability } from '../../utils/cli-installed-probes.js';
|
||||
import {
|
||||
CLI_INSTALL_TIMEOUT_MS,
|
||||
forgetResolvedCli,
|
||||
runInstallCommand,
|
||||
tryBeginCliInstall,
|
||||
type CliInstallResult,
|
||||
} from '../../cli-install-runner.js';
|
||||
|
||||
// The install runner lives in src/cli-install-runner.ts, shared with the local model install
|
||||
// job. These two stay importable from here, where the route's tests take them from.
|
||||
export { installEnv, npmGlobalPrefixWritable } from '../../cli-install-runner.js';
|
||||
|
||||
/**
|
||||
* `cliManagementEnabled` defaults OFF, same reasoning as
|
||||
@@ -78,17 +82,6 @@ export interface CliListItem {
|
||||
installCommand?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forget every cached binary lookup for this CLI — the generic per-id resolver (which
|
||||
* captures the entry's binaries when first built) and every underlying per-binary cache,
|
||||
* success and negative-cache backoff alike. Called after anything that changes what is on
|
||||
* disk or what the CLI's binary IS; see `invalidateCliExecutableResolvers`.
|
||||
*/
|
||||
function forgetResolvedCli(id: string, binaries: readonly string[]): void {
|
||||
invalidateCliExecutableResolvers(binaries);
|
||||
invalidateCliResolverCache(id);
|
||||
}
|
||||
|
||||
const STOCK_IDS = new Set(STOCK_CLIS.map((e) => e.id as string));
|
||||
|
||||
/**
|
||||
@@ -202,195 +195,6 @@ function nextOrder(): number {
|
||||
return (orders.length ? Math.max(...orders) : 0) + 10;
|
||||
}
|
||||
|
||||
/** Bounded execution: `PATH_INSTALL_TIMEOUT_MS`, output capped, process GROUP killed on timeout. */
|
||||
const CLI_INSTALL_TIMEOUT_MS = 300_000;
|
||||
|
||||
/**
|
||||
* Ids with an install running right now. A second request for the same id gets 409 rather
|
||||
* than a second `curl | bash` or `npm install -g` racing the first over the same prefix.
|
||||
*/
|
||||
const installsInFlight = new Set<string>();
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/**
|
||||
* True when `npm install -g` can write to this process's npm global prefix, or when that cannot
|
||||
* be determined (then nothing is redirected: a wrong guess would move installs somewhere the
|
||||
* user did not choose). `npm config get prefix` is asked rather than guessed from `process.execPath`
|
||||
* because a user `.npmrc` / `NPM_CONFIG_PREFIX` can point it anywhere.
|
||||
*
|
||||
* Async so the server keeps serving while npm boots (130 to 240 ms), and killed with SIGKILL on
|
||||
* timeout because `SIGTERM` alone leaves the wait running. A prefix that does not exist yet is
|
||||
* judged by the nearest ancestor that does: npm creates the missing directories, so a user
|
||||
* `.npmrc` pointing at `~/.npm-global` before it was made is not moved.
|
||||
*/
|
||||
export async function npmGlobalPrefixWritable(source: NodeJS.ProcessEnv): Promise<boolean> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('npm', ['config', 'get', 'prefix'], {
|
||||
env: source,
|
||||
encoding: 'utf8',
|
||||
timeout: 5_000,
|
||||
killSignal: 'SIGKILL',
|
||||
});
|
||||
const prefix = stdout.trim();
|
||||
if (!prefix) return true;
|
||||
// npm creates lib/node_modules under the prefix; walk up to the first directory that exists.
|
||||
let dir = join(prefix, 'lib', 'node_modules');
|
||||
for (;;) {
|
||||
try {
|
||||
await access(dir, fsConstants.W_OK);
|
||||
return true;
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return false;
|
||||
const parent = dirname(dir);
|
||||
if (parent === dir) return false;
|
||||
dir = parent;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The server's environment minus every `CODEMAN_*` variable. An install script is third-party
|
||||
* code, and those variables carry Codeman's own secrets and wiring (`CODEMAN_PASSWORD`, the
|
||||
* data dir, the tmux socket), none of which an installer needs.
|
||||
*
|
||||
* It also points `NPM_CONFIG_PREFIX` at `$HOME/.local` so an `npm install -g` lands somewhere the
|
||||
* server user can write and Codeman's resolvers already search (`~/.local/bin`):
|
||||
* - inside the Docker Compose container (`CODEMAN_IN_CONTAINER=1`), so installs survive an image
|
||||
* update (the image's own prefix is image content);
|
||||
* - on a native install whose npm global prefix is not writable by the server user (a system node
|
||||
* under `/usr`, installed by root). Without this `npm install -g` died with EACCES (exit 243),
|
||||
* e.g. DeepSeek's `npm install -g @deepseek-ai/dsh`. An explicit `NPM_CONFIG_PREFIX` the
|
||||
* operator set is respected, and so is a prefix that is writable (nvm, `~/.npm-global`, ...).
|
||||
*/
|
||||
export function installEnv(
|
||||
source: NodeJS.ProcessEnv = process.env,
|
||||
prefixWritable: (env: NodeJS.ProcessEnv) => boolean = () => true
|
||||
): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {};
|
||||
for (const [key, value] of Object.entries(source)) {
|
||||
if (!key.startsWith('CODEMAN_')) env[key] = value;
|
||||
}
|
||||
// ⚠️ In the Docker Compose deployment the image sets NPM_CONFIG_PREFIX=/opt/codeman-cli, which is IMAGE
|
||||
// content: `Update-Codeman.sh` recreates the container and every CLI installed there (dsh, pi, ...)
|
||||
// vanishes. HOME is the persistent bind mount and `~/.local/bin` is already on every resolver's search
|
||||
// list, so npm-based installs are redirected there. curl|bash installers already target HOME.
|
||||
if (source.CODEMAN_IN_CONTAINER === '1' && source.HOME) {
|
||||
redirectNpmPrefix(env, source.HOME);
|
||||
} else if (process.platform !== 'win32' && source.HOME && !source.NPM_CONFIG_PREFIX && !prefixWritable(env)) {
|
||||
redirectNpmPrefix(env, source.HOME);
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
/**
|
||||
* Point npm at `$HOME/.local`, dropping every spelling of the prefix key first. `npm run` exports a
|
||||
* lowercase `npm_config_prefix`, npm reads `npm_config_*` case-insensitively, and when both spellings
|
||||
* are present a `/bin/sh` that sorts its environment (bash) lets the older value win. The explicit
|
||||
* operator guard in `installEnv` stays on the uppercase key only: npm always injects the lowercase one.
|
||||
*/
|
||||
function redirectNpmPrefix(env: NodeJS.ProcessEnv, home: string): void {
|
||||
for (const key of Object.keys(env)) if (/^npm_config_prefix$/i.test(key)) delete env[key];
|
||||
env.NPM_CONFIG_PREFIX = `${home}/.local`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `installEnv` for this process, with the (async) npm prefix probe done first and only when the
|
||||
* command runs npm at all: a `curl | bash` installer never pays for it.
|
||||
*/
|
||||
async function installEnvFor(command: string, source: NodeJS.ProcessEnv = process.env): Promise<NodeJS.ProcessEnv> {
|
||||
const usesNpm = /\bnpm\b/.test(command);
|
||||
const probeNeeded =
|
||||
usesNpm &&
|
||||
source.CODEMAN_IN_CONTAINER !== '1' &&
|
||||
process.platform !== 'win32' &&
|
||||
!!source.HOME &&
|
||||
!source.NPM_CONFIG_PREFIX;
|
||||
const writable = probeNeeded ? await npmGlobalPrefixWritable(installEnv(source)) : true;
|
||||
return installEnv(source, () => writable);
|
||||
}
|
||||
|
||||
interface InstallResult {
|
||||
code: number | null;
|
||||
output: string;
|
||||
timedOut: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a STOCK entry's already-vetted install command. `shell: true` is unavoidable here —
|
||||
* the shipped commands are genuinely `curl | bash` / `npm install -g` one-liners — but this
|
||||
* is NOT a reopening of the config-shell-text concern the registry's `shellToken` pattern
|
||||
* exists to prevent: the string executed here is NEVER user input, only ever what is
|
||||
* already hardcoded and reviewed in `stock.ts` (`resolveInstallCommandForPlatform`), and a
|
||||
* CUSTOM entry can never reach this function at all — see the route's own guard below.
|
||||
*/
|
||||
async function runInstallCommand(command: string): Promise<InstallResult> {
|
||||
const env = await installEnvFor(command);
|
||||
return new Promise((resolve) => {
|
||||
let child: ReturnType<typeof spawn>;
|
||||
try {
|
||||
child = spawn(command, {
|
||||
shell: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
// Own process group; the timeout below kills the whole tree by hand, mirroring
|
||||
// the DeepSeek profile-install endpoint's own reasoning: an install command fans
|
||||
// out into package-manager children, and spawn's own `timeout` option signals
|
||||
// only the direct child, leaving survivors holding the pipes open forever.
|
||||
detached: true,
|
||||
env,
|
||||
});
|
||||
} catch (err) {
|
||||
resolve({ code: null, output: `spawn failed: ${getErrorMessage(err)}`, timedOut: false });
|
||||
return;
|
||||
}
|
||||
|
||||
let output = '';
|
||||
let timedOut = false;
|
||||
let settled = false;
|
||||
let killTimer: NodeJS.Timeout | undefined;
|
||||
let reapTimer: NodeJS.Timeout | undefined;
|
||||
|
||||
const capture = (chunk: Buffer) => {
|
||||
if (output.length < 16_384) output += chunk.toString('utf-8');
|
||||
};
|
||||
child.stdout?.on('data', capture);
|
||||
child.stderr?.on('data', capture);
|
||||
|
||||
const killTree = (signal: NodeJS.Signals) => {
|
||||
try {
|
||||
if (child.pid) process.kill(-child.pid, signal);
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
};
|
||||
|
||||
const finish = (code: number | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (killTimer) clearTimeout(killTimer);
|
||||
if (reapTimer) clearTimeout(reapTimer);
|
||||
resolve({ code, output, timedOut });
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
killTree('SIGTERM');
|
||||
killTimer = setTimeout(() => killTree('SIGKILL'), 3_000);
|
||||
reapTimer = setTimeout(() => finish(null), 8_000);
|
||||
}, CLI_INSTALL_TIMEOUT_MS);
|
||||
|
||||
child.on('error', (err) => {
|
||||
output = `${output}\n${err.message}`;
|
||||
finish(null);
|
||||
});
|
||||
child.on('close', (code) => finish(code));
|
||||
});
|
||||
}
|
||||
|
||||
export function registerCliRegistryRoutes(app: FastifyInstance): void {
|
||||
// ---- Phase 2: read ----------------------------------------------------
|
||||
// GET /api/clis — every registry entry, disabled ones included (this is an
|
||||
@@ -461,6 +265,8 @@ export function registerCliRegistryRoutes(app: FastifyInstance): void {
|
||||
|
||||
// ---- Phase 4: auto-install (stock only) --------------------------------
|
||||
// One install per id at a time (409 otherwise), and the script never sees CODEMAN_* env.
|
||||
// Bounded execution (`CLI_INSTALL_TIMEOUT_MS`), output capped, process GROUP killed on
|
||||
// timeout: all of that is `runInstallCommand()` in src/cli-install-runner.ts.
|
||||
// POST /api/clis/:id/install — runs the entry's already-vetted install
|
||||
// command. Separate endpoint from Phase 3's toggle: installing is a bigger
|
||||
// action than a boolean flip and gets its own audit entry. Never auto-
|
||||
@@ -488,15 +294,16 @@ export function registerCliRegistryRoutes(app: FastifyInstance): void {
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, `"${id}" has no install command for this platform`);
|
||||
}
|
||||
|
||||
if (installsInFlight.has(id)) {
|
||||
// ONE slot per id, shared with the local model install job (src/cli-install-runner.ts).
|
||||
const release = tryBeginCliInstall(id);
|
||||
if (!release) {
|
||||
return createErrorResponse(ApiErrorCode.CONFLICT, `"${id}" is already being installed`);
|
||||
}
|
||||
installsInFlight.add(id);
|
||||
let result: InstallResult;
|
||||
let result: CliInstallResult;
|
||||
try {
|
||||
result = await runInstallCommand(command);
|
||||
} finally {
|
||||
installsInFlight.delete(id);
|
||||
release();
|
||||
}
|
||||
// Even a failed or timed-out install may have left a binary behind, so forget the
|
||||
// cached lookups either way: the next Run click or badge read probes afresh
|
||||
|
||||
@@ -12,17 +12,34 @@
|
||||
* connect time, redirects included — a save-time hostname check alone would
|
||||
* let `models.example` resolve to 169.254.169.254 later. The endpoint is
|
||||
* admin-configured, so this is defence in depth rather than the only gate.
|
||||
*
|
||||
* Every write of `custom-model-hosts.json` goes through `mutateCustomModelHosts()`
|
||||
* (src/custom-model-hosts-writer.ts): the four writing routes and the re-discovery sweep run
|
||||
* one at a time, each check ("the id is free", "the record still exists") inside the same
|
||||
* serialized step as its write, and a file that does not parse is refused with 409 rather than
|
||||
* overwritten. They used to read, change and write on their own, through one shared temp file
|
||||
* name: a route and the sweep could tear the file, and the next writer then saved a list that
|
||||
* held only its own record.
|
||||
*
|
||||
* The local model install (src/local-model/) keeps ONE record here under a reserved id
|
||||
* (`LOCAL_MODEL_ENDPOINT_ID`). A new endpoint may not take that id. While the record is the
|
||||
* managed one (`isManagedLocalEndpoint()`: the local model state file records it as ours) it
|
||||
* is not edited, deleted or re-discovered from here: its `models` must stay the one model the
|
||||
* install checked, and its `baseUrl` the port of the runtime Codeman supervises. It is changed
|
||||
* and removed through the local model routes.
|
||||
*/
|
||||
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import { ApiErrorCode, createErrorResponse, type ApiResponse } from '../../types.js';
|
||||
import { ApiErrorCode, createErrorResponse, LOCAL_MODEL_INSTALL_LABELS, type ApiResponse } from '../../types.js';
|
||||
import { isAdmin, parseBody, readJsonConfig, SETTINGS_PATH } from '../route-helpers.js';
|
||||
import { isMultiUserMode } from '../../config/multiuser.js';
|
||||
import { getDataDir } from '../../config/instance.js';
|
||||
import { isBlockedWebviewUrl } from '../webview-egress-policy.js';
|
||||
import { egressBlockedReason, webviewFetch } from '../webview-egress.js';
|
||||
import { CustomModelHostSchema, MAX_DISCOVERED_CONTEXT_TOKENS } from '../schemas.js';
|
||||
import { readCustomModelHosts, writeCustomModelHosts, type CustomModelHost } from '../../custom-model-hosts.js';
|
||||
import { readCustomModelHosts, type CustomModelHost } from '../../custom-model-hosts.js';
|
||||
import { customModelHostsWriteErrorResponse, mutateCustomModelHosts } from '../../custom-model-hosts-writer.js';
|
||||
import { isLocalModelEndpointId, isManagedLocalEndpoint } from '../../local-model/connect.js';
|
||||
import type { CliEntry } from '../../config/cli-registry/types.js';
|
||||
|
||||
const CODEMAN_CONFIG_DIR = getDataDir();
|
||||
@@ -795,20 +812,30 @@ export async function refreshAllCustomModelHosts(): Promise<void> {
|
||||
const hosts = await readCustomModelHosts(dataDir);
|
||||
for (const host of hosts) {
|
||||
if (isBlockedWebviewUrl(host.baseUrl)) continue;
|
||||
// The local model's own record keeps the one model its install checked: whatever else the
|
||||
// runtime lists (a model somebody pulled through its port) must not become launchable.
|
||||
if (await isManagedLocalEndpoint(host.id)) continue;
|
||||
let result: DiscoveryResult;
|
||||
try {
|
||||
result = await discoverModels(host);
|
||||
} catch {
|
||||
continue; // unreachable this cycle — try again next tick, not fatal to the sweep
|
||||
}
|
||||
// Re-read + splice by id rather than reusing the array captured above: an
|
||||
// admin editing or deleting an endpoint via the API mid-sweep must win,
|
||||
// not be silently overwritten by a refresh that started before their change.
|
||||
const current = await readCustomModelHosts(dataDir);
|
||||
const index = current.findIndex((item) => item.id === host.id);
|
||||
if (index === -1) continue; // deleted mid-sweep
|
||||
current[index] = applyDiscoveredModels(current[index], result);
|
||||
await writeCustomModelHosts(dataDir, current);
|
||||
// Spliced by id inside the serialized writer, onto the list as it is THEN, rather than
|
||||
// the array captured above: an admin editing or deleting an endpoint via the API mid-sweep
|
||||
// must win, not be silently overwritten by a refresh that started before their change.
|
||||
try {
|
||||
await mutateCustomModelHosts<void>((current) => {
|
||||
const index = current.findIndex((item) => item.id === host.id);
|
||||
if (index === -1) return { result: undefined }; // deleted mid-sweep
|
||||
current[index] = applyDiscoveredModels(current[index], result);
|
||||
return { hosts: current, result: undefined };
|
||||
}, dataDir);
|
||||
} catch {
|
||||
// A file that must not be overwritten (it does not parse) refuses every write of this
|
||||
// sweep the same way. The writer logged why; nothing more can be saved this cycle.
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -897,6 +924,18 @@ export async function detectCustomModelSwapDisplacements(
|
||||
return displacements;
|
||||
}
|
||||
|
||||
/** A write the serialized writer refused (the file does not parse) is 409 with the fix; any other failure stays in the envelope. */
|
||||
function refusedHostsWrite(err: unknown, reply: { code: (n: number) => unknown }): ApiResponse<never> {
|
||||
const response = customModelHostsWriteErrorResponse(err);
|
||||
if (!response.success && response.errorCode === ApiErrorCode.CONFLICT) reply.code(409);
|
||||
return response;
|
||||
}
|
||||
|
||||
/** The answer to an edit or a delete of the record the local model install manages. */
|
||||
function managedEndpointRefusal(): ApiResponse<never> {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, LOCAL_MODEL_INSTALL_LABELS.endpointManaged);
|
||||
}
|
||||
|
||||
export function registerCustomModelRoutes(app: FastifyInstance): void {
|
||||
app.get('/api/model-endpoints', async (req): Promise<RedactedHost[]> => {
|
||||
if (isMultiUserMode() && !isAdmin(req)) return [];
|
||||
@@ -913,12 +952,19 @@ export function registerCustomModelRoutes(app: FastifyInstance): void {
|
||||
}
|
||||
const badDefault = invalidDefaultModel(host);
|
||||
if (badDefault) return badDefault;
|
||||
const hosts = await readCustomModelHosts(CODEMAN_CONFIG_DIR);
|
||||
if (hosts.some((item) => item.id === host.id)) {
|
||||
return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, 'Model endpoint already exists');
|
||||
if (isLocalModelEndpointId(host.id)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, LOCAL_MODEL_INSTALL_LABELS.endpointIdReserved);
|
||||
}
|
||||
try {
|
||||
return await mutateCustomModelHosts<ApiResponse<{ host: RedactedHost }>>((hosts) => {
|
||||
if (hosts.some((item) => item.id === host.id)) {
|
||||
return { result: createErrorResponse(ApiErrorCode.ALREADY_EXISTS, 'Model endpoint already exists') };
|
||||
}
|
||||
return { hosts: [...hosts, host], result: { success: true, data: { host: redactApiKey(host) } } };
|
||||
}, CODEMAN_CONFIG_DIR);
|
||||
} catch (err) {
|
||||
return refusedHostsWrite(err, reply);
|
||||
}
|
||||
await writeCustomModelHosts(CODEMAN_CONFIG_DIR, [...hosts, host]);
|
||||
return { success: true, data: { host: redactApiKey(host) } };
|
||||
});
|
||||
|
||||
app.put('/api/model-endpoints/:id', async (req, reply): Promise<ApiResponse<{ host: RedactedHost }>> => {
|
||||
@@ -931,26 +977,37 @@ export function registerCustomModelRoutes(app: FastifyInstance): void {
|
||||
}
|
||||
const badDefault = invalidDefaultModel(incoming);
|
||||
if (badDefault) return badDefault;
|
||||
const hosts = await readCustomModelHosts(CODEMAN_CONFIG_DIR);
|
||||
const index = hosts.findIndex((item) => item.id === id);
|
||||
if (index === -1) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Model endpoint not found');
|
||||
const host = applyDiscoveredFields(applyStoredApiKey(incoming, hosts[index]), hosts[index]);
|
||||
const next = [...hosts];
|
||||
next[index] = host;
|
||||
await writeCustomModelHosts(CODEMAN_CONFIG_DIR, next);
|
||||
return { success: true, data: { host: redactApiKey(host) } };
|
||||
if (await isManagedLocalEndpoint(id)) return managedEndpointRefusal();
|
||||
try {
|
||||
return await mutateCustomModelHosts<ApiResponse<{ host: RedactedHost }>>((hosts) => {
|
||||
const index = hosts.findIndex((item) => item.id === id);
|
||||
if (index === -1) return { result: createErrorResponse(ApiErrorCode.NOT_FOUND, 'Model endpoint not found') };
|
||||
const host = applyDiscoveredFields(applyStoredApiKey(incoming, hosts[index]), hosts[index]);
|
||||
const next = [...hosts];
|
||||
next[index] = host;
|
||||
return { hosts: next, result: { success: true, data: { host: redactApiKey(host) } } };
|
||||
}, CODEMAN_CONFIG_DIR);
|
||||
} catch (err) {
|
||||
return refusedHostsWrite(err, reply);
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/model-endpoints/:id', async (req, reply): Promise<ApiResponse<{ id: string }>> => {
|
||||
const denied = adminOnly(req, reply);
|
||||
if (denied) return denied;
|
||||
const { id } = req.params as { id: string };
|
||||
const hosts = await readCustomModelHosts(CODEMAN_CONFIG_DIR);
|
||||
await writeCustomModelHosts(
|
||||
CODEMAN_CONFIG_DIR,
|
||||
hosts.filter((item) => item.id !== id)
|
||||
);
|
||||
return { success: true, data: { id } };
|
||||
if (await isManagedLocalEndpoint(id)) return managedEndpointRefusal();
|
||||
try {
|
||||
return await mutateCustomModelHosts<ApiResponse<{ id: string }>>((hosts) => {
|
||||
const next = hosts.filter((item) => item.id !== id);
|
||||
// Nothing to take out: the file is left as it is, and the answer is the same.
|
||||
return next.length === hosts.length
|
||||
? { result: { success: true, data: { id } } }
|
||||
: { hosts: next, result: { success: true, data: { id } } };
|
||||
}, CODEMAN_CONFIG_DIR);
|
||||
} catch (err) {
|
||||
return refusedHostsWrite(err, reply);
|
||||
}
|
||||
});
|
||||
|
||||
app.post(
|
||||
@@ -966,12 +1023,12 @@ export function registerCustomModelRoutes(app: FastifyInstance): void {
|
||||
if (isBlockedWebviewUrl(host.baseUrl)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Endpoint base URL is not allowed');
|
||||
}
|
||||
// The local model's own record is not probed: it lists the one model its install checked,
|
||||
// and that list is the answer.
|
||||
if (await isManagedLocalEndpoint(id)) return { success: true, data: { models: host.models ?? [] } };
|
||||
let result: DiscoveryResult;
|
||||
try {
|
||||
const result = await discoverModels(host);
|
||||
const next = [...hosts];
|
||||
next[index] = applyDiscoveredModels(host, result);
|
||||
await writeCustomModelHosts(CODEMAN_CONFIG_DIR, next);
|
||||
return { success: true, data: { models: result.models } };
|
||||
result = await discoverModels(host);
|
||||
} catch (err) {
|
||||
const blocked = egressBlockedReason(err);
|
||||
return createErrorResponse(
|
||||
@@ -979,6 +1036,18 @@ export function registerCustomModelRoutes(app: FastifyInstance): void {
|
||||
blocked ? `Endpoint refused: ${blocked}` : `Could not reach endpoint: ${describeFetchError(err)}`
|
||||
);
|
||||
}
|
||||
try {
|
||||
// Onto the record as it is NOW: the probe above took a moment, and an edit made
|
||||
// meanwhile must not be replaced by the copy read before it.
|
||||
return await mutateCustomModelHosts<ApiResponse<{ models: string[] }>>((current) => {
|
||||
const at = current.findIndex((item) => item.id === id);
|
||||
if (at === -1) return { result: createErrorResponse(ApiErrorCode.NOT_FOUND, 'Model endpoint not found') };
|
||||
current[at] = applyDiscoveredModels(current[at], result);
|
||||
return { hosts: current, result: { success: true, data: { models: result.models } } };
|
||||
}, CODEMAN_CONFIG_DIR);
|
||||
} catch (err) {
|
||||
return refusedHostsWrite(err, reply);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -1,18 +1,34 @@
|
||||
/**
|
||||
* @fileoverview `GET /api/local-model`: what this Mac is and which local model fits it.
|
||||
* @fileoverview The local model routes: what this Mac is and which local model fits it
|
||||
* (`GET /api/local-model`), and the verbs that install one, start and stop it and remove it.
|
||||
*
|
||||
* Answers `{ success: true, data: LocalModelStatus }`, built from the hardware probe, the
|
||||
* catalogue, the harness facts and the pure `recommend()`:
|
||||
* `{ hardware, recommendation, catalogUpdated }`. Nothing is reformatted here: every size text
|
||||
* and every sentence in the payload was chosen by the modules that produced it.
|
||||
* | Route | Body | Answer |
|
||||
* |----------------------------------|-----------------------------|------------------------------------------------|
|
||||
* | `GET /api/local-model` | none | `{ hardware, recommendation, catalogUpdated, install }` |
|
||||
* | `POST /api/local-model/install` | `LocalModelInstallRequest` | the install view; 400, 409 |
|
||||
* | `POST /api/local-model/cancel` | none | the install view; 409 |
|
||||
* | `POST /api/local-model/resume` | `LocalModelResumeRequest` | the install view; 409 |
|
||||
* | `POST /api/local-model/runtime` | `LocalModelRuntimeRequest` | the install view; 409 |
|
||||
* | `DELETE /api/local-model` | `LocalModelRemoveRequest` | the install view; 409 |
|
||||
*
|
||||
* EXPERIMENTAL (docs/versioning-policy.md, "Experimental local model recommendation"): the
|
||||
* route and its payload are outside the stable `/api/v1` contract until the stage that sets a
|
||||
* model up ships, because that stage will change what the fields mean. docs/api-reference.md
|
||||
* says so in its section; keep the two in step, and drop both labels together.
|
||||
* The GET is built from the hardware probe, the catalogue, the harness facts and the pure
|
||||
* `recommend()`, plus the `install` object of the install service
|
||||
* (`LocalModelService.view()`). Nothing is reformatted here: every size text and every
|
||||
* sentence in the payload was chosen by the modules that produced it. There is no SSE event:
|
||||
* the window polls the GET once a second while it is open.
|
||||
*
|
||||
* EXPERIMENTAL (docs/versioning-policy.md, "Experimental local model routes"): the routes and
|
||||
* their payloads are outside the stable `/api/v1` contract. docs/api-reference.md says so in
|
||||
* its section; keep the two in step, and drop both labels together.
|
||||
*
|
||||
* Rules:
|
||||
* - Read-only. It downloads nothing, installs nothing, writes no file and reads no setting.
|
||||
* - Every route is admin only in multi-user mode (403), the same bar as `GET /api/doctor`:
|
||||
* the GET names hardware of the host, and the verbs download and run a program, install a
|
||||
* coding agent and write the server-wide settings. The gate runs before anything is probed,
|
||||
* parsed or started.
|
||||
* - The GET changes nothing a person asked to keep: it downloads nothing, installs nothing
|
||||
* and writes no setting. Its one write is the service's own bookkeeping (a job a server
|
||||
* restart interrupted is marked paused the first time anything looks at it).
|
||||
* - A failed probe is an answer, never a 500. `readHardware()` reports a spawn that failed
|
||||
* in the hardware's `source` (`os-fallback`), and a server that is not on macOS as
|
||||
* `not-probed`; both go out as a 200 whose recommendation is verdict `none` or computed
|
||||
@@ -21,10 +37,19 @@
|
||||
* `source` values.
|
||||
* - A 500 is left for a fault that is not a probe: the catalogue, the harness facts or
|
||||
* `recommend()` throwing. That is a bug, and it must not be dressed up as "no model fits".
|
||||
* - The payload names hardware of the host, so in multi-user mode it is admin only (403), the
|
||||
* same bar as `GET /api/doctor`. The gate runs before anything is probed.
|
||||
* - A verb answers the view AFTER the verb. A refusal the service names is a 400 (the request
|
||||
* is not a row the server offers) or a 409 whose `data` is the `LocalModelConflict`
|
||||
* (`reason`, the sentence, and for `size-changed` the server's own total, for
|
||||
* `sessions-open` the session names). A 400 the service names carries its sentence as
|
||||
* `data.message` too, so the window prints it in its own language. A write of the settings
|
||||
* or of the endpoint store that was refused (a file that does not parse) is a 409 without
|
||||
* `data`, with the fix.
|
||||
* - The verbs do the work in the install service; this file only gates, parses and maps.
|
||||
* `DELETE`, `runtime` and `resume` look at the live sessions: they hand their names to the
|
||||
* service, which refuses a removal, a stop and a change of port while one of them still
|
||||
* uses the model.
|
||||
* - Every dependency is injected (`LocalModelRouteDeps`), so a route test spawns nothing and
|
||||
* does not need a Mac: it passes its own hardware and harness facts.
|
||||
* does not need a Mac: it passes its own hardware, harness facts and service.
|
||||
*/
|
||||
|
||||
import { arch, totalmem } from 'node:os';
|
||||
@@ -37,23 +62,64 @@ import {
|
||||
type HardwareFacts,
|
||||
type HarnessFact,
|
||||
type LocalModelCatalog,
|
||||
type LocalModelConflict,
|
||||
type LocalModelInstallView,
|
||||
type LocalModelRefusal,
|
||||
type LocalModelStatus,
|
||||
type Recommendation,
|
||||
type RecommendOptions,
|
||||
} from '../../types.js';
|
||||
import { isAdmin } from '../route-helpers.js';
|
||||
import { getAuthUser, isAdmin, parseBody } from '../route-helpers.js';
|
||||
import { isMultiUserMode } from '../../config/multiuser.js';
|
||||
import { getLocalModelCatalog } from '../../config/local-model-catalog.js';
|
||||
import {
|
||||
CustomModelHostsWriteRefusedError,
|
||||
customModelHostsWriteErrorResponse,
|
||||
} from '../../custom-model-hosts-writer.js';
|
||||
import { sessionNamesUsingEndpoint } from '../../local-model/connect.js';
|
||||
import { formatGb, memClassGb } from '../../local-model/format.js';
|
||||
import { readHardware } from '../../local-model/hardware.js';
|
||||
import { buildHarnessFacts } from '../../local-model/harness-facts.js';
|
||||
import {
|
||||
formatInstallMessage,
|
||||
getLocalModelService,
|
||||
type LocalModelActor,
|
||||
type LocalModelService,
|
||||
type LocalModelVerbResult,
|
||||
} from '../../local-model/install-job.js';
|
||||
import { recommend } from '../../local-model/recommend.js';
|
||||
import {
|
||||
LocalModelInstallSchema,
|
||||
LocalModelRemoveSchema,
|
||||
LocalModelResumeSchema,
|
||||
LocalModelRuntimeSchema,
|
||||
} from '../schemas.js';
|
||||
import { SettingsWriteRefusedError, settingsWriteErrorResponse } from '../settings-writer.js';
|
||||
|
||||
/** What the route calls. Each member defaults to the real module; a test overrides what it needs. */
|
||||
/** A live session as the DELETE needs it: its name, and the endpoint its model comes from. */
|
||||
export interface LocalModelSessionLike {
|
||||
name: string;
|
||||
customModel?: { endpointId: string };
|
||||
}
|
||||
|
||||
/** What the routes read of the server: its live sessions. */
|
||||
export interface LocalModelRouteContext {
|
||||
sessions: ReadonlyMap<string, LocalModelSessionLike>;
|
||||
}
|
||||
|
||||
/** What the routes call. Each member defaults to the real module; a test overrides what it needs. */
|
||||
export interface LocalModelRouteDeps {
|
||||
readHardware: () => Promise<HardwareFacts>;
|
||||
getCatalog: () => LocalModelCatalog;
|
||||
buildHarnessFacts: (catalog: LocalModelCatalog) => Promise<HarnessFact[]>;
|
||||
recommend: (hw: HardwareFacts, catalog: LocalModelCatalog, harnessFacts: readonly HarnessFact[]) => Recommendation;
|
||||
recommend: (
|
||||
hw: HardwareFacts,
|
||||
catalog: LocalModelCatalog,
|
||||
harnessFacts: readonly HarnessFact[],
|
||||
options?: RecommendOptions
|
||||
) => Recommendation;
|
||||
/** The install service. Looked up on every request, so the server's one service is built on first use. */
|
||||
service: () => LocalModelService;
|
||||
}
|
||||
|
||||
export const defaultLocalModelRouteDeps: LocalModelRouteDeps = {
|
||||
@@ -61,6 +127,7 @@ export const defaultLocalModelRouteDeps: LocalModelRouteDeps = {
|
||||
getCatalog: getLocalModelCatalog,
|
||||
buildHarnessFacts: (catalog) => buildHarnessFacts(catalog),
|
||||
recommend,
|
||||
service: getLocalModelService,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -80,15 +147,94 @@ export function hardwareFromOs(): HardwareFacts {
|
||||
};
|
||||
}
|
||||
|
||||
export function registerLocalModelRoutes(app: FastifyInstance, deps: Partial<LocalModelRouteDeps> = {}): void {
|
||||
/** The 409 of a verb the service refused: the error envelope plus the conflict as `data`. */
|
||||
export interface LocalModelConflictResponse {
|
||||
success: false;
|
||||
/** The conflict's sentence in English, its slots filled. */
|
||||
error: string;
|
||||
errorCode: ApiErrorCode;
|
||||
data: LocalModelConflict;
|
||||
}
|
||||
|
||||
/** The 400 (or 507) of a verb the service refused with a sentence: the error envelope plus that sentence as `data`. */
|
||||
export interface LocalModelRefusalResponse {
|
||||
success: false;
|
||||
/** The sentence in English, its slots filled. */
|
||||
error: string;
|
||||
errorCode: ApiErrorCode;
|
||||
data: LocalModelRefusal;
|
||||
}
|
||||
|
||||
/** What a verb answers: the view after it, an error envelope, or a refusal that carries its sentence. */
|
||||
export type LocalModelVerbResponse =
|
||||
| ApiResponse<LocalModelInstallView>
|
||||
| LocalModelConflictResponse
|
||||
| LocalModelRefusalResponse;
|
||||
|
||||
/** 403 for a non-admin in multi-user mode, before anything else runs. `null`: go on. */
|
||||
function adminOnly(req: FastifyRequest, reply: FastifyReply): ApiResponse<never> | null {
|
||||
if (!isMultiUserMode() || isAdmin(req)) return null;
|
||||
reply.code(403);
|
||||
return createErrorResponse(ApiErrorCode.FORBIDDEN, 'Admin only in multi-user mode');
|
||||
}
|
||||
|
||||
function actorOf(req: FastifyRequest): LocalModelActor {
|
||||
return { username: getAuthUser(req).username, ip: req.ip };
|
||||
}
|
||||
|
||||
/** A verb's result as its HTTP answer. */
|
||||
function respond(result: LocalModelVerbResult, reply: FastifyReply): LocalModelVerbResponse {
|
||||
if (result.ok) return { success: true, data: result.view };
|
||||
reply.code(result.status);
|
||||
if (result.status !== 409) {
|
||||
return {
|
||||
success: false,
|
||||
error: formatInstallMessage(result.message),
|
||||
errorCode: result.status === 400 ? ApiErrorCode.INVALID_INPUT : ApiErrorCode.OPERATION_FAILED,
|
||||
data: { message: result.message },
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
error: formatInstallMessage(result.conflict.message),
|
||||
errorCode: ApiErrorCode.CONFLICT,
|
||||
data: result.conflict,
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs one verb. What the service did not name as a refusal: a refused config write is a 409 with the fix, anything else a 500. */
|
||||
async function runVerb(
|
||||
reply: FastifyReply,
|
||||
verb: () => Promise<LocalModelVerbResult>
|
||||
): Promise<LocalModelVerbResponse> {
|
||||
try {
|
||||
return respond(await verb(), reply);
|
||||
} catch (err) {
|
||||
if (err instanceof CustomModelHostsWriteRefusedError) {
|
||||
reply.code(409);
|
||||
return customModelHostsWriteErrorResponse(err);
|
||||
}
|
||||
if (err instanceof SettingsWriteRefusedError) {
|
||||
reply.code(409);
|
||||
return settingsWriteErrorResponse(err);
|
||||
}
|
||||
reply.code(500);
|
||||
return createErrorResponse(ApiErrorCode.INTERNAL_ERROR, `The local model request failed: ${getErrorMessage(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function registerLocalModelRoutes(
|
||||
app: FastifyInstance,
|
||||
ctx: LocalModelRouteContext,
|
||||
deps: Partial<LocalModelRouteDeps> = {}
|
||||
): void {
|
||||
const resolved: LocalModelRouteDeps = { ...defaultLocalModelRouteDeps, ...deps };
|
||||
|
||||
app.get(
|
||||
'/api/local-model',
|
||||
async (req: FastifyRequest, reply: FastifyReply): Promise<ApiResponse<LocalModelStatus>> => {
|
||||
if (isMultiUserMode() && !isAdmin(req)) {
|
||||
reply.code(403);
|
||||
return createErrorResponse(ApiErrorCode.FORBIDDEN, 'Admin only in multi-user mode');
|
||||
}
|
||||
const denied = adminOnly(req, reply);
|
||||
if (denied) return denied;
|
||||
|
||||
let hardware: HardwareFacts;
|
||||
try {
|
||||
@@ -101,8 +247,13 @@ export function registerLocalModelRoutes(app: FastifyInstance, deps: Partial<Loc
|
||||
try {
|
||||
const catalog = resolved.getCatalog();
|
||||
const harnessFacts = await resolved.buildHarnessFacts(catalog);
|
||||
const recommendation = resolved.recommend(hardware, catalog, harnessFacts);
|
||||
return { success: true, data: { hardware, recommendation, catalogUpdated: catalog.updated } };
|
||||
const service = resolved.service();
|
||||
// The measured budget once the runtime reported it, and the runtime download that an
|
||||
// install would still add: what turns the estimate into the figures of the consent.
|
||||
const options = await service.recommendOptions();
|
||||
const recommendation = resolved.recommend(hardware, catalog, harnessFacts, options);
|
||||
const install = await service.view();
|
||||
return { success: true, data: { hardware, recommendation, catalogUpdated: catalog.updated, install } };
|
||||
} catch (err) {
|
||||
reply.code(500);
|
||||
return createErrorResponse(
|
||||
@@ -112,4 +263,44 @@ export function registerLocalModelRoutes(app: FastifyInstance, deps: Partial<Loc
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
app.post('/api/local-model/install', async (req, reply): Promise<LocalModelVerbResponse> => {
|
||||
const denied = adminOnly(req, reply);
|
||||
if (denied) return denied;
|
||||
const body = parseBody(LocalModelInstallSchema, req.body);
|
||||
return runVerb(reply, () => resolved.service().install(body, actorOf(req)));
|
||||
});
|
||||
|
||||
app.post('/api/local-model/cancel', async (req, reply): Promise<LocalModelVerbResponse> => {
|
||||
const denied = adminOnly(req, reply);
|
||||
if (denied) return denied;
|
||||
return runVerb(reply, () => resolved.service().cancel());
|
||||
});
|
||||
|
||||
app.post('/api/local-model/resume', async (req, reply): Promise<LocalModelVerbResponse> => {
|
||||
const denied = adminOnly(req, reply);
|
||||
if (denied) return denied;
|
||||
const body = parseBody(LocalModelResumeSchema, req.body ?? {});
|
||||
const sessionNames = sessionNamesUsingEndpoint(ctx.sessions.values());
|
||||
return runVerb(reply, () => resolved.service().resume(body, actorOf(req), sessionNames));
|
||||
});
|
||||
|
||||
app.post('/api/local-model/runtime', async (req, reply): Promise<LocalModelVerbResponse> => {
|
||||
const denied = adminOnly(req, reply);
|
||||
if (denied) return denied;
|
||||
const body = parseBody(LocalModelRuntimeSchema, req.body);
|
||||
// Asked at the moment of the request, like the DELETE: a stop or a change of port leaves
|
||||
// a live session calling an address nothing of ours holds.
|
||||
const sessionNames = sessionNamesUsingEndpoint(ctx.sessions.values());
|
||||
return runVerb(reply, () => resolved.service().runtime(body, sessionNames));
|
||||
});
|
||||
|
||||
app.delete('/api/local-model', async (req, reply): Promise<LocalModelVerbResponse> => {
|
||||
const denied = adminOnly(req, reply);
|
||||
if (denied) return denied;
|
||||
const body = parseBody(LocalModelRemoveSchema, req.body ?? {});
|
||||
// Asked at the moment of the request: a session that started a second ago counts.
|
||||
const sessionNames = sessionNamesUsingEndpoint(ctx.sessions.values());
|
||||
return runVerb(reply, () => resolved.service().remove(body, sessionNames, actorOf(req)));
|
||||
});
|
||||
}
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
isWorkingDirAllowedForUsername,
|
||||
sessionCapacityMessage,
|
||||
} from '../route-helpers.js';
|
||||
import { getLocalModelService } from '../../local-model/install-job.js';
|
||||
import { rebootRestoreRegistry } from '../reboot-restore-registry.js';
|
||||
import { rejectAlreadyLive, type RebootRestoreEntry, type RebootRestoreRejection } from '../../reboot-restore.js';
|
||||
import { clampEnvOverridesForOwner } from '../../session-env-clamp.js';
|
||||
@@ -163,6 +164,21 @@ export function registerRebootRestoreRoutes(app: FastifyInstance, ctx: RebootRes
|
||||
failures.push({ sessionId: entry.sessionId, reason: 'workspace-forbidden' });
|
||||
continue;
|
||||
}
|
||||
// A session that ran on the model Codeman runs on this Mac is rebuilt only while that
|
||||
// model can be started on: its own runtime is up and its digest is the one stored at
|
||||
// install time. Asked before anything is built, like the two session routes; the
|
||||
// session's own launch guard would refuse the start too, but only after the session
|
||||
// exists. Every other endpoint, and a session without one, is answered `undefined`.
|
||||
const savedModel = (entry.state as { __customModel?: { endpointId?: string; modelId?: string } }).__customModel;
|
||||
if (savedModel && typeof savedModel.endpointId === 'string' && typeof savedModel.modelId === 'string') {
|
||||
const refusal = await getLocalModelService().launchRefusalMessage(savedModel.endpointId, savedModel.modelId);
|
||||
if (refusal) {
|
||||
console.warn(`[reboot-restore] ${entry.sessionId} is not rebuilt: ${refusal}`);
|
||||
// Left on offer: the model can be started (or installed again) and the click repeated.
|
||||
failures.push({ sessionId: entry.sessionId, reason: 'local-model-not-ready' });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const saved = entry.state;
|
||||
const claudeModeConfig = await ctx.getClaudeModeConfig();
|
||||
|
||||
@@ -82,6 +82,7 @@ import {
|
||||
CustomModelSelectionSchema,
|
||||
} from '../schemas.js';
|
||||
import { readCustomModelHosts, resolveCustomModelContextLength } from '../../custom-model-hosts.js';
|
||||
import { getLocalModelService } from '../../local-model/install-job.js';
|
||||
import { applyCustomModelInjection, removeConfigDir } from '../../custom-model-injection-apply.js';
|
||||
import { buildCustomModelInjection } from '../../custom-model-injection.js';
|
||||
import {
|
||||
@@ -1783,6 +1784,11 @@ export function registerSessionRoutes(
|
||||
if (!endpoint) {
|
||||
return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Model endpoint not found');
|
||||
}
|
||||
// The model Codeman runs on this Mac: only while its own runtime is up, and only the model
|
||||
// that was installed, with the digest stored then (undefined for every other endpoint).
|
||||
// Before anything is written or restarted.
|
||||
const localModelRefusal = await getLocalModelService().launchRefusalMessage(endpoint.id, body.modelId);
|
||||
if (localModelRefusal) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, localModelRefusal);
|
||||
// Discovery's per-model figure wins; the endpoint's user-set default covers models
|
||||
// whose size discovery could not determine (a gateway that states none, say). With
|
||||
// neither, the existing "no override, CLI assumes its own default" behaviour stands.
|
||||
@@ -4772,6 +4778,11 @@ export function registerSessionRoutes(
|
||||
const cmHosts = await readCustomModelHosts(CODEMAN_CONFIG_DIR);
|
||||
const cmEndpoint = cmHosts.find((h) => h.id === customModel.endpointId);
|
||||
if (!cmEndpoint) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Model endpoint not found');
|
||||
// See the dedicated route: the model Codeman runs on this Mac is launched only while its
|
||||
// own runtime is up and its digest is the one stored at install time. Before any
|
||||
// confirmation is asked for and before a session exists.
|
||||
const cmLocalModelRefusal = await getLocalModelService().launchRefusalMessage(cmEndpoint.id, customModel.modelId);
|
||||
if (cmLocalModelRefusal) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, cmLocalModelRefusal);
|
||||
// Per-model discovery figure first, user-set endpoint default second, nothing third
|
||||
// (see the dedicated route's own comment above).
|
||||
const cmContextLength = resolveCustomModelContextLength(cmEndpoint, customModel.modelId);
|
||||
|
||||
@@ -2466,6 +2466,43 @@ export const CustomModelHostSchema = z.object({
|
||||
defaultContextLength: z.number().int().positive().max(MAX_DISCOVERED_CONTEXT_TOKENS).optional(),
|
||||
});
|
||||
|
||||
// ---------- Local model install (src/web/routes/local-model-routes.ts) ----------
|
||||
|
||||
/**
|
||||
* A model id as the local model catalogue writes it: `name:tag`, lowercase, no slash. The
|
||||
* same pattern as `LOCAL_MODEL_ID_PATTERN` in config/local-model-catalog.ts, repeated here as
|
||||
* a request-shape check: without a slash an id can never name another registry host. The
|
||||
* real gate is the route's own lookup of the id in what the server offers.
|
||||
*/
|
||||
const localModelId = z
|
||||
.string()
|
||||
.max(200)
|
||||
.regex(/^[a-z0-9][a-z0-9._-]*:[a-z0-9][a-z0-9._-]*$/, 'Invalid model id');
|
||||
|
||||
/** POST /api/local-model/install: the row the person chose and the size they confirmed. */
|
||||
export const LocalModelInstallSchema = z
|
||||
.object({
|
||||
modelId: localModelId,
|
||||
cli: z
|
||||
.string()
|
||||
.max(64)
|
||||
.regex(/^[a-z0-9][a-z0-9_-]*$/, 'Invalid coding agent id'),
|
||||
context: z.number().int().positive().max(MAX_DISCOVERED_CONTEXT_TOKENS),
|
||||
acknowledgedBytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** POST /api/local-model/resume. The body may be empty. */
|
||||
export const LocalModelResumeSchema = z.object({ newPort: z.boolean().optional() }).strict();
|
||||
|
||||
/** POST /api/local-model/runtime. */
|
||||
export const LocalModelRuntimeSchema = z
|
||||
.object({ action: z.enum(['start', 'stop']), newPort: z.boolean().optional() })
|
||||
.strict();
|
||||
|
||||
/** DELETE /api/local-model. The body may be empty. */
|
||||
export const LocalModelRemoveSchema = z.object({ removeModel: z.boolean().optional() }).strict();
|
||||
|
||||
/**
|
||||
* A shell-safe bare word, mirroring `config/cli-registry/schema.ts`'s own `shellToken` —
|
||||
* duplicated rather than imported, since the REAL safety boundary for anything built from
|
||||
|
||||
@@ -113,6 +113,11 @@ const SENSITIVE_PATTERNS: RegExp[] = [
|
||||
/\/\.codeman[^/]*\/webhook\.json$/,
|
||||
/\/\.codeman[^/]*\/custom-model-hosts\.json$/,
|
||||
/\/\.codeman[^/]*\/custom-model-configs\//,
|
||||
// The local model runtime (src/local-model/) is started with a private HOME inside the data
|
||||
// dir and makes a key pair for itself there (`home/.ollama/id_ed25519`). A runtime the user
|
||||
// runs on their own keeps the same key under their real home.
|
||||
/\/\.codeman[^/]*\/local-model\/home\//,
|
||||
/\/\.ollama\/id_ed25519$/,
|
||||
// Config backups are dated COPIES of the files above (users.json and settings.json
|
||||
// included), which the name-anchored patterns do not match. A custom
|
||||
// `configBackupDir` is outside what a pattern here can name.
|
||||
|
||||
+28
-1
@@ -146,6 +146,7 @@ import { probeLocalPaths, readClaudeEditSources, resolveClaudeTranscript } from
|
||||
import { remoteLocateClaudeTranscript, remoteProbePaths, remoteReadClaudeEditSources } from '../remote-files.js';
|
||||
import { remoteTmuxLocation } from '../tmux-manager.js';
|
||||
import { stopDeepSeekWeb } from '../deepseek-web-server.js';
|
||||
import { getLocalModelService } from '../local-model/install-job.js';
|
||||
import {
|
||||
wireRespawnListeners,
|
||||
setupTimedRespawn,
|
||||
@@ -1418,7 +1419,7 @@ export class WebServer extends EventEmitter {
|
||||
registerDoctorRoutes(this.app);
|
||||
registerCustomModelRoutes(this.app);
|
||||
registerCliRegistryRoutes(this.app);
|
||||
registerLocalModelRoutes(this.app);
|
||||
registerLocalModelRoutes(this.app, ctx);
|
||||
|
||||
// Cron: build the service from the same context, recompute
|
||||
// due times for any persisted jobs, then expose it to its routes.
|
||||
@@ -2193,6 +2194,17 @@ export class WebServer extends EventEmitter {
|
||||
// First keep-warm evaluation: publishes the effective opt-in for the Session Options
|
||||
// readout even before any cache report arrives.
|
||||
void this.keepWarmService.schedule(session.id);
|
||||
// Before every start of a NEW agent process the session asks this (a fresh pane, the
|
||||
// respawn of a dead one, a restart in place; never an attach to an agent that runs).
|
||||
// The model Codeman runs on this Mac is the one endpoint with something to say: no agent
|
||||
// is started on it while its runtime is down or its model is not the one that was
|
||||
// installed. Every other session, and every other endpoint, is answered `undefined`.
|
||||
// Set on every call, above the idempotency return: it holds no state of its own.
|
||||
session.setLaunchGuard(async () => {
|
||||
const selection = session.customModel;
|
||||
if (!selection) return undefined;
|
||||
return getLocalModelService().launchRefusalMessage(selection.endpointId, selection.modelId);
|
||||
});
|
||||
// Idempotent: the wiring exit handler detaches ALL listeners on every PTY exit
|
||||
// (removeSessionListenerRefs), so the re-attach routes (/interactive,
|
||||
// /interactive-respawn, /shell) call this again to restore observability
|
||||
@@ -3441,6 +3453,14 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// The model Codeman runs on this Mac (src/local-model/): a job a restart interrupted comes
|
||||
// back paused and waits for a click, and an installed runtime that was not stopped is
|
||||
// started again (an own orphan on its port is adopted or replaced). Off the startup path:
|
||||
// boot() never throws, and nothing waits for a runtime to answer. Not in tests.
|
||||
if (!this.testMode) {
|
||||
void getLocalModelService().boot();
|
||||
}
|
||||
|
||||
// Sweep agent preamble caches whose sessions are gone (see
|
||||
// pruneAgentSessionPreambles). Once per boot, after restore, so every session this
|
||||
// instance owns is in the keep set. Best-effort and off the startup critical path.
|
||||
@@ -4590,6 +4610,13 @@ export class WebServer extends EventEmitter {
|
||||
// got wrong once.
|
||||
void stopDeepSeekWeb();
|
||||
|
||||
// The local model runtime is a non-detached child, but a child is not ended by its
|
||||
// parent's exit: it gets SIGTERM here, and an install job in flight is interrupted (the
|
||||
// next start reads it as paused). An orphan a hard kill leaves is adopted at the next boot.
|
||||
if (!this.testMode) {
|
||||
void getLocalModelService().shutdown();
|
||||
}
|
||||
|
||||
// The header's GPU / CPU clock sampler is a Windows child process under WSL, and its idle sweep a timer.
|
||||
stopHostSensors();
|
||||
|
||||
|
||||
Reference in new issue
Block a user