@openagents-org/agent-launcher 0.2.210 → 0.2.212

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,150 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Workspace API client for DeepSeek Harness runs on Windows.
4
+ *
5
+ * dsh's Windows sandbox (`workspace-write`, the default) runs shell commands
6
+ * under a restricted token that has no Schannel credentials, so `curl.exe` and
7
+ * `Invoke-WebRequest` both fail every HTTPS request with SEC_E_NO_CREDENTIALS
8
+ * — on dsh 0.2.1-rc.2 and rc.5 alike. Node's own TLS stack is unaffected, so the
9
+ * task file points the agent at this script instead of the curl recipes every
10
+ * other adapter uses.
11
+ *
12
+ * Standalone on purpose: it runs inside the sandbox as `node <this file>`, so it
13
+ * requires nothing but Node built-ins. The token, endpoint, workspace and agent
14
+ * name come from the child environment (see DeepSeekAdapter._buildSubprocessEnv);
15
+ * none of them is ever passed on the command line.
16
+ *
17
+ * node deepseek-workspace-api.js GET "/v1/files?network=<id>"
18
+ * '<json>' | node deepseek-workspace-api.js POST /v1/events
19
+ * node deepseek-workspace-api.js POST /v1/events --body-file body.json
20
+ * node deepseek-workspace-api.js upload <file> --channel <name> [--type <mime>]
21
+ * node deepseek-workspace-api.js download <file-id> <out-path>
22
+ *
23
+ * The body of POST/PUT/PATCH is read from --body-file or stdin. Piping a
24
+ * single-quoted PowerShell string keeps its double quotes intact, which passing
25
+ * JSON as an argument to a native program on Windows PowerShell 5.1 does not.
26
+ */
27
+
28
+ 'use strict';
29
+
30
+ const fs = require('fs');
31
+ const path = require('path');
32
+
33
+ const ENV = {
34
+ token: 'OPENAGENTS_WORKSPACE_AUTH',
35
+ endpoint: 'OPENAGENTS_WORKSPACE_ENDPOINT',
36
+ workspace: 'OPENAGENTS_WORKSPACE_ID',
37
+ agent: 'OPENAGENTS_AGENT_NAME',
38
+ };
39
+
40
+ const MIME = {
41
+ '.md': 'text/markdown', '.txt': 'text/plain', '.html': 'text/html', '.htm': 'text/html',
42
+ '.json': 'application/json', '.csv': 'text/csv', '.pdf': 'application/pdf',
43
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
44
+ '.svg': 'image/svg+xml', '.webp': 'image/webp', '.zip': 'application/zip',
45
+ };
46
+
47
+ function fail(message) {
48
+ process.stderr.write(`workspace-api: ${message}\n`);
49
+ process.exit(2);
50
+ }
51
+
52
+ function takeFlag(args, name) {
53
+ const i = args.indexOf(name);
54
+ if (i === -1) return undefined;
55
+ const value = args[i + 1];
56
+ if (value === undefined) fail(`${name} needs a value`);
57
+ args.splice(i, 2);
58
+ return value;
59
+ }
60
+
61
+ function readStdin() {
62
+ if (process.stdin.isTTY) return Promise.resolve('');
63
+ return new Promise((resolve, reject) => {
64
+ const chunks = [];
65
+ process.stdin.on('data', (c) => chunks.push(c));
66
+ process.stdin.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
67
+ process.stdin.on('error', reject);
68
+ });
69
+ }
70
+
71
+ async function call(method, route, body) {
72
+ const endpoint = (process.env[ENV.endpoint] || '').replace(/\/+$/, '');
73
+ const token = process.env[ENV.token];
74
+ if (!endpoint) fail(`${ENV.endpoint} is not set`);
75
+ if (!token) fail(`${ENV.token} is not set`);
76
+ if (!route.startsWith('/')) fail(`the path must start with "/" (got ${route})`);
77
+
78
+ const headers = { 'X-Workspace-Token': token };
79
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
80
+ const res = await fetch(endpoint + route, { method, headers, body });
81
+ return res;
82
+ }
83
+
84
+ async function printResponse(res) {
85
+ const text = await res.text();
86
+ process.stdout.write(text.endsWith('\n') ? text : text + '\n');
87
+ if (!res.ok) {
88
+ process.stderr.write(`workspace-api: HTTP ${res.status}\n`);
89
+ process.exit(1);
90
+ }
91
+ }
92
+
93
+ async function upload(args) {
94
+ const channel = takeFlag(args, '--channel');
95
+ const type = takeFlag(args, '--type');
96
+ const file = args[0];
97
+ if (!file) fail('usage: upload <file> --channel <name> [--type <mime>]');
98
+ if (!channel) fail('upload needs --channel <name>');
99
+ const workspace = process.env[ENV.workspace];
100
+ if (!workspace) fail(`${ENV.workspace} is not set`);
101
+
102
+ let data;
103
+ try { data = fs.readFileSync(file); } catch (e) { fail(`cannot read ${file}: ${e.message}`); }
104
+ const agent = process.env[ENV.agent];
105
+ const body = JSON.stringify({
106
+ filename: path.basename(file),
107
+ content_base64: data.toString('base64'),
108
+ content_type: type || MIME[path.extname(file).toLowerCase()] || 'application/octet-stream',
109
+ network: workspace,
110
+ channel_name: channel,
111
+ ...(agent ? { source: `openagents:${agent}` } : {}),
112
+ });
113
+ await printResponse(await call('POST', '/v1/files/base64', body));
114
+ }
115
+
116
+ async function download(args) {
117
+ const [id, out] = args;
118
+ if (!id || !out) fail('usage: download <file-id> <out-path>');
119
+ const workspace = process.env[ENV.workspace] || '';
120
+ const res = await call('GET', `/v1/files/${encodeURIComponent(id)}?network=${encodeURIComponent(workspace)}`);
121
+ if (!res.ok) return printResponse(res);
122
+ fs.writeFileSync(out, Buffer.from(await res.arrayBuffer()));
123
+ process.stdout.write(`saved ${out}\n`);
124
+ }
125
+
126
+ async function main() {
127
+ const args = process.argv.slice(2);
128
+ const verb = (args.shift() || '').toLowerCase();
129
+ if (verb === 'upload') return upload(args);
130
+ if (verb === 'download') return download(args);
131
+
132
+ const method = verb.toUpperCase();
133
+ if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
134
+ fail('usage: <GET|POST|PUT|PATCH|DELETE> <path> | upload <file> --channel <name> | download <file-id> <out-path>');
135
+ }
136
+ const bodyFile = takeFlag(args, '--body-file');
137
+ const route = args[0];
138
+ if (!route) fail(`usage: ${method} <path>`);
139
+
140
+ let body;
141
+ if (method !== 'GET' && method !== 'DELETE') {
142
+ body = bodyFile ? fs.readFileSync(bodyFile, 'utf-8') : (await readStdin());
143
+ body = body.replace(/^/, '').trim();
144
+ if (!body) fail(`${method} needs a JSON body on stdin or --body-file`);
145
+ try { JSON.parse(body); } catch (e) { fail(`the body is not valid JSON: ${e.message}`); }
146
+ }
147
+ await printResponse(await call(method, route, body));
148
+ }
149
+
150
+ main().catch((e) => fail(e && e.message ? e.message : String(e)));
@@ -54,7 +54,7 @@ const { execFileSync, execSync } = require('child_process');
54
54
  const { spawn } = require('../wsl');
