@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.
- package/icons/mimo-code.svg +1 -0
- package/icons/qoder-cn.svg +1 -0
- package/icons/qoder.svg +1 -0
- package/icons/qwen-code.svg +1 -0
- package/package.json +1 -1
- package/registry.json +378 -6
- package/src/adapters/base.js +25 -4
- package/src/adapters/deepseek-runtime.js +31 -5
- package/src/adapters/deepseek-workspace-api.js +150 -0
- package/src/adapters/deepseek.js +51 -6
- package/src/adapters/index.js +13 -1
- package/src/adapters/kimi-stream.js +6 -5
- package/src/adapters/mimo-code-runtime.js +266 -0
- package/src/adapters/mimo-code.js +581 -0
- package/src/adapters/opencode.js +21 -16
- package/src/adapters/pi.js +91 -8
- package/src/adapters/qoder-cn.js +24 -0
- package/src/adapters/qoder-runtime.js +611 -0
- package/src/adapters/qoder.js +946 -0
- package/src/adapters/qwen-code-stream.js +735 -0
- package/src/adapters/qwen-code.js +1125 -0
- package/src/adapters/workspace-prompt.js +41 -4
- package/src/agent-login.js +93 -0
- package/src/cli-models.js +45 -2
- package/src/cli.js +117 -11
- package/src/daemon.js +80 -4
- package/src/env.js +3 -0
- package/src/installer.js +49 -17
- package/src/paths.js +21 -0
- package/src/probe.js +44 -1
- package/src/workspace-client.js +12 -1
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MiMo Code adapter — Xiaomi's terminal coding agent (`mimo`).
|
|
3
|
+
*
|
|
4
|
+
* The CLI is a fork of OpenCode: `run --format json` streams OpenCode's JSON
|
|
5
|
+
* events and `--session` resumes, so stream parsing, sessions and the failure
|
|
6
|
+
* taxonomy are OpenCodeAdapter's. What differs (verified against 0.1.14 and
|
|
7
|
+
* 0.1.15):
|
|
8
|
+
*
|
|
9
|
+
* - Installed by Xiaomi's own script into ~/.mimocode/bin (Windows:
|
|
10
|
+
* %USERPROFILE%\.mimocode\bin\mimo.exe, or MIMOCODE_INSTALL_DIR), never
|
|
11
|
+
* npm. The file is the native binary itself, so it is spawned directly.
|
|
12
|
+
* - Everything a run needs — the provider, the key, the workspace MCP server
|
|
13
|
+
* and the workspace briefing — goes in through MIMOCODE_CONFIG_CONTENT,
|
|
14
|
+
* which MiMo loads after the user's own config and keeps out of the
|
|
15
|
+
* environment of the commands its tools run. Nothing is written into the
|
|
16
|
+
* project or into the user's MiMo config. See mimo-code-runtime.js for why
|
|
17
|
+
* the run is pinned to one provider.
|
|
18
|
+
* - The briefing is an `instructions` file read on every run, so it is part
|
|
19
|
+
* of the system prompt each turn (fresh mode and pinned decisions) rather
|
|
20
|
+
* than a preamble in the first message.
|
|
21
|
+
* - Nearly every failure exits 0: an API error is an `error` event on stdout;
|
|
22
|
+
* no credential, or a session the CLI does not have, is an `error:` line
|
|
23
|
+
* on stderr after a dump of the CLI's bundled source.
|
|
24
|
+
* - A permission the run would have to ask for is refused on the spot and
|
|
25
|
+
* the turn ends with no reply, so runs pass --dangerously-skip-permissions:
|
|
26
|
+
* the daemon is the approval boundary, as for every other agent here.
|
|
27
|
+
* - Stop: the CLI has no signal handling and dies at once, while each shell
|
|
28
|
+
* command it started runs in a session of its own — outside the CLI's
|
|
29
|
+
* process group — and is left running. Stop walks the process tree.
|
|
30
|
+
* - Claude Code's MCP servers (~/.claude.json) and its CLAUDE.md, which
|
|
31
|
+
* MiMo imports by default, are left out (MIMOCODE_DISABLE_CLAUDE_CODE_MCP,
|
|
32
|
+
* MIMOCODE_DISABLE_CLAUDE_CODE_PROMPT).
|
|
33
|
+
* - Its scheduler is turned off (MIMOCODE_EXPERIMENTAL_CRON=0): a one-shot
|
|
34
|
+
* run cannot fire a schedule, and while on it creates `.mimocode/` in the
|
|
35
|
+
* project, which the next run then installs MiMo's plugin package into.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
'use strict';
|
|
39
|
+
|
|
40
|
+
const { execFile, execFileSync, execSync } = require('child_process');
|
|
41
|
+
const crypto = require('crypto');
|
|
42
|
+
const fs = require('fs');
|
|
43
|
+
const os = require('os');
|
|
44
|
+
const path = require('path');
|
|
45
|
+
|
|
46
|
+
const OpenCodeAdapter = require('./opencode');
|
|
47
|
+
const { buildClaudeSystemPrompt } = require('./workspace-prompt');
|
|
48
|
+
const { whichBinary } = require('../paths');
|
|
49
|
+
const { REASON } = require('./health-status');
|
|
50
|
+
const {
|
|
51
|
+
MIMO_DEFAULT_BASE_URL,
|
|
52
|
+
resolveMimoRoute,
|
|
53
|
+
parseMimoModelList,
|
|
54
|
+
pickMimoModel,
|
|
55
|
+
buildMimoRunConfig,
|
|
56
|
+
buildMimoRunArgs,
|
|
57
|
+
descendantsOf,
|
|
58
|
+
parseProcessTable,
|
|
59
|
+
mimoErrorLine,
|
|
60
|
+
isMissingSession,
|
|
61
|
+
} = require('./mimo-code-runtime');
|
|
62
|
+
|
|
63
|
+
const IS_WINDOWS = process.platform === 'win32';
|
|
64
|
+
|
|
65
|
+
/** Newest CLI this adapter was checked against. Newer still runs, flagged. */
|
|
66
|
+
const MIMO_TESTED_VERSION = '0.1.16';
|
|
67
|
+
/** Oldest release still downloadable when this was written, and verified to work. */
|
|
68
|
+
const MIMO_MIN_VERSION = '0.1.14';
|
|
69
|
+
|
|
70
|
+
/** How long Stop waits for a polite exit before SIGKILL. */
|
|
71
|
+
const STOP_GRACE_MS = 1500;
|
|
72
|
+
|
|
73
|
+
const INSTALL_HINT = 'curl -fsSL https://mimo.xiaomi.com/install | bash (Windows: irm https://mimo.xiaomi.com/install.ps1 | iex)';
|
|
74
|
+
const KEY_URL = 'https://platform.xiaomimimo.com';
|
|
75
|
+
|
|
76
|
+
const FAILURE_MESSAGES = {
|
|
77
|
+
cli_not_found: `MiMo Code CLI not found. Install it (${INSTALL_HINT}) and try again.`,
|
|
78
|
+
cli_not_executable: 'MiMo Code CLI was found but could not be started. Reinstall it, then retry.',
|
|
79
|
+
unsupported_version: `This MiMo Code version is not supported (requires >= ${MIMO_MIN_VERSION}). Update it with \`mimo upgrade\` and retry.`,
|
|
80
|
+
model_missing: "No model is configured for MiMo Code. Set a model (LLM_MODEL) in this agent's configuration, then retry.",
|
|
81
|
+
credential_missing: `MiMo Code is not signed in and has no API key. Sign in with a Xiaomi account (the agent's Sign in button, or \`mimo providers login -p xiaomi\`), or add an API key (LLM_API_KEY — a MiMo key from ${KEY_URL}, or a key for the base URL you set) in this agent's configuration, then retry.`,
|
|
82
|
+
auth_failed: "The model service rejected MiMo Code's API key. Check LLM_API_KEY, and that it belongs to the base URL you set (a Token Plan key needs its Token Plan base URL), then retry. Signed in with a Xiaomi account instead? Sign in again — the key that sign-in created may have been deleted on the MiMo platform.",
|
|
83
|
+
provider_not_configured: "MiMo Code has no usable model provider. Check this agent's base URL and model, then retry.",
|
|
84
|
+
model_not_found: 'The configured model was not found or this key cannot use it. Pick one from the model list in this agent\'s configuration, then retry.',
|
|
85
|
+
rate_limited: 'The model service is rate-limiting requests. Wait a moment and retry.',
|
|
86
|
+
network_error: 'MiMo Code could not reach the model service (network or service error). Retry shortly.',
|
|
87
|
+
provider_server_error: 'The model service returned a server error. Retry shortly.',
|
|
88
|
+
timeout: 'MiMo Code went quiet for too long and was stopped. If the model service keeps failing, MiMo retries without saying so — check the base URL and model, then retry.',
|
|
89
|
+
stream_parse_error: 'MiMo Code produced output this version could not parse. Update it with `mimo upgrade`, or open diagnostics.',
|
|
90
|
+
empty_response: 'MiMo Code finished without producing a final reply. Retry; if it persists, open diagnostics.',
|
|
91
|
+
incomplete_run: 'MiMo Code stopped mid-task right after a tool call and never produced a final reply — its progress notes are shown above. Send "continue" to pick up where it left off.',
|
|
92
|
+
process_crashed: 'MiMo Code exited unexpectedly. Open diagnostics or retry.',
|
|
93
|
+
cwd_unavailable: "MiMo Code's working directory is not accessible. Check the agent's configured path (or agent home) permissions.",
|
|
94
|
+
session_missing: 'MiMo Code no longer has this conversation\'s session. Send the message again to start a new one.',
|
|
95
|
+
unknown_error: 'MiMo Code failed for an undetermined reason. Open diagnostics or retry.',
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
class MiMoCodeAdapter extends OpenCodeAdapter {
|
|
99
|
+
constructor(opts) {
|
|
100
|
+
super(opts);
|
|
101
|
+
this._runDir = path.join(this.agentHome, 'mimo-code');
|
|
102
|
+
/** channel → the `mimo models` child its turn is waiting on. */
|
|
103
|
+
this._modelLookups = new Map();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
_cliLabel() {
|
|
107
|
+
return 'MiMo Code';
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
_installHint() {
|
|
111
|
+
return `Install with: ${INSTALL_HINT}`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
_failureMessages() {
|
|
115
|
+
return FAILURE_MESSAGES;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* `mimo` where the installer puts it. ~/.mimocode/bin and
|
|
120
|
+
* MIMOCODE_INSTALL_DIR are among the known bin dirs (paths.js), so the
|
|
121
|
+
* lookup that decides whether the CLI is installed is the one that runs it.
|
|
122
|
+
*/
|
|
123
|
+
_findOpencodeBinary() {
|
|
124
|
+
return whichBinary('mimo');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The daemon's gate before join: without `mimo` there is nothing to run, so
|
|
129
|
+
* say so instead of joining and failing every message.
|
|
130
|
+
*/
|
|
131
|
+
preflight() {
|
|
132
|
+
const binary = this._opencodeBinary || this._findOpencodeBinary();
|
|
133
|
+
if (!binary) {
|
|
134
|
+
return {
|
|
135
|
+
ok: false,
|
|
136
|
+
reason: REASON.RUNTIME_MISSING,
|
|
137
|
+
message: `MiMo Code CLI (mimo) not found. ${this._installHint()}`,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
this._opencodeBinary = binary;
|
|
141
|
+
return { ok: true };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Besides the configured key and the workspace token: the Xiaomi-account
|
|
146
|
+
* sign-in key read out of auth.json, which a run passes to the CLI in its
|
|
147
|
+
* config and which has no shape the pattern rules know.
|
|
148
|
+
*/
|
|
149
|
+
_knownSecrets() {
|
|
150
|
+
let signInKey = '';
|
|
151
|
+
try { signInKey = this._route().apiKey; } catch { /* unreadable: nothing to add */ }
|
|
152
|
+
return [...new Set([...super._knownSecrets(), signInKey].filter(Boolean))]
|
|
153
|
+
.sort((x, y) => y.length - x.length);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Where one run goes — see resolveMimoRoute. */
|
|
157
|
+
_route() {
|
|
158
|
+
const env = this.agentEnv || process.env;
|
|
159
|
+
return resolveMimoRoute(env, this.workspaceModel, {
|
|
160
|
+
signIn: MiMoCodeAdapter._readSignIn(env),
|
|
161
|
+
fallbackModel: this._fallbackModel || '',
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The model a run on MiMo's endpoints uses when none is set: what the
|
|
167
|
+
* launcher would preselect from the CLI's own list (deprecated models are
|
|
168
|
+
* already left out of it). Asked once. Without it the run would leave the
|
|
169
|
+
* pick to MiMo, and the user's own `model` / `agent.*.model` settings — on
|
|
170
|
+
* other providers, so "Model not found" — would take it.
|
|
171
|
+
*/
|
|
172
|
+
async _ensureFallbackModel(channel = '') {
|
|
173
|
+
if (this._fallbackModel) return;
|
|
174
|
+
const route = this._route();
|
|
175
|
+
if (route.providerId !== 'xiaomi' || route.model) return;
|
|
176
|
+
const binary = this._opencodeBinary || this._findOpencodeBinary();
|
|
177
|
+
if (!binary) return;
|
|
178
|
+
const env = { ...(this.agentEnv || process.env) };
|
|
179
|
+
delete env.LLM_API_KEY;
|
|
180
|
+
delete env.XIAOMI_API_KEY;
|
|
181
|
+
const out = await new Promise((resolve) => {
|
|
182
|
+
const child = execFile(binary, ['models', 'xiaomi'], {
|
|
183
|
+
env: {
|
|
184
|
+
...env,
|
|
185
|
+
MIMOCODE_AUTH_CONTENT: '{}',
|
|
186
|
+
MIMOCODE_CONFIG_CONTENT: JSON.stringify({ enabled_providers: ['xiaomi'], disabled_providers: [] }),
|
|
187
|
+
MIMOCODE_DISABLE_AUTOUPDATE: '1',
|
|
188
|
+
},
|
|
189
|
+
// The first command on a machine migrates MiMo's database.
|
|
190
|
+
timeout: 120000,
|
|
191
|
+
windowsHide: true,
|
|
192
|
+
}, (err, stdout) => {
|
|
193
|
+
if (this._modelLookups.get(channel) === child) this._modelLookups.delete(channel);
|
|
194
|
+
resolve(err ? '' : String(stdout || ''));
|
|
195
|
+
});
|
|
196
|
+
// Stop ends the lookup along with the turn (see _stopChannelWork).
|
|
197
|
+
this._modelLookups.set(channel, child);
|
|
198
|
+
});
|
|
199
|
+
this._fallbackModel = pickMimoModel(parseMimoModelList(out));
|
|
200
|
+
if (this._fallbackModel) this._log(`MiMo Code: no model set — using ${this._fallbackModel}, the first pro model it lists`);
|
|
201
|
+
else this._log('MiMo Code: no model set and its model list could not be read — MiMo picks', 'warn');
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* The model lookup runs before the turn's process exists, and can take a
|
|
206
|
+
* while (the first command on a machine migrates MiMo's database). A Stop
|
|
207
|
+
* that lands then ends it, so the turn does not sit out the lookup's
|
|
208
|
+
* timeout; the run itself is then never started (_stoppedBeforeStart).
|
|
209
|
+
*/
|
|
210
|
+
_killModelLookup(channel) {
|
|
211
|
+
const child = this._modelLookups.get(channel);
|
|
212
|
+
if (!child) return false;
|
|
213
|
+
this._modelLookups.delete(channel);
|
|
214
|
+
if (child.exitCode !== null || child.signalCode) return false;
|
|
215
|
+
if (IS_WINDOWS) {
|
|
216
|
+
try { execSync(`taskkill /F /T /PID ${child.pid}`, { timeout: 5000, windowsHide: true }); } catch {}
|
|
217
|
+
}
|
|
218
|
+
try { child.kill('SIGKILL'); } catch {}
|
|
219
|
+
this._log(`MiMo Code: stopped the model lookup for channel=${channel}`);
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async _stopChannelWork(channel) {
|
|
224
|
+
const looking = this._killModelLookup(channel);
|
|
225
|
+
const outcome = await super._stopChannelWork(channel);
|
|
226
|
+
return looking && outcome === 'idle' ? 'stopped' : outcome;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
stop() {
|
|
230
|
+
for (const channel of [...this._modelLookups.keys()]) this._killModelLookup(channel);
|
|
231
|
+
super.stop();
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** `provider/model`, or '' when none is given for a sign-in or a non-MiMo endpoint. */
|
|
235
|
+
_resolveModel() {
|
|
236
|
+
return this._route().modelRef;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** MiMo picks on its own endpoints; only another endpoint needs a model named. */
|
|
240
|
+
_modelRequired() {
|
|
241
|
+
return this._route().providerId !== 'xiaomi';
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
modelLabel() {
|
|
245
|
+
return this._route().model || super.modelLabel();
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Providers are declared per run in MIMOCODE_CONFIG_CONTENT, never on disk,
|
|
249
|
+
// and the workspace is reached over MCP rather than a skill file.
|
|
250
|
+
_customBaseUrl() {
|
|
251
|
+
return '';
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
_ensureCustomProviderConfig() {}
|
|
255
|
+
|
|
256
|
+
_ensureWorkspaceSkill() {}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* 'present' with a key in this agent's configuration, or with a
|
|
260
|
+
* Xiaomi-account sign-in. A model on some other provider the user set up in
|
|
261
|
+
* MiMo is theirs to vouch for: 'unknown', and the run reports what the CLI
|
|
262
|
+
* says.
|
|
263
|
+
*/
|
|
264
|
+
_credentialState() {
|
|
265
|
+
const route = this._route();
|
|
266
|
+
if (route.mode === 'own') return 'unknown';
|
|
267
|
+
return route.apiKey ? 'present' : 'missing';
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* The Xiaomi-account sign-in: an API key the MiMo platform issued for the
|
|
272
|
+
* CLI, stored under `xiaomi` in auth.json, with the Token Plan base URL for
|
|
273
|
+
* an account on one. An entry without a key signs nothing in.
|
|
274
|
+
*/
|
|
275
|
+
static _readSignIn(env) {
|
|
276
|
+
const auth = MiMoCodeAdapter._readAuthFile(env);
|
|
277
|
+
const entry = auth && auth.xiaomi;
|
|
278
|
+
if (!entry || typeof entry !== 'object') return null;
|
|
279
|
+
const key = String(entry.key || '').trim();
|
|
280
|
+
if (!key) return null;
|
|
281
|
+
const meta = entry.metadata && typeof entry.metadata === 'object' ? entry.metadata : {};
|
|
282
|
+
return { key, baseURL: String(meta.base_url || '').trim() };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* MiMo's credential store: $MIMOCODE_HOME/data/auth.json when MIMOCODE_HOME
|
|
287
|
+
* is set, else under the XDG data dir on every platform (on Windows too,
|
|
288
|
+
* under the user profile), as OpenCode's is.
|
|
289
|
+
*/
|
|
290
|
+
static _authFilePath(env = process.env, home = os.homedir()) {
|
|
291
|
+
const mimoHome = String(env.MIMOCODE_HOME || '').trim();
|
|
292
|
+
if (mimoHome && path.isAbsolute(mimoHome)) return path.join(mimoHome, 'data', 'auth.json');
|
|
293
|
+
const dataHome = String(env.XDG_DATA_HOME || '').trim() || path.join(home, '.local', 'share');
|
|
294
|
+
return path.join(dataHome, 'mimocode', 'auth.json');
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
static _readAuthFile(env) {
|
|
298
|
+
try {
|
|
299
|
+
const data = JSON.parse(fs.readFileSync(MiMoCodeAdapter._authFilePath(env), 'utf-8'));
|
|
300
|
+
return data && typeof data === 'object' ? data : null;
|
|
301
|
+
} catch {
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
static _classifyVersion(version) {
|
|
307
|
+
if (!version || !/^\d+\.\d+/.test(String(version))) return 'unknown';
|
|
308
|
+
if (OpenCodeAdapter._cmpVer(version, MIMO_MIN_VERSION) < 0) return 'unsupported';
|
|
309
|
+
return OpenCodeAdapter._cmpVer(version, MIMO_TESTED_VERSION) > 0 ? 'degraded' : 'ok';
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// ------------------------------------------------------------------
|
|
313
|
+
// One run
|
|
314
|
+
// ------------------------------------------------------------------
|
|
315
|
+
|
|
316
|
+
_buildRunArgs({ runCwd, model, sessionId, channel }) {
|
|
317
|
+
return buildMimoRunArgs({
|
|
318
|
+
runCwd,
|
|
319
|
+
model,
|
|
320
|
+
sessionId,
|
|
321
|
+
title: `OpenAgents - ${channel || this.channelName}`,
|
|
322
|
+
plan: this._mode === 'plan',
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* The message as typed. The briefing reaches the model through the run's
|
|
328
|
+
* `instructions` file; only when that file could not be written does a new
|
|
329
|
+
* session fall back to carrying it in its first message.
|
|
330
|
+
*/
|
|
331
|
+
_composePrompt(content, msgChannel, sessionId) {
|
|
332
|
+
if (this._instructionsReady(msgChannel)) return content;
|
|
333
|
+
return super._composePrompt(content, msgChannel, sessionId);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
_buildSystemContext(channelName) {
|
|
337
|
+
return buildClaudeSystemPrompt({
|
|
338
|
+
agentName: this.agentName,
|
|
339
|
+
workspaceId: this.workspaceId,
|
|
340
|
+
channelName,
|
|
341
|
+
mode: this._mode,
|
|
342
|
+
model: this.modelLabel(),
|
|
343
|
+
browserEnabled: !!this._browserEnabledCache,
|
|
344
|
+
toolMode: 'mcp',
|
|
345
|
+
...this.pinnedPromptOpts(channelName),
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
_instructionsPath(channel) {
|
|
350
|
+
const slug = crypto.createHash('sha256').update(String(channel)).digest('hex').slice(0, 16);
|
|
351
|
+
return path.join(this._runDir, `instructions-${slug}.md`);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
_instructionsReady(channel) {
|
|
355
|
+
return !!(this._instructionsWritten && this._instructionsWritten.has(channel));
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** (Re)write this channel's briefing, read by the CLI at the start of the run. */
|
|
359
|
+
_writeInstructions(channel) {
|
|
360
|
+
if (!this._instructionsWritten) this._instructionsWritten = new Set();
|
|
361
|
+
try {
|
|
362
|
+
fs.mkdirSync(this._runDir, { recursive: true });
|
|
363
|
+
fs.writeFileSync(this._instructionsPath(channel), this._buildSystemContext(channel), 'utf-8');
|
|
364
|
+
this._instructionsWritten.add(channel);
|
|
365
|
+
} catch (e) {
|
|
366
|
+
this._instructionsWritten.delete(channel);
|
|
367
|
+
this._log(`Could not write the workspace briefing (it goes in the first message instead): ${this._redact(e && e.message)}`, 'warn');
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* The workspace MCP server: this package's own CLI, run by the Node that
|
|
373
|
+
* runs the daemon (or the launcher's portable one). Its token goes in the
|
|
374
|
+
* server's environment only.
|
|
375
|
+
*/
|
|
376
|
+
_mcpServer(channel) {
|
|
377
|
+
const entry = path.resolve(__dirname, '..', '..', 'bin', 'agent-connector.js');
|
|
378
|
+
if (!fs.existsSync(entry)) {
|
|
379
|
+
this._log('Could not find the agent-connector CLI — workspace MCP tools are unavailable this run', 'warn');
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
const args = [
|
|
383
|
+
entry, 'mcp-server',
|
|
384
|
+
'--workspace-id', this.workspaceId,
|
|
385
|
+
'--channel-name', channel,
|
|
386
|
+
'--agent-name', this.agentName,
|
|
387
|
+
'--endpoint', this.endpoint,
|
|
388
|
+
];
|
|
389
|
+
if (this.disabledModules.has('files')) args.push('--disable-files');
|
|
390
|
+
if (this.disabledModules.has('browser')) args.push('--disable-browser');
|
|
391
|
+
if (this.disabledModules.has('knowledge')) args.push('--disable-knowledge');
|
|
392
|
+
return { command: this._nodeBin(), args, env: { OA_WORKSPACE_TOKEN: this.token } };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** The launcher's portable Node when present, else the one running the daemon. */
|
|
396
|
+
_nodeBin() {
|
|
397
|
+
const root = path.join(os.homedir(), '.openagents', 'nodejs');
|
|
398
|
+
const candidates = IS_WINDOWS
|
|
399
|
+
? [path.join(root, 'node.exe')]
|
|
400
|
+
: [path.join(root, 'node'), path.join(root, 'bin', 'node')];
|
|
401
|
+
return candidates.find((c) => fs.existsSync(c)) || process.execPath;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
_spawnEnv(channel) {
|
|
405
|
+
const env = { ...(this.agentEnv || process.env) };
|
|
406
|
+
// The key is in the run config, which MiMo keeps away from its tools'
|
|
407
|
+
// commands; left in the environment, any `env` the model runs would print
|
|
408
|
+
// it. XIAOMI_API_KEY is MiMo's own way in to the provider the run is
|
|
409
|
+
// pinned to, which neither a key run nor a sign-in run is meant to take.
|
|
410
|
+
delete env.LLM_API_KEY;
|
|
411
|
+
delete env.XIAOMI_API_KEY;
|
|
412
|
+
const ch = channel || this.channelName;
|
|
413
|
+
const config = buildMimoRunConfig(this._route(), {
|
|
414
|
+
mcp: this._mcpServer(ch),
|
|
415
|
+
instructions: this._instructionsReady(ch) ? [this._instructionsPath(ch)] : [],
|
|
416
|
+
});
|
|
417
|
+
const route = this._route();
|
|
418
|
+
return {
|
|
419
|
+
...env,
|
|
420
|
+
MIMOCODE_CONFIG_CONTENT: JSON.stringify(config),
|
|
421
|
+
// The run's credential is the one declared in its config — the agent's
|
|
422
|
+
// key, or the sign-in's, read by the adapter. The CLI reads this in place
|
|
423
|
+
// of auth.json, so nothing MiMo has stored (the sign-in under a key run,
|
|
424
|
+
// another provider's key under either) stands in for it. Only a run on
|
|
425
|
+
// a provider of the user's own MiMo setup reads auth.json. MiMo keeps
|
|
426
|
+
// this variable out of its tools' commands, like the config.
|
|
427
|
+
...(route.mode !== 'own' ? { MIMOCODE_AUTH_CONTENT: '{}' } : {}),
|
|
428
|
+
MIMOCODE_EXPERIMENTAL_CRON: '0',
|
|
429
|
+
MIMOCODE_DISABLE_AUTOUPDATE: '1',
|
|
430
|
+
// MiMo otherwise starts every MCP server in Claude Code's ~/.claude.json
|
|
431
|
+
// on each run and offers its tools to the model, and puts Claude Code's
|
|
432
|
+
// ~/.claude/CLAUDE.md in the system prompt. MiMo's own AGENTS.md still loads.
|
|
433
|
+
MIMOCODE_DISABLE_CLAUDE_CODE_MCP: '1',
|
|
434
|
+
MIMOCODE_DISABLE_CLAUDE_CODE_PROMPT: '1',
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Prepare the briefing, then run. A session the CLI no longer has (its
|
|
440
|
+
* database was reset, or the agent moved machines) fails the resume; the
|
|
441
|
+
* binding is dropped and the turn runs once more in a new session.
|
|
442
|
+
*/
|
|
443
|
+
async _runOpencode(content, msgChannel) {
|
|
444
|
+
await this.getBrowserEnabled();
|
|
445
|
+
await this._ensureFallbackModel(msgChannel);
|
|
446
|
+
this._writeInstructions(msgChannel);
|
|
447
|
+
try {
|
|
448
|
+
return await super._runOpencode(content, msgChannel);
|
|
449
|
+
} catch (e) {
|
|
450
|
+
if (!e || e.category !== 'session_missing' || !this._channelSessions[msgChannel]) throw e;
|
|
451
|
+
this._log(`MiMo Code has no session ${this._channelSessions[msgChannel]} — starting a new one`);
|
|
452
|
+
delete this._channelSessions[msgChannel];
|
|
453
|
+
this._saveSessions();
|
|
454
|
+
return super._runOpencode(content, msgChannel);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* Remember the session as soon as the CLI names it, not only when the run
|
|
460
|
+
* ends cleanly: a stopped turn is resumable, and the next message should
|
|
461
|
+
* continue it rather than start over.
|
|
462
|
+
*/
|
|
463
|
+
async _handleStreamEvent(event, msgChannel, responseState = null) {
|
|
464
|
+
const sid = event && typeof event.sessionID === 'string' ? event.sessionID : '';
|
|
465
|
+
if (sid && this._channelSessions[msgChannel] !== sid) {
|
|
466
|
+
this._channelSessions[msgChannel] = sid;
|
|
467
|
+
this._saveSessions();
|
|
468
|
+
this._log(`MiMo Code session for channel ${msgChannel}: ${sid}`);
|
|
469
|
+
}
|
|
470
|
+
// Reasoning only appears with --thinking, which runs do not pass; should
|
|
471
|
+
// it ever arrive it is not part of the reply.
|
|
472
|
+
if (event && event.type === 'reasoning') return;
|
|
473
|
+
return super._handleStreamEvent(event, msgChannel, responseState);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// ------------------------------------------------------------------
|
|
477
|
+
// Stop
|
|
478
|
+
// ------------------------------------------------------------------
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* End the CLI and every command it started. Returns whether the CLI itself
|
|
482
|
+
* is gone.
|
|
483
|
+
*
|
|
484
|
+
* Windows: taskkill /T walks the tree by parent, which is all it takes — as
|
|
485
|
+
* long as the CLI is still alive to walk from, so it is not asked to exit
|
|
486
|
+
* first. Elsewhere the descendants are read from the process table before
|
|
487
|
+
* anything is signalled, because each shell command sits in its own session
|
|
488
|
+
* and is reparented the moment the CLI dies.
|
|
489
|
+
*/
|
|
490
|
+
async _stopProcess(proc) {
|
|
491
|
+
if (!proc || proc.exitCode !== null || proc.signalCode) return true;
|
|
492
|
+
if (IS_WINDOWS) {
|
|
493
|
+
try { execSync(`taskkill /F /T /PID ${proc.pid}`, { timeout: 5000, windowsHide: true }); } catch {}
|
|
494
|
+
return this._waitForExit(proc, STOP_GRACE_MS);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const groups = new Set([proc.pid]);
|
|
498
|
+
const pids = new Set();
|
|
499
|
+
for (const d of descendantsOf(MiMoCodeAdapter._processTable(), proc.pid)) {
|
|
500
|
+
pids.add(d.pid);
|
|
501
|
+
if (d.pgid > 1 && d.pgid !== process.pid) groups.add(d.pgid);
|
|
502
|
+
}
|
|
503
|
+
const signal = (sig) => {
|
|
504
|
+
for (const g of groups) { try { process.kill(-g, sig); } catch {} }
|
|
505
|
+
for (const p of pids) { try { process.kill(p, sig); } catch {} }
|
|
506
|
+
try { proc.kill(sig); } catch {}
|
|
507
|
+
};
|
|
508
|
+
|
|
509
|
+
signal('SIGTERM');
|
|
510
|
+
if (await this._waitForExit(proc, STOP_GRACE_MS) && ![...pids].some(MiMoCodeAdapter._alive)) return true;
|
|
511
|
+
signal('SIGKILL');
|
|
512
|
+
return this._waitForExit(proc, 1000);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
_waitForExit(proc, ms) {
|
|
516
|
+
if (proc.exitCode !== null || proc.signalCode) return Promise.resolve(true);
|
|
517
|
+
return new Promise((resolve) => {
|
|
518
|
+
const timer = setTimeout(() => resolve(proc.exitCode !== null || !!proc.signalCode), ms);
|
|
519
|
+
proc.once('exit', () => { clearTimeout(timer); resolve(true); });
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
static _processTable() {
|
|
524
|
+
try {
|
|
525
|
+
return parseProcessTable(execFileSync('ps', ['-A', '-o', 'pid=,ppid=,pgid='], { encoding: 'utf-8', timeout: 3000 }));
|
|
526
|
+
} catch {
|
|
527
|
+
return [];
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
static _alive(pid) {
|
|
532
|
+
try { process.kill(pid, 0); return true; } catch (e) { return !!(e && e.code === 'EPERM'); }
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// ------------------------------------------------------------------
|
|
536
|
+
// Failure classification
|
|
537
|
+
// ------------------------------------------------------------------
|
|
538
|
+
|
|
539
|
+
/** OpenCode's taxonomy plus the CLI's own wording, read from its error line. */
|
|
540
|
+
static _classifyFailure(input = {}) {
|
|
541
|
+
const line = mimoErrorLine(input.stderr);
|
|
542
|
+
const result = super._classifyFailure(line ? { ...input, stderr: line } : input);
|
|
543
|
+
if (isMissingSession(input.stderr)) return { ...result, category: 'session_missing' };
|
|
544
|
+
// "MiMo free API service has ended. Sign in or configure a third-party API."
|
|
545
|
+
if (/free API service has ended|sign in or configure/i.test(line)) {
|
|
546
|
+
return { ...result, category: 'credential_missing' };
|
|
547
|
+
}
|
|
548
|
+
// MiMo's API answers a model it does not serve with a 400 worded
|
|
549
|
+
// "Unsupported model <id>", which OpenCode's patterns read as unknown.
|
|
550
|
+
const err = input.stdoutErr || OpenCodeAdapter._extractErrorFromStdout(input.stdout || '');
|
|
551
|
+
if (/unsupported model/i.test(`${(err && err.message) || ''} ${line}`)) {
|
|
552
|
+
return { ...result, category: 'model_not_found' };
|
|
553
|
+
}
|
|
554
|
+
return result;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Exit 0 with nothing on stdout is a failure the CLI described on stderr —
|
|
559
|
+
* a missing credential, an unknown session — not an empty reply.
|
|
560
|
+
*/
|
|
561
|
+
static _outcomeForCleanExit(args = {}) {
|
|
562
|
+
const outcome = super._outcomeForCleanExit(args);
|
|
563
|
+
if (!outcome.failure || outcome.failure.category !== 'empty_response') return outcome;
|
|
564
|
+
const line = mimoErrorLine(args.stderr);
|
|
565
|
+
if (!line && !isMissingSession(args.stderr)) return outcome;
|
|
566
|
+
const cls = this._classifyFailure({ code: 0, signal: null, stdout: '', stderr: args.stderr });
|
|
567
|
+
return {
|
|
568
|
+
failure: {
|
|
569
|
+
category: ['stream_parse_error', 'process_crashed'].includes(cls.category) ? 'unknown_error' : cls.category,
|
|
570
|
+
diagnostic: `exit 0, stderr: ${line}`,
|
|
571
|
+
detail: OpenCodeAdapter._redact(line).slice(0, 200),
|
|
572
|
+
},
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
MiMoCodeAdapter.MIMO_TESTED_VERSION = MIMO_TESTED_VERSION;
|
|
578
|
+
MiMoCodeAdapter.MIMO_MIN_VERSION = MIMO_MIN_VERSION;
|
|
579
|
+
MiMoCodeAdapter.MIMO_DEFAULT_BASE_URL = MIMO_DEFAULT_BASE_URL;
|
|
580
|
+
|
|
581
|
+
module.exports = MiMoCodeAdapter;
|
package/src/adapters/opencode.js
CHANGED
|
@@ -164,6 +164,17 @@ class OpenCodeAdapter extends BaseAdapter {
|
|
|
164
164
|
return args;
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
+
/**
|
|
168
|
+
* The text sent on stdin for one turn. A new session carries the workspace
|
|
169
|
+
* context ahead of the message; a resumed one already holds it.
|
|
170
|
+
*/
|
|
171
|
+
_composePrompt(content, msgChannel, sessionId) {
|
|
172
|
+
if (sessionId) return content;
|
|
173
|
+
this._ensureWorkspaceSkill(msgChannel);
|
|
174
|
+
const context = this._buildSystemContext(msgChannel);
|
|
175
|
+
return `${context}\n\n---\n\n${content}`;
|
|
176
|
+
}
|
|
177
|
+
|
|
167
178
|
/** Environment the CLI is spawned with. */
|
|
168
179
|
|
|
169
180
|
/** Test seam for the inactivity watchdog. */
|
|
@@ -422,8 +433,8 @@ class OpenCodeAdapter extends BaseAdapter {
|
|
|
422
433
|
return;
|
|
423
434
|
}
|
|
424
435
|
const category = (e && e.category) ? e.category : this._classifyErrno(e);
|
|
425
|
-
const diagnostic =
|
|
426
|
-
this._log(`OpenCode failure [${category}] in ${msgChannel}: ${diagnostic.slice(0, 300)}
|
|
436
|
+
const diagnostic = this._redact((e && (e.diagnostic || e.message)) || '');
|
|
437
|
+
this._log(`OpenCode failure [${category}] in ${msgChannel}: ${diagnostic.slice(0, 300)}`, 'error');
|
|
427
438
|
await this._sendClassifiedError(msgChannel, category, e && e.detail);
|
|
428
439
|
}
|
|
429
440
|
}
|
|
@@ -850,20 +861,12 @@ class OpenCodeAdapter extends BaseAdapter {
|
|
|
850
861
|
}
|
|
851
862
|
const model = this._resolveModel();
|
|
852
863
|
const sessionId = this._channelSessions[msgChannel];
|
|
853
|
-
const args = this._buildRunArgs({ runCwd, model, sessionId });
|
|
854
|
-
|
|
855
|
-
let fullPrompt;
|
|
856
|
-
if (sessionId) {
|
|
857
|
-
fullPrompt = content;
|
|
858
|
-
} else {
|
|
859
|
-
this._ensureWorkspaceSkill(msgChannel);
|
|
860
|
-
const context = this._buildSystemContext(msgChannel);
|
|
861
|
-
fullPrompt = `${context}\n\n---\n\n${content}`;
|
|
862
|
-
}
|
|
864
|
+
const args = this._buildRunArgs({ runCwd, model, sessionId, channel: msgChannel });
|
|
865
|
+
const fullPrompt = this._composePrompt(content, msgChannel, sessionId);
|
|
863
866
|
|
|
864
867
|
this._log(`CLI: ${binary} ${args.join(' ')}`);
|
|
865
868
|
|
|
866
|
-
const spawnEnv = this._spawnEnv();
|
|
869
|
+
const spawnEnv = this._spawnEnv(msgChannel);
|
|
867
870
|
|
|
868
871
|
let spawnBinary = binary;
|
|
869
872
|
let spawnArgs = args;
|
|
@@ -981,7 +984,7 @@ class OpenCodeAdapter extends BaseAdapter {
|
|
|
981
984
|
|
|
982
985
|
if (code !== 0) {
|
|
983
986
|
const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
|
|
984
|
-
this._log(`opencode exited code ${code} → [${cls.category}]: ${
|
|
987
|
+
this._log(`opencode exited code ${code} → [${cls.category}]: ${this._redact(cls.diagnostic).slice(0, 300)}`);
|
|
985
988
|
return finish(reject, this._failure(cls.category, cls.diagnostic, cls.detail));
|
|
986
989
|
}
|
|
987
990
|
|
|
@@ -990,7 +993,7 @@ class OpenCodeAdapter extends BaseAdapter {
|
|
|
990
993
|
const outcome = this.constructor._outcomeForCleanExit({ stdout, stderr, stdoutErr, responseState });
|
|
991
994
|
if (outcome.text) return finish(resolve, outcome.text);
|
|
992
995
|
const f = outcome.failure;
|
|
993
|
-
this._log(`opencode exit 0 → [${f.category}]: ${
|
|
996
|
+
this._log(`opencode exit 0 → [${f.category}]: ${this._redact(f.diagnostic).slice(0, 300)}`);
|
|
994
997
|
return finish(reject, this._failure(f.category, f.diagnostic, f.detail));
|
|
995
998
|
});
|
|
996
999
|
});
|
|
@@ -1232,7 +1235,9 @@ class OpenCodeAdapter extends BaseAdapter {
|
|
|
1232
1235
|
if (this._isMuted(channel)) return;
|
|
1233
1236
|
const messages = this._failureMessages();
|
|
1234
1237
|
const base = messages[category] || messages.unknown_error;
|
|
1235
|
-
|
|
1238
|
+
// The instance redaction: this agent's own secrets by value (whatever their
|
|
1239
|
+
// format), then the credential shapes the static pass already took.
|
|
1240
|
+
const safe = detail ? this._redact(detail).trim() : '';
|
|
1236
1241
|
const body = safe ? `${base}\n\n> ${safe}` : base;
|
|
1237
1242
|
const label = this._cliLabel();
|
|
1238
1243
|
const headline = category === 'incomplete_run' ? `${label} stopped mid-task` : `${label} couldn't run`;
|