@m2canvas/connect 0.7.3 → 0.9.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.
package/README.md CHANGED
@@ -39,7 +39,8 @@ Lets M2 (in Chrome or another Chromium browser) start and talk to the agents on
39
39
  - **Pairing.** When you start the bridge with the command M2 gives you, the page that gave it pairs automatically within 10 minutes. The command only carries a hash (`--pair`); the secret it matches stays in that browser tab, so the command is safe to appear in your shell history, and it works once. Any other page asks for the pairing code printed in this window; the window also shows which site is asking. After that the page remembers the pairing for 30 days of inactivity. After too many wrong codes, new pages can't pair until you restart the bridge (pages already paired keep working); close the page the window names first. `bridge --unpair` forgets all paired pages. If you can't find this window, run the command M2 shows under the code box: it adds `--replace`, which stops the M2 bridge already running on the port (its agent sessions end) and starts a new one that pairs by itself. It only stops a bridge (0.6.0 or later) it can recognize from a small state file in `~/.m2canvas` (process id and start time; no codes or tokens are written there), never anything else on the port, and not on Windows. When it can't recognize what holds the port, it shows you that process (or how to find it) and leaves it alone. With an older bridge, M2 shows the Ctrl+C instructions instead.
40
40
  - **Your own logins.** Agents use their own sign-in and their own M2 MCP setup. It starts agents with a minimal environment, so variables set by a host app (for example `ANTHROPIC_BASE_URL` inside Claude Code) don't leak into them.