55
55
 
56
56
  const BaseAdapter = require('./base');
57
- const { whichBinary, getEnhancedEnv } = require('../paths');
57
+ const { whichBinary, getEnhancedEnv, resolveManagedNpmBinary } = require('../paths');
58
58
  const { formatAttachmentsForPrompt } = require('./utils');
59
59
  const { buildDeepSeekTaskFile } = require('./workspace-prompt');
60
60
  const { sampleRecap } = require('./decision-log');
@@ -121,8 +121,25 @@ const BOOTSTRAP_KEY = '\u0000bootstrap';
121
121
  const RECAP_HEAD = 30;
122
122
  const RECAP_TAIL = 60;
123
123
 
124
- /** The environment variable the task file tells the agent to read. */
125
- const TOKEN_ENV = 'OPENAGENTS_WORKSPACE_TOKEN';
124
+ /**
125
+ * The environment variable the task file tells the agent to read.
126
+ *
127
+ * Deliberately NOT `OPENAGENTS_WORKSPACE_TOKEN`: dsh strips every variable whose
128
+ * name matches /KEY|PASSWORD|SECRET|TOKEN/i from the commands it runs
129
+ * (`SENSITIVE_ENV_PATTERN` in @deepseek-ai/dsh-subprocess, rc.2 and rc.5 alike),
130
+ * and has no setting to let one through. Under that name the agent's shell never
131
+ * saw the token, so agents went looking for it — one read it out of daemon.yaml
132
+ * and wrote it into its reasoning, which sent it to the model provider and into
133
+ * dsh's session log. This token is meant for the agent's shell; the scrub
134
+ * exists for the harness's own credentials (DEEPSEEK_API_KEY stays scrubbed).
135
+ */
136
+ const TOKEN_ENV = 'OPENAGENTS_WORKSPACE_AUTH';
137
+
138
+ /**
139
+ * The workspace API client Windows runs use instead of curl, which dsh's
140
+ * Windows sandbox leaves without TLS credentials. See deepseek-workspace-api.js.
141
+ */
142
+ const WORKSPACE_API_HELPER = path.join(__dirname, 'deepseek-workspace-api.js');
126
143
 
