@openagents-org/agent-launcher 0.2.210 → 0.2.211

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,266 @@
1
+ /**
2
+ * Pure helpers for MiMoCodeAdapter: which provider and model a run goes to,
3
+ * the per-run config handed to the CLI, the process-tree walk Stop needs, and
4
+ * reading the CLI's own error output. No I/O here — the adapter supplies the
5
+ * environment, the process table and the CLI's output.
6
+ *
7
+ * Verified against MiMo Code 0.1.14 and 0.1.15.
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ /** MiMo's own OpenAI-compatible API — where a form key goes when no base URL is given. */
13
+ const MIMO_DEFAULT_BASE_URL = 'https://api.xiaomimimo.com/v1';
14
+
15
+ /**
16
+ * MiMo Code's built-in provider for MiMo's API. Routing a MiMo key through it,
17
+ * rather than through a provider we declare, keeps what the CLI's catalog knows
18
+ * about each model: its context window, and that its reasoning has to be sent
19
+ * back between tool calls.
20
+ */
21
+ const XIAOMI_PROVIDER = 'xiaomi';
22
+
23
+ /** The provider declared for any other OpenAI-compatible endpoint. */
24
+ const CUSTOM_PROVIDER = 'openagents';
25
+
26
+ /** Name of the workspace MCP server; MiMo names its tools `<server>_<tool>`. */
27
+ const MCP_SERVER_NAME = 'openagents-workspace';
28
+
29
+ /** True for MiMo's API and its Token Plan endpoints (token-plan-<region>.xiaomimimo.com). */
30
+ function isMimoHost(baseUrl) {
31
+ let host = '';
32
+ try { host = new URL(String(baseUrl || '').trim()).hostname.toLowerCase(); } catch { return false; }
33
+ return host === 'xiaomimimo.com' || host.endsWith('.xiaomimimo.com');
34
+ }
35
+
36
+ /**
37
+ * Where one run goes.
38
+ *
39
+ * With an API key in the agent's configuration (LLM_API_KEY) the run uses that
40
+ * key and nothing else: the base URL defaults to MiMo's API, a MiMo endpoint
41
+ * runs on the built-in `xiaomi` provider and any other on a provider declared
42
+ * for this run. The model id is sent upstream as written — a gateway's
43
+ * `vendor/model` ids included — except that a `xiaomi/` prefix on a MiMo
44
+ * endpoint only repeats the provider and is dropped.
45
+ *
46
+ * Without a key the run is on the Xiaomi-account sign-in (`signIn`, the key
47
+ * and base URL MiMo stored for it, read by the adapter), declared for the run
48
+ * exactly as a key is — so nothing the user configured in MiMo, and no
49
+ * XIAOMI_API_KEY, can stand in for it. A model written `provider/model` with
50
+ * another provider names one the user set up in MiMo Code (`mode: 'own'`) and
51
+ * is taken as given.
52
+ *
53
+ * On MiMo's endpoints a blank model is `fallbackModel`, which the adapter asks
54
+ * the CLI for. There is no fixed default: MiMo drops every model its catalog
55
+ * marks deprecated, and the catalog moves — it marked the v2.5 line deprecated,
56
+ * after which `mimo-v2.5-pro` was "Model not found".
57
+ *
58
+ * The workspace's model choice, when there is one, replaces LLM_MODEL.
59
+ */
60
+ function resolveMimoRoute(env = {}, workspaceModel = null, { signIn = null, fallbackModel = '' } = {}) {
61
+ const val = (k) => (env[k] == null ? '' : String(env[k])).trim();
62
+ const apiKey = val('LLM_API_KEY');
63
+ const requested = String(workspaceModel || '').trim() || val('LLM_MODEL');
64
+ const fallback = String(fallbackModel || '').trim();
65
+ const bare = (m) => (m.toLowerCase().startsWith(`${XIAOMI_PROVIDER}/`) ? m.slice(XIAOMI_PROVIDER.length + 1) : m);
66
+ const route = (mode, providerId, model, baseURL, key) => ({
67
+ mode, providerId, model, modelRef: model ? `${providerId}/${model}` : '', baseURL, apiKey: key,
68
+ });
69
+
70
+ if (apiKey) {
71
+ const baseURL = val('LLM_BASE_URL') || MIMO_DEFAULT_BASE_URL;
72
+ if (!isMimoHost(baseURL)) return route('key', CUSTOM_PROVIDER, requested, baseURL, apiKey);
73
+ return route('key', XIAOMI_PROVIDER, bare(requested) || bare(fallback), baseURL, apiKey);
74
+ }
75
+
76
+ const slash = requested.indexOf('/');
77
+ if (slash > 0 && requested.slice(0, slash).toLowerCase() !== XIAOMI_PROVIDER) {
78
+ return route('own', requested.slice(0, slash), requested.slice(slash + 1), '', '');
79
+ }
80
+ const key = signIn && signIn.key ? String(signIn.key) : '';
81
+ const baseURL = key ? (String(signIn.baseURL || '').trim() || MIMO_DEFAULT_BASE_URL) : '';
82
+ return route('signin', XIAOMI_PROVIDER, bare(requested) || bare(fallback), baseURL, key);
83
+ }
84
+
85
+ /**
86
+ * `mimo models xiaomi`: `xiaomi/<model> — window …` per line, deprecated
87
+ * models already left out. Returns the bare ids.
88
+ */
89
+ function parseMimoModelList(out) {
90
+ const ids = [];
91
+ for (const line of String(out || '').split(/\r?\n/)) {
92
+ const m = line.trim().match(/^xiaomi\/([\w.-]+)(?:\s|$)/);
93
+ if (m && !ids.includes(m[1])) ids.push(m[1]);
94
+ }
95
+ return ids;
96
+ }
97
+
98
+ /** The first plain `-pro` model, else the first — the launcher preselects the same. */
99
+ function pickMimoModel(ids) {
100
+ return (ids || []).find((id) => /-pro$/.test(id)) || (ids || [])[0] || '';
101
+ }
102
+
103
+ /**
104
+ * The config one run is started with, passed as MIMOCODE_CONFIG_CONTENT. MiMo
105
+ * loads it after the user's global and project config, so what it sets wins;
106
+ * MiMo also keeps that variable out of the environment of the commands its
107
+ * tools run, which is why the key travels here and not as an env var.
108
+ *
109
+ * Routing is pinned to the one provider and model the route names. Without
110
+ * that the user's own MiMo config reroutes parts of the run, under the user's
111
+ * key for another provider: a `small_model` there received every session's
112
+ * first message for titling, and a subagent ran on the user's
113
+ * `agent.general.model`. Providers MiMo picks up from the environment
114
+ * (DASHSCOPE_API_KEY, XIAOMI_API_KEY, …) or its auth.json would likewise stay
115
+ * available to a model the agent names itself — the subagent tool takes a
116
+ * `provider/model` or a model group. Arrays in MiMo's config replace rather
117
+ * than merge, so the provider lists are exactly ours; anything still naming
118
+ * another provider fails instead of leaving.
119
+ *
120
+ * `instructions`, unlike other arrays, MiMo concatenates with the user's own —
121
+ * the workspace briefing is added to them, not swapped in for them.
122
+ */
123
+ function buildMimoRunConfig(route, { mcp = null, instructions = [] } = {}) {
124
+ const ref = route.modelRef;
125
+ const config = { enabled_providers: [route.providerId], disabled_providers: [] };
126
+ // With no model (the CLI could not be asked for one) the pick is MiMo's; the
127
+ // provider pin alone still keeps every request on it.
128
+ if (ref) {
129
+ Object.assign(config, {
130
+ model: ref,
131
+ small_model: ref,
132
+ model_groups: { lite: ref, standard: ref, ultra: ref },
133
+ agent: { general: { model: ref }, explore: { model: ref } },
134
+ });
135
+ }
136
+
137
+ // A key, or the sign-in's key, is declared for the run; MiMo's own
138
+ // credentials are kept out of it (MIMOCODE_AUTH_CONTENT, set by the adapter).
139
+ if (route.apiKey) {
140
+ // `id` is set explicitly: a model entry of the same name in the user's own
141
+ // provider config could otherwise rename what is sent upstream. `headers`
142
+ // is cleared for the same reason — objects merge, so headers the user set
143
+ // on this provider were sent with every request, and an `Authorization`
144
+ // among them replaced the agent's key.
145
+ //
146
+ // A model picked on MiMo's endpoint is marked `beta`: MiMo drops a model
147
+ // its catalog calls deprecated even when the run declares it, and the API
148
+ // the key belongs to still serves those (the picker lists them from it).
149
+ // Choosing one is the user's call. (`active` is not a status MiMo accepts.)
150
+ const xiaomi = route.providerId === XIAOMI_PROVIDER;
151
+ const models = route.model
152
+ ? { [route.model]: { id: route.model, name: route.model, ...(xiaomi ? { status: 'beta' } : {}) } }
153
+ : undefined;
154
+ const options = { baseURL: route.baseURL, apiKey: route.apiKey, headers: null };
155
+ config.provider = {
156
+ [route.providerId]: xiaomi
157
+ ? { options, ...(models ? { models } : {}) }
158
+ : { npm: '@ai-sdk/openai-compatible', name: 'OpenAgents', options, models },
159
+ };
160
+ }
161
+
162
+ if (mcp && mcp.command) {
163
+ config.mcp = {
164
+ [MCP_SERVER_NAME]: {
165
+ type: 'local',
166
+ command: [mcp.command, ...(mcp.args || [])],
167
+ environment: mcp.env || {},
168
+ },
169
+ };
170
+ }
171
+
172
+ const files = (instructions || []).filter(Boolean);
173
+ if (files.length) config.instructions = files;
174
+ return config;
175
+ }
176
+
177
+ /**
178
+ * The CLI's `run` arguments. A new session gets a title of ours: without one
179
+ * MiMo asks the model to write it, which is a second request carrying the
180
+ * user's first message. Plan mode is MiMo's own `plan` agent, whose edit ban
181
+ * the permission bypass does not lift.
182
+ */
183
+ function buildMimoRunArgs({ runCwd, model, sessionId = null, title = '', plan = false } = {}) {
184
+ const args = ['run', '--format', 'json', '--dangerously-skip-permissions', '--dir', runCwd];
185
+ if (model) args.push('--model', model);
186
+ if (plan) args.push('--agent', 'plan');
187
+ if (sessionId) args.push('--session', sessionId);
188
+ else if (title) args.push('--title', title);
189
+ return args;
190
+ }
191
+
192
+ /**
193
+ * Every descendant of `rootPid` in a process table of { pid, ppid, pgid } rows,
194
+ * nearest first. MiMo runs each shell command in its own session, so these are
195
+ * not in the CLI's process group, and once the CLI is gone they are reparented
196
+ * — the table has to be read while it is still alive.
197
+ */
198
+ function descendantsOf(rows, rootPid) {
199
+ const children = new Map();
200
+ for (const r of rows || []) {
201
+ if (!r || !Number.isInteger(r.pid) || r.pid === r.ppid) continue;
202
+ if (!children.has(r.ppid)) children.set(r.ppid, []);
203
+ children.get(r.ppid).push(r);
204
+ }
205
+ const out = [];
206
+ const seen = new Set([rootPid]);
207
+ const queue = [rootPid];
208
+ while (queue.length) {
209
+ const pid = queue.shift();
210
+ for (const c of children.get(pid) || []) {
211
+ if (seen.has(c.pid)) continue;
212
+ seen.add(c.pid);
213
+ out.push(c);
214
+ queue.push(c.pid);
215
+ }
216
+ }
217
+ return out;
218
+ }
219
+
220
+ /** Parse `ps -A -o pid=,ppid=,pgid=` output. */
221
+ function parseProcessTable(text) {
222
+ const rows = [];
223
+ for (const line of String(text || '').split('\n')) {
224
+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)$/);
225
+ if (m) rows.push({ pid: Number(m[1]), ppid: Number(m[2]), pgid: Number(m[3]) });
226
+ }
227
+ return rows;
228
+ }
229
+
230
+ /**
231
+ * The line that matters in the CLI's stderr. A failure that is not an API
232
+ * error (no credential, an unknown session) prints a chunk of the CLI's bundled
233
+ * source and a stack trace, then exits 0; classifying that source text would
234
+ * find "network" or "timeout" in someone's variable names, so only the error
235
+ * line itself is read: `error: <message>`, or a named error's `message: "…"`.
236
+ */
237
+ function mimoErrorLine(stderr) {
238
+ const text = String(stderr || '');
239
+ const plain = text.match(/^\s*error:\s*(.+)$/gm);
240
+ if (plain) return plain[plain.length - 1].replace(/^\s*error:\s*/, '').trim();
241
+ const named = text.match(/^([A-Z][A-Za-z]*Error):[^\n]*\n(?:\s*data:\s*\{\s*\n)?\s*message:\s*"([^"\n]*)"/m);
242
+ if (named) return `${named[1]}: ${named[2]}`;
243
+ return '';
244
+ }
245
+
246
+ /** True when the CLI refused `--session` because it has no such session. */
247
+ function isMissingSession(stderr) {
248
+ return /Session not found/i.test(String(stderr || ''));
249
+ }
250
+
251
+ module.exports = {
252
+ MIMO_DEFAULT_BASE_URL,
253
+ XIAOMI_PROVIDER,
254
+ CUSTOM_PROVIDER,
255
+ MCP_SERVER_NAME,
256
+ isMimoHost,
257
+ resolveMimoRoute,
258
+ parseMimoModelList,
259
+ pickMimoModel,
260
+ buildMimoRunConfig,
261
+ buildMimoRunArgs,
262
+ descendantsOf,
263
+ parseProcessTable,
264
+ mimoErrorLine,
265
+ isMissingSession,
266
+ };