41
41
  - **Signing in from M2 (macOS).** M2 can start an agent's own sign-in, or its M2 authorization, for you: the bridge runs that agent's own command from a fixed list in this package, and M2 opens the sign-in page in the browser you are using (Codex opens your default browser itself). You finish signing in there; nothing is entered for you. The page only picks the agent and whether to sign in or authorize M2, never the command. Covered: sign-in for Claude Code, Codex, Cursor and Qoder; M2 authorization for Claude Code, Codex, Cursor and OpenCode (Qoder's M2 authorization is only available inside Qoder). Claude Code's M2 authorization needs a terminal, so the bridge provides one with macOS's built-in `/usr/bin/expect`. A sign-in can be canceled from M2, gives up after 10 minutes, and stops when the page disconnects or the bridge exits. On other systems M2 shows the command to run instead.
42
- - **Claude and Codex** run through pinned versions of the official adapters (`@agentclientprotocol/claude-agent-acp@0.84.0`, `@agentclientprotocol/codex-acp@2.1.0`). They are installed on first use into `~/.m2canvas/acp-adapters/` from the lockfiles in this package (about 270 MB and 350 MB, because they bundle the agent); M2 shows the download progress. You don't need Claude Code or Codex installed yourself: checking sign-in, adding M2 and signing in all use the bundled `claude` and `codex`, which read the same settings as your own installs.
42
+ - **Claude and Codex** run through pinned versions of the official adapters (`@agentclientprotocol/claude-agent-acp@0.84.0`, `@agentclientprotocol/codex-acp@2.1.0`). They are installed on first use into `~/.m2canvas/acp-adapters/` from the lockfiles in this package (they bundle the agent: about 110 MB and 140 MB to download, 270 MB and 350 MB on disk); M2 shows the download progress. You don't need Claude Code or Codex installed yourself: checking sign-in, adding M2 and signing in all use the bundled `claude` and `codex`, which read the same settings as your own installs.
43
+ - **Checking an agent before use.** Before starting an agent, M2 asks the bridge whether it is signed in and has M2 set up (commands such as `claude auth status` and `claude mcp list`; `claude mcp list` starts the MCP servers you configured in order to check them). From 0.9.0 the bridge runs this check for Claude Code and Codex once when it starts, and remembers a result that passed, so opening another project doesn't wait for it again. It checks again when you click "Check again" in M2 and when M2 adds itself to an agent or signs in for you; when a page uses a remembered result that is more than 5 minutes old, it also checks again in the background and tells M2 if the result no longer holds. There is no periodic check. Results that need you to do something are never remembered, and nothing is written to disk.
43
44
  - Cursor runs as `agent acp`, OpenCode as `opencode acp`, Qoder as `qodercli --acp`.
44
45
 
45
46
  Agent sessions start in that directory.
@@ -59,6 +60,6 @@ curl -fsSL https://m2ui.ai/connect/install.sh | sh -s -- --pair <value from M2>
59
60
  - **No pairing codes in the background.** A bridge started this way has no window to show a code in. When a page isn't paired yet (another browser, or the pairing expired), M2 gives it the same start command: the new bridge process sees the one already running and hands the page's pairing value to it, so the page pairs without restarting the bridge and other tabs keep their sessions. The handoff goes through `~/.m2canvas/bridge-<port>.sock` plus a one-time file in `~/.m2canvas`, so only a process that can write to that folder (your account; agent sandboxes normally can't write there) can hand a pairing value over; the file holds only the hash and is deleted right away. If that doesn't work, M2 offers to restart the bridge with `--replace`, which ends the sessions on the old one.
60
61
  - **Sandboxes.** Codex needs its Full access permission mode: its default sandbox can't reach the network or write to your home folder. Inside the Codex or Claude command sandbox, the scripts change nothing and say what to do instead.
61
62
  - **What it leaves alone.** macOS 13.5 or later. It doesn't use sudo, register anything to start at login, change your shell config or PATH, or touch a Node.js you installed yourself. Logs are in `~/.m2canvas/logs/`.
62
- - **Uninstall** with `curl -fsSL https://m2ui.ai/connect/uninstall.sh | sh`, or "Uninstall local connection" in the Local Agent tab's ⋯ menu. It stops the bridge and removes what the installer added; `~/.m2canvas/workspace` is kept if it has files in it, and your agents' M2 settings stay as they are.
63
+ - **Uninstall** with "Uninstall local connection" in the Local Agent tab's ⋯ menu, or `curl -fsSL https://m2ui.ai/connect/uninstall.sh | sh`. It stops the bridge and removes what the installer added; `~/.m2canvas/workspace` is kept if it has files in it, and your agents' M2 settings stay as they are. While a bridge started this way (0.8.0 or later) is running, M2 asks it to uninstall itself: it stops its agents, runs the same uninstaller (shipped in this package as `install/uninstall.sh`), reports what happened to M2, and exits. Only a paired page can ask, and it can't pass anything that changes what gets removed. Otherwise M2 offers the M2 app, an agent app or the Terminal command.
63
64
 
64
65
  The `npx` command above still works and is what M2 shows under "Advanced", for running the bridge in a folder you choose.
@@ -14,7 +14,7 @@
14
14
  * - 安装目录名带 lockfile 哈希:换了 lockfile 就是新目录,旧目录不会被半新半旧地复用。旧目录目前不清理(FU-2026-10-02-120)。
15
15
  * - 先装到临时目录、写好就绪标记再原子改名;残留的临时目录或没有标记的目录一律视为未安装。
16
16
  * - 升级 Claude 适配器时复核 bundledClaudePath 与 SDK 自身的解析规则是否仍一致(acp-terminal-free-auth evidence/sdk-binary-resolution.md),
17
- * 并按新版本实测 installedBytes。
17
+ * 并按新版本实测 installedBytes 与 downloadBytes。
18
18
  */
19
19
  import { createHash, randomBytes } from 'node:crypto';
20
20
  import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
@@ -29,6 +29,7 @@ export const ADAPTERS = {
29
29
  version: '0.84.0',
30
30
  entry: 'node_modules/@agentclientprotocol/claude-agent-acp/dist/index.js',
31
31
  installedBytes: 268_451_230,
32
+ downloadBytes: 106_768_111,
32
33
  },
33
34
  codex: {
34
35
  dir: 'codex-acp',
@@ -36,6 +37,7 @@ export const ADAPTERS = {
36
37
  version: '2.1.0',
37
38
  entry: 'node_modules/@agentclientprotocol/codex-acp/dist/index.js',
38
39
  installedBytes: 346_221_434,
40
+ downloadBytes: 135_994_489,
39
41
  },
40
42
  };
41
43
  /** 适配器自带的 codex:预检与授权命令都要用它(本机旧版 codex 存的凭证,新版本刷新不了,PoC 报告 §2.2) */
@@ -136,6 +138,7 @@ export class AdapterManager {
136
138
  options;
137
139
  installing = new Map();
138
140
  lastError = new Map();
141
+ stopped = false;
139
142
  progress = new Map();
140
143
  constructor(options) {
141
144
  this.options = options;
@@ -166,10 +169,19 @@ export class AdapterManager {
166
169
  const error = this.lastError.get(agent);
167
170
  return error ? { ...base, state: 'failed', error } : { ...base, state: 'not_installed', error: null };
168
171
  }
172
+ /**
173
+ * bridge 在卸载自己(change bridge-uninstall-from-page 实现中发现 I1):之后不再开始新的安装。
174
+ * 安装第一步就 mkdir 临时目录,会把刚被卸载脚本删掉的 `~/.m2canvas` 重建出来;进行中的 npm ci 由调用方 killActiveExecs 结束。
175
+ */
176
+ stopInstalling() {
177
+ this.stopped = true;
178
+ }
169
179
  /** 已就绪直接返回;正在装就等同一次安装;否则开始安装。失败不抛错,返回 state = failed */
170
180
  prepare(agent) {
171
181
  if (this.isReady(agent))
172
182
  return Promise.resolve(this.info(agent));
183
+ if (this.stopped)
184
+ return Promise.resolve({ ...this.info(agent), state: 'failed', error: 'the bridge is uninstalling itself' });
173
185
  const running = this.installing.get(agent);
174
186
  if (running)
175
187
  return running;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * bridge 方法的分派(从 server.ts 拆出):未配对只放行 pair,其余按方法交给 service / ProcessManager / auth-call.ts。
3
+ * 连接状态(是否已配对、连接是否还在)只在 server.ts 里改,这里经 ctx 的回调读写。
4
+ *
5
+ * 安全边界同 server.ts 文件头:页面可控的参数只有 agent id(枚举校验)、配对码、processId,进不了 spawn 的命令、参数、cwd、环境;
6
+ * agent/authorize 与 agent/authorize-cancel 的参数校验在 auth-call.ts。
7
+ * bridge/uninstall 不经过这里:server.ts 在调用 handleCall 之前就把它交给 uninstall-call.ts(它要等回复写出再关连接、退出)。
8
+ */
9
+ import { isBridgeAgentId } from './agents.js';
10
+ import { handleAuthCall } from './auth-call.js';
11
+ import { handlePairCall } from './pair-call.js';
12
+ import { TOKEN_IDLE_DAYS } from './pairing.js';
13
+ import { ProcessError } from './processes.js';
14
+ import { BridgeFailure } from './service.js';
15
+ export async function handleCall(ctx, conn, id, method, params) {
16
+ if (method === 'pair') {
17
+ const token = handlePairCall(ctx.pairing, conn.origin, params);
18
+ ctx.markPaired(conn.id);
19
+ ctx.log(`Paired with ${conn.origin}.`);
20
+ return { token, cwd: ctx.cwd, idleExpiryDays: TOKEN_IDLE_DAYS };
21
+ }
22
+ if (!conn.paired)
23
+ throw new BridgeFailure('not_paired', 'pair this page first');
24
+ if (method === 'process/stop') {
25
+ const processId = params.processId;
26
+ if (typeof processId !== 'string' || !ctx.processes.stop(conn.id, processId))
27
+ throw new BridgeFailure('process_not_found', 'no such process on this connection');
28
+ return {};
29
+ }
30
+ if (method === 'agents/list')
31
+ return { agents: await ctx.service.list() };
32
+ if (method === 'agent/authorize' || method === 'agent/authorize-cancel')
33
+ return handleAuthCall(ctx.auth, conn.id, method, params);
34
+ const agent = params.agent;
35
+ if (!isBridgeAgentId(agent))
36
+ throw new BridgeFailure('unknown_agent', `unknown agent ${String(agent)}`);
37
+ switch (method) {
38
+ case 'agent/prepare':
39
+ return { agent, adapter: await ctx.service.prepare(agent) };
40
+ case 'agent/precheck':
41
+ // 带连接 id:每条连接第一次查这家可用缓存,之后一律真跑(契约 18)
42
+ return ctx.service.precheck(agent, conn.id);
43
+ case 'm2/configure':
44
+ ctx.log(`Page asked to add M2 to ${agent}'s MCP config.`);
45
+ return { agent, ...(await ctx.service.configure(agent)) };
46
+ case 'process/start': {
47
+ const launch = await ctx.service.launch(agent);
48
+ try {
49
+ const processId = await ctx.processes.start(conn.id, agent, launch);
50
+ // 启动期间页面已断开:没有人会再停它,立刻清理
51
+ if (!ctx.isConnected(conn.id))
52
+ ctx.processes.stopOwner(conn.id);
53
+ ctx.log(`Started ${agent}.`);
54
+ return { processId, agent, cwd: ctx.cwd };
55
+ }
56
+ catch (error) {
57
+ if (error instanceof ProcessError)
58
+ throw new BridgeFailure(error.code, error.message);
59
+ throw error;
60
+ }
61
+ }
62
+ }
63
+ // 未知方法在调用前已被 server.ts 的 isMethod 拦下;走到这里说明 BRIDGE_METHODS 与上面的分支不一致
64
+ throw new BridgeFailure('internal', `unhandled method ${method} (call ${id})`);
65
+ }
@@ -9,12 +9,13 @@
9
9
  * 后台模式(`--background`,只由启动器 `~/.m2canvas/bin/m2-bridge` 使用,change acp-bridge-one-time-install):输出写进日志文件,
10
10
  * 所以不出配对码(契约 2)、不提示「保持窗口打开」;页面经 `welcome.bridge.background` 得知,改走「重新连接」。
11
11
  * 端口上已有认定的 M2 bridge 时以 EXIT_ALREADY_RUNNING 退出,启动器把它当成功。
12
+ * 后台模式且在 macOS 上时还能卸载自己(`bridge/uninstall`,change bridge-uninstall-from-page D2 / D3;执行在 uninstall.ts)。
12
13
  */
13
14
  import { existsSync, readFileSync, statSync } from 'node:fs';
14
15
  import { join } from 'node:path';
15
16
  import { fileURLToPath } from 'node:url';
16
17
  import { home, isExecutable, which } from '../system.js';
17
- import { AdapterManager, ADAPTERS } from './adapters.js';
18
+ import { AdapterManager, ADAPTERS, isAdapterAgent } from './adapters.js';
18
19
  import { BRIDGE_HELP, EXIT_ALREADY_RUNNING, EXIT_PORT_UNAVAILABLE, backgroundLifetimeMs, parseBridgeArgs } from './args.js';
19
20
  import { detectAgent } from './agents.js';
20
21
  import { EXPECT_PATH } from './authorize.js';
@@ -22,17 +23,22 @@ import { buildAgentEnv, buildNpmEnv, buildProbeEnv } from './env.js';
22
23
  import { execCommand, killActiveExecs } from './exec.js';
23
24
  import { createLsofProbe, createPsProbe, createStopDeps, identifyRunningBridge, instanceFilePath, listenWithReplace, processStartedAt, removeInstanceRecord, stopRunningBridge, writeInstanceRecord } from './instance.js';
24
25
  import { handOffCommitment, listenForHandoff } from './handoff.js';
26
+ import { installLayout } from './install-layout.js';
25
27
  import { installShutdownSignals } from './lifecycle.js';
26
28
  import { PairingManager, createFilePairingStore } from './pairing.js';
27
29
  import { BRIDGE_AGENT_IDS, BRIDGE_WS_PATH } from './protocol.js';
28
30
  import { resolveNpmCommand } from './npm-command.js';
29
31
  import { allowedOrigins } from './security.js';
32
+ import { prewarmPrechecks } from './precheck-cache.js';
30
33
  import { selfTestProblems } from './self-test.js';
31
34
  import { runCheckUpdate } from './update-io.js';
32
35
  import { startBridgeServer } from './server.js';
33
36
  import { createAgentService } from './service.js';
34
37
  import { KILL_GRACE_MS } from './processes.js';
38
+ import { createSelfUninstaller, uninstallScriptPath } from './uninstall.js';
35
39
  const NPM_CI_TIMEOUT_MS = 15 * 60 * 1000;
40
+ /** 启动时预热预检的 agent(契约 18;用户 2026-11-04 拍板 B-P1:随包的两家,不管用没用过) */
41
+ const PREWARM_AGENTS = ['claude', 'codex'];
36
42
  const LABELS = {
37
43
  claude: 'Claude Code',
38
44
  codex: 'Codex',
@@ -188,6 +194,9 @@ export async function runBridge(argv) {
188
194
  cliPath: fileURLToPath(new URL('../cli.js', import.meta.url)),
189
195
  platform: process.platform,
190
196
  expectAvailable: () => isExecutable(EXPECT_PATH),
197
+ // 出现过「通过」之后一次真跑没通过:告诉之前可能拿到通过的页面(尽力收回,契约 18)
198
+ onPrecheckRevoked: (result) => server?.broadcast('precheck/updated', result),
199
+ log,
191
200
  });
192
201
  const version = packageVersion();
193
202
  const origins = allowedOrigins(parsed.dev);
@@ -196,6 +205,23 @@ export async function runBridge(argv) {
196
205
  let alreadyRunning = false;
197
206
  /** 最近一次因 Origin 不在白名单被拒的页面(desktop-bridge-launcher D15):交接 socket 的状态查询带回给 M2 Mac 客户端 */
198
207
  let lastRejected = null;
208
+ // 只有启动器从 ~/.m2canvas 拉起的后台 bridge、且在 macOS 上(后台安装只有 macOS,契约 15)才能卸载自己(D2)。
209
+ // 回调里用到的 handoff / stop 在下面才赋值:卸载只会在服务开始监听、它们都已就绪之后被调用
210
+ const uninstaller = parsed.background && process.platform === 'darwin'
211
+ ? createSelfUninstaller({
212
+ scriptPath: uninstallScriptPath(PACKAGE_ROOT),
213
+ home,
214
+ workspace: installLayout(home).workspace,
215
+ env: buildAgentEnv(),
216
+ exec: execCommand,
217
+ exists: existsSync,
218
+ stopInstalling: () => adapters.stopInstalling(),
219
+ killExecs: killActiveExecs,
220
+ forgetSelf: () => removeInstanceRecord(instancePath, process.pid),
221
+ closeHandoff: () => handoff?.close(),
222
+ exit: () => void stop(),
223
+ })
224
+ : undefined;
199
225
  server = await listenWithReplace(() => startBridgeServer({
200
226
  port: parsed.port,
201
227
  cwd: parsed.cwd,
@@ -211,6 +237,7 @@ export async function runBridge(argv) {
211
237
  service,
212
238
  agentEnv: buildAgentEnv(),
213
239
  allowedOrigins: origins,
240
+ uninstall: uninstaller,
214
241
  onOriginRejected: (origin) => {
215
242
  lastRejected = { origin, at: Date.now() };
216
243
  },
@@ -309,6 +336,13 @@ export async function runBridge(argv) {
309
336
  log,
310
337
  });
311
338
  }
339
+ // 预热(契约 18,用户 2026-11-04 拍板 B-P1):信号处理装好之后再起,收尾时 killActiveExecs 能杀掉它的命令;不等它,页面来查会加入
340
+ void prewarmPrechecks({
341
+ agents: PREWARM_AGENTS,
342
+ ready: (agent) => isAdapterAgent(agent) && adapters.isReady(agent),
343
+ warm: (agent) => service.warmPrecheck(agent),
344
+ log,
345
+ });
312
346
  const lifetime = backgroundLifetimeMs(parsed);
313
347
  if (lifetime !== null) {
314
348
  setTimeout(() => {
@@ -0,0 +1,144 @@
1
+ /** 缓存最长可用这么久;之后的第一次查询真跑 */
2
+ export const PRECHECK_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
3
+ /** 用到的缓存比这更旧时,同时在后台复查一次 */
4
+ export const PRECHECK_REFRESH_AFTER_MS = 5 * 60 * 1000;
5
+ /** 能缓存的「通过」:比页面的 precheckPasses 严 —— 登录 unknown、已跳过的 m2 unknown 页面放行,这里都不记 */
6
+ export function isCacheablePrecheck(result) {
7
+ const login = result.login.state;
8
+ const m2 = result.m2.state;
9
+ return (login === 'logged_in' || login === 'not_required') && (m2 === 'ready' || m2 === 'unverified');
10
+ }
11
+ export class PrecheckCache {
12
+ deps;
13
+ slots = new Map();
14
+ /** 每条连接查过哪几家;连接关闭时 forgetConnection */
15
+ asked = new Map();
16
+ sequence = 0;
17
+ constructor(deps) {
18
+ this.deps = deps;
19
+ }
20
+ /** 页面连接上的一次 `agent/precheck` */
21
+ forConnection(connectionId, agent) {
22
+ const asked = this.asked.get(connectionId) ?? new Set();
23
+ this.asked.set(connectionId, asked);
24
+ if (asked.has(agent))
25
+ return this.fresh(agent, 'same page checked again');
26
+ asked.add(agent);
27
+ const slot = this.slot(agent);
28
+ const cached = slot.cached;
29
+ if (cached && this.deps.usable(agent)) {
30
+ const age = this.deps.now() - cached.startedAt;
31
+ // 年龄为负(系统时钟往回拨过)当作过期:不能让它一直「不到 5 分钟」而永不复查(review r1 N2)
32
+ if (age >= 0 && age <= PRECHECK_CACHE_MAX_AGE_MS) {
33
+ const refresh = age > PRECHECK_REFRESH_AFTER_MS;
34
+ this.deps.log(`Precheck of ${agent} for a page: used the result from ${Math.round(age / 1000)}s ago${refresh ? ' (checking again in the background)' : ''}.`);
35
+ if (refresh)
36
+ this.warm(agent, 'background re-check').catch(() => undefined); // 结果与出错由 start 记日志
37
+ slot.passHandedOut = true;
38
+ return Promise.resolve(cached.result);
39
+ }
40
+ }
41
+ if (slot.shared) {
42
+ this.deps.log(`Precheck of ${agent} for a page: joined a check already running.`);
43
+ return slot.shared;
44
+ }
45
+ return this.warm(agent, 'first check for a page');
46
+ }
47
+ /** 独立的一次真跑(同一连接的再查、授权结束后的重查):不加入任何在跑的,结果照常写回 */
48
+ fresh(agent, reason) {
49
+ return this.start(agent, reason);
50
+ }
51
+ /** 可共享的真跑:这家已有一次在跑就加入它,否则起一次 */
52
+ warm(agent, reason) {
53
+ const slot = this.slot(agent);
54
+ if (slot.shared)
55
+ return slot.shared;
56
+ const running = this.start(agent, reason);
57
+ slot.shared = running;
58
+ const clear = () => {
59
+ if (slot.shared === running)
60
+ slot.shared = null;
61
+ };
62
+ running.then(clear, clear);
63
+ return running;
64
+ }
65
+ /** 写配置 / 授权开始时:这家的状态马上要变 */
66
+ invalidate(agent) {
67
+ const slot = this.slot(agent);
68
+ slot.generation += 1;
69
+ slot.cached = null;
70
+ slot.latest = null;
71
+ slot.shared = null;
72
+ }
73
+ forgetConnection(connectionId) {
74
+ this.asked.delete(connectionId);
75
+ }
76
+ slot(agent) {
77
+ let slot = this.slots.get(agent);
78
+ if (!slot) {
79
+ slot = { generation: 0, cached: null, latest: null, lastWrite: 0, passHandedOut: false, shared: null };
80
+ this.slots.set(agent, slot);
81
+ }
82
+ return slot;
83
+ }
84
+ start(agent, reason) {
85
+ const slot = this.slot(agent);
86
+ const run = { sequence: ++this.sequence, generation: slot.generation, startedAt: this.deps.now() };
87
+ return this.deps.run(agent).then((result) => {
88
+ const seconds = ((this.deps.now() - run.startedAt) / 1000).toFixed(1);
89
+ this.deps.log(`Precheck of ${agent} (${reason}): ${verdict(result)} in ${seconds}s.`);
90
+ this.write(agent, run, result);
91
+ // 被更晚开始、已写入的真跑推翻:交出那个更新的结论。不看代数:latest 作废时清空、之后只由作废后开始的真跑写入,必然更新
92
+ const handedOut = run.sequence < slot.lastWrite && slot.latest ? slot.latest : result;
93
+ if (isCacheablePrecheck(handedOut))
94
+ slot.passHandedOut = true;
95
+ return handedOut;
96
+ }, (error) => {
97
+ this.deps.log(`Precheck of ${agent} (${reason}) did not run: ${error instanceof Error ? error.message : String(error)}`);
98
+ // 前置条件不满足:原来的通过不再可信,删掉;不推送 —— 调用方自己会拿到这个错误
99
+ if (this.canWrite(slot, run)) {
100
+ slot.lastWrite = run.sequence;
101
+ slot.cached = null;
102
+ slot.latest = null;
103
+ }
104
+ throw error;
105
+ });
106
+ }
107
+ canWrite(slot, run) {
108
+ return run.generation === slot.generation && run.sequence > slot.lastWrite;
109
+ }
110
+ write(agent, run, result) {
111
+ const slot = this.slot(agent);
112
+ if (!this.canWrite(slot, run))
113
+ return;
114
+ slot.lastWrite = run.sequence;
115
+ slot.latest = result;
116
+ if (isCacheablePrecheck(result)) {
117
+ slot.cached = { result, startedAt: run.startedAt };
118
+ return;
119
+ }
120
+ slot.cached = null;
121
+ if (slot.passHandedOut) {
122
+ slot.passHandedOut = false;
123
+ this.deps.onRevoked(agent, result);
124
+ }
125
+ }
126
+ }
127
+ function verdict(result) {
128
+ return isCacheablePrecheck(result) ? 'passed' : `not passed (sign-in ${result.login.state}, M2 ${result.m2.state})`;
129
+ }
130
+ /**
131
+ * bridge 开始监听之后预热(design D6,用户 2026-11-04 拍板 B-P1:Claude 与 Codex,不管用没用过)。
132
+ * 副作用(契约 8):`claude mcp list` 会启动用户配置的 stdio MCP 并联网,客户端用户同意连接后每次打开客户端都会发生一次。
133
+ * 只在启动时一次,不定时重复;各家并行;失败不抛出。结果与耗时由检查本身记一行(`Precheck of … (startup): …`),
134
+ * 真机的 bridge.log 因此自带每次启动的预检耗时。
135
+ */
136
+ export async function prewarmPrechecks(deps) {
137
+ await Promise.all(deps.agents.map(async (agent) => {
138
+ if (!deps.ready(agent)) {
139
+ deps.log(`Skipped the startup precheck of ${agent}: its adapter isn't installed.`);
140
+ return;
141
+ }
142
+ await deps.warm(agent).catch(() => undefined);
143
+ }));
144
+ }
@@ -10,7 +10,8 @@
10
10
  * - 不调用 ACP authenticate 探测登录:Qoder 未登录时 60 秒不响应(PoC 报告 §2.5)。
11
11
  * - `qodercli mcp list` 会以 `mcp-test-client` 身份连 M2,服务端判成 mcp、不进项目房间(总控 §6):页面不要把这次连接当成 Qoder 会话。
12
12
  * - Cursor 的 m2 授权按目录保存,mcp list 与授权命令都必须在会话 cwd 下执行。
13
- * - Codex 的预检与授权都用适配器自带的 codex(调用方保证适配器已就绪)。
13
+ * - Codex 的预检与授权都用适配器自带的 codex(调用方保证适配器已就绪)。Codex 的 m2 检查先断网跑一次,只有本地就能定的
14
+ * 三种结果直接用,其余联网再跑(`CODEX_OFFLINE_PROXY` 处的说明)。
14
15
  * - Claude 同样用适配器自带的 claude(D9):会话用的就是它,本机那份只决定兜底命令怎么显示。找不到自带程序时报 unknown,
15
16
  * 不退回本机的 claude(否则预检和会话看的是两个程序)。
16
17
  */
@@ -20,6 +21,24 @@ import { ADAPTERS, CODEX_BIN_LINK, CODEX_SCRIPT } from './adapters.js';
20
21
  import { combinedOutput } from './exec.js';
21
22
  import { parseClaudeAuthStatus, parseClaudeMcpList, parseCodexLoginStatus, parseCodexMcpListJson, parseCursorMcpList, parseCursorStatus, parseOpencodeMcpList, parseQoderMcpList, parseQoderStatus, tail, } from './precheck-parse.js';
22
23
  export const PRECHECK_TIMEOUT_MS = 45_000;
24
+ /**
25
+ * Codex 的 m2 检查先断网跑一次(change bridge-precheck-speedup D12)。`codex mcp list --json` 联网时会探测每个还没存凭证的
26
+ * HTTP 服务器支不支持 OAuth(用户真实环境 3–6.6 秒);而 M2 的 `o_auth`(有本地凭证)、没配置、停用三种状态只由本地配置与凭证决定,
27
+ * 断网结果与联网一致(2026-11-04 隔离实测,`evidence/measurement.md` §1c)。「配了没授权」断网会给 unknown(联网是 not_logged_in),
28
+ * 所以只有这三种直接采用,其余一律联网再跑、以联网为准 —— 结果与只联网逐状态一致,变化只在耗时。
29
+ * 依赖 Codex 的实现细节:升级 Codex 适配器时按该 evidence 的做法重测三种状态(契约 7)。
30
+ */
31
+ export const CODEX_OFFLINE_PROXY = 'http://127.0.0.1:9';
32
+ /**
33
+ * 断网那次实测 0.06 秒;超过这个时限就当没结果、联网再跑。不用更紧的值:新铺的程序第一次运行有约 4 秒的系统扫描
34
+ * (`desktop-bundled-local-runtime` 实测),太紧会让首次 Codex 预检白等一次再联网(review r1 N3)。
35
+ */
36
+ export const CODEX_OFFLINE_TIMEOUT_MS = 10_000;
37
+ const OFFLINE_TRUSTED = new Set(['unverified', 'not_configured', 'needs_enable']);
38
+ function offlineEnv(env) {
39
+ const proxy = CODEX_OFFLINE_PROXY;
40
+ return { ...env, HTTPS_PROXY: proxy, HTTP_PROXY: proxy, ALL_PROXY: proxy, https_proxy: proxy, http_proxy: proxy, all_proxy: proxy, NO_PROXY: '', no_proxy: '' };
41
+ }
23
42
  export function shellQuote(value) {
24
43
  return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
25
44
  }
@@ -74,6 +93,7 @@ function plan(agent, deps) {
74
93
  login: { args: ['login', 'status'], parse: (r) => parseCodexLoginStatus(combinedOutput(r), r.code), next: run(display, ['login']) },
75
94
  m2: {
76
95
  args: ['mcp', 'list', '--json'],
96
+ offlineFirst: true,
77
97
  parse: (r) => parseCodexMcpListJson(r.stdout, r.code),
78
98
  next: (state, entry) => state === 'needs_auth' || state === 'unverified'
79
99
  ? run(display, ['mcp', 'login', entry])
@@ -132,13 +152,23 @@ function plan(agent, deps) {
132
152
  };
133
153
  }
134
154
  }
135
- async function runStep(deps, p, args) {
136
- return deps.exec(p.exec.command, [...p.exec.prefix, ...args], { env: deps.env, cwd: deps.cwd, timeoutMs: PRECHECK_TIMEOUT_MS });
155
+ async function runStep(deps, p, args, options = {}) {
156
+ return deps.exec(p.exec.command, [...p.exec.prefix, ...args], {
157
+ env: options.offline ? offlineEnv(deps.env) : deps.env,
158
+ cwd: deps.cwd,
159
+ timeoutMs: options.offline ? CODEX_OFFLINE_TIMEOUT_MS : PRECHECK_TIMEOUT_MS,
160
+ });
137
161
  }
138
162
  export async function precheckM2(agent, deps) {
139
163
  const p = plan(agent, deps);
140
164
  if (p.missing)
141
165
  return toM2({ state: 'unknown', entry: null, raw: tail(p.missing) }, p.m2.next);
166
+ if (p.m2.offlineFirst) {
167
+ // 断网那次出任何意外(起不来、超时、退出码非 0、认不出),Codex 的解析都给 unknown(退出码不是 0 就不信输出),于是联网再跑
168
+ const offline = p.m2.parse(await runStep(deps, p, p.m2.args, { offline: true }));
169
+ if (OFFLINE_TRUSTED.has(offline.state))
170
+ return toM2(offline, p.m2.next);
171
+ }
142
172
  const result = await runStep(deps, p, p.m2.args);
143
173
  const failure = failed(result);
144
174
  return toM2(failure ? { state: 'unknown', entry: null, raw: failure } : p.m2.parse(result), p.m2.next);
@@ -48,6 +48,8 @@ export class ProcessManager {
48
48
  processes = new Map();
49
49
  /** 已调用 spawn、还没等到 'spawn' 事件的进程(按 owner 计):也要计入上限,否则同一批并发的 start 能突破上限 */
50
50
  starting = new Map();
51
+ /** bridge 在卸载自己:之后不再拉起任何 agent(`close`) */
52
+ closed = false;
51
53
  constructor(options) {
52
54
  this.options = options;
53
55
  }
@@ -71,8 +73,17 @@ export class ProcessManager {
71
73
  else
72
74
  this.starting.delete(ownerId);
73
75
  }
76
+ /**
77
+ * 不再拉起新的 agent(bridge 卸载自己时调用,change bridge-uninstall-from-page review r1 N1):卸载开始前已在途、
78
+ * 还卡在检测阶段的 process/start 之后走到这里也会被拒,不会在卸载脚本运行时从正在被删的适配器目录拉起 agent。已在跑的由调用方停。
79
+ */
80
+ close() {
81
+ this.closed = true;
82
+ }
74
83
  /** 等到子进程真正启动('spawn' 事件)才返回,启动失败(如 ENOENT)以 ProcessError 拒绝 */
75
84
  start(ownerId, agent, launch) {
85
+ if (this.closed)
86
+ return Promise.reject(new ProcessError('spawn_failed', 'the bridge is shutting down and starts no new agents'));
76
87
  if (this.countFor(ownerId) >= (this.options.maxPerOwner ?? MAX_PROCESSES_PER_OWNER)) {
77
88
  return Promise.reject(new ProcessError('too_many_processes', 'too many agent processes for this page'));
78
89
  }
@@ -73,6 +73,7 @@ export const BRIDGE_METHODS = [
73
73
  'process/stop',
74
74
  'agent/authorize',
75
75
  'agent/authorize-cancel',
76
+ 'bridge/uninstall',
76
77
  ];
77
78
  export const BRIDGE_CLOSE_CODES = {
78
79
  normal: 1000,
@@ -12,6 +12,7 @@ import { existsSync } from 'node:fs';
12
12
  import { join } from 'node:path';
13
13
  import { ADAPTERS } from './adapters.js';
14
14
  import { bundledNpmCli } from './npm-command.js';
15
+ import { uninstallScriptPath } from './uninstall.js';
15
16
  /** 返回发现的问题(英文,写进 update.log);空数组 = 通过 */
16
17
  export function selfTestProblems(input) {
17
18
  const exists = input.exists ?? existsSync;
@@ -26,5 +27,9 @@ export function selfTestProblems(input) {
26
27
  const npm = bundledNpmCli(input.execPath);
27
28
  if (!exists(npm))
28
29
  problems.push(`missing ${npm}`);
30
+ // bridge/uninstall 运行的就是它(change bridge-uninstall-from-page D3):缺了就不切换到这个版本
31
+ const uninstaller = uninstallScriptPath(input.packageRoot);
32
+ if (!exists(uninstaller))
33
+ problems.push(`missing ${uninstaller}`);
29
34
  return problems;
30
35
  }
@@ -9,8 +9,9 @@
9
9
  * - 握手后第一条消息必须是 hello;未配对的连接只能调用 pair,其余已知方法与 acp 帧一律 not_paired。
10
10
  * 连接只有两种方式成为已配对:hello 带有效 token,或 hello 的 pairSecret 与启动命令的承诺一致(pairing.ts 文件头)。
11
11
  * - bridge 自己的方法里,页面可控的参数只有 agent id(枚举校验)、授权动作(枚举校验)、配对码、processId —— 进不了 spawn 的命令、参数、cwd、环境。
12
- * agent/authorize 与 agent/authorize-cancel 的 params 只能有规定的键,多一个就 bad_message(分派在 auth-call.ts,命令清单写死在 authorize.ts)。
12
+ * 方法分派在 call-dispatch.ts;agent/authorize 与 agent/authorize-cancel 的 params 只能有规定的键,多一个就 bad_message(auth-call.ts,命令清单写死在 authorize.ts)。
13
13
  * - 页面发给 agent 的 ACP 行禁止含换行,并经 acp-guard.ts 检查:只能用白名单里的方法、会话目录固定为 bridge 的 cwd、不能让 agent 额外拉起 MCP 服务器。
14
+ * - bridge/uninstall(0.8.0,uninstall-call.ts):开始后拒绝新连接与一切其他帧(握手与配对会写盘、重建 ~/.m2canvas),端口占到退出,结果回出去后退出。
14
15
  *
15
16
  * 边界:bridge 不解析 agent 发来的 ACP,不判断用户是否开通了本地 Agent(change 4 / 3 负责)。
16
17
  * 登录 / m2 授权只代跑写死清单里的命令,授权页由用户在浏览器里亲自完成(authorize.ts);授权链接只发给发起的连接,不进终端日志。
@@ -18,16 +19,14 @@
18
19
  import { createServer } from 'node:http';
19
20
  import { randomUUID } from 'node:crypto';
20
21
  import { WebSocketServer } from 'ws';
21
- import { TOKEN_IDLE_DAYS } from './pairing.js';
22
- import { ProcessError, ProcessManager } from './processes.js';
23
- import { isBridgeAgentId } from './agents.js';
24
- import { handleAuthCall } from './auth-call.js';
25
- import { handlePairCall } from './pair-call.js';
22
+ import { KILL_GRACE_MS, ProcessManager } from './processes.js';
23
+ import { handleCall } from './call-dispatch.js';
26
24
  import { AuthorizationManager } from './authorize.js';
27
25
  import { BRIDGE_CLOSE_CODES, BRIDGE_METHODS, BRIDGE_SUPPORTED_PROTOCOLS, } from './protocol.js';
28
26
  import { checkPageAcpLine } from './acp-guard.js';
29
27
  import { checkUpgrade } from './security.js';
30
28
  import { BridgeFailure } from './service.js';
29
+ import { startUninstall } from './uninstall-call.js';
31
30
  export const HELLO_TIMEOUT_MS = 10_000;
32
31
  export const UNPAIRED_TIMEOUT_MS = 10 * 60 * 1000;
33
32
  export const MAX_UNPAIRED_CONNECTIONS = 4;
@@ -42,7 +41,7 @@ function isMethod(value) {
42
41
  return typeof value === 'string' && BRIDGE_METHODS.includes(value);
43
42
  }
44
43
  function rejectUpgrade(socket, status) {
45
- const text = status === 403 ? 'Forbidden' : 'Not Found';
44
+ const text = status === 403 ? 'Forbidden' : status === 404 ? 'Not Found' : 'Service Unavailable';
46
45
  socket.end(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
47
46
  socket.destroy();
48
47
  }
@@ -59,6 +58,10 @@ export function startBridgeServer(options) {
59
58
  conn.ws.send(JSON.stringify(frame));
60
59
  };
61
60
  const sendError = (conn, id, error) => send(conn, { type: 'error', id, error });
61
+ /** 等数据写进 socket 再完成:bridge/uninstall 回复之后紧接着关连接、退出 */
62
+ const sendAndWait = (conn, frame) => new Promise((done) => (conn.ws.readyState === conn.ws.OPEN ? conn.ws.send(JSON.stringify(frame), () => done()) : done()));
63
+ /** bridge/uninstall 已开始(D3 ⓪):不再接受新连接,已有连接上的其他帧一律拒绝 */
64
+ let uninstalling = false;
62
65
  const processes = new ProcessManager({
63
66
  env: options.agentEnv,
64
67
  cwd: options.cwd,
@@ -97,6 +100,16 @@ export function startBridgeServer(options) {
97
100
  send(owner, { type: 'event', event: 'auth/link', data });
98
101
  },
99
102
  };
103
+ const uninstallContext = {
104
+ uninstaller: options.uninstall,
105
+ processes,
106
+ authorizations,
107
+ killGraceMs: options.timing?.killGraceMs ?? KILL_GRACE_MS,
108
+ stopAccepting: () => {
109
+ uninstalling = true;
110
+ },
111
+ log,
112
+ };
100
113
  const unpairedCount = () => [...connections.values()].filter((conn) => !conn.paired).length;
101
114
  const markPaired = (conn) => {
102
115
  conn.paired = true;
@@ -104,56 +117,20 @@ export function startBridgeServer(options) {
104
117
  clearTimeout(conn.timer);
105
118
  conn.timer = null;
106
119
  };
107
- async function handleCall(conn, id, method, params) {
108
- if (method === 'pair') {
109
- const token = handlePairCall(options.pairing, conn.origin, params);
110
- markPaired(conn);
111
- log(`Paired with ${conn.origin}.`);
112
- return { token, cwd: options.cwd, idleExpiryDays: TOKEN_IDLE_DAYS };
113
- }
114
- if (!conn.paired)
115
- throw new BridgeFailure('not_paired', 'pair this page first');
116
- if (method === 'process/stop') {
117
- const processId = params.processId;
118
- if (typeof processId !== 'string' || !processes.stop(conn.id, processId))
119
- throw new BridgeFailure('process_not_found', 'no such process on this connection');
120
- return {};
121
- }
122
- if (method === 'agents/list')
123
- return { agents: await options.service.list() };
124
- if (method === 'agent/authorize' || method === 'agent/authorize-cancel')
125
- return handleAuthCall(authContext, conn.id, method, params);
126
- const agent = params.agent;
127
- if (!isBridgeAgentId(agent))
128
- throw new BridgeFailure('unknown_agent', `unknown agent ${String(agent)}`);
129
- switch (method) {
130
- case 'agent/prepare':
131
- return { agent, adapter: await options.service.prepare(agent) };
132
- case 'agent/precheck':
133
- return options.service.precheck(agent);
134
- case 'm2/configure':
135
- log(`Page asked to add M2 to ${agent}'s MCP config.`);
136
- return { agent, ...(await options.service.configure(agent)) };
137
- case 'process/start': {
138
- const launch = await options.service.launch(agent);
139
- try {
140
- const processId = await processes.start(conn.id, agent, launch);
141
- // 启动期间页面已断开:没有人会再停它,立刻清理
142
- if (!connections.has(conn.id))
143
- processes.stopOwner(conn.id);
144
- log(`Started ${agent}.`);
145
- return { processId, agent, cwd: options.cwd };
146
- }
147
- catch (error) {
148
- if (error instanceof ProcessError)
149
- throw new BridgeFailure(error.code, error.message);
150
- throw error;
151
- }
152
- }
153
- }
154
- // 未知方法在调用前已被 isMethod 拦下;走到这里说明 BRIDGE_METHODS 与上面的分支不一致
155
- throw new BridgeFailure('internal', `unhandled method ${method} (call ${id})`);
156
- }
120
+ const callContext = {
121
+ cwd: options.cwd,
122
+ pairing: options.pairing,
123
+ service: options.service,
124
+ processes,
125
+ auth: authContext,
126
+ log,
127
+ isConnected: (connectionId) => connections.has(connectionId),
128
+ markPaired: (connectionId) => {
129
+ const conn = connections.get(connectionId);
130
+ if (conn)
131
+ markPaired(conn);
132
+ },
133
+ };
157
134
  function onHello(conn, frame) {
158
135
  const protocols = Array.isArray(frame.protocols) ? frame.protocols.filter((value) => typeof value === 'number') : [];
159
136
  if (frame.type !== 'hello' || protocols.length === 0) {
@@ -222,6 +199,13 @@ export function startBridgeServer(options) {
222
199
  catch {
223
200
  frame = null;
224
201
  }
202
+ if (uninstalling) {
203
+ // 卸载开始后:不再握手(带 token 的 hello 会刷新使用时间、写配对文件),也不再处理任何调用
204
+ if (!conn.hello)
205
+ return conn.ws.close(BRIDGE_CLOSE_CODES.goingAway, 'bridge is uninstalling');
206
+ const id = isObject(frame) && typeof frame.id === 'string' && frame.id.length > 0 && frame.id.length <= MAX_CALL_ID ? frame.id : null;
207
+ return sendError(conn, id, { code: 'uninstalling', message: 'this bridge is uninstalling itself' });
208
+ }
225
209
  if (!conn.hello) {
226
210
  if (isObject(frame))
227
211
  onHello(conn, frame);
@@ -257,7 +241,13 @@ export function startBridgeServer(options) {
257
241
  if (!isMethod(method))
258
242
  return sendError(conn, id, { code: 'unknown_method', message: `unknown method ${String(method)}` });
259
243
  const params = isObject(frame.params) ? frame.params : {};
260
- handleCall(conn, id, method, params).then((result) => send(conn, { type: 'result', id, result }), (error) => {
244
+ if (method === 'bridge/uninstall') {
245
+ const refusal = startUninstall(uninstallContext, { paired: conn.paired, params: frame.params, reply: (result) => sendAndWait(conn, { type: 'result', id, result }) });
246
+ if (refusal)
247
+ sendError(conn, id, refusal);
248
+ return;
249
+ }
250
+ handleCall(callContext, conn, id, method, params).then((result) => send(conn, { type: 'result', id, result }), (error) => {
261
251
  if (error instanceof BridgeFailure)
262
252
  sendError(conn, id, { code: error.code, message: error.message, ...(error.data === undefined ? {} : { data: error.data }) });
263
253
  else {
@@ -275,6 +265,9 @@ export function startBridgeServer(options) {
275
265
  });
276
266
  const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES });
277
267
  http.on('upgrade', (req, socket, head) => {
268
+ // 卸载开始后不再接受新连接;监听本身留到退出才关 —— 端口一直占着,卸载期间被拉起的新 bridge 撞端口、认不出而退出(review r1 S1)
269
+ if (uninstalling)
270
+ return rejectUpgrade(socket, 503);
278
271
  const port = http.address()?.port ?? options.port;
279
272
  const decision = checkUpgrade({ origin: req.headers.origin, host: req.headers.host, remoteAddress: req.socket.remoteAddress, path: req.url }, port, options.allowedOrigins);
280
273
  if (!decision.ok) {
@@ -311,6 +304,7 @@ export function startBridgeServer(options) {
311
304
  connections.delete(conn.id);
312
305
  processes.stopOwner(conn.id);
313
306
  authorizations.cancelOwner(conn.id);
307
+ options.service.forgetConnection(conn.id);
314
308
  });
315
309
  // ws 的错误(非法帧、超过 maxPayload 等)之后必然紧跟 'close',清理在 close 里做;这里只防止未处理的 error 事件让进程崩溃
316
310
  ws.on('error', () => undefined);
@@ -14,6 +14,10 @@
14
14
  * 授权(change acp-terminal-free-auth):authorizePlan 按写死清单生成命令(authorize.ts),m2 的配置项名只取 bridge 自己的 m2 预检:
15
15
  * 优先用最近一次预检 / 写配置时得到的名字(D19,页面先预检才会显示按钮,省掉一次重跑 —— Claude 的 `mcp list` 实测约 5 秒),没有记录时重跑;
16
16
  * 预检 / 写配置的结果按同一判据带上 `authorize` 能力,页面只在能力存在时才调用 agent/authorize。
17
+ *
18
+ * 预检缓存(change bridge-precheck-speedup,契约 18,规则在 precheck-cache.ts):带连接 id 的预检是页面的 `agent/precheck`,
19
+ * 每条连接第一次查某家可以用缓存;不带的(授权结束后的重查)一律真跑并写回。写配置、授权在**开始运行之前**作废这家的缓存 ——
20
+ * 前置条件不满足而什么都没运行时不作废。缓存存不带能力的原始结果,给出时再按当前判据加 `authorize`。
17
21
  */
18
22
  import { dirname, join } from 'node:path';
19
23
  import { ADAPTERS, isAdapterAgent } from './adapters.js';
@@ -23,6 +27,7 @@ import { authCapability, buildAuthPlan, isSafeAuthEntry } from './authorize.js';
23
27
  import { prependPath } from './env.js';
24
28
  import { combinedOutput } from './exec.js';
25
29
  import { precheckAgent, precheckM2 } from './precheck.js';
30
+ import { PrecheckCache } from './precheck-cache.js';
26
31
  import { BRIDGE_AGENT_IDS, } from './protocol.js';
27
32
  export const CONFIGURE_TIMEOUT_MS = 120_000;
28
33
  /**
@@ -92,6 +97,18 @@ export function createAgentService(deps) {
92
97
  login: withCapability(result.login, result.agent, 'login'),
93
98
  m2: withCapability(result.m2, result.agent, 'm2'),
94
99
  });
100
+ const precheckCache = new PrecheckCache({
101
+ run: async (agent) => {
102
+ const result = await precheckAgent(await ready(agent), precheckDeps);
103
+ remember(agent, result.m2);
104
+ return result;
105
+ },
106
+ // 只看文件状态、不起子进程;原生 agent 的检测要跑命令行,不在给缓存前做(拉起时 launch 会报 agent_not_installed)
107
+ usable: (agent) => !isAdapterAgent(agent) || deps.adapters.isReady(agent),
108
+ now: deps.now ?? Date.now,
109
+ onRevoked: (_agent, result) => deps.onPrecheckRevoked?.(withCapabilities(result)),
110
+ log: deps.log ?? (() => undefined),
111
+ });
95
112
  /** D10:clients.ts 只认 PATH 上能跑起来的 claude / codex */
96
113
  function configureEnv(agent) {
97
114
  const node = dirname(deps.nodePath);
@@ -130,13 +147,21 @@ export function createAgentService(deps) {
130
147
  }
131
148
  return info;
132
149
  },
133
- async precheck(agent) {
134
- const result = await precheckAgent(await ready(agent), precheckDeps);
135
- remember(agent, result.m2);
150
+ async precheck(agent, connectionId) {
151
+ // 不带连接的只有授权结束后的重查(auth-call.ts):一律新起一次真跑,不加入授权期间别的连接起的共享真跑(契约 12 delta)
152
+ const result = connectionId === undefined ? await precheckCache.fresh(agent, 'after sign-in or M2 authorization') : await precheckCache.forConnection(connectionId, agent);
136
153
  return withCapabilities(result);
137
154
  },
155
+ async warmPrecheck(agent) {
156
+ return precheckCache.warm(agent, 'startup');
157
+ },
158
+ forgetConnection(connectionId) {
159
+ precheckCache.forgetConnection(connectionId);
160
+ },
138
161
  async configure(agent) {
139
162
  const detected = await ready(agent);
163
+ // 马上要写配置:这家的预检结果不再可信(契约 18)
164
+ precheckCache.invalidate(agent);
140
165
  const result = await deps.exec(deps.nodePath, [deps.cliPath, '--client', CLIENT_ID[agent], '--yes'], {
141
166
  env: configureEnv(agent),
142
167
  cwd: deps.cwd,
@@ -165,6 +190,9 @@ export function createAgentService(deps) {
165
190
  const detected = await ready(agent);
166
191
  if (!capability(agent, action))
167
192
  throw new BridgeFailure('auth_unavailable', `the bridge cannot run ${verb} for ${agent}; use the terminal command instead`);
193
+ // 取计划之后就运行授权命令(AuthorizationManager.run):登录 / 授权状态马上要变,先作废缓存(契约 18)。
194
+ // 下面因配置项名缺失而 auth_unavailable 时也已作废 —— 没运行任何命令,多一次真跑无害
195
+ precheckCache.invalidate(agent);
168
196
  let entry = null;
169
197
  if (action === 'm2') {
170
198
  // 配置项名不一定叫 m2,也不能由页面指定:用 bridge 最近一次预检的结果,没有就重跑(D19);OpenCode 总是重跑(D21)
@@ -0,0 +1,47 @@
1
+ async function stopAgents(ctx) {
2
+ ctx.processes.close();
3
+ ctx.authorizations.killAllNow();
4
+ ctx.processes.stopAll();
5
+ const deadline = Date.now() + ctx.killGraceMs;
6
+ while (ctx.processes.size > 0 && Date.now() < deadline)
7
+ await new Promise((resolve) => setTimeout(resolve, 100));
8
+ ctx.processes.killAllNow();
9
+ }
10
+ async function perform(ctx, uninstaller, request) {
11
+ ctx.stopAccepting();
12
+ ctx.log('Page asked to uninstall the M2 bridge. No longer accepting pages; stopping agents…');
13
+ try {
14
+ uninstaller.begin();
15
+ await stopAgents(ctx);
16
+ let result;
17
+ try {
18
+ result = await uninstaller.run();
19
+ }
20
+ catch (error) {
21
+ ctx.log(`Uninstall failed with an internal error: ${error instanceof Error ? error.message : String(error)}`);
22
+ result = { outcome: 'failed', kept: null, message: 'M2 bridge: the uninstall stopped because of an internal error. Run the uninstall command in Terminal.' };
23
+ }
24
+ ctx.log(`Uninstall ${result.outcome}: ${result.message}`);
25
+ await request.reply(result);
26
+ }
27
+ finally {
28
+ uninstaller.exit();
29
+ }
30
+ }
31
+ /** 开始卸载;不能开始时返回要回给页面的错误(什么都不做) */
32
+ export function startUninstall(ctx, request) {
33
+ if (!request.paired)
34
+ return { code: 'not_paired', message: 'pair this page first' };
35
+ // 只能省略或是空对象:null、数组、字符串都不当成 {};自有属性一个都不能有(`__proto__` 之类的也算)—— 页面不能传任何影响卸载的东西
36
+ const { params } = request;
37
+ const empty = params === undefined || (typeof params === 'object' && params !== null && !Array.isArray(params) && Object.keys(params).length === 0);
38
+ if (!empty)
39
+ return { code: 'bad_message', message: 'bridge/uninstall takes no params' };
40
+ const uninstaller = ctx.uninstaller;
41
+ if (!uninstaller)
42
+ return { code: 'uninstall_unavailable', message: 'only a bridge started in the background by the M2 launcher on macOS can uninstall itself' };
43
+ // stopAccepting 在 perform 的同步部分执行:本函数返回之前,后续到达的帧已经会被拒。
44
+ // 兜住意外的 rejection:未处理的 rejection 会让 bridge 直接退出,跳过收尾
45
+ perform(ctx, uninstaller, request).catch((error) => ctx.log(`Uninstall failed with an internal error: ${error instanceof Error ? error.message : String(error)}`));
46
+ return null;
47
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * `bridge/uninstall` 在 main 一侧的执行(change bridge-uninstall-from-page D3 ②③④):bridge 运行随包发布的卸载脚本卸载自己。
3
+ * 门槛、停止接受新连接、停 agent、回复与退出在 server.ts / uninstall-call.ts;本文件只管「怎么跑脚本、怎么读结果」。
4
+ *
5
+ * 不在 TypeScript 里再写一份删除逻辑:删除范围只有 `install/uninstall.sh` 一份实现(`connect/local-bridge` 契约 15「卸载脚本」),
6
+ * 终端、agent 应用、M2 Mac 客户端运行的是 m2ui.ai 上它的逐字副本(`connect:install-assets -- --check` 锁住)。
7
+ *
8
+ * 维护约束:
9
+ * - **先删自己的状态文件,再运行脚本。** 脚本只停它能从状态文件找到的 M2 bridge(`--stop` 发 SIGTERM);自己的还在,
10
+ * 脚本就会停掉自己,收尾会先关掉全部连接 —— 页面收不到结果。删不掉就不运行脚本,如实回 failed。
11
+ * - **脚本会删掉 bridge 自己所在的安装目录**(含正在运行的 node 与已加载的模块,verification §3 实测仍能回复):
12
+ * 本文件与卸载之后会走到的代码都只能用静态 import,不得动态加载模块(删除后会 ERR_MODULE_NOT_FOUND)。
13
+ * - 脚本用白名单环境运行(调用方传 `buildAgentEnv()`):里面没有沙箱标记,脚本不会误判自己在 agent 沙箱里(grep-summary §3)。
14
+ */
15
+ import { join } from 'node:path';
16
+ /** 脚本对每个还在运行的 bridge 最多等 8 + 3 秒(`--stop`);通常只有自己,而自己已从状态文件里拿掉 */
17
+ export const UNINSTALL_SCRIPT_TIMEOUT_MS = 60_000;
18
+ /** 页面只显示一行,太长的截掉 */
19
+ const MAX_MESSAGE_CHARS = 1000;
20
+ const RESULT_PREFIX = 'M2 bridge:';
21
+ /** 包内卸载脚本的位置(`package.json` 的 files 带上了它) */
22
+ export function uninstallScriptPath(packageRoot) {
23
+ return join(packageRoot, 'install', 'uninstall.sh');
24
+ }
25
+ function clip(message) {
26
+ return message.length > MAX_MESSAGE_CHARS ? `${message.slice(0, MAX_MESSAGE_CHARS - 3)}...` : message;
27
+ }
28
+ /** 输出里最后一行以 `M2 bridge:` 开头的(契约 15:脚本的结果行) */
29
+ function resultLine(output) {
30
+ const lines = output
31
+ .split('\n')
32
+ .map((line) => line.trim())
33
+ .filter((line) => line.startsWith(RESULT_PREFIX));
34
+ return lines[lines.length - 1] ?? null;
35
+ }
36
+ /** 按退出码与结果行组结果:退出 0 才算卸载了;超时、没能运行、没有结果行都写 bridge 自己的说明,不留空 */
37
+ export function uninstallResult(exec, kept, timeoutMs = UNINSTALL_SCRIPT_TIMEOUT_MS) {
38
+ const line = resultLine(exec.stdout) ?? resultLine(exec.stderr);
39
+ if (exec.code === 0)
40
+ return { outcome: 'uninstalled', kept, message: clip(line ?? `${RESULT_PREFIX} uninstalled.`) };
41
+ if (exec.timedOut) {
42
+ return { outcome: 'failed', kept, message: `${RESULT_PREFIX} the uninstaller didn't finish within ${Math.round(timeoutMs / 1000)} seconds. Run the uninstall command in Terminal.` };
43
+ }
44
+ if (exec.code === null && exec.signal) {
45
+ return { outcome: 'failed', kept, message: `${RESULT_PREFIX} the uninstaller was stopped (${exec.signal}). Run the uninstall command in Terminal.` };
46
+ }
47
+ if (exec.code === null)
48
+ return { outcome: 'failed', kept, message: `${RESULT_PREFIX} couldn't run the uninstaller. Run the uninstall command in Terminal.` };
49
+ return { outcome: 'failed', kept, message: clip(line ?? `${RESULT_PREFIX} the uninstaller exited with code ${exec.code}. Run the uninstall command in Terminal.`) };
50
+ }
51
+ /** 不抛出:任何一步出错都变成 failed 结果,server 照常回复并退出 */
52
+ export async function runSelfUninstall(deps) {
53
+ deps.stopCommands();
54
+ try {
55
+ deps.forgetSelf();
56
+ }
57
+ catch {
58
+ return {
59
+ outcome: 'failed',
60
+ kept: null,
61
+ message: `${RESULT_PREFIX} couldn't remove its own state file, so it didn't run the uninstaller. Run the uninstall command in Terminal.`,
62
+ };
63
+ }
64
+ try {
65
+ deps.closeHandoff();
66
+ }
67
+ catch {
68
+ // socket 文件删不掉不影响卸载:脚本会把停掉的 bridge 的 socket 一并删掉
69
+ }
70
+ const timeoutMs = deps.timeoutMs ?? UNINSTALL_SCRIPT_TIMEOUT_MS;
71
+ const result = await deps.exec('/bin/sh', [deps.scriptPath], { env: deps.env, cwd: deps.home, timeoutMs, maxOutput: 64 * 1024 });
72
+ return uninstallResult(result, deps.exists(deps.workspace) ? deps.workspace : null, timeoutMs);
73
+ }
74
+ /**
75
+ * main 提供给 server 的卸载能力(review r1 S2 / S3:接线抽成可单测的工厂)。
76
+ * begin 在 ⓪ 就停新安装、杀一次性命令(与停止接受新连接同时);run 在 ② 再来一遍,收掉 ① 期间才走到这里的在途调用。
77
+ */
78
+ export function createSelfUninstaller(deps) {
79
+ const stopCommands = () => {
80
+ deps.stopInstalling();
81
+ deps.killExecs();
82
+ };
83
+ return {
84
+ begin: stopCommands,
85
+ run: () => runSelfUninstall({ ...deps, stopCommands }),
86
+ exit: deps.exit,
87
+ };
88
+ }
@@ -0,0 +1,125 @@
1
+ #!/bin/sh
2
+ # M2 local connection uninstaller: https://m2ui.ai/connect/uninstall.sh
3
+ # curl -fsSL https://m2ui.ai/connect/uninstall.sh | sh
4
+ #
5
+ # What it does:
6
+ # 1. Stops the M2 bridge if one is running (only a bridge it can recognize, and only with
7
+ # SIGTERM, so it shuts down its agents cleanly).
8
+ # 2. Removes what the installer put in ~/.m2canvas: runtime, bridge, bin, logs, acp-adapters,
9
+ # the pairing records, the bridge state files, pairing-handoff sockets and leftover
10
+ # handoff files.
11
+ # 3. Removes ~/.m2canvas/workspace only if it is empty; otherwise keeps it and prints its path.
12
+ # Removes ~/.m2canvas itself only if nothing else is left in it.
13
+ # It does not touch your agents' M2 settings (set up by npx @m2canvas/connect, they work
14
+ # without the bridge) or any Node.js you installed yourself.
15
+ #
16
+ # Maintenance: keep this file ASCII-only, POSIX sh, and write every variable as ${VAR}.
17
+ # The layout must match packages/connect/src/bridge/install-layout.ts.
18
+ # The source is packages/connect/install/uninstall.sh; it ships in the npm package (a running bridge uses it
19
+ # to uninstall itself) and public/connect/uninstall.sh is a generated copy (npm run connect:install-assets).
20
+
21
+ say() {
22
+ printf 'M2 bridge: %s\n' "$*"
23
+ }
24
+
25
+ main() {
26
+ if [ -n "${CODEX_SANDBOX:-}" ]; then
27
+ say "Codex is running this command in its sandbox, where files in your home folder can't be removed. In Codex, switch the permission mode to Full access and run it again, or run it in Terminal."
28
+ exit 0
29
+ fi
30
+ if [ "${SANDBOX_RUNTIME:-}" = "1" ]; then
31
+ say "Claude is running this command in its sandbox, where files in your home folder can't be removed. Run this exact command again outside the sandbox."
32
+ exit 1
33
+ fi
34
+ case "${HOME:-}" in
35
+ /?*) ;;
36
+ *)
37
+ say "HOME is not set."
38
+ exit 1
39
+ ;;
40
+ esac
41
+
42
+ M2_HOME="${HOME}/.m2canvas"
43
+ if [ ! -d "${M2_HOME}" ]; then
44
+ say "nothing to uninstall."
45
+ exit 0
46
+ fi
47
+
48
+ # 1. Stop running bridges with the installed bridge itself (it knows how to recognize one).
49
+ CURRENT="$(readlink "${M2_HOME}/bridge/current" 2>/dev/null)"
50
+ NODE="$(cat "${M2_HOME}/bridge/${CURRENT}/node-path" 2>/dev/null)"
51
+ CLI="${M2_HOME}/bridge/${CURRENT}/node_modules/@m2canvas/connect/dist/cli.js"
52
+ # A bridge that didn't stop keeps its state file, so a later --replace can still recognize it.
53
+ STILL_RUNNING=""
54
+ if [ -n "${CURRENT}" ] && [ -x "${NODE}" ] && [ -f "${CLI}" ]; then
55
+ for STATE in "${M2_HOME}"/bridge-*.json; do
56
+ [ -f "${STATE}" ] || continue
57
+ PORT="${STATE##*/bridge-}"
58
+ PORT="${PORT%.json}"
59
+ case "${PORT}" in
60
+ "" | *[!0-9]*) continue ;;
61
+ esac
62
+ if ! "${NODE}" "${CLI}" bridge --stop --port "${PORT}" </dev/null; then
63
+ STILL_RUNNING="${STILL_RUNNING} ${PORT}"
64
+ fi
65
+ done
66
+ else
67
+ # Without a working bridge it can't recognize what is running, so it stops nothing. A state file whose
68
+ # process is still alive is kept and reported (that process may be the bridge); the others are stale.
69
+ echo "The installed bridge is incomplete, so a running bridge (if any) was not stopped."
70
+ for STATE in "${M2_HOME}"/bridge-*.json; do
71
+ [ -f "${STATE}" ] || continue
72
+ PORT="${STATE##*/bridge-}"
73
+ PORT="${PORT%.json}"
74
+ PID="$(sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "${STATE}" | head -n 1)"
75
+ if [ -n "${PID}" ] && kill -0 "${PID}" 2>/dev/null; then
76
+ STILL_RUNNING="${STILL_RUNNING} ${PORT}"
77
+ fi
78
+ done
79
+ fi
80
+
81
+ # 2. Remove what the installer created, and check that it is really gone.
82
+ FAILED=""
83
+ for NAME in runtime bridge bin logs acp-adapters bridge-pairings.json; do
84
+ rm -rf "${M2_HOME:?}/${NAME}"
85
+ if [ -e "${M2_HOME}/${NAME}" ]; then
86
+ FAILED="${FAILED} ${M2_HOME}/${NAME}"
87
+ fi
88
+ done
89
+ # State files and pairing-handoff sockets of the bridges that stopped (a running bridge removes its own socket when it exits).
90
+ for STATE in "${M2_HOME}"/bridge-*.json "${M2_HOME}"/bridge-*.sock; do
91
+ [ -e "${STATE}" ] || continue
92
+ PORT="${STATE##*/bridge-}"
93
+ PORT="${PORT%.*}"
94
+ case " ${STILL_RUNNING} " in
95
+ *" ${PORT} "*) continue ;;
96
+ esac
97
+ rm -f "${STATE}"
98
+ done
99
+ # One-time pairing-handoff files: the process that wrote one removes it within seconds, so any left over is stale.
100
+ rm -f "${M2_HOME}"/handoff-*.pending
101
+
102
+ # 3. Keep the workspace if anything is in it (the agents may have created files there).
103
+ KEPT=""
104
+ if [ -d "${M2_HOME}/workspace" ] && ! rmdir "${M2_HOME}/workspace" 2>/dev/null; then
105
+ KEPT="${M2_HOME}/workspace"
106
+ fi
107
+ rmdir "${M2_HOME}" 2>/dev/null
108
+
109
+ # The last line is what the agent repeats to the user: it must not claim success that didn't happen.
110
+ if [ -n "${FAILED}" ]; then
111
+ say "couldn't remove${FAILED}. Remove them yourself, or run this again."
112
+ exit 1
113
+ fi
114
+ if [ -n "${STILL_RUNNING}" ]; then
115
+ say "uninstalled, but the M2 bridge on port${STILL_RUNNING} is still running. Restart your Mac to stop it."
116
+ exit 1
117
+ fi
118
+ if [ -n "${KEPT}" ]; then
119
+ say "uninstalled. Kept ${KEPT} because it has files in it; delete it yourself if you don't need them."
120
+ else
121
+ say "uninstalled."
122
+ fi
123
+ }
124
+
125
+ main "$@"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@m2canvas/connect",
3
- "version": "0.7.3",
3
+ "version": "0.9.0",
4
4
  "description": "Connect your local agent clients (Claude Code, Codex, Cursor, OpenCode, Qoder) to M2 Canvas over MCP in one command, and run the local bridge that lets M2 drive them over ACP.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,7 +8,8 @@
8
8
  },
9
9
  "files": [
10
10
  "dist",
11
- "adapters"
11
+ "adapters",
12
+ "install/uninstall.sh"
12
13
  ],
13
14
  "engines": {
14
15
  "node": ">=18"