127
144
  /**
128
145
  * The notice for a stop that could NOT be confirmed (BaseAdapter posts it when
@@ -252,7 +269,14 @@ class DeepSeekAdapter extends BaseAdapter {
252
269
  * when nothing resolves.
253
270
  */
254
271
  _resolveDshCommand() {
255
- const bin = whichBinary('dsh');
272
+ // The launcher-managed copy first, the same Tier 0 the installer uses. A
273
+ // plain PATH lookup ranks every global npm prefix above
274
+ // ~/.openagents/runtimes, so an old global dsh (a 0.1.0-rc.6 left from
275
+ // before the pin moved) shadowed the managed pinned one: the launcher
276
+ // reported the pinned version with nothing to update, while every start
277
+ // refused the global copy as unsupported.
278
+ const bin = resolveManagedNpmBinary('deepseek', '@deepseek-ai/dsh', 'dsh')
279
+ || whichBinary('dsh');
256
280
  if (!bin) return null;
257
281
  const nodeBin = this._findNodeBin();
258
282
 
@@ -273,6 +297,15 @@ class DeepSeekAdapter extends BaseAdapter {
273
297
  return null;
274
298
  }
275
299
 
300
+ /**
301
+ * Drop the resolved dsh so the next preflight resolves it afresh — after the
302
+ * daemon installed the pinned version into the managed prefix.
303
+ */
304
+ forgetRuntime() {
305
+ this._nodeBin = null;
306
+ this._jsEntry = null;
307
+ }
308
+
276
309
  /** `dsh -V` output, or null. Synchronous: preflight() is a sync contract. */
277
310
  _readDshVersion() {
278
311
  if (!this._jsEntry) return null;
@@ -363,7 +396,9 @@ class DeepSeekAdapter extends BaseAdapter {
363
396
  || defaultInstallCommand(supported);
364
397
  const gate = classifyDshVersion(this._readDshVersion(), supported, installCmd);
365
398
  if (gate.compatible === false || gate.compatible === null) {
366
- return { ok: false, reason: REASON.VERSION_INCOMPATIBLE, message: gate.message };
399
+ // repairable: the daemon installs the pinned version and asks again
400
+ // (see Daemon._repairRuntime), so a stale dsh never reaches the user.
401
+ return { ok: false, reason: REASON.VERSION_INCOMPATIBLE, message: gate.message, repairable: true };
367
402
  }
368
403
 
369
404
  if (!this._apiKey()) {
@@ -545,7 +580,11 @@ class DeepSeekAdapter extends BaseAdapter {
545
580
  * starts mid-write can never read a half-file.
546
581
  */
547
582
  _writePrivatePatch() {
548
- const { text } = buildPrivatePatch({ model: this._model(), gatewayBaseUrl: this._gatewayBaseUrl() });
583
+ const { text } = buildPrivatePatch({
584
+ model: this._model(),
585
+ gatewayBaseUrl: this._gatewayBaseUrl(),
586
+ officialEndpoint: !this._baseUrl(),
587
+ });
549
588
  const tmp = `${this._patchFile}.${process.pid}.tmp`;
550
589
  fs.writeFileSync(tmp, text, { encoding: 'utf-8', mode: 0o600 });
551
590
  fs.renameSync(tmp, this._patchFile);
@@ -585,6 +624,11 @@ class DeepSeekAdapter extends BaseAdapter {
585
624
 
586
625
  // The task file references this by NAME; the value never appears in it.
587
626
  env[TOKEN_ENV] = this.token;
627
+ // Read by deepseek-workspace-api.js, so a Windows run's commands carry no
628
+ // endpoint, workspace or identity of their own to get wrong.
629
+ env.OPENAGENTS_WORKSPACE_ENDPOINT = this.endpoint;
630
+ env.OPENAGENTS_WORKSPACE_ID = this.workspaceId;
631
+ env.OPENAGENTS_AGENT_NAME = this.agentName;
588
632
  return env;
589
633
  }
590
634
 
@@ -937,6 +981,7 @@ class DeepSeekAdapter extends BaseAdapter {
937
981
  recap,
938
982
  request: content,
939
983
  attachments: attachmentText,
984
+ windowsApi: IS_WINDOWS ? { node: this._nodeBin, helper: WORKSPACE_API_HELPER } : null,
940
985
  });
941
986
 
942
987
  this._taskCounter += 1;
@@ -27,6 +27,10 @@ const CommandCodeAdapter = require('./commandcode');
27
27
  const OpenWorkerAdapter = require('./openworker');
28
28
  const CodeBuddyAdapter = require('./codebuddy');
29
29
  const CodeArtsAdapter = require('./codearts');
30
+ const MiMoCodeAdapter = require('./mimo-code');
31
+ const QoderAdapter = require('./qoder');
32
+ const QoderCnAdapter = require('./qoder-cn');
33
+ const QwenCodeAdapter = require('./qwen-code');
30
34
 
31
35
  const ADAPTER_MAP = {
32
36
  openclaw: OpenClawAdapter,
@@ -51,11 +55,15 @@ const ADAPTER_MAP = {
51
55
  openworker: OpenWorkerAdapter,
52
56
  codebuddy: CodeBuddyAdapter,
53
57
  codearts: CodeArtsAdapter,
58
+ 'mimo-code': MiMoCodeAdapter,
59
+ qoder: QoderAdapter,
60
+ 'qoder-cn': QoderCnAdapter,
61
+ 'qwen-code': QwenCodeAdapter,
54
62
  };
55
63
 
56
64
  /**
57
65
  * Create an adapter instance for the given agent type.
58
- * @param {string} type - Agent type (openclaw, claude, codex, opencode, nanoclaw, cursor, hermes, gemini, kimi, aider, goose, copilot, cline, amp, mini-swe-agent, pi, deepseek, antigravity, commandcode, openworker, codebuddy, codearts)
66
+ * @param {string} type - Agent type (openclaw, claude, codex, opencode, nanoclaw, cursor, hermes, gemini, kimi, aider, goose, copilot, cline, amp, mini-swe-agent, pi, deepseek, antigravity, commandcode, openworker, codebuddy, codearts, mimo-code, qoder, qoder-cn, qwen-code)
59
67
  * @param {object} opts - Adapter constructor options
60
68
  * @returns {BaseAdapter}
61
69
  */
@@ -90,6 +98,10 @@ module.exports = {
90
98
  CommandCodeAdapter,
91
99
  OpenWorkerAdapter,
92
100
  CodeArtsAdapter,
101
+ MiMoCodeAdapter,
102
+ QoderAdapter,
103
+ QoderCnAdapter,
104
+ QwenCodeAdapter,
93
105
  createAdapter,
94
106
  ADAPTER_MAP,
95
107
  };
@@ -19,9 +19,10 @@
19
19
  * 1 permanent failure (config/auth/quota), 75 transient (retryable).
20
20
  *
21
21
  * IMPORTANT product distinction: two Moonshot products install a `kimi`
22
- * binary. Kimi Code CLI (npm `@moonshot-ai/kimi-code`) versions are 0.x;
23
- * the legacy Python `kimi-cli` (PyPI) is 1.x and has a DIFFERENT headless
24
- * interface. A 1.x `kimi --version` therefore means the WRONG product.
22
+ * binary. Kimi Code CLI (npm `@moonshot-ai/kimi-code`) versions are 0.x and
23
+ * 2.x+ (current line); the legacy Python `kimi-cli` (PyPI) is 1.x and has a
24
+ * DIFFERENT headless interface. A 1.x `kimi --version` therefore means the
25
+ * WRONG product.
25
26
  */
26
27
 
27
28
  'use strict';
@@ -42,7 +43,7 @@ function parseKimiVersion(raw) {
42
43
  /**
43
44
  * Classify `kimi --version` output into a product identity.
44
45
  * @returns {{version: string|null, product: 'kimi-code'|'legacy'|null}}
45
- * 'kimi-code' → the real Kimi Code CLI (0.x) this adapter drives
46
+ * 'kimi-code' → the real Kimi Code CLI (0.x, 2.x+) this adapter drives
46
47
  * 'legacy' → the wound-down Python kimi-cli (1.x) — incompatible
47
48
  * null → undetermined (unparseable output); proceed leniently
48
49
  */
@@ -50,7 +51,7 @@ function classifyKimiVersion(rawVersion) {
50
51
  const version = parseKimiVersion(rawVersion);
51
52
  if (!version) return { version: null, product: null };
52
53
  const major = parseInt(version.split('.')[0], 10);
53
- return { version, product: major === 0 ? 'kimi-code' : 'legacy' };
54
+ return { version, product: major === 1 ? 'legacy' : 'kimi-code' };
54
55
  }
55
56
 
56
57
  // ---------------------------------------------------------------------------
@@ -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
+ };