ai-agentmanager 1.52.0 → 1.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,260 @@
1
+ // Local models: what runs on this computer. Ollama, LM Studio, llama.cpp, MLX and any other server
2
+ // that speaks the OpenAI API are found by asking their usual addresses (and any in config.json's
3
+ // "localModels": { "servers": { "<name>": "<address>" } }), and their models are offered to the
4
+ // "Local model" engine (engines/local.js) as "<server>/<model>", say "ollama/qwen3-coder:30b".
5
+ // Nothing is sent anywhere but those addresses.
6
+
7
+ import os from 'node:os';
8
+
9
+ export const LOCAL_DEFAULTS = { enabled: true, context: 32768 };
10
+ export const LOCAL_PRESETS = {
11
+ ollama: { label: 'Ollama', url: 'http://127.0.0.1:11434' },
12
+ lmstudio: { label: 'LM Studio', url: 'http://127.0.0.1:1234' },
13
+ // llama.cpp's llama-server and MLX's mlx_lm.server both start here.
14
+ llamacpp: { label: 'llama.cpp or MLX', url: 'http://127.0.0.1:8080' },
15
+ };
16
+ const KIND_LABEL = { ollama: 'Ollama', lmstudio: 'LM Studio', llamacpp: 'llama.cpp', mlx: 'MLX', openai: 'OpenAI API' };
17
+ export const HARNESSES = ['codex', 'opencode', 'claude'];
18
+ const SERVER_ID = /^[a-z][a-z0-9-]{0,30}$/;
19
+ const MIN_CONTEXT = 8192;
20
+ const MAX_CONTEXT = 1_048_576;
21
+
22
+ /** An address as kept: http(s), no path but what a proxy needs, no trailing "/v1". Null when it isn't one. */
23
+ export function cleanUrl(v) {
24
+ try {
25
+ const u = new URL(String(v ?? '').trim());
26
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
27
+ return `${u.origin}${u.pathname.replace(/\/+$/, '').replace(/\/v1$/, '')}`;
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ export function localSettings(config = {}) {
34
+ const c = config.localModels ?? {};
35
+ const servers = {};
36
+ for (const [id, p] of Object.entries(LOCAL_PRESETS)) servers[id] = { ...p, preset: true };
37
+ for (const [id, v] of Object.entries(c.servers ?? {})) {
38
+ if (!SERVER_ID.test(id)) continue;
39
+ if (v === false) {
40
+ delete servers[id];
41
+ continue;
42
+ }
43
+ const url = cleanUrl(typeof v === 'string' ? v : v?.url);
44
+ if (url) servers[id] = { label: (typeof v === 'object' && v?.label) || servers[id]?.label || id, url, preset: false };
45
+ }
46
+ const n = Number(c.context);
47
+ return {
48
+ enabled: c.enabled !== false,
49
+ // The room Ollama gives a model for an agent (it starts models with far less); 0 leaves Ollama's own.
50
+ context: n === 0 ? 0 : Number.isInteger(n) && n >= MIN_CONTEXT && n <= MAX_CONTEXT ? n : LOCAL_DEFAULTS.context,
51
+ default: typeof c.default === 'string' && c.default.includes('/') ? c.default : null,
52
+ // The harness "local" stands for; null is the first installed (engines/index.js).
53
+ harness: HARNESSES.includes(c.harness) ? c.harness : null,
54
+ servers,
55
+ };
56
+ }
57
+
58
+ /** "ollama/qwen3-coder:30b" as { server, name }; a model's own name may have slashes. */
59
+ export function parseModel(id) {
60
+ const s = String(id ?? '').trim();
61
+ const at = s.indexOf('/');
62
+ if (at < 1 || at === s.length - 1) return null;
63
+ return { server: s.slice(0, at), name: s.slice(at + 1) };
64
+ }
65
+
66
+ /**
67
+ * The copy of an Ollama model with room for an agent: "gpt-oss:20b" with 32768 tokens is
68
+ * "gpt-oss-am32k:20b". A copy is a few lines in Ollama's list; the weights are shared.
69
+ */
70
+ export function variantName(name, context) {
71
+ const at = name.lastIndexOf(':');
72
+ const tagged = at > name.lastIndexOf('/');
73
+ return `${tagged ? name.slice(0, at) : name}-am${Math.round(context / 1024)}k:${tagged ? name.slice(at + 1) : 'latest'}`;
74
+ }
75
+ const VARIANT = /-am\d+k(:[^/]*)?$/;
76
+ const untagged = (name) => name.replace(/:latest$/, '');
77
+
78
+ /** "20.9B" or "568M" as billions of parameters. */
79
+ const billions = (v) => {
80
+ const m = /^([\d.]+)\s*([BM])/i.exec(String(v ?? ''));
81
+ return m ? Number(m[1]) / (m[2].toUpperCase() === 'M' ? 1000 : 1) : null;
82
+ };
83
+
84
+ /** Ollama's /api/tags (and /api/ps, for what is in memory) as models; the copies this app makes are left out. */
85
+ export function ollamaModels(tags, ps = null) {
86
+ // A copy of ours in memory is its model in memory.
87
+ const loaded = new Set((ps?.models ?? []).map((m) => untagged(String(m.name ?? '').replace(/-am\d+k(?=:[^/]*$|$)/, ''))));
88
+ const out = [];
89
+ for (const m of tags?.models ?? []) {
90
+ const name = String(m?.name ?? '');
91
+ if (!name || VARIANT.test(name)) continue;
92
+ const caps = Array.isArray(m.capabilities) ? m.capabilities : null;
93
+ if (caps && !caps.includes('completion')) continue; // an embedding model
94
+ out.push({
95
+ name: untagged(name),
96
+ sizeBytes: Number(m.size) || null,
97
+ params: m.details?.parameter_size ?? null,
98
+ quant: m.details?.quantization_level ?? null,
99
+ // Older Ollama doesn't say here; null is "not known".
100
+ tools: caps ? caps.includes('tools') : null,
101
+ maxContext: Number(m.details?.context_length) || null,
102
+ loaded: loaded.has(untagged(name)),
103
+ });
104
+ }
105
+ return out;
106
+ }
107
+
108
+ /** LM Studio's /api/v0/models as models. */
109
+ export function lmstudioModels(list) {
110
+ return (list?.data ?? [])
111
+ .filter((m) => m?.id && m.type !== 'embeddings')
112
+ .map((m) => ({
113
+ name: String(m.id),
114
+ sizeBytes: null,
115
+ params: null,
116
+ quant: m.quantization ?? null,
117
+ tools: Array.isArray(m.capabilities) ? m.capabilities.includes('tool_use') : null,
118
+ maxContext: Number(m.max_context_length) || null,
119
+ context: Number(m.loaded_context_length) || null,
120
+ loaded: m.state === 'loaded',
121
+ }));
122
+ }
123
+
124
+ /** Any server's /v1/models as models (llama.cpp adds sizes under "meta"). */
125
+ export function openaiModels(list) {
126
+ return (list?.data ?? [])
127
+ .filter((m) => m?.id)
128
+ .map((m) => ({
129
+ name: String(m.id),
130
+ sizeBytes: Number(m.meta?.size) || null,
131
+ params: m.meta?.n_params ? `${(m.meta.n_params / 1e9).toFixed(1)}B` : null,
132
+ quant: null,
133
+ tools: null,
134
+ maxContext: Number(m.meta?.n_ctx_train) || null,
135
+ loaded: m.owned_by === 'llamacpp' ? true : null,
136
+ }));
137
+ }
138
+
139
+ /** Whether a model can do an agent's work here, and what to know before choosing it. */
140
+ export function judgeModel(m, { memory = os.totalmem() } = {}) {
141
+ const notes = [];
142
+ if (m.tools === false) return { usable: false, notes: ["Can't call tools, which an agent needs to read and change files"] };
143
+ if (m.sizeBytes && m.sizeBytes > memory * 0.7) notes.push('Large for the memory of this computer: expect it to be slow');
144
+ const b = billions(m.params);
145
+ if (b != null && b < 7) notes.push('Small: fine for a quick question, unlikely to manage a task of many steps');
146
+ if (m.tools == null) notes.push("The server doesn't say whether it can call tools");
147
+ return { usable: true, notes };
148
+ }
149
+
150
+ async function getJson(url, { timeoutMs = 1500 } = {}) {
151
+ try {
152
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: 'application/json' } });
153
+ return res.ok ? await res.json() : null;
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+
159
+ /** One address: what answers there and its models, or `running: false`. */
160
+ export async function probeServer(id, server, { get = getJson, memory = os.totalmem() } = {}) {
161
+ const base = { id, label: server.label, url: server.url, preset: Boolean(server.preset) };
162
+ const done = (kind, models, more = {}) => ({
163
+ ...base,
164
+ label: server.preset && id === 'llamacpp' ? KIND_LABEL[kind] ?? server.label : server.label,
165
+ kind,
166
+ running: true,
167
+ ...more,
168
+ models: models.map((m) => ({ id: `${id}/${m.name}`, ...m, ...judgeModel(m, { memory }) })).sort((a, b) => a.name.localeCompare(b.name)),
169
+ });
170
+ const tags = await get(`${server.url}/api/tags`);
171
+ if (Array.isArray(tags?.models)) {
172
+ const [ps, version] = await Promise.all([get(`${server.url}/api/ps`), get(`${server.url}/api/version`)]);
173
+ return done('ollama', ollamaModels(tags, ps), { version: version?.version ?? null });
174
+ }
175
+ const v0 = await get(`${server.url}/api/v0/models`);
176
+ if (Array.isArray(v0?.data)) return done('lmstudio', lmstudioModels(v0));
177
+ const list = await get(`${server.url}/v1/models`);
178
+ if (Array.isArray(list?.data)) {
179
+ const kind = list.data.some((m) => m?.owned_by === 'llamacpp') ? 'llamacpp' : list.data.some((m) => /^mlx-community\//.test(m?.id ?? '')) ? 'mlx' : 'openai';
180
+ return done(kind, openaiModels(list));
181
+ }
182
+ return { ...base, kind: null, running: false, models: [] };
183
+ }
184
+
185
+ // What the last look found, for checks that can't wait for a new one (engines/local.js).
186
+ let seen = null;
187
+ export const lastSeen = () => seen;
188
+
189
+ /** The servers and their models, looked up again when the last look is older than a few seconds. */
190
+ export class LocalModels {
191
+ constructor({ config, save = () => {}, probe = probeServer, now = () => Date.now(), keepMs = 10_000 }) {
192
+ Object.assign(this, { config, save, probe, now, keepMs, at: 0, pending: null, found: [] });
193
+ }
194
+
195
+ get settings() {
196
+ return localSettings(this.config);
197
+ }
198
+
199
+ async look() {
200
+ const s = this.settings;
201
+ this.found = s.enabled ? await Promise.all(Object.entries(s.servers).map(([id, server]) => this.probe(id, server))) : [];
202
+ this.at = this.now();
203
+ seen = this.found;
204
+ return this.found;
205
+ }
206
+
207
+ async view({ fresh = false } = {}) {
208
+ if (fresh || this.now() - this.at > this.keepMs) await (this.pending ??= this.look().finally(() => (this.pending = null)));
209
+ const s = this.settings;
210
+ const models = this.found.flatMap((x) => x.models);
211
+ return {
212
+ enabled: s.enabled,
213
+ context: s.context,
214
+ default: s.default,
215
+ memory: os.totalmem(),
216
+ // A server at its usual address that isn't running is not worth a row; one you added is.
217
+ servers: this.found.filter((x) => x.running || !x.preset),
218
+ models: models.filter((m) => m.usable).map((m) => m.id),
219
+ };
220
+ }
221
+
222
+ /** Changes from the API: `enabled`, `context`, `default`, `add: { name, url }`, `remove: name`. */
223
+ change(b = {}) {
224
+ const bad = (m) => Object.assign(new Error(m), { status: 400 });
225
+ const next = { ...this.config.localModels, servers: { ...this.config.localModels?.servers } };
226
+ if ('enabled' in b) next.enabled = b.enabled === true || b.enabled === 'on';
227
+ if ('context' in b) {
228
+ const n = Number(b.context);
229
+ if (!(n === 0 || (Number.isInteger(n) && n >= MIN_CONTEXT && n <= MAX_CONTEXT))) throw bad(`The context is a number of tokens from ${MIN_CONTEXT} to ${MAX_CONTEXT}, or 0 to leave the server's own`);
230
+ next.context = n;
231
+ }
232
+ if ('default' in b) {
233
+ const id = String(b.default ?? '').trim();
234
+ if (id && !parseModel(id)) throw bad('A model is written "<server>/<model>", say "ollama/qwen3-coder:30b"');
235
+ next.default = id || null;
236
+ }
237
+ if ('harness' in b) {
238
+ const h = String(b.harness ?? '').trim().toLowerCase();
239
+ if (h && !HARNESSES.includes(h)) throw bad(`The harness is one of ${HARNESSES.join(', ')}`);
240
+ next.harness = h || null;
241
+ }
242
+ if (b.add) {
243
+ const name = String(b.add.name ?? '').trim().toLowerCase();
244
+ const url = cleanUrl(b.add.url);
245
+ if (!SERVER_ID.test(name)) throw bad('A server\'s name is lowercase letters, digits and "-", starting with a letter');
246
+ if (!url) throw bad('The address is an http or https one, say http://127.0.0.1:8081');
247
+ next.servers[name] = url;
248
+ }
249
+ if (b.remove) {
250
+ const name = String(b.remove).trim().toLowerCase();
251
+ if (!localSettings({ localModels: next }).servers[name]) throw bad(`No server named "${name}"`);
252
+ // One of the usual addresses is switched off; one you added is forgotten.
253
+ if (LOCAL_PRESETS[name]) next.servers[name] = false;
254
+ else delete next.servers[name];
255
+ }
256
+ this.config.localModels = next;
257
+ this.save({ localModels: next });
258
+ this.at = 0;
259
+ }
260
+ }
package/src/manager.js CHANGED
@@ -3,12 +3,13 @@ import { EventEmitter } from 'node:events';
3
3
  import { ownStatusLine } from './trust.js';
4
4
  import { statusLineScript, usageFile } from './usage.js';
5
5
  import { leanScript } from './lean.js';
6
+ import { laneEnv, laneOf, lanePrompt, laneSettings, nextLane } from './lanes.js';
6
7
  import fs from 'node:fs';
7
8
  import os from 'node:os';
8
9
  import path from 'node:path';
9
10
  import pty from 'node-pty';
10
- import { expandHome, paths } from './config.js';
11
- import { DEFAULT_ENGINE, ENGINES, engineOf, installed, notInstalled } from './engines/index.js';
11
+ import { PORT, expandHome, paths } from './config.js';
12
+ import { DEFAULT_ENGINE, ENGINES, engineOf, installed, localEngineId, notInstalled } from './engines/index.js';
12
13
  import {
13
14
  DOC_KINDS,
14
15
  diagramsOnly,
@@ -389,6 +390,8 @@ export class AgentManager extends EventEmitter {
389
390
  priority: agent.priority ?? 2,
390
391
  activeAt: this.activeAt(agent, rt),
391
392
  projectInfo: this.projectInfo(agent),
393
+ // Its ports and name ending (lanes.js), once it has been started with lanes on.
394
+ laneInfo: laneSettings(this.config).enabled ? laneOf(agent.lane, laneSettings(this.config)) : null,
392
395
  usage,
393
396
  // Claude Code's own cost figure from the transcripts (absent until it records one).
394
397
  costUsd: costs.length ? costs.reduce((a, b) => a + b, 0) : null,
@@ -650,8 +653,12 @@ export class AgentManager extends EventEmitter {
650
653
  }) {
651
654
  intent = (intent ?? '').trim();
652
655
  const staged = stagedFiles(attachments);
656
+ // "local": a model served on this computer, in the harness chosen for those.
657
+ if (engine === 'local') engine = localEngineId(this.config);
653
658
  const engineDef = engineOf(engine || this.config.engine || DEFAULT_ENGINE);
654
659
  const engineId = engineDef.id;
660
+ // Some engines need a model, or take only the ones they know (a local model's server and name).
661
+ if (engineDef.checkModel) model = engineDef.checkModel(model, this.config);
655
662
  this.plugins.check('agent.create', {
656
663
  input: { kind, intent, name, repo, dir, worktree, base, permissionMode: permissionMode || this.config.permissionMode || null, model, project, priority, engine: engineId, imported: Boolean(imported) },
657
664
  });
@@ -1450,6 +1457,9 @@ export class AgentManager extends EventEmitter {
1450
1457
  prompts.push(teamPrompt(agent.team.role, dir));
1451
1458
  }
1452
1459
  }
1460
+ // Its own ports and name ending, so what it starts doesn't collide with another agent's.
1461
+ const lane = this.laneFor(agent);
1462
+ if (lane && task) prompts.push(lanePrompt(lane, laneSettings(this.config)));
1453
1463
  // Appended system prompts last only for the process they're passed to, so they go on every launch.
1454
1464
  // Files attached for it (at creation or in its terminal): readable without a permission prompt.
1455
1465
  const uploads = path.join(paths.uploads, agent.id);
@@ -1808,8 +1818,26 @@ export class AgentManager extends EventEmitter {
1808
1818
  });
1809
1819
  }
1810
1820
 
1821
+ /**
1822
+ * The agent's lane: ports and a name ending no other agent has (lanes.js). Given the first time
1823
+ * it is asked for and kept until the agent is deleted. Null with lanes off, or in a container,
1824
+ * which has its own ports.
1825
+ */
1826
+ laneFor(agent) {
1827
+ const settings = laneSettings(this.config);
1828
+ if (!agent || !settings.enabled || agent.isolation === 'container' || agent.machine) return null;
1829
+ if (!laneOf(agent.lane, settings)) {
1830
+ const n = nextLane(this.store.list().map((a) => a.lane).filter(Boolean), settings, [PORT]);
1831
+ if (!n || !this.store.patch(agent.id, { lane: n })) return null;
1832
+ agent.lane = n;
1833
+ }
1834
+ return laneOf(agent.lane, settings);
1835
+ }
1836
+
1811
1837
  childEnv(agent) {
1812
- const env = { ...process.env, ...(agent ? { AGENTMGR_AGENT_ID: agent.id, AGENTMGR_LEAN_DIR: leanDir(agent.id) } : {}), TERM: 'xterm-256color', COLORTERM: 'truecolor', AGENTMGR_TERMINAL: '1', AGENTMGR_USAGE_FILE: usageFile(), AGENTMGR_USER_STATUSLINE: ownStatusLine() };
1838
+ // An engine's own variables (a local model's Codex home, say).
1839
+ const own = agent && Object.hasOwn(ENGINES, agent.engine ?? '') ? ENGINES[agent.engine].env?.(this.config) : null;
1840
+ const env = { ...process.env, ...own, ...(agent ? { AGENTMGR_AGENT_ID: agent.id, AGENTMGR_LEAN_DIR: leanDir(agent.id), ...laneEnv(this.laneFor(agent), laneSettings(this.config)) } : {}), TERM: 'xterm-256color', COLORTERM: 'truecolor', AGENTMGR_TERMINAL: '1', AGENTMGR_USAGE_FILE: usageFile(), AGENTMGR_USER_STATUSLINE: ownStatusLine() };
1813
1841
  for (const key of STRIP_ENV) delete env[key];
1814
1842
  return env;
1815
1843
  }
@@ -1889,7 +1917,10 @@ export class AgentManager extends EventEmitter {
1889
1917
  if (mode && !modes.includes(mode)) throw bad(`${engineOf(agent).label} has no "${mode}" mode (use ${modes.join(', ')})`);
1890
1918
  allowed.permissionMode = mode;
1891
1919
  }
1892
- if ('model' in fields) allowed.model = String(fields.model ?? '').trim() || null;
1920
+ if ('model' in fields) {
1921
+ allowed.model = String(fields.model ?? '').trim() || null;
1922
+ if (engineOf(agent).checkModel) allowed.model = engineOf(agent).checkModel(allowed.model, this.config);
1923
+ }
1893
1924
  // Keep: clean up never closes or deletes it.
1894
1925
  if ('keep' in fields) allowed.keep = Boolean(fields.keep);
1895
1926
  if ('budgetUsd' in fields) {
package/src/races.js CHANGED
@@ -5,6 +5,7 @@ import crypto from 'node:crypto';
5
5
  import { spawn } from 'node:child_process';
6
6
  import { EventEmitter } from 'node:events';
7
7
  import * as git from './git.js';
8
+ import { cleanRuns, repeatRuns } from './eval.js';
8
9
 
9
10
  const err = (status, message) => Object.assign(new Error(message), { status });
10
11
  const now = () => new Date().toISOString();
@@ -112,9 +113,10 @@ export class Races extends EventEmitter {
112
113
  }
113
114
 
114
115
  /** Run the race's test command in every attempt's worktree (two at a time). */
115
- async runTests(id, { command } = {}) {
116
+ async runTests(id, { command, runs } = {}) {
116
117
  const race = this.get(id);
117
118
  if (command !== undefined) race.testCommand = command.trim() || null;
119
+ if (runs !== undefined) race.testRuns = cleanRuns(runs);
118
120
  if (!race.testCommand) throw err(400, 'Set a test command first');
119
121
  const queue = race.members.map((m) => this.manager.store.get(m)).filter((a) => a?.workdir);
120
122
  for (const a of queue) race.tests[a.id] = { status: 'queued', at: now() };
@@ -126,9 +128,22 @@ export class Races extends EventEmitter {
126
128
  return this.view(id);
127
129
  }
128
130
 
129
- runOne(race, agent) {
131
+ /**
132
+ * The test command in one attempt's folder, as many times as the race asks (eval.js: one run
133
+ * that fails is run once more). Passed in some runs and failed in others is "flaky".
134
+ */
135
+ async runOne(race, agent) {
130
136
  race.tests[agent.id] = { status: 'running', at: now() };
131
137
  this.save(race);
138
+ const started = Date.now();
139
+ const all = await repeatRuns(() => this.runOnce(race, agent), race.testRuns);
140
+ const { exitCode, output, at, status } = all.shown;
141
+ race.tests[agent.id] = { status: status === 'error' ? 'error' : all.passed ? 'passed' : all.flaky ? 'flaky' : 'failed', exitCode, runs: all.runs, passes: all.passes, seconds: Math.round((Date.now() - started) / 1000), output, at };
142
+ this.save(race);
143
+ }
144
+
145
+ /** One run: { status, exitCode, output, at, passed, timedOut }. */
146
+ runOnce(race, agent) {
132
147
  return new Promise((resolve) => {
133
148
  const child = spawn(process.env.SHELL || '/bin/sh', ['-lc', race.testCommand], { cwd: agent.workdir, env: this.manager.childEnv(agent), detached: true });
134
149
  this.running.set(`${race.id}:${agent.id}`, child);
@@ -136,8 +151,9 @@ export class Races extends EventEmitter {
136
151
  const keep = (d) => (out = (out + d).slice(-6000));
137
152
  child.stdout.on('data', keep);
138
153
  child.stderr.on('data', keep);
139
- const started = Date.now();
154
+ let timedOut = false;
140
155
  const timer = setTimeout(() => {
156
+ timedOut = true;
141
157
  try {
142
158
  process.kill(-child.pid, 'SIGKILL');
143
159
  } catch {}
@@ -145,15 +161,8 @@ export class Races extends EventEmitter {
145
161
  const finish = (code, error) => {
146
162
  clearTimeout(timer);
147
163
  this.running.delete(`${race.id}:${agent.id}`);
148
- race.tests[agent.id] = {
149
- status: error ? 'error' : code === 0 ? 'passed' : 'failed',
150
- exitCode: code,
151
- seconds: Math.round((Date.now() - started) / 1000),
152
- output: (error ? `${error}\n` : '') + out.slice(-4000),
153
- at: now(),
154
- };
155
- this.save(race);
156
- resolve();
164
+ // A command that could not be started is not run again.
165
+ resolve({ status: error ? 'error' : code === 0 ? 'passed' : 'failed', exitCode: code, output: (error ? `${error}\n` : '') + out.slice(-4000), at: now(), passed: !error && code === 0, timedOut: timedOut || Boolean(error) });
157
166
  };
158
167
  child.on('error', (e) => finish(null, e.message));
159
168
  child.on('close', (code) => finish(code));
package/src/server.js CHANGED
@@ -31,7 +31,8 @@ import { Studio } from './studio.js';
31
31
  import { Memory } from './memory.js';
32
32
  import { doctor } from './doctor.js';
33
33
  import { Triggers, tokenMatches } from './triggers.js';
34
- import { listEngines, registerAcpEngines, registerEngine } from './engines/index.js';
34
+ import { installed, listEngines, localEngineId, registerAcpEngines, registerEngine } from './engines/index.js';
35
+ import { LOCAL_ENGINES } from './engines/local.js';
35
36
  import { Plugins, pluginSpecs } from './plugins.js';
36
37
  import { HubLink, linkUrls } from './hublink.js';
37
38
  import { Notifier, isWorkflowUrl, loadNotify, publicNotify, saveNotify, sendSlack } from './notify.js';
@@ -56,6 +57,8 @@ import { Runbooks } from './runbooks.js';
56
57
  import { reaStatus } from './rea.js';
57
58
  import { EngineUsage, codexWindows } from './usage.js';
58
59
  import { leanSettings, leanStats, leanSweep } from './lean.js';
60
+ import { laneOf, laneSettings } from './lanes.js';
61
+ import { LocalModels } from './localmodels.js';
59
62
  import { Skills } from './skills.js';
60
63
  import { Milestones } from './milestones.js';
61
64
  import { Decisions } from './decisions.js';
@@ -100,7 +103,7 @@ function isAllowedOrigin(origin, port) {
100
103
  const PUBLIC_REMOTE_API = new Set(['POST /api/login', 'GET /api/session']);
101
104
  // Updates are not here: a signed-in device (a phone) can install the newest release too. It only
102
105
  // ever installs an official release from where this copy came from (git tag or npm) and restarts.
103
- const LOCAL_ONLY_API = /^\/api\/(remote(\/|$)|notify(\/|$)|hub(\/|$)|triggers(\/|$)|service$|jira(\/check)?$|isolation\/|editors$|agentkit\/connect$|agents\/[\w-]+\/open-in$|shutdown$)/;
106
+ const LOCAL_ONLY_API = /^\/api\/(remote(\/|$)|notify(\/|$)|hub(\/|$)|triggers(\/|$)|service$|jira(\/check)?$|isolation\/|editors$|agentkit\/connect$|agents\/[\w-]+\/open-in$|local-models\/settings$|shutdown$)/;
104
107
  const HOOK_PATH = '/api/hooks/agents';
105
108
  const REPORT_PATH = '/api/agentkit/report';
106
109
  const NO_REPO_KINDS = new Set(['general', 'assistant']);
@@ -114,6 +117,8 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
114
117
  // ACP agents (Gemini CLI, OpenCode, Goose, … and config's "acp") become engines.
115
118
  registerAcpEngines(config);
116
119
  const manager = new AgentManager({ store, config, plugins });
120
+ const localModels = new LocalModels({ config, save: saveConfig });
121
+ localModels.view().catch(() => {});
117
122
  const backlog = new Backlog({ manager, store, config });
118
123
  const proposed = new ProposedIssues({ store, manager });
119
124
  const myActions = new MyActions({ store, manager });
@@ -331,7 +336,8 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
331
336
  const usage = new EngineUsage({
332
337
  store,
333
338
  config,
334
- engines: () => listEngines(config),
339
+ // Models served on this computer have no plan and no limits to show.
340
+ engines: () => listEngines(config).filter((e) => !e.local),
335
341
  probe: () => manager.readUsage(),
336
342
  onChange: () => pushUsage(),
337
343
  notify: async (text, plain) => {
@@ -423,7 +429,8 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
423
429
  // "Open on this machine" links from the hub point at remote access, when it's on.
424
430
  // OS: this computer and its load right now, and what each open session takes (system.js).
425
431
  const system = new System({
426
- agents: () => store.list().map((x) => ({ id: x.id, name: x.name, pid: x.pid })),
432
+ agents: () => store.list().map((x) => ({ id: x.id, name: x.name, pid: x.pid, lane: laneSettings(config).enabled ? laneOf(x.lane, laneSettings(config)) : null })),
433
+ lanes: () => laneSettings(config),
427
434
  folders: () => [['Home', os.homedir()], ['Agents and data', paths.home]],
428
435
  version: pkgVersion,
429
436
  });
@@ -503,7 +510,10 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
503
510
  // `closing` while shutting down: it still answers until every agent is closed, then exits.
504
511
  api.get('/health', wrap(() => ({ ok: true, pid: process.pid, home: paths.home, claudeBin: config.claudeBin, closing })));
505
512
  api.get('/agents', wrap(() => manager.list()));
506
- api.get('/engines', wrap(() => listEngines(config)));
513
+ api.get('/engines', wrap(async () => {
514
+ await localModels.view(); // the "Local model" engine is offered while a server runs here
515
+ return listEngines(config);
516
+ }));
507
517
  api.post(
508
518
  '/agents',
509
519
  wrap((req) => {
@@ -1050,7 +1060,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1050
1060
  evals.verify(a.id).catch((e) => console.log(`[agentmgr] eval: ${e.message}`));
1051
1061
  return { started: true };
1052
1062
  }));
1053
- api.put('/agents/:id/eval/command', wrap((req) => evals.setTestCommand(req.params.id, req.body?.command)));
1063
+ api.put('/agents/:id/eval/command', wrap((req) => evals.setTestCommand(req.params.id, req.body?.command, req.body?.runs)));
1054
1064
  api.post('/agents/:id/eval/gaps', wrap((req) => evals.closeGaps(req.params.id)));
1055
1065
  api.post('/agents/:id/eval/seen', wrap((req) => evals.seen(req.params.id, req.body?.seen !== false)));
1056
1066
  api.post('/agents/:id/eval/post', wrap((req) => review.postEval(req.params.id, evals.view(manager.mustGet(req.params.id).id)?.markdown)));
@@ -1236,6 +1246,42 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1236
1246
  api.put('/calendar', wrap((req) => calendar.set(req.body ?? {}, saveConfig)));
1237
1247
  // AI News: the entries, a refresh now (answers at once; the page hears when it's done), and "seen".
1238
1248
  api.get('/system', wrap(() => system.view()));
1249
+ // Lanes: every agent's own ports and name ending (lanes.js), and the settings for them. A change
1250
+ // reaches a session the next time it starts.
1251
+ const lanesView = () => {
1252
+ const settings = laneSettings(config);
1253
+ return { ...settings, agents: store.list().filter((a) => laneOf(a.lane, settings)).map((a) => ({ id: a.id, name: a.name, running: Boolean(a.pid), ...laneOf(a.lane, settings) })).sort((x, y) => x.n - y.n) };
1254
+ };
1255
+ api.get('/lanes', wrap(() => lanesView()));
1256
+ api.put('/lanes', wrap((req) => {
1257
+ const b = req.body ?? {};
1258
+ const on = (v) => v === true || v === 'on';
1259
+ const next = { ...config.lanes };
1260
+ if ('enabled' in b) next.enabled = on(b.enabled);
1261
+ if ('port' in b) next.port = on(b.port);
1262
+ for (const k of ['base', 'size']) {
1263
+ if (!(k in b)) continue;
1264
+ if (laneSettings({ lanes: { [k]: b[k] } })[k] !== Number(b[k])) throw fail(400, k === 'base' ? 'The first port is a number from 1024 to 32667' : 'A lane has 1 to 100 ports');
1265
+ next[k] = Number(b[k]);
1266
+ }
1267
+ config.lanes = next;
1268
+ saveConfig({ lanes: next });
1269
+ for (const a of store.list()) manager.changed?.(a);
1270
+ return lanesView();
1271
+ }));
1272
+ // Local models: the servers running on this computer and their models (localmodels.js). The
1273
+ // settings are changed from this computer only: an address added here is one the daemon asks.
1274
+ // The harnesses that can drive a local model, with the one "local" stands for.
1275
+ const localView = async (opts) => {
1276
+ const v = await localModels.view(opts);
1277
+ const engines = listEngines(config);
1278
+ return { ...v, harness: LOCAL_ENGINES.find((e) => e.id === localEngineId(config)).harness, harnesses: LOCAL_ENGINES.map((e) => ({ id: e.harness, engine: e.id, label: e.label.replace(/^Local · /, ''), installed: installed(e, config), offered: Boolean(engines.find((x) => x.id === e.id)?.installed) })) };
1279
+ };
1280
+ api.get('/local-models', wrap((req) => localView({ fresh: req.query.fresh === '1' })));
1281
+ api.put('/local-models/settings', wrap((req) => {
1282
+ localModels.change(req.body ?? {});
1283
+ return localView({ fresh: true });
1284
+ }));
1239
1285
  api.get('/news', wrap(() => news.view()));
1240
1286
  api.post('/news/refresh', wrap((req) => {
1241
1287
  news.refresh({ search: req.body?.search === true ? true : null }).catch(() => {});
package/src/system.js CHANGED
@@ -7,6 +7,7 @@ import { execFile } from 'node:child_process';
7
7
  import fs from 'node:fs';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
10
+ import { listeners, portsBySession } from './lanes.js';
10
11
 
11
12
  const SAMPLE_MS = 5000;
12
13
  const KEEP = 120; // ten minutes of samples
@@ -157,9 +158,12 @@ async function disks(folders) {
157
158
  }
158
159
 
159
160
  export class System {
160
- /** `agents()` lists the agent records (id, name, pid of its open session); `folders()` the [label, dir] pairs whose disks to show. */
161
- constructor({ agents = () => [], folders = () => [['Home', os.homedir()]], version = null, timer = true } = {}) {
162
- Object.assign(this, { agents, folders, version });
161
+ /**
162
+ * `agents()` lists the agent records (id, name, pid of its open session, its lane or null);
163
+ * `folders()` the [label, dir] pairs whose disks to show; `lanes()` the lane settings (lanes.js).
164
+ */
165
+ constructor({ agents = () => [], folders = () => [['Home', os.homedir()]], lanes = () => null, version = null, timer = true } = {}) {
166
+ Object.assign(this, { agents, folders, lanes, version });
163
167
  this.history = [];
164
168
  this.last = cpuTimes();
165
169
  this.cpuPercent = 0;
@@ -187,16 +191,20 @@ export class System {
187
191
  async view() {
188
192
  const cpus = os.cpus();
189
193
  const cores = cpus.length || 1;
190
- const [name, mem, disk, ps] = await Promise.all([(this.osName ??= osName()), memory(), disks(this.folders()), run('ps', ['-Ao', 'pid=,ppid=,pcpu=,rss=,comm='])]);
194
+ const [name, mem, disk, ps, listening] = await Promise.all([(this.osName ??= osName()), memory(), disks(this.folders()), run('ps', ['-Ao', 'pid=,ppid=,pcpu=,rss=,comm=']), listeners()]);
191
195
  const procs = parsePs(ps);
192
196
  // The memory in the history is the same measure as the one shown (what can't be freed at once).
193
197
  if (this.history.length) this.history[this.history.length - 1].mem = mem.percent;
194
198
  const load = os.loadavg().map((n) => Math.round(n * 100) / 100);
195
- const sessions = this.agents()
196
- .filter((a) => a.pid)
197
- .map((a) => ({ id: a.id, name: a.name, pid: a.pid, ...(treeUsage(procs, a.pid) ?? { cpu: 0, mem: 0, count: 0 }) }))
198
- .filter((a) => a.count)
199
- .sort((x, y) => y.cpu - x.cpu || y.mem - x.mem);
199
+ // With what each listens on, and whether that is inside its own lane of ports.
200
+ const sessions = portsBySession(
201
+ this.agents()
202
+ .filter((a) => a.pid)
203
+ .map((a) => ({ id: a.id, name: a.name, pid: a.pid, lane: a.lane ?? null, ...(treeUsage(procs, a.pid) ?? { cpu: 0, mem: 0, count: 0 }) }))
204
+ .filter((a) => a.count),
205
+ procs,
206
+ listening,
207
+ ).sort((x, y) => y.cpu - x.cpu || y.mem - x.mem);
200
208
  const self = treeUsage(procs, process.pid);
201
209
  const nets = Object.entries(os.networkInterfaces())
202
210
  .flatMap(([nic, list]) => (list ?? []).filter((n) => !n.internal && n.family === 'IPv4').map((n) => ({ nic, address: n.address })));
@@ -232,6 +240,7 @@ export class System {
232
240
  count: procs.length,
233
241
  top: [...procs].sort((x, y) => y.cpu - x.cpu || y.mem - x.mem).slice(0, 12).map(({ pid, cpu, mem: m, name: n, command }) => ({ pid, cpu, mem: m, name: n, command })),
234
242
  },
243
+ lanes: this.lanes(),
235
244
  history: this.history,
236
245
  sampleSeconds: SAMPLE_MS / 1000,
237
246
  };