@yitom/acp-client 0.1.7 → 0.1.9

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/dist/index.js CHANGED
@@ -162,7 +162,323 @@ function findBuiltinAcpRuntime(id) {
162
162
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
163
163
  }
164
164
  // src/version.ts
165
- var ACP_CLIENT_VERSION = "0.1.7";
165
+ var ACP_CLIENT_VERSION = "0.1.9";
166
+ // src/client/sdk-client.ts
167
+ import { PassThrough, Readable, Writable } from "node:stream";
168
+ import {
169
+ client as createSdkClientApp,
170
+ ndJsonStream
171
+ } from "@agentclientprotocol/sdk";
172
+ var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
173
+ function createSdkStreamHandle(child) {
174
+ const stdoutBridge = new PassThrough;
175
+ const stdinBridge = new PassThrough;
176
+ child.stdout.pipe(stdoutBridge);
177
+ stdinBridge.pipe(child.stdin, { end: false });
178
+ const output = Writable.toWeb(stdinBridge);
179
+ const input = Readable.toWeb(stdoutBridge);
180
+ const stream = ndJsonStream(output, input);
181
+ let disposed = false;
182
+ return {
183
+ stream,
184
+ dispose: () => {
185
+ if (disposed)
186
+ return;
187
+ disposed = true;
188
+ try {
189
+ child.stdout.unpipe(stdoutBridge);
190
+ } catch {}
191
+ try {
192
+ stdinBridge.unpipe(child.stdin);
193
+ } catch {}
194
+ try {
195
+ stdoutBridge.destroy();
196
+ } catch {}
197
+ try {
198
+ stdinBridge.destroy();
199
+ } catch {}
200
+ }
201
+ };
202
+ }
203
+ function connectSdkClient(child, configure, runtimeId) {
204
+ if (runtimeId && true) {
205
+ console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
206
+ }
207
+ const app = createSdkClientApp({ name: "inkdown" });
208
+ configure(app);
209
+ const streamHandle = createSdkStreamHandle(child);
210
+ const connection = app.connect(streamHandle.stream);
211
+ return { app, connection, streamHandle };
212
+ }
213
+ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
214
+ const controller = new AbortController;
215
+ let timer;
216
+ try {
217
+ const pending = agent.request(method, params, {
218
+ cancellationSignal: controller.signal
219
+ });
220
+ const timeout = new Promise((_, reject) => {
221
+ timer = setTimeout(() => {
222
+ controller.abort();
223
+ reject(new Error(`请求超时: ${method}`));
224
+ }, timeoutMs);
225
+ timer.unref?.();
226
+ });
227
+ return await Promise.race([pending, timeout]);
228
+ } finally {
229
+ if (timer !== undefined)
230
+ clearTimeout(timer);
231
+ }
232
+ }
233
+ async function closeAcpSessions(agent, sessionIds, timeoutMs = 2000) {
234
+ const failed = [];
235
+ await Promise.all([...new Set(sessionIds)].map(async (sessionId) => {
236
+ try {
237
+ await sdkRequest(agent, "session/close", { sessionId }, timeoutMs);
238
+ } catch {
239
+ failed.push(sessionId);
240
+ }
241
+ }));
242
+ return failed;
243
+ }
244
+
245
+ // src/resources/session-config.ts
246
+ import { existsSync } from "node:fs";
247
+ import { mkdtemp, mkdir, writeFile, readdir, readFile, lstat, realpath, rm } from "node:fs/promises";
248
+ import { tmpdir } from "node:os";
249
+ import { join as join2, resolve, relative, isAbsolute as isAbsolute2, sep } from "node:path";
250
+
251
+ // src/resources/app-resources.ts
252
+ import { createHash } from "node:crypto";
253
+ import { readdirSync, readFileSync, statSync } from "node:fs";
254
+ import { isAbsolute, join } from "node:path";
255
+ var APP_RULES_FILE = "AGENTS.md";
256
+ var APP_SKILLS_DIR = "skills";
257
+ var APP_SKILL_FILE = "SKILL.md";
258
+ function parseSkillFrontmatter(text) {
259
+ const lines = text.split(`
260
+ `);
261
+ if (lines[0]?.trim() !== "---")
262
+ return {};
263
+ const out = {};
264
+ for (let i = 1;i < lines.length; i += 1) {
265
+ const line = lines[i] ?? "";
266
+ if (line.trim() === "---")
267
+ break;
268
+ const cut = line.indexOf(":");
269
+ if (cut <= 0)
270
+ continue;
271
+ const key = line.slice(0, cut).trim().toLowerCase();
272
+ if (key !== "name" && key !== "description")
273
+ continue;
274
+ const value = line.slice(cut + 1).trim().replace(/^['"]|['"]$/g, "");
275
+ if (value)
276
+ out[key] = value;
277
+ }
278
+ return out;
279
+ }
280
+ function sha256Hex(text) {
281
+ return createHash("sha256").update(text, "utf8").digest("hex");
282
+ }
283
+ function readTextFile(path) {
284
+ try {
285
+ if (!statSync(path).isFile())
286
+ return null;
287
+ const text = readFileSync(path, "utf8");
288
+ return text.trim() ? text : null;
289
+ } catch {
290
+ return null;
291
+ }
292
+ }
293
+ function readAppResourcesDir(directory) {
294
+ const warnings = [];
295
+ if (!isAbsolute(directory))
296
+ return { directoryReadable: false, rules: null, skills: [], warnings: ["资源目录必须是本机绝对路径"] };
297
+ let directoryReadable = false;
298
+ try {
299
+ directoryReadable = statSync(directory).isDirectory();
300
+ } catch {
301
+ directoryReadable = false;
302
+ }
303
+ if (!directoryReadable) {
304
+ return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
305
+ }
306
+ let rules = null;
307
+ const rulesText = readTextFile(join(directory, APP_RULES_FILE));
308
+ if (rulesText === null) {
309
+ warnings.push(`缺常驻规则: ${APP_RULES_FILE}`);
310
+ } else {
311
+ rules = { chars: rulesText.length, digest: sha256Hex(`app-rules-v1
312
+ ${rulesText}`) };
313
+ }
314
+ const skills = [];
315
+ const skillsRoot = join(directory, APP_SKILLS_DIR);
316
+ let skillNames = [];
317
+ try {
318
+ if (statSync(skillsRoot).isDirectory()) {
319
+ skillNames = readdirSync(skillsRoot).filter((name) => {
320
+ try {
321
+ return statSync(join(skillsRoot, name)).isDirectory();
322
+ } catch {
323
+ return false;
324
+ }
325
+ });
326
+ }
327
+ } catch {
328
+ skillNames = [];
329
+ }
330
+ for (const name of skillNames.sort()) {
331
+ const rel = `${APP_SKILLS_DIR}/${name}/${APP_SKILL_FILE}`;
332
+ const text = readTextFile(join(directory, rel));
333
+ if (text === null) {
334
+ warnings.push(`技能缺正文已跳过: ${rel}`);
335
+ continue;
336
+ }
337
+ const front = parseSkillFrontmatter(text);
338
+ const skillName = front.name || name;
339
+ if (skills.some((s) => s.name === skillName)) {
340
+ warnings.push(`技能重名已跳过(保留首个): ${skillName}`);
341
+ continue;
342
+ }
343
+ const description = front.description || "";
344
+ skills.push({
345
+ name: skillName,
346
+ description,
347
+ path: rel,
348
+ chars: text.length,
349
+ digest: sha256Hex(`app-skill-v1
350
+ ${skillName}
351
+ ${description}
352
+ ${text}`)
353
+ });
354
+ }
355
+ return { directoryReadable: true, rules, skills, warnings };
356
+ }
357
+ function digestAppResources(load) {
358
+ if (!load.rules)
359
+ return null;
360
+ const skillPart = load.skills.map((s) => `${s.name}:${s.digest}`).join(`
361
+ `);
362
+ return sha256Hex(`app-resources-v1
363
+ ${load.rules.digest}
364
+ ${skillPart}`);
365
+ }
366
+ function readAppRulesText(directory) {
367
+ return readTextFile(join(directory, APP_RULES_FILE));
368
+ }
369
+ function isAbsolutePathLike(path) {
370
+ return isAbsolute(path);
371
+ }
372
+
373
+ // src/resources/session-config.ts
374
+ async function createSessionConfigHome(runtime, resources) {
375
+ if (!isAbsolute2(resources))
376
+ throw new Error("Resources must be an absolute path");
377
+ const id = runtime === "cursor" ? "cursor-cli" : runtime;
378
+ const supported = ["agy", "codex-acp", "claude", "gemini", "copilot", "cursor-cli", "opencode", "opencode-v2"];
379
+ if (!supported.includes(id))
380
+ throw new Error("Session configuration home is not verified for runtime: " + runtime);
381
+ const text = readAppRulesText(resources);
382
+ if (!text)
383
+ throw new Error("Session configuration requires nonempty AGENTS.md");
384
+ const parent = resolve(tmpdir());
385
+ const directory = await mkdtemp(join2(parent, "acp-session-config-"));
386
+ const checkRoot = () => {
387
+ if (resolve(directory) === parent || !resolve(directory).startsWith(parent + sep) || !relative(parent, directory).startsWith("acp-session-config-"))
388
+ throw new Error("Unsafe configuration cleanup target");
389
+ };
390
+ const dispose = async () => {
391
+ checkRoot();
392
+ let failure;
393
+ for (let i = 0;i < 30; i++) {
394
+ try {
395
+ await rm(directory, { recursive: true, force: true });
396
+ return;
397
+ } catch (error) {
398
+ failure = error;
399
+ await new Promise((r) => setTimeout(r, 100));
400
+ }
401
+ }
402
+ throw failure;
403
+ };
404
+ try {
405
+ const config = join2(directory, "config");
406
+ await mkdir(config, { recursive: true, mode: 448 });
407
+ let env;
408
+ let rulesFile;
409
+ let skillsRoot = join2(config, "skills");
410
+ let nativeRules = true;
411
+ if (id === "agy") {
412
+ rulesFile = join2(config, "AGENTS.md");
413
+ env = { AGY_ACP_RESOURCES_DIR: config };
414
+ nativeRules = false;
415
+ } else if (id === "gemini") {
416
+ const root = join2(directory, "home", ".gemini");
417
+ await mkdir(root, { recursive: true, mode: 448 });
418
+ rulesFile = join2(root, "GEMINI.md");
419
+ skillsRoot = join2(root, "skills");
420
+ env = { GEMINI_CLI_HOME: join2(directory, "home") };
421
+ } else if (id === "claude") {
422
+ rulesFile = join2(config, "CLAUDE.md");
423
+ env = { CLAUDE_CONFIG_DIR: config };
424
+ } else if (id === "codex-acp") {
425
+ rulesFile = join2(config, "AGENTS.md");
426
+ env = { CODEX_HOME: config };
427
+ } else if (id === "copilot") {
428
+ rulesFile = join2(config, "copilot-instructions.md");
429
+ env = { COPILOT_HOME: config, COPILOT_CUSTOM_INSTRUCTIONS_DIRS: config, COPILOT_SKILLS_DIRS: skillsRoot };
430
+ await writeFile(join2(config, "AGENTS.md"), text, { mode: 384 });
431
+ } else if (id === "cursor-cli") {
432
+ rulesFile = join2(config, "AGENTS.md");
433
+ env = { CURSOR_CONFIG_DIR: config };
434
+ nativeRules = false;
435
+ } else {
436
+ const root = join2(directory, "xdg-config", "opencode");
437
+ await mkdir(root, { recursive: true, mode: 448 });
438
+ rulesFile = join2(root, "AGENTS.md");
439
+ skillsRoot = join2(root, "skills");
440
+ env = { XDG_CONFIG_HOME: join2(directory, "xdg-config"), XDG_DATA_HOME: join2(directory, "xdg-data"), XDG_CACHE_HOME: join2(directory, "xdg-cache"), XDG_STATE_HOME: join2(directory, "xdg-state") };
441
+ if (id === "opencode")
442
+ env.OPENCODE_CONFIG_DIR = root;
443
+ const skills = id === "opencode" ? { paths: [skillsRoot] } : [skillsRoot];
444
+ await writeFile(join2(root, "opencode.json"), JSON.stringify({ instructions: [rulesFile], skills }), { mode: 384 });
445
+ }
446
+ await writeFile(rulesFile, text, { mode: 384 });
447
+ const input = join2(resources, "skills");
448
+ try {
449
+ const info = await lstat(input);
450
+ if (info.isSymbolicLink() || !info.isDirectory())
451
+ throw new Error("Skill root must be a regular directory");
452
+ const physical = await realpath(input);
453
+ const copy = async (from, to) => {
454
+ await mkdir(to, { recursive: true, mode: 448 });
455
+ for (const entry of await readdir(from, { withFileTypes: true })) {
456
+ const src = join2(from, entry.name);
457
+ const info = await lstat(src);
458
+ if (info.isSymbolicLink())
459
+ throw new Error("Skill symlink is not allowed");
460
+ const actual = await realpath(src);
461
+ const rel = relative(physical, actual);
462
+ if (rel.startsWith(".." + sep) || rel === ".." || isAbsolute2(rel))
463
+ throw new Error("Skill path escapes resources");
464
+ if (info.isDirectory())
465
+ await copy(src, join2(to, entry.name));
466
+ else if (info.isFile() && entry.name.toLowerCase().endsWith(".md"))
467
+ await writeFile(join2(to, entry.name), await readFile(src), { mode: 384 });
468
+ }
469
+ };
470
+ await copy(input, skillsRoot);
471
+ } catch (error) {
472
+ if (error.code !== "ENOENT" || existsSync(input))
473
+ throw error;
474
+ }
475
+ return { directory, env, rulesFile, nativeRules, dispose };
476
+ } catch (error) {
477
+ await dispose();
478
+ throw error;
479
+ }
480
+ }
481
+
166
482
  // src/session/available-commands.ts
167
483
  function normalizeCommand(raw) {
168
484
  if (!raw || typeof raw !== "object")
@@ -412,15 +728,15 @@ import {
412
728
  } from "@agentclientprotocol/sdk";
413
729
 
414
730
  // src/runtimes/codex/quota.ts
415
- import { existsSync as existsSync2, readFileSync } from "node:fs";
416
- import { join as join2 } from "node:path";
731
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
732
+ import { join as join4 } from "node:path";
417
733
  import { spawn } from "node:child_process";
418
734
  import readline from "node:readline";
419
735
 
420
736
  // src/runtimes/codex/codex-auth-preflight.ts
421
- import { existsSync } from "node:fs";
737
+ import { existsSync as existsSync2 } from "node:fs";
422
738
  import { homedir } from "node:os";
423
- import { join } from "node:path";
739
+ import { join as join3 } from "node:path";
424
740
  function emptyAcpAuthPreflight() {
425
741
  return {
426
742
  codexHome: "",
@@ -437,12 +753,12 @@ function resolveCodexHome() {
437
753
  const fromEnv = process.env.CODEX_HOME?.trim();
438
754
  if (fromEnv)
439
755
  return fromEnv;
440
- return join(homedir(), ".codex");
756
+ return join3(homedir(), ".codex");
441
757
  }
442
758
  function probeCodexAuth() {
443
759
  const codexHome = resolveCodexHome();
444
- const hasCodexHome = existsSync(codexHome);
445
- const hasAuthFile = existsSync(join(codexHome, "auth.json"));
760
+ const hasCodexHome = existsSync2(codexHome);
761
+ const hasAuthFile = existsSync2(join3(codexHome, "auth.json"));
446
762
  const hasApiKeyEnv = Boolean(process.env.CODEX_API_KEY?.trim() || process.env.OPENAI_API_KEY?.trim());
447
763
  return {
448
764
  codexHome,
@@ -492,7 +808,7 @@ async function queryCodexAppServer(timeoutMs = 1e4) {
492
808
  };
493
809
  timer = setTimeout(() => cleanup(null), timeoutMs);
494
810
  try {
495
- const cmd = process.platform === "win32" ? "codex" : existsSync2("/mnt/c/Users") ? "codex.exe" : "codex";
811
+ const cmd = process.platform === "win32" ? "codex" : existsSync3("/mnt/c/Users") ? "codex.exe" : "codex";
496
812
  proc = spawn(cmd, ["app-server"], {
497
813
  stdio: ["pipe", "pipe", "pipe"],
498
814
  shell: process.platform === "win32",
@@ -563,13 +879,13 @@ function formatEpochTime(epochSeconds) {
563
879
  }
564
880
  async function probeCodexQuota(options) {
565
881
  const codexHome = resolveCodexHome();
566
- const authPath = join2(codexHome, "auth.json");
882
+ const authPath = join4(codexHome, "auth.json");
567
883
  let accountEmail;
568
884
  let accountPlan = "Codex Free / Local";
569
885
  let isLoggedIn = false;
570
- if (existsSync2(authPath)) {
886
+ if (existsSync3(authPath)) {
571
887
  try {
572
- const authData = JSON.parse(readFileSync(authPath, "utf8"));
888
+ const authData = JSON.parse(readFileSync2(authPath, "utf8"));
573
889
  if (authData.OPENAI_API_KEY) {
574
890
  isLoggedIn = true;
575
891
  accountPlan = "OpenAI API Key";
@@ -660,8 +976,92 @@ async function probeCodexQuota(options) {
660
976
  }
661
977
 
662
978
  // src/runtimes/codex/index.ts
663
- import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
664
- import { join as join5 } from "node:path";
979
+ import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "node:fs/promises";
980
+ import { dirname, join as join7 } from "node:path";
981
+ import { homedir as homedir3 } from "node:os";
982
+ import { existsSync as existsSync5 } from "node:fs";
983
+ import { createHash as createHash2 } from "node:crypto";
984
+
985
+ // src/resources/config-text.ts
986
+ function mergeCodexConfigJson(input) {
987
+ const block = (input.hostBlock ?? "").trim();
988
+ if (!block)
989
+ return { ok: false, reason: "empty-block" };
990
+ const raw = (input.existingRaw ?? "").trim();
991
+ if (!raw) {
992
+ return { ok: true, json: JSON.stringify({ developer_instructions: block }), preservedUserInstructions: false };
993
+ }
994
+ let parsed;
995
+ try {
996
+ parsed = JSON.parse(raw);
997
+ } catch {
998
+ return { ok: false, reason: "invalid-json" };
999
+ }
1000
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1001
+ return { ok: false, reason: "invalid-json" };
1002
+ }
1003
+ const merged = { ...parsed };
1004
+ const existing = merged["developer_instructions"];
1005
+ if (existing === undefined) {
1006
+ merged["developer_instructions"] = block;
1007
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: false };
1008
+ }
1009
+ if (typeof existing !== "string") {
1010
+ return { ok: false, reason: "conflicting-value" };
1011
+ }
1012
+ const kept = existing.trim();
1013
+ merged["developer_instructions"] = kept ? `${block}
1014
+
1015
+ ${kept}` : block;
1016
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: kept !== "" };
1017
+ }
1018
+ function mergeConfigTomlPreserving(input) {
1019
+ const block = (input.replacementBlock ?? "").trim() ? `${input.replacementBlock.trim()}
1020
+ ` : "";
1021
+ if (!input.existingText || !input.existingText.trim())
1022
+ return block;
1023
+ if (/"""|'''/.test(input.existingText) || /^\s*\[.*["'].*\]|^\s*\[\[|^\s*["'](?:model|model_provider)["']\s*=/m.test(input.existingText)) {
1024
+ throw new Error("复杂 TOML 配置需要结构化合并,已保留原文件");
1025
+ }
1026
+ const topKeys = new Set(input.managedTopKeys);
1027
+ const tables = new Set(input.managedTables);
1028
+ const out = [];
1029
+ let inManagedTable = false;
1030
+ let inAnyTable = false;
1031
+ for (const line of input.existingText.split(`
1032
+ `)) {
1033
+ const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(line)?.[1]?.trim() ?? null;
1034
+ if (header !== null) {
1035
+ inAnyTable = true;
1036
+ inManagedTable = tables.has(header);
1037
+ if (!inManagedTable)
1038
+ out.push(line);
1039
+ continue;
1040
+ }
1041
+ if (inManagedTable)
1042
+ continue;
1043
+ if (!inAnyTable) {
1044
+ const key = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1];
1045
+ if (key && topKeys.has(key))
1046
+ continue;
1047
+ }
1048
+ out.push(line);
1049
+ }
1050
+ const kept = out.join(`
1051
+ `).trim();
1052
+ if (!kept)
1053
+ return block;
1054
+ const tableAt = block.search(/^\s*\[/m);
1055
+ if (tableAt < 0)
1056
+ return block + `
1057
+ ` + kept + `
1058
+ `;
1059
+ return block.slice(0, tableAt).trimEnd() + `
1060
+
1061
+ ` + kept + `
1062
+
1063
+ ` + block.slice(tableAt);
1064
+ }
665
1065
 
666
1066
  // src/runtimes/codex/codex-provider-home.ts
667
1067
  var INKDOWN_PROVIDER_ID = "inkdown-custom";
@@ -693,13 +1093,13 @@ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
693
1093
  }
694
1094
 
695
1095
  // src/runtimes/codex/codex-provider.ts
696
- import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
697
- import { existsSync as existsSync3 } from "node:fs";
698
- import { join as join4 } from "node:path";
1096
+ import { mkdir as mkdir2, readFile as readFile2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
1097
+ import { existsSync as existsSync4 } from "node:fs";
1098
+ import { join as join6 } from "node:path";
699
1099
 
700
1100
  // src/client/acp-paths.ts
701
1101
  import { homedir as homedir2 } from "node:os";
702
- import { join as join3 } from "node:path";
1102
+ import { join as join5 } from "node:path";
703
1103
  function getDefaultAgentDataDir() {
704
1104
  if (process.env.INKDOWN_DATA_DIR) {
705
1105
  return process.env.INKDOWN_DATA_DIR;
@@ -708,20 +1108,20 @@ function getDefaultAgentDataDir() {
708
1108
  return process.env.ACP_DATA_DIR;
709
1109
  }
710
1110
  if (process.platform === "win32") {
711
- return process.env.LOCALAPPDATA || process.env.APPDATA || join3(homedir2(), "AppData", "Local", "inkdown");
1111
+ return process.env.LOCALAPPDATA || process.env.APPDATA || join5(homedir2(), "AppData", "Local", "inkdown");
712
1112
  }
713
1113
  if (process.platform === "darwin") {
714
- return join3(homedir2(), "Library", "Application Support", "inkdown");
1114
+ return join5(homedir2(), "Library", "Application Support", "inkdown");
715
1115
  }
716
- return process.env.XDG_DATA_HOME || join3(homedir2(), ".local", "share", "inkdown");
1116
+ return process.env.XDG_DATA_HOME || join5(homedir2(), ".local", "share", "inkdown");
717
1117
  }
718
1118
 
719
1119
  // src/runtimes/codex/codex-provider.ts
720
1120
  function providerFilePath(dir) {
721
- return join4(dir, "agent", "provider.json");
1121
+ return join6(dir, "agent", "provider.json");
722
1122
  }
723
1123
  function providerHomePath(dir) {
724
- return join4(dir, "agent", "codex-home");
1124
+ return join6(dir, "agent", "codex-home");
725
1125
  }
726
1126
  function toStatus(stored) {
727
1127
  if (!stored)
@@ -747,10 +1147,10 @@ function validate(payload) {
747
1147
  }
748
1148
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
749
1149
  const file = providerFilePath(dir);
750
- if (!existsSync3(file))
1150
+ if (!existsSync4(file))
751
1151
  return null;
752
1152
  try {
753
- const raw = JSON.parse(await readFile(file, "utf8"));
1153
+ const raw = JSON.parse(await readFile2(file, "utf8"));
754
1154
  if (typeof raw.baseUrl !== "string" || typeof raw.model !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
755
1155
  return null;
756
1156
  }
@@ -776,7 +1176,7 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
776
1176
  const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
777
1177
  if (!apiKey)
778
1178
  return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
779
- await mkdir(join4(dir, "agent"), { recursive: true });
1179
+ await mkdir2(join6(dir, "agent"), { recursive: true });
780
1180
  const stored = {
781
1181
  name: payload.name?.trim() || undefined,
782
1182
  baseUrl: payload.baseUrl.trim(),
@@ -784,11 +1184,11 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
784
1184
  apiKey,
785
1185
  wireApi: payload.wireApi === "responses" ? "responses" : "chat"
786
1186
  };
787
- await writeFile(file, JSON.stringify(stored, null, 2), "utf8");
1187
+ await writeFile2(file, JSON.stringify(stored, null, 2), "utf8");
788
1188
  return ok(toStatus(stored));
789
1189
  }
790
1190
  async function clearAcpProvider(dir = getDefaultAgentDataDir()) {
791
- await rm(providerFilePath(dir), { force: true });
1191
+ await rm2(providerFilePath(dir), { force: true });
792
1192
  return ok(undefined);
793
1193
  }
794
1194
  function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
@@ -798,8 +1198,20 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
798
1198
  // src/runtimes/codex/index.ts
799
1199
  async function provisionCustomProviderCodexHome(provider, codexHome) {
800
1200
  try {
801
- await mkdir2(codexHome, { recursive: true });
802
- await writeFile2(join5(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
1201
+ await mkdir3(codexHome, { recursive: true });
1202
+ let existing = null;
1203
+ try {
1204
+ existing = await readFile3(join7(codexHome, "config.toml"), "utf8");
1205
+ } catch (error) {
1206
+ if (error.code !== "ENOENT")
1207
+ throw error;
1208
+ }
1209
+ await writeFile3(join7(codexHome, "config.toml"), mergeConfigTomlPreserving({
1210
+ existingText: existing,
1211
+ managedTopKeys: ["model", "model_provider"],
1212
+ managedTables: [`model_providers.${INKDOWN_PROVIDER_ID}`],
1213
+ replacementBlock: buildCustomProviderConfigToml(provider)
1214
+ }), "utf8");
803
1215
  return true;
804
1216
  } catch (error) {
805
1217
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -809,6 +1221,78 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
809
1221
  var codexAdapter = {
810
1222
  id: "codex-acp",
811
1223
  probeQuota: async (options) => probeCodexQuota(options),
1224
+ supportedBridgeVersions: ["2.2.2"],
1225
+ prepareAppResources: async ({ directory, workspaceRoot, env: overrideEnv }) => {
1226
+ const load = readAppResourcesDir(directory);
1227
+ const skillsFound = load.skills.map((s) => s.name);
1228
+ const rulesText = readAppRulesText(directory);
1229
+ if (!rulesText) {
1230
+ return {
1231
+ report: {
1232
+ rulesApplied: false,
1233
+ rulesChars: 0,
1234
+ profileDigest: null,
1235
+ skillsFound,
1236
+ reason: "rules-missing"
1237
+ }
1238
+ };
1239
+ }
1240
+ const env = { ...process.env, ...overrideEnv };
1241
+ const notApplied = (reason) => ({ report: {
1242
+ rulesApplied: false,
1243
+ rulesPrepared: false,
1244
+ skillsApplied: false,
1245
+ rulesChars: rulesText.length,
1246
+ profileDigest: digestAppResources(load),
1247
+ skillsFound,
1248
+ reason
1249
+ } });
1250
+ if (!load.directoryReadable)
1251
+ return notApplied("invalid-resource-directory");
1252
+ if (env.CODEX_PATH)
1253
+ return notApplied("execution-not-verified");
1254
+ const codexHome = env.CODEX_HOME || join7(homedir3(), ".codex");
1255
+ try {
1256
+ await readFile3(join7(codexHome, "config.toml"));
1257
+ return notApplied("effective-config-not-verified");
1258
+ } catch (error) {
1259
+ if (error.code !== "ENOENT")
1260
+ return notApplied("effective-config-not-verified");
1261
+ }
1262
+ for (let dir = workspaceRoot;dir; ) {
1263
+ if (existsSync5(join7(dir, ".codex", "config.toml")))
1264
+ return notApplied("effective-config-not-verified");
1265
+ if (existsSync5(join7(dir, ".git")))
1266
+ break;
1267
+ const parent = dirname(dir);
1268
+ if (parent === dir)
1269
+ break;
1270
+ dir = parent;
1271
+ }
1272
+ const merged = mergeCodexConfigJson({ existingRaw: env["CODEX_CONFIG"], hostBlock: rulesText });
1273
+ if (!merged.ok) {
1274
+ return {
1275
+ report: {
1276
+ rulesApplied: false,
1277
+ rulesChars: rulesText.length,
1278
+ profileDigest: digestAppResources(load),
1279
+ skillsFound,
1280
+ reason: merged.reason === "invalid-json" ? "invalid-codex-config" : "conflicting-codex-config"
1281
+ }
1282
+ };
1283
+ }
1284
+ return {
1285
+ env: { CODEX_CONFIG: merged.json },
1286
+ report: {
1287
+ rulesApplied: false,
1288
+ rulesPrepared: true,
1289
+ skillsApplied: false,
1290
+ rulesChars: rulesText.length,
1291
+ profileDigest: createHash2("sha256").update(JSON.stringify([digestAppResources(load), codexHome, workspaceRoot, merged.json])).digest("hex"),
1292
+ skillsFound
1293
+ }
1294
+ };
1295
+ },
812
1296
  probeAuth: () => {
813
1297
  return probeCodexAuth();
814
1298
  },
@@ -825,11 +1309,84 @@ var codexAdapter = {
825
1309
  }
826
1310
  };
827
1311
 
828
- // src/runtimes/claude/quota.ts
829
- import { existsSync as existsSync4, readFileSync as readFileSync2 } from "node:fs";
830
- import { homedir as homedir3 } from "node:os";
831
- import { join as join6 } from "node:path";
1312
+ // src/resources/runtime-bindings.ts
1313
+ import { join as join8 } from "node:path";
832
1314
  import { execFile } from "node:child_process";
1315
+ import { promisify } from "node:util";
1316
+ var APP_RESOURCE_CAPABILITIES = {
1317
+ "codex-acp": { entry: "CODEX_CONFIG", strategy: "native-overlay", configHome: "CODEX_HOME" },
1318
+ opencode: { entry: "OPENCODE_CONFIG_CONTENT", strategy: "native-overlay", configHome: "OPENCODE_CONFIG_DIR" },
1319
+ "opencode-v2": { entry: null, strategy: "compatibility", configHome: null },
1320
+ claude: { entry: "_meta.systemPrompt + _meta.claudeCode.options.plugins", strategy: "native-session", configHome: "CLAUDE_CONFIG_DIR" },
1321
+ gemini: { entry: null, strategy: "compatibility", configHome: "GEMINI_CLI_HOME" },
1322
+ copilot: { entry: null, strategy: "compatibility", configHome: "COPILOT_HOME", candidateEntry: "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" },
1323
+ "cursor-cli": { entry: null, strategy: "compatibility", configHome: "CURSOR_CONFIG_DIR" },
1324
+ agy: { entry: "_meta.appResources.directory", strategy: "native-session", configHome: null },
1325
+ deepseek: { entry: null, strategy: "compatibility", configHome: null }
1326
+ };
1327
+ function prepareCompatibilityResources(directory, reason) {
1328
+ const load = readAppResourcesDir(directory);
1329
+ return { report: {
1330
+ rulesApplied: false,
1331
+ rulesPrepared: false,
1332
+ skillsApplied: false,
1333
+ rulesChars: load.rules?.chars ?? 0,
1334
+ profileDigest: digestAppResources(load),
1335
+ skillsFound: load.skills.map((s) => s.name),
1336
+ reason
1337
+ } };
1338
+ }
1339
+ function mergeOpenCodeAppConfig(raw, directory) {
1340
+ const value = raw?.trim() ? JSON.parse(raw) : {};
1341
+ if (!value || typeof value !== "object" || Array.isArray(value))
1342
+ throw new Error("invalid-opencode-config");
1343
+ const config = value;
1344
+ if (config.instructions !== undefined && (!Array.isArray(config.instructions) || config.instructions.some((v) => typeof v !== "string")))
1345
+ throw new Error("invalid-opencode-instructions");
1346
+ if (config.skills !== undefined && (!config.skills || typeof config.skills !== "object" || Array.isArray(config.skills)))
1347
+ throw new Error("invalid-opencode-skills");
1348
+ const skills = config.skills ?? {};
1349
+ if (skills.paths !== undefined && (!Array.isArray(skills.paths) || skills.paths.some((v) => typeof v !== "string")))
1350
+ throw new Error("invalid-opencode-skill-paths");
1351
+ return JSON.stringify({
1352
+ ...config,
1353
+ instructions: [...new Set([...config.instructions ?? [], join8(directory, "AGENTS.md")])],
1354
+ skills: { ...skills, paths: [...new Set([...skills.paths ?? [], join8(directory, "skills")])] }
1355
+ });
1356
+ }
1357
+ async function prepareOpenCodeResources(input) {
1358
+ const prep = prepareCompatibilityResources(input.directory, "native-entry-not-verified");
1359
+ if (!input.command || !readAppRulesText(input.directory))
1360
+ return prep;
1361
+ try {
1362
+ const { stdout } = await promisify(execFile)(input.command, ["--version"], { env: input.env, timeout: 8000, windowsHide: true });
1363
+ if (stdout.trim() !== "1.18.35")
1364
+ return prep;
1365
+ const json = mergeOpenCodeAppConfig(input.env?.OPENCODE_CONFIG_CONTENT, input.directory);
1366
+ return { env: { OPENCODE_CONFIG_CONTENT: json }, report: { ...prep.report, rulesPrepared: true, reason: undefined } };
1367
+ } catch {
1368
+ return { ...prep, report: { ...prep.report, reason: "native-config-prepare-failed" } };
1369
+ }
1370
+ }
1371
+ function prepareClaudeResources(directory) {
1372
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
1373
+ return { ...prep, report: { ...prep.report, rulesPrepared: !!readAppRulesText(directory) } };
1374
+ }
1375
+ function claudeResourceSessionMeta(directory) {
1376
+ const text = readAppRulesText(directory);
1377
+ if (!text)
1378
+ return;
1379
+ return {
1380
+ systemPrompt: { type: "preset", preset: "claude_code", append: text },
1381
+ claudeCode: { options: { plugins: [{ type: "local", path: directory }] } }
1382
+ };
1383
+ }
1384
+
1385
+ // src/runtimes/claude/quota.ts
1386
+ import { existsSync as existsSync6, readFileSync as readFileSync3 } from "node:fs";
1387
+ import { homedir as homedir4 } from "node:os";
1388
+ import { join as join9 } from "node:path";
1389
+ import { execFile as execFile2 } from "node:child_process";
833
1390
  var cachedClaudeAuth = null;
834
1391
  async function queryClaudeAuthStatus(timeoutMs = 1200) {
835
1392
  if (cachedClaudeAuth && Date.now() - cachedClaudeAuth.time < 30000) {
@@ -837,7 +1394,7 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
837
1394
  }
838
1395
  return new Promise((resolve) => {
839
1396
  try {
840
- execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
1397
+ execFile2("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
841
1398
  if (!stdout)
842
1399
  return resolve(null);
843
1400
  try {
@@ -855,15 +1412,15 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
855
1412
  }
856
1413
  async function probeClaudeQuota(options) {
857
1414
  const claudeHome = resolveClaudeHome();
858
- const claudeJsonPath = join6(homedir3(), ".claude.json");
859
- const credsPath = join6(claudeHome, ".credentials.json");
1415
+ const claudeJsonPath = join9(homedir4(), ".claude.json");
1416
+ const credsPath = join9(claudeHome, ".credentials.json");
860
1417
  let isLoggedIn = false;
861
1418
  let isBanned = false;
862
1419
  let accountEmail;
863
1420
  let plan = "Claude Free / Default";
864
- if (existsSync4(claudeJsonPath)) {
1421
+ if (existsSync6(claudeJsonPath)) {
865
1422
  try {
866
- const data = JSON.parse(readFileSync2(claudeJsonPath, "utf8"));
1423
+ const data = JSON.parse(readFileSync3(claudeJsonPath, "utf8"));
867
1424
  if (data.oauthAccount) {
868
1425
  isLoggedIn = true;
869
1426
  accountEmail = data.oauthAccount.emailAddress;
@@ -874,9 +1431,9 @@ async function probeClaudeQuota(options) {
874
1431
  }
875
1432
  } catch {}
876
1433
  }
877
- if (existsSync4(credsPath)) {
1434
+ if (existsSync6(credsPath)) {
878
1435
  try {
879
- const creds = JSON.parse(readFileSync2(credsPath, "utf8"));
1436
+ const creds = JSON.parse(readFileSync3(credsPath, "utf8"));
880
1437
  if (creds.accessToken || creds.sessionKey)
881
1438
  isLoggedIn = true;
882
1439
  } catch {}
@@ -928,19 +1485,19 @@ async function probeClaudeQuota(options) {
928
1485
  }
929
1486
 
930
1487
  // src/runtimes/claude/index.ts
931
- import { existsSync as existsSync5 } from "node:fs";
932
- import { homedir as homedir4 } from "node:os";
933
- import { join as join7 } from "node:path";
1488
+ import { existsSync as existsSync7 } from "node:fs";
1489
+ import { homedir as homedir5 } from "node:os";
1490
+ import { join as join10 } from "node:path";
934
1491
  function resolveClaudeHome() {
935
1492
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
936
1493
  if (fromEnv)
937
1494
  return fromEnv;
938
- return join7(homedir4(), ".claude");
1495
+ return join10(homedir5(), ".claude");
939
1496
  }
940
1497
  function probeClaudeAuth() {
941
1498
  const claudeHome = resolveClaudeHome();
942
- const hasCodexHome = existsSync5(claudeHome);
943
- const hasAuthFile = existsSync5(join7(homedir4(), ".claude.json")) || existsSync5(join7(claudeHome, ".credentials.json"));
1499
+ const hasCodexHome = existsSync7(claudeHome);
1500
+ const hasAuthFile = existsSync7(join10(homedir5(), ".claude.json")) || existsSync7(join10(claudeHome, ".credentials.json"));
944
1501
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
945
1502
  return {
946
1503
  codexHome: claudeHome,
@@ -952,6 +1509,9 @@ function probeClaudeAuth() {
952
1509
  }
953
1510
  var claudeAdapter = {
954
1511
  id: "claude",
1512
+ supportedBridgeVersions: ["0.91.0"],
1513
+ prepareAppResources: async ({ directory }) => prepareClaudeResources(directory),
1514
+ appResourceSessionMeta: claudeResourceSessionMeta,
955
1515
  probeAuth: () => probeClaudeAuth(),
956
1516
  probeQuota: async (options) => probeClaudeQuota(options),
957
1517
  orderAuthMethods: (methods) => methods,
@@ -959,16 +1519,16 @@ var claudeAdapter = {
959
1519
  };
960
1520
 
961
1521
  // src/runtimes/gemini/index.ts
962
- import { existsSync as existsSync6 } from "node:fs";
963
- import { homedir as homedir5 } from "node:os";
964
- import { join as join8 } from "node:path";
1522
+ import { existsSync as existsSync8 } from "node:fs";
1523
+ import { homedir as homedir6 } from "node:os";
1524
+ import { join as join11 } from "node:path";
965
1525
  function resolveGeminiHome() {
966
- return join8(homedir5(), ".gemini");
1526
+ return join11(homedir6(), ".gemini");
967
1527
  }
968
1528
  function probeGeminiAuth() {
969
1529
  const geminiHome = resolveGeminiHome();
970
- const hasCodexHome = existsSync6(geminiHome);
971
- const hasAuthFile = existsSync6(join8(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
1530
+ const hasCodexHome = existsSync8(geminiHome);
1531
+ const hasAuthFile = existsSync8(join11(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
972
1532
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
973
1533
  return {
974
1534
  codexHome: geminiHome,
@@ -980,24 +1540,25 @@ function probeGeminiAuth() {
980
1540
  }
981
1541
  var geminiAdapter = {
982
1542
  id: "gemini",
1543
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-would-isolate-auth"),
983
1544
  probeAuth: () => probeGeminiAuth(),
984
1545
  orderAuthMethods: (methods) => methods,
985
1546
  canSkipInteractiveAuth: () => false
986
1547
  };
987
1548
 
988
1549
  // src/runtimes/copilot/index.ts
989
- import { existsSync as existsSync7, readFileSync as readFileSync3 } from "node:fs";
990
- import { homedir as homedir6 } from "node:os";
991
- import { join as join9 } from "node:path";
1550
+ import { existsSync as existsSync9, readFileSync as readFileSync4 } from "node:fs";
1551
+ import { homedir as homedir7 } from "node:os";
1552
+ import { join as join12 } from "node:path";
992
1553
  function resolveCopilotHome() {
993
1554
  const fromEnv = process.env.COPILOT_HOME?.trim();
994
1555
  if (fromEnv)
995
1556
  return fromEnv;
996
- return join9(homedir6(), ".copilot");
1557
+ return join12(homedir7(), ".copilot");
997
1558
  }
998
1559
  function hasCopilotLogin(home) {
999
1560
  try {
1000
- const raw = readFileSync3(join9(home, "config.json"), "utf8");
1561
+ const raw = readFileSync4(join12(home, "config.json"), "utf8");
1001
1562
  const parsed = JSON.parse(raw);
1002
1563
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
1003
1564
  } catch {
@@ -1006,7 +1567,7 @@ function hasCopilotLogin(home) {
1006
1567
  }
1007
1568
  function probeCopilotAuth() {
1008
1569
  const copilotHome = resolveCopilotHome();
1009
- const hasCodexHome = existsSync7(copilotHome);
1570
+ const hasCodexHome = existsSync9(copilotHome);
1010
1571
  const hasAuthFile = hasCopilotLogin(copilotHome);
1011
1572
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
1012
1573
  return {
@@ -1019,20 +1580,21 @@ function probeCopilotAuth() {
1019
1580
  }
1020
1581
  var copilotAdapter = {
1021
1582
  id: "copilot",
1583
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-entry-not-verified"),
1022
1584
  probeAuth: () => probeCopilotAuth(),
1023
1585
  orderAuthMethods: (methods) => methods,
1024
1586
  canSkipInteractiveAuth: () => false
1025
1587
  };
1026
1588
 
1027
1589
  // src/runtimes/opencode/quota.ts
1028
- import { existsSync as existsSync8, readFileSync as readFileSync4 } from "node:fs";
1029
- import { execFile as execFile2 } from "node:child_process";
1590
+ import { existsSync as existsSync10, readFileSync as readFileSync5 } from "node:fs";
1591
+ import { execFile as execFile3 } from "node:child_process";
1030
1592
  import * as os from "node:os";
1031
1593
  import * as path from "node:path";
1032
1594
  function resolveOpencodeAuthPath() {
1033
1595
  const candidates = resolveOpencodeAuthCandidates();
1034
1596
  for (const c of candidates) {
1035
- if (existsSync8(c))
1597
+ if (existsSync10(c))
1036
1598
  return c;
1037
1599
  }
1038
1600
  return candidates[0] ?? null;
@@ -1044,7 +1606,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
1044
1606
  }
1045
1607
  return new Promise((resolve) => {
1046
1608
  try {
1047
- execFile2("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1609
+ execFile3("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1048
1610
  if (!stdout)
1049
1611
  return resolve(null);
1050
1612
  try {
@@ -1063,7 +1625,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
1063
1625
  async function queryOpencodeAuthList(timeoutMs = 1200) {
1064
1626
  return new Promise((resolve) => {
1065
1627
  try {
1066
- execFile2("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1628
+ execFile3("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1067
1629
  if (!stdout)
1068
1630
  return resolve([]);
1069
1631
  const lines = stdout.split(`
@@ -1083,7 +1645,7 @@ function readLocalOpencodeCredentials() {
1083
1645
  path.join(home, ".config", "opencode", "opencode.db")
1084
1646
  ].filter(Boolean);
1085
1647
  for (const dbPath of dbPaths) {
1086
- if (!existsSync8(dbPath))
1648
+ if (!existsSync10(dbPath))
1087
1649
  continue;
1088
1650
  try {
1089
1651
  let rows = [];
@@ -1112,7 +1674,7 @@ function readLocalOpencodeCredentials() {
1112
1674
  }
1113
1675
  } catch {
1114
1676
  try {
1115
- const buf = readFileSync4(dbPath, "utf8");
1677
+ const buf = readFileSync5(dbPath, "utf8");
1116
1678
  const emailMatch = buf.match(/"email"\s*:\s*"([^"]+)"/);
1117
1679
  const tokenMatch = buf.match(/"access"\s*:\s*"(st_[a-zA-Z0-9_\\-]+)"/);
1118
1680
  const orgMatch = buf.match(/"orgID"\s*:\s*"(wrk_[a-zA-Z0-9_\\-]+)"/);
@@ -1236,9 +1798,9 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1236
1798
  let accountEmail = dbCreds.email;
1237
1799
  let accountName = dbCreds.name;
1238
1800
  let plan = "OpenCode Community";
1239
- if (authPath && existsSync8(authPath)) {
1801
+ if (authPath && existsSync10(authPath)) {
1240
1802
  try {
1241
- const data = JSON.parse(readFileSync4(authPath, "utf8"));
1803
+ const data = JSON.parse(readFileSync5(authPath, "utf8"));
1242
1804
  if (data && typeof data === "object") {
1243
1805
  const keys = Object.keys(data);
1244
1806
  if (keys.length > 0) {
@@ -1298,16 +1860,16 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1298
1860
  }
1299
1861
 
1300
1862
  // src/runtimes/opencode/index.ts
1301
- import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
1302
- import { homedir as homedir8 } from "node:os";
1303
- import { dirname, join as join11 } from "node:path";
1863
+ import { existsSync as existsSync11, readFileSync as readFileSync6 } from "node:fs";
1864
+ import { homedir as homedir9 } from "node:os";
1865
+ import { dirname as dirname2, join as join14 } from "node:path";
1304
1866
  function pickEnv(env, key) {
1305
1867
  return env?.[key]?.trim() ?? "";
1306
1868
  }
1307
1869
  function resolveOpencodeAuthCandidates(overrides) {
1308
1870
  const platform = overrides?.platform ?? process.platform;
1309
1871
  const env = overrides?.env ?? process.env;
1310
- const home = overrides?.home ?? homedir8();
1872
+ const home = overrides?.home ?? homedir9();
1311
1873
  const seen = new Set;
1312
1874
  const out = [];
1313
1875
  const push = (p) => {
@@ -1318,27 +1880,27 @@ function resolveOpencodeAuthCandidates(overrides) {
1318
1880
  };
1319
1881
  const xdg = pickEnv(env, "XDG_DATA_HOME");
1320
1882
  if (xdg)
1321
- push(join11(xdg, "opencode", "auth.json"));
1883
+ push(join14(xdg, "opencode", "auth.json"));
1322
1884
  if (platform === "win32") {
1323
- const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? join11(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
1885
+ const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? join14(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
1324
1886
  if (localAppData)
1325
- push(join11(localAppData, "opencode", "auth.json"));
1887
+ push(join14(localAppData, "opencode", "auth.json"));
1326
1888
  const userProfile = pickEnv(env, "USERPROFILE") || home;
1327
1889
  if (userProfile)
1328
- push(join11(userProfile, ".local", "share", "opencode", "auth.json"));
1890
+ push(join14(userProfile, ".local", "share", "opencode", "auth.json"));
1329
1891
  } else if (home) {
1330
- push(join11(home, ".local", "share", "opencode", "auth.json"));
1892
+ push(join14(home, ".local", "share", "opencode", "auth.json"));
1331
1893
  }
1332
1894
  return out;
1333
1895
  }
1334
1896
  function resolveOpencodeAuthFile() {
1335
- return resolveOpencodeAuthCandidates()[0] ?? join11(homedir8(), ".local", "share", "opencode", "auth.json");
1897
+ return resolveOpencodeAuthCandidates()[0] ?? join14(homedir9(), ".local", "share", "opencode", "auth.json");
1336
1898
  }
1337
1899
  function isValidOpencodeAuthFile(authFile) {
1338
1900
  try {
1339
- if (!authFile || !existsSync9(authFile))
1901
+ if (!authFile || !existsSync11(authFile))
1340
1902
  return false;
1341
- const raw = readFileSync5(authFile, "utf8").trim();
1903
+ const raw = readFileSync6(authFile, "utf8").trim();
1342
1904
  if (!raw)
1343
1905
  return false;
1344
1906
  const parsed = JSON.parse(raw);
@@ -1356,7 +1918,7 @@ function probeOpencodeAuth(overrides) {
1356
1918
  for (const candidate of candidates) {
1357
1919
  let exists = false;
1358
1920
  try {
1359
- exists = existsSync9(candidate);
1921
+ exists = existsSync11(candidate);
1360
1922
  } catch {
1361
1923
  exists = false;
1362
1924
  }
@@ -1369,10 +1931,10 @@ function probeOpencodeAuth(overrides) {
1369
1931
  validFile = candidate;
1370
1932
  }
1371
1933
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
1372
- const authDir = dirname(authFile);
1934
+ const authDir = dirname2(authFile);
1373
1935
  let hasCodexHome = false;
1374
1936
  try {
1375
- hasCodexHome = existsSync9(authDir);
1937
+ hasCodexHome = existsSync11(authDir);
1376
1938
  } catch {
1377
1939
  hasCodexHome = false;
1378
1940
  }
@@ -1387,6 +1949,8 @@ function probeOpencodeAuth(overrides) {
1387
1949
  }
1388
1950
  var opencodeAdapter = {
1389
1951
  id: "opencode",
1952
+ supportedBridgeVersions: ["1.18.35"],
1953
+ prepareAppResources: prepareOpenCodeResources,
1390
1954
  probeAuth: () => probeOpencodeAuth(),
1391
1955
  probeQuota: async () => probeOpencodeQuota(),
1392
1956
  orderAuthMethods: (methods) => methods,
@@ -1397,6 +1961,7 @@ var opencodeAdapter = {
1397
1961
  // src/runtimes/opencode-v2/index.ts
1398
1962
  var opencodeV2Adapter = {
1399
1963
  id: "opencode-v2",
1964
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
1400
1965
  probeAuth: () => probeOpencodeAuth(),
1401
1966
  orderAuthMethods: (methods) => methods,
1402
1967
  canSkipInteractiveAuth: () => false,
@@ -1428,15 +1993,15 @@ async function probeCursorQuota() {
1428
1993
 
1429
1994
  // src/runtimes/cursor/index.ts
1430
1995
  import { spawnSync } from "node:child_process";
1431
- import { existsSync as existsSync10, readFileSync as readFileSync6 } from "node:fs";
1432
- import { homedir as homedir9 } from "node:os";
1433
- import { delimiter, dirname as dirname2, join as join12 } from "node:path";
1996
+ import { existsSync as existsSync12, readFileSync as readFileSync7 } from "node:fs";
1997
+ import { homedir as homedir10 } from "node:os";
1998
+ import { delimiter, dirname as dirname3, join as join15 } from "node:path";
1434
1999
  function cursorLocalAppData(env) {
1435
2000
  const local = env.LOCALAPPDATA?.trim();
1436
2001
  if (local)
1437
2002
  return local;
1438
2003
  const profile = env.USERPROFILE?.trim();
1439
- return profile ? join12(profile, "AppData", "Local") : "";
2004
+ return profile ? join15(profile, "AppData", "Local") : "";
1440
2005
  }
1441
2006
  function isOnPath(command, env, platform) {
1442
2007
  const pathValue = env.PATH ?? env.Path ?? "";
@@ -1448,7 +2013,7 @@ function isOnPath(command, env, platform) {
1448
2013
  if (!trimmed)
1449
2014
  continue;
1450
2015
  try {
1451
- if (existsSync10(join12(trimmed, command)))
2016
+ if (existsSync12(join15(trimmed, command)))
1452
2017
  return true;
1453
2018
  } catch {}
1454
2019
  }
@@ -1457,24 +2022,24 @@ function isOnPath(command, env, platform) {
1457
2022
  function resolveDirectCursorCommand(platform, env, home) {
1458
2023
  if (platform === "win32") {
1459
2024
  const localAppData = cursorLocalAppData(env);
1460
- return localAppData ? join12(localAppData, "cursor-agent", "agent.cmd") : "";
2025
+ return localAppData ? join15(localAppData, "cursor-agent", "agent.cmd") : "";
1461
2026
  }
1462
- return home ? join12(home, ".local", "bin", "agent") : "";
2027
+ return home ? join15(home, ".local", "bin", "agent") : "";
1463
2028
  }
1464
2029
  function resolveCursorCommand(overrides) {
1465
2030
  const args = ["acp"];
1466
2031
  const platform = overrides?.platform ?? process.platform;
1467
2032
  const env = overrides?.env ?? process.env;
1468
- const home = overrides?.home ?? homedir9();
2033
+ const home = overrides?.home ?? homedir10();
1469
2034
  if (platform === "win32") {
1470
2035
  const directCmd = resolveDirectCursorCommand(platform, env, home);
1471
- if (directCmd && existsSync10(directCmd)) {
2036
+ if (directCmd && existsSync12(directCmd)) {
1472
2037
  return { command: directCmd, args };
1473
2038
  }
1474
2039
  return { command: "agent.cmd", args };
1475
2040
  }
1476
2041
  const directBin = resolveDirectCursorCommand(platform, env, home);
1477
- if (directBin && existsSync10(directBin)) {
2042
+ if (directBin && existsSync12(directBin)) {
1478
2043
  return { command: directBin, args };
1479
2044
  }
1480
2045
  return { command: "agent", args };
@@ -1483,11 +2048,11 @@ function resolveCursorSpawnCommand(overrides) {
1483
2048
  const args = ["acp"];
1484
2049
  const platform = overrides?.platform ?? process.platform;
1485
2050
  const env = overrides?.env ?? process.env;
1486
- const home = overrides?.home ?? homedir9();
2051
+ const home = overrides?.home ?? homedir10();
1487
2052
  const binary = platform === "win32" ? "agent.cmd" : "agent";
1488
2053
  const direct = resolveDirectCursorCommand(platform, env, home);
1489
2054
  try {
1490
- if (direct && existsSync10(direct))
2055
+ if (direct && existsSync12(direct))
1491
2056
  return { command: direct, args };
1492
2057
  } catch {}
1493
2058
  if (isOnPath(binary, env, platform))
@@ -1509,12 +2074,12 @@ function cursorRoamingAppData(env, home) {
1509
2074
  if (roaming)
1510
2075
  return roaming;
1511
2076
  const profile = pickEnv2(env, "USERPROFILE") || home;
1512
- return profile ? join12(profile, "AppData", "Roaming") : "";
2077
+ return profile ? join15(profile, "AppData", "Roaming") : "";
1513
2078
  }
1514
2079
  function resolveCursorAuthCandidates(overrides) {
1515
2080
  const platform = overrides?.platform ?? process.platform;
1516
2081
  const env = overrides?.env ?? process.env;
1517
- const home = overrides?.home ?? homedir9();
2082
+ const home = overrides?.home ?? homedir10();
1518
2083
  const seen = new Set;
1519
2084
  const out = [];
1520
2085
  const push = (p) => {
@@ -1525,16 +2090,16 @@ function resolveCursorAuthCandidates(overrides) {
1525
2090
  };
1526
2091
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
1527
2092
  if (xdg)
1528
- push(join12(xdg, "cursor", "auth.json"));
2093
+ push(join15(xdg, "cursor", "auth.json"));
1529
2094
  if (platform === "win32") {
1530
2095
  const profile = pickEnv2(env, "USERPROFILE") || home;
1531
2096
  if (profile)
1532
- push(join12(profile, ".config", "cursor", "auth.json"));
2097
+ push(join15(profile, ".config", "cursor", "auth.json"));
1533
2098
  const roaming = cursorRoamingAppData(env, home);
1534
2099
  if (roaming)
1535
- push(join12(roaming, "Cursor", "User", "globalStorage", "storage.json"));
2100
+ push(join15(roaming, "Cursor", "User", "globalStorage", "storage.json"));
1536
2101
  } else if (home) {
1537
- push(join12(home, ".config", "cursor", "auth.json"));
2102
+ push(join15(home, ".config", "cursor", "auth.json"));
1538
2103
  }
1539
2104
  return out;
1540
2105
  }
@@ -1545,9 +2110,9 @@ function isValidCursorAuthFile(authFile) {
1545
2110
  try {
1546
2111
  if (!authFile || isStorageHintPath(authFile))
1547
2112
  return false;
1548
- if (!existsSync10(authFile))
2113
+ if (!existsSync12(authFile))
1549
2114
  return false;
1550
- const raw = readFileSync6(authFile, "utf8").trim();
2115
+ const raw = readFileSync7(authFile, "utf8").trim();
1551
2116
  if (!raw)
1552
2117
  return false;
1553
2118
  const parsed = JSON.parse(raw);
@@ -1565,9 +2130,9 @@ function isHintCursorStorageFile(authFile) {
1565
2130
  try {
1566
2131
  if (!authFile || !isStorageHintPath(authFile))
1567
2132
  return false;
1568
- if (!existsSync10(authFile))
2133
+ if (!existsSync12(authFile))
1569
2134
  return false;
1570
- const raw = readFileSync6(authFile, "utf8").trim();
2135
+ const raw = readFileSync7(authFile, "utf8").trim();
1571
2136
  if (!raw)
1572
2137
  return false;
1573
2138
  const parsed = JSON.parse(raw);
@@ -1583,7 +2148,7 @@ function isValidCursorCandidate(authFile) {
1583
2148
  }
1584
2149
  function probeCursorAuth(overrides) {
1585
2150
  const env = overrides?.env ?? process.env;
1586
- const home = overrides?.home ?? homedir9();
2151
+ const home = overrides?.home ?? homedir10();
1587
2152
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
1588
2153
  const candidates = resolveCursorAuthCandidates(overrides);
1589
2154
  let firstExisting = null;
@@ -1591,7 +2156,7 @@ function probeCursorAuth(overrides) {
1591
2156
  for (const candidate of candidates) {
1592
2157
  let exists = false;
1593
2158
  try {
1594
- exists = existsSync10(candidate);
2159
+ exists = existsSync12(candidate);
1595
2160
  } catch {
1596
2161
  exists = false;
1597
2162
  }
@@ -1603,12 +2168,12 @@ function probeCursorAuth(overrides) {
1603
2168
  if (isValidCursorCandidate(candidate))
1604
2169
  validFile = candidate;
1605
2170
  }
1606
- const fallback = home ? join12(home, ".config", "cursor", "auth.json") : "";
2171
+ const fallback = home ? join15(home, ".config", "cursor", "auth.json") : "";
1607
2172
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
1608
- const authDir = authFile ? dirname2(authFile) : "";
2173
+ const authDir = authFile ? dirname3(authFile) : "";
1609
2174
  let hasCodexHome = false;
1610
2175
  try {
1611
- hasCodexHome = authDir ? existsSync10(authDir) : false;
2176
+ hasCodexHome = authDir ? existsSync12(authDir) : false;
1612
2177
  } catch {
1613
2178
  hasCodexHome = false;
1614
2179
  }
@@ -1622,6 +2187,7 @@ function probeCursorAuth(overrides) {
1622
2187
  }
1623
2188
  var cursorAdapter = {
1624
2189
  id: "cursor-cli",
2190
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-does-not-guarantee-rules"),
1625
2191
  probeAuth: () => probeCursorAuth(),
1626
2192
  probeQuota: async () => probeCursorQuota(),
1627
2193
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
@@ -1735,6 +2301,7 @@ function probeDeepseekAuth() {
1735
2301
  }
1736
2302
  var deepseekAdapter = {
1737
2303
  id: "deepseek",
2304
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
1738
2305
  probeAuth: () => probeDeepseekAuth(),
1739
2306
  resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
1740
2307
  resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
@@ -1743,13 +2310,13 @@ var deepseekAdapter = {
1743
2310
  };
1744
2311
 
1745
2312
  // src/runtimes/agy/quota.ts
1746
- import { existsSync as existsSync11, readFileSync as readFileSync7, readdirSync, statSync } from "node:fs";
1747
- import { join as join13 } from "node:path";
2313
+ import { existsSync as existsSync13, readFileSync as readFileSync8, readdirSync as readdirSync2, statSync as statSync2 } from "node:fs";
2314
+ import { join as join16 } from "node:path";
1748
2315
  import { execFileSync } from "node:child_process";
1749
2316
  import * as os2 from "node:os";
1750
2317
  function resolveGeminiHome2() {
1751
2318
  const home = process.env.USERPROFILE || process.env.HOME || "";
1752
- return join13(home, ".gemini");
2319
+ return join16(home, ".gemini");
1753
2320
  }
1754
2321
  function resolveAntigravityAccount() {
1755
2322
  if (process.env.GOOGLE_ACCOUNT?.trim()) {
@@ -1762,14 +2329,14 @@ function resolveAntigravityAccount() {
1762
2329
  }
1763
2330
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
1764
2331
  const candidates = [
1765
- process.env.APPDATA ? join13(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
1766
- join13(home, ".config", "Antigravity", "app_storage.json"),
1767
- join13(home, "Library", "Application Support", "Antigravity", "app_storage.json")
2332
+ process.env.APPDATA ? join16(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
2333
+ join16(home, ".config", "Antigravity", "app_storage.json"),
2334
+ join16(home, "Library", "Application Support", "Antigravity", "app_storage.json")
1768
2335
  ].filter(Boolean);
1769
2336
  for (const file of candidates) {
1770
2337
  try {
1771
- if (existsSync11(file)) {
1772
- const raw = readFileSync7(file, "utf8");
2338
+ if (existsSync13(file)) {
2339
+ const raw = readFileSync8(file, "utf8");
1773
2340
  const json = JSON.parse(raw);
1774
2341
  const username = json["jetski.onboarding.lastLoginUsername"];
1775
2342
  if (username && typeof username === "string" && username.trim()) {
@@ -1790,30 +2357,30 @@ function resolveAntigravityAccount() {
1790
2357
  }
1791
2358
  function resolveAntigravityLanguageServer() {
1792
2359
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
1793
- const appData = process.env.APPDATA || (process.platform === "win32" ? join13(home, "AppData", "Roaming") : "");
2360
+ const appData = process.env.APPDATA || (process.platform === "win32" ? join16(home, "AppData", "Roaming") : "");
1794
2361
  const baseDirs = [
1795
- appData ? join13(appData, "Antigravity IDE", "logs") : null,
1796
- appData ? join13(appData, "Antigravity", "logs") : null,
1797
- join13(home, ".config", "Antigravity IDE", "logs"),
1798
- join13(home, ".config", "Antigravity", "logs"),
1799
- join13(home, "Library", "Application Support", "Antigravity IDE", "logs"),
1800
- join13(home, "Library", "Application Support", "Antigravity", "logs")
2362
+ appData ? join16(appData, "Antigravity IDE", "logs") : null,
2363
+ appData ? join16(appData, "Antigravity", "logs") : null,
2364
+ join16(home, ".config", "Antigravity IDE", "logs"),
2365
+ join16(home, ".config", "Antigravity", "logs"),
2366
+ join16(home, "Library", "Application Support", "Antigravity IDE", "logs"),
2367
+ join16(home, "Library", "Application Support", "Antigravity", "logs")
1801
2368
  ].filter(Boolean);
1802
2369
  for (const base of baseDirs) {
1803
2370
  try {
1804
- if (!existsSync11(base))
2371
+ if (!existsSync13(base))
1805
2372
  continue;
1806
- const sessionDirs = readdirSync(base).map((d) => {
2373
+ const sessionDirs = readdirSync2(base).map((d) => {
1807
2374
  try {
1808
- return { name: d, time: statSync(join13(base, d)).mtimeMs };
2375
+ return { name: d, time: statSync2(join16(base, d)).mtimeMs };
1809
2376
  } catch {
1810
2377
  return null;
1811
2378
  }
1812
2379
  }).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
1813
2380
  for (const s of sessionDirs) {
1814
- const logFile = join13(base, s.name, "ls-main.log");
1815
- if (existsSync11(logFile)) {
1816
- const content = readFileSync7(logFile, "utf8");
2381
+ const logFile = join16(base, s.name, "ls-main.log");
2382
+ if (existsSync13(logFile)) {
2383
+ const content = readFileSync8(logFile, "utf8");
1817
2384
  const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
1818
2385
  const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
1819
2386
  if (csrfMatch && portMatch) {
@@ -1970,7 +2537,7 @@ async function probeAgyQuota(options) {
1970
2537
  } catch {}
1971
2538
  }
1972
2539
  const geminiHome = resolveGeminiHome2();
1973
- const hasAgyDir = existsSync11(join13(geminiHome, "antigravity")) || existsSync11(join13(geminiHome, "antigravity-cli"));
2540
+ const hasAgyDir = existsSync13(join16(geminiHome, "antigravity")) || existsSync13(join16(geminiHome, "antigravity-cli"));
1974
2541
  const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
1975
2542
  const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
1976
2543
  if (!isAvailable) {
@@ -2042,6 +2609,12 @@ function probeAgyAuth() {
2042
2609
  }
2043
2610
  var agyAdapter = {
2044
2611
  id: "agy",
2612
+ prepareAppResources: async ({ directory }) => {
2613
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
2614
+ return { ...prep, env: { AGY_ACP_RESOURCES_DIR: directory }, report: { ...prep.report, rulesPrepared: prep.report.rulesChars > 0 } };
2615
+ },
2616
+ appResourceSessionMeta: (directory) => ({ appResources: { directory } }),
2617
+ supportedBridgeVersions: ["0.1.24"],
2045
2618
  probeAuth: () => probeAgyAuth(),
2046
2619
  probeQuota: (options) => probeAgyQuota(options),
2047
2620
  orderAuthMethods: (methods) => methods,
@@ -2082,6 +2655,9 @@ function getAcpRuntimeAdapter(runtimeId) {
2082
2655
 
2083
2656
  // src/process/process-manager.ts
2084
2657
  import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
2658
+ function processKey(runtimeId, scopeKey) {
2659
+ return scopeKey ? `${scopeKey}:${runtimeId}` : runtimeId;
2660
+ }
2085
2661
  var active = new Map;
2086
2662
  var ACP_EARLY_EXIT_WINDOW_MS = 3000;
2087
2663
  var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
@@ -2113,7 +2689,8 @@ function spawnAcpProcess(options) {
2113
2689
  if (!options.runtime?.id || !options.runtime.command || !Array.isArray(options.runtime.args)) {
2114
2690
  throw new Error(`ACP 运行时模板缺失 command/args: ${options.runtime?.id ?? "(empty)"}`);
2115
2691
  }
2116
- const existing = active.get(options.runtime.id);
2692
+ const key = processKey(options.runtime.id, options.scopeKey);
2693
+ const existing = active.get(key);
2117
2694
  if (existing) {
2118
2695
  existing.kill();
2119
2696
  }
@@ -2174,6 +2751,9 @@ function spawnAcpProcess(options) {
2174
2751
  });
2175
2752
  const handle = {
2176
2753
  runtimeId: options.runtime.id,
2754
+ scopeKey: options.scopeKey,
2755
+ executionContext: options.executionContext,
2756
+ profileTag: options.profileTag ?? null,
2177
2757
  child,
2178
2758
  spawnedAt: Date.now(),
2179
2759
  stderrTail,
@@ -2191,7 +2771,7 @@ function spawnAcpProcess(options) {
2191
2771
  } catch {}
2192
2772
  }
2193
2773
  }
2194
- active.delete(options.runtime.id);
2774
+ active.delete(key);
2195
2775
  }
2196
2776
  };
2197
2777
  child.on("exit", (code, signal) => {
@@ -2199,10 +2779,11 @@ function spawnAcpProcess(options) {
2199
2779
  if (rest)
2200
2780
  pushStderrTailLine(rest);
2201
2781
  stderrBuffer = "";
2202
- active.delete(options.runtime.id);
2782
+ if (active.get(key) === handle)
2783
+ active.delete(key);
2203
2784
  options.onExit?.(code, signal);
2204
2785
  });
2205
- active.set(options.runtime.id, handle);
2786
+ active.set(key, handle);
2206
2787
  return handle;
2207
2788
  }
2208
2789
  function getAcpEarlyExitStderrDetail(handle, _now = Date.now()) {
@@ -2230,112 +2811,64 @@ function disposeAllAcpProcesses() {
2230
2811
  }
2231
2812
  active.clear();
2232
2813
  }
2233
- function getActiveAcpProcess(runtimeId) {
2234
- return active.get(runtimeId);
2814
+ function getActiveAcpProcess(runtimeId, scopeKey) {
2815
+ return active.get(processKey(runtimeId, scopeKey));
2235
2816
  }
2236
2817
  function listLiveAcpRuntimeIds() {
2237
- const ids = [];
2238
- for (const [runtimeId, handle] of active) {
2818
+ const ids = new Set;
2819
+ for (const handle of active.values()) {
2239
2820
  if (isSpawnedAcpProcessAlive(handle))
2240
- ids.push(runtimeId);
2821
+ ids.add(handle.runtimeId);
2241
2822
  }
2242
- return ids.sort();
2823
+ return [...ids].sort();
2243
2824
  }
2244
- function getLiveAcpProcess(runtimeId) {
2245
- const handle = active.get(runtimeId);
2825
+ function getLiveAcpProcess(runtimeId, query = {}) {
2826
+ const key = processKey(runtimeId, query.scopeKey);
2827
+ const handle = active.get(key);
2246
2828
  if (!handle)
2247
2829
  return;
2248
2830
  if (!isSpawnedAcpProcessAlive(handle)) {
2249
- active.delete(runtimeId);
2831
+ active.delete(key);
2250
2832
  return;
2251
2833
  }
2252
- return handle;
2253
- }
2254
-
2255
- // src/client/sdk-client.ts
2256
- import { PassThrough, Readable, Writable } from "node:stream";
2257
- import {
2258
- client as createSdkClientApp,
2259
- ndJsonStream
2260
- } from "@agentclientprotocol/sdk";
2261
- var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
2262
- function createSdkStreamHandle(child) {
2263
- const stdoutBridge = new PassThrough;
2264
- const stdinBridge = new PassThrough;
2265
- child.stdout.pipe(stdoutBridge);
2266
- stdinBridge.pipe(child.stdin, { end: false });
2267
- const output = Writable.toWeb(stdinBridge);
2268
- const input = Readable.toWeb(stdoutBridge);
2269
- const stream = ndJsonStream(output, input);
2270
- let disposed = false;
2271
- return {
2272
- stream,
2273
- dispose: () => {
2274
- if (disposed)
2275
- return;
2276
- disposed = true;
2277
- try {
2278
- child.stdout.unpipe(stdoutBridge);
2279
- } catch {}
2280
- try {
2281
- stdinBridge.unpipe(child.stdin);
2282
- } catch {}
2283
- try {
2284
- stdoutBridge.destroy();
2285
- } catch {}
2286
- try {
2287
- stdinBridge.destroy();
2288
- } catch {}
2289
- }
2290
- };
2291
- }
2292
- function connectSdkClient(child, configure, runtimeId) {
2293
- if (runtimeId && true) {
2294
- console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
2834
+ if (query.executionContext !== undefined && (handle.executionContext ?? null) !== query.executionContext) {
2835
+ return;
2295
2836
  }
2296
- const app = createSdkClientApp({ name: "inkdown" });
2297
- configure(app);
2298
- const streamHandle = createSdkStreamHandle(child);
2299
- const connection = app.connect(streamHandle.stream);
2300
- return { app, connection, streamHandle };
2837
+ if (query.expectedTag !== undefined && (handle.profileTag ?? null) !== query.expectedTag)
2838
+ return;
2839
+ return handle;
2301
2840
  }
2302
- async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
2303
- const controller = new AbortController;
2304
- let timer;
2305
- try {
2306
- const pending = agent.request(method, params, {
2307
- cancellationSignal: controller.signal
2308
- });
2309
- const timeout = new Promise((_, reject) => {
2310
- timer = setTimeout(() => {
2311
- controller.abort();
2312
- reject(new Error(`请求超时: ${method}`));
2313
- }, timeoutMs);
2314
- timer.unref?.();
2315
- });
2316
- return await Promise.race([pending, timeout]);
2317
- } finally {
2318
- if (timer !== undefined)
2319
- clearTimeout(timer);
2320
- }
2841
+ function tryReuseLiveAcpProcess(runtimeId, query = {}) {
2842
+ const hit = getLiveAcpProcess(runtimeId, query);
2843
+ if (hit)
2844
+ return { status: "hit", handle: hit };
2845
+ if (query.expectedTag === undefined)
2846
+ return { status: "miss" };
2847
+ const stale = getLiveAcpProcess(runtimeId, { scopeKey: query.scopeKey, executionContext: query.executionContext });
2848
+ if (!stale)
2849
+ return { status: "miss" };
2850
+ if (query.isBusy?.(stale))
2851
+ return { status: "busy", handle: stale };
2852
+ stale.kill();
2853
+ return { status: "miss" };
2321
2854
  }
2322
2855
 
2323
2856
  // src/client/client-handlers.ts
2324
2857
  import { methods, RequestError } from "@agentclientprotocol/sdk";
2325
2858
 
2326
2859
  // src/client/acp-fs.ts
2327
- import { access, readFile as readFile2, writeFile as writeFile3 } from "node:fs/promises";
2328
- import { dirname as dirname3, extname, resolve, sep } from "node:path";
2329
- import { mkdir as mkdir3 } from "node:fs/promises";
2860
+ import { access, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
2861
+ import { dirname as dirname4, extname, resolve as resolve2, sep as sep2 } from "node:path";
2862
+ import { mkdir as mkdir4 } from "node:fs/promises";
2330
2863
  var MAX_READ_BYTES = 2 * 1024 * 1024;
2331
2864
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
2332
2865
  function isBinaryDocumentPath(filePath) {
2333
2866
  return BINARY_DOCUMENT_EXTENSIONS.has(extname(filePath).toLowerCase());
2334
2867
  }
2335
2868
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
2336
- const root = resolve(workspaceRoot);
2337
- const target = resolve(filePath);
2338
- const rootWithSep = root.endsWith(sep) ? root : root + sep;
2869
+ const root = resolve2(workspaceRoot);
2870
+ const target = resolve2(filePath);
2871
+ const rootWithSep = root.endsWith(sep2) ? root : root + sep2;
2339
2872
  if (target !== root && !target.startsWith(rootWithSep)) {
2340
2873
  throw new Error(`路径不在工作区内: ${filePath}`);
2341
2874
  }
@@ -2347,7 +2880,7 @@ async function acpReadTextFile(params) {
2347
2880
  }
2348
2881
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
2349
2882
  await access(abs);
2350
- let content = await readFile2(abs, "utf-8");
2883
+ let content = await readFile4(abs, "utf-8");
2351
2884
  if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
2352
2885
  content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
2353
2886
  content += `
@@ -2366,8 +2899,8 @@ async function acpReadTextFile(params) {
2366
2899
  }
2367
2900
  async function acpWriteTextFile(params) {
2368
2901
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
2369
- await mkdir3(dirname3(abs), { recursive: true });
2370
- await writeFile3(abs, params.content, "utf-8");
2902
+ await mkdir4(dirname4(abs), { recursive: true });
2903
+ await writeFile4(abs, params.content, "utf-8");
2371
2904
  return {};
2372
2905
  }
2373
2906
 
@@ -2727,6 +3260,25 @@ function isTransientAcpTransportError(error) {
2727
3260
  async function restoreOrCreateAcpSession(input) {
2728
3261
  const resumeId = input.resumeSessionId?.trim() || null;
2729
3262
  const restoreAttempts = [];
3263
+ let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
3264
+ let nativeSessionAccepted = false;
3265
+ const request = async (method, params) => {
3266
+ if (!input.sessionMeta)
3267
+ return input.request(method, params);
3268
+ try {
3269
+ const result = await input.request(method, { ...params, _meta: input.sessionMeta });
3270
+ nativeSessionAccepted = true;
3271
+ return result;
3272
+ } catch (error) {
3273
+ const rejected = error instanceof RequestError2 && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
3274
+ if (!rejected || isTransientAcpTransportError(error))
3275
+ throw error;
3276
+ log("warn", "native resource options failed; retry without extension");
3277
+ const result = await input.request(method, params);
3278
+ nativeSessionAccepted = false;
3279
+ return result;
3280
+ }
3281
+ };
2730
3282
  const delayMs = input.retryDelayMs ?? 250;
2731
3283
  const log = input.log ?? ((level, message, data) => {
2732
3284
  if (level === "info" && false)
@@ -2748,7 +3300,7 @@ async function restoreOrCreateAcpSession(input) {
2748
3300
  maxTries
2749
3301
  });
2750
3302
  try {
2751
- const result = await input.request(rpcMethod, {
3303
+ const result = await request(rpcMethod, {
2752
3304
  sessionId: resumeId,
2753
3305
  cwd: input.cwd,
2754
3306
  mcpServers: input.mcpServers ?? []
@@ -2787,7 +3339,7 @@ async function restoreOrCreateAcpSession(input) {
2787
3339
  mcpServers: input.mcpServers ?? []
2788
3340
  };
2789
3341
  try {
2790
- return await input.request("session/new", baseParams);
3342
+ return await request("session/new", baseParams);
2791
3343
  } catch (firstError) {
2792
3344
  if ((input.mcpServers ?? []).length === 0)
2793
3345
  throw firstError;
@@ -2795,10 +3347,12 @@ async function restoreOrCreateAcpSession(input) {
2795
3347
  error: errorMessage(firstError)
2796
3348
  });
2797
3349
  try {
2798
- return await input.request("session/new", {
3350
+ const result = await request("session/new", {
2799
3351
  cwd: input.cwd,
2800
3352
  mcpServers: []
2801
3353
  });
3354
+ mcpServersAccepted = false;
3355
+ return result;
2802
3356
  } catch {
2803
3357
  throw firstError;
2804
3358
  }
@@ -2814,6 +3368,8 @@ async function restoreOrCreateAcpSession(input) {
2814
3368
  configOptions: withModelsFallback(resumed),
2815
3369
  restoreMethod: "resume",
2816
3370
  sessionRestored: true,
3371
+ mcpServersAccepted,
3372
+ nativeSessionAccepted,
2817
3373
  requestedSessionId: resumeId,
2818
3374
  restoreAttempts
2819
3375
  };
@@ -2832,6 +3388,8 @@ async function restoreOrCreateAcpSession(input) {
2832
3388
  configOptions: withModelsFallback(loaded),
2833
3389
  restoreMethod: "load",
2834
3390
  sessionRestored: true,
3391
+ mcpServersAccepted,
3392
+ nativeSessionAccepted,
2835
3393
  requestedSessionId: resumeId,
2836
3394
  restoreAttempts
2837
3395
  };
@@ -2853,6 +3411,8 @@ async function restoreOrCreateAcpSession(input) {
2853
3411
  configOptions: withModelsFallback(sessionResult),
2854
3412
  restoreMethod: "new",
2855
3413
  sessionRestored: false,
3414
+ mcpServersAccepted,
3415
+ nativeSessionAccepted,
2856
3416
  requestedSessionId: resumeId ?? undefined,
2857
3417
  restoreAttempts
2858
3418
  };
@@ -3043,9 +3603,9 @@ class AcpTerminalManager {
3043
3603
  }
3044
3604
 
3045
3605
  // src/client/acp-proxy-service.ts
3046
- import { mkdir as mkdir4, readFile as readFile3, writeFile as writeFile4 } from "node:fs/promises";
3047
- import { existsSync as existsSync12 } from "node:fs";
3048
- import { join as join14 } from "node:path";
3606
+ import { mkdir as mkdir5, readFile as readFile5, writeFile as writeFile5 } from "node:fs/promises";
3607
+ import { existsSync as existsSync14 } from "node:fs";
3608
+ import { join as join17 } from "node:path";
3049
3609
  var DEFAULT_ACP_PROXY_SETTINGS = {
3050
3610
  enabled: false,
3051
3611
  host: "127.0.0.1",
@@ -3054,7 +3614,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
3054
3614
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
3055
3615
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
3056
3616
  function proxyFilePath(dir) {
3057
- return join14(dir, "agent", "proxy.json");
3617
+ return join17(dir, "agent", "proxy.json");
3058
3618
  }
3059
3619
  function validate2(settings) {
3060
3620
  if (!settings.host.trim())
@@ -3066,10 +3626,10 @@ function validate2(settings) {
3066
3626
  }
3067
3627
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
3068
3628
  const file = proxyFilePath(dir);
3069
- if (!existsSync12(file))
3629
+ if (!existsSync14(file))
3070
3630
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
3071
3631
  try {
3072
- const raw = JSON.parse(await readFile3(file, "utf8"));
3632
+ const raw = JSON.parse(await readFile5(file, "utf8"));
3073
3633
  return {
3074
3634
  enabled: raw.enabled === true,
3075
3635
  host: typeof raw.host === "string" && raw.host.trim() ? raw.host : DEFAULT_ACP_PROXY_SETTINGS.host,
@@ -3088,8 +3648,8 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
3088
3648
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
3089
3649
  port: payload.port
3090
3650
  };
3091
- await mkdir4(join14(dir, "agent"), { recursive: true });
3092
- await writeFile4(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
3651
+ await mkdir5(join17(dir, "agent"), { recursive: true });
3652
+ await writeFile5(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
3093
3653
  return ok(stored);
3094
3654
  }
3095
3655
  function buildAcpProxySpawnEnv(settings) {
@@ -3111,6 +3671,116 @@ function buildAcpProxySpawnEnv(settings) {
3111
3671
  };
3112
3672
  }
3113
3673
 
3674
+ // src/session/compat-guide.ts
3675
+ var COMPAT_CONTEXT_TAG = "acp-compat-context";
3676
+ function shortDigest(digest) {
3677
+ return digest ? digest.slice(0, 16) : "none";
3678
+ }
3679
+ function buildCompatGuideText(input) {
3680
+ const hasRules = (input.rulesText ?? "").trim() !== "";
3681
+ const hasSkills = input.skills.length > 0;
3682
+ if (!hasRules && !hasSkills)
3683
+ return null;
3684
+ const lines = [];
3685
+ lines.push(`<${COMPAT_CONTEXT_TAG} mode="compatibility" profile="${shortDigest(input.digest)}" session="${input.sessionId}" gen="${input.generation}">`, "NOTE FOR THE MODEL: the block below is host-provided context delivered over the user channel", "(compatibility mode). It is NOT a system or developer instruction and does not override them.", "");
3686
+ if (hasRules) {
3687
+ lines.push("--- host rules (same source as the host app, delivered once per session) ---", "");
3688
+ lines.push(input.rulesText.trim(), "");
3689
+ }
3690
+ if (hasSkills) {
3691
+ lines.push("--- host skills catalog (names and descriptions only; read full text on demand) ---", "");
3692
+ for (const skill of input.skills) {
3693
+ lines.push(`- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`);
3694
+ }
3695
+ lines.push("", input.skillsViaMcp ? "Read a skill body with the app_read_skill MCP tool before claiming its content." : "Skill bodies are available on request; ask the host if no skill tool is listed.");
3696
+ lines.push("");
3697
+ }
3698
+ lines.push(`</${COMPAT_CONTEXT_TAG}>`);
3699
+ return lines.join(`
3700
+ `);
3701
+ }
3702
+ function compatDeliveryKey(sessionId, generation, digest) {
3703
+ return `${generation}:${sessionId}:${digest ?? "none"}`;
3704
+ }
3705
+
3706
+ // src/mcp/app-skills-mcp.ts
3707
+ import { dirname as dirname5, join as join18 } from "node:path";
3708
+ import { fileURLToPath } from "node:url";
3709
+ import { existsSync as existsSync15, readFileSync as readFileSync9, statSync as statSync3 } from "node:fs";
3710
+ var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
3711
+ var APP_SKILLS_TOOLS = [
3712
+ {
3713
+ name: "app_list_skills",
3714
+ description: "List host skill catalog (names and one-line descriptions). " + "Call this first to discover available skills; then read a body with app_read_skill before claiming its content. " + "Skill bodies are never inlined here—always read on demand.",
3715
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
3716
+ },
3717
+ {
3718
+ name: "app_read_skill",
3719
+ description: "Read one registered skill body by exact name from app_list_skills. " + "Optional ref reads another Markdown file in the same skill directory " + "(same-directory relative .md only; anything else is rejected).",
3720
+ inputSchema: {
3721
+ type: "object",
3722
+ properties: {
3723
+ name: { type: "string", description: "Exact skill name from app_list_skills" },
3724
+ ref: {
3725
+ type: "string",
3726
+ description: "Optional same-directory relative Markdown file (default SKILL.md)"
3727
+ }
3728
+ },
3729
+ required: ["name"],
3730
+ additionalProperties: false
3731
+ }
3732
+ }
3733
+ ];
3734
+ function buildAppSkillsMcpServer(directory, opts) {
3735
+ return {
3736
+ name: opts?.name ?? APP_SKILLS_MCP_SERVER_NAME,
3737
+ command: process.execPath,
3738
+ env: process.versions.electron ? [{ name: "ELECTRON_RUN_AS_NODE", value: "1" }] : [],
3739
+ args: [opts?.runnerPath ?? resolveAppSkillsRunnerPath(), directory]
3740
+ };
3741
+ }
3742
+ function resolveAppSkillsRunnerPath(fromFile) {
3743
+ const base = fromFile ?? fileURLToPath(import.meta.url);
3744
+ const candidates = [
3745
+ join18(dirname5(base), "app-skills-mcp-serve.cjs"),
3746
+ join18(dirname5(base), "app-skills-mcp-serve.ts")
3747
+ ];
3748
+ for (const candidate of candidates) {
3749
+ if (existsSync15(candidate))
3750
+ return candidate;
3751
+ }
3752
+ throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
3753
+ }
3754
+
3755
+ // src/client/acp-client.ts
3756
+ import { randomUUID as randomUUID2 } from "node:crypto";
3757
+
3758
+ // src/resources/eligibility.ts
3759
+ var NATIVE_ELIGIBLE_BRIDGE_VERSIONS = {
3760
+ "codex-acp": ["2.2.2"],
3761
+ opencode: ["1.18.35"],
3762
+ claude: ["0.91.0"],
3763
+ agy: ["0.1.24"]
3764
+ };
3765
+ function resolveRuntimeEligibility(runtimeId) {
3766
+ const id = (runtimeId ?? "").trim();
3767
+ if (!id || !(id in NATIVE_ELIGIBLE_BRIDGE_VERSIONS)) {
3768
+ return { eligible: false, reason: "runtime-not-verified" };
3769
+ }
3770
+ return { eligible: true };
3771
+ }
3772
+ function isSupportedBridgeVersion(runtimeId, version) {
3773
+ const versions = NATIVE_ELIGIBLE_BRIDGE_VERSIONS[(runtimeId ?? "").trim()];
3774
+ if (!versions)
3775
+ return { eligible: false, reason: "runtime-not-verified" };
3776
+ const normalized = version?.trim().replace(/^v/, "");
3777
+ if (!normalized)
3778
+ return { eligible: false, reason: "unknown-bridge-version" };
3779
+ if (!versions.includes(normalized))
3780
+ return { eligible: false, reason: "unsupported-bridge-version" };
3781
+ return { eligible: true };
3782
+ }
3783
+
3114
3784
  // src/session/session-capabilities.ts
3115
3785
  function parseLoadSessionSupported(caps) {
3116
3786
  return caps.loadSession === true;
@@ -3147,11 +3817,13 @@ class AcpSessionHandle {
3147
3817
  client;
3148
3818
  restoreMethod;
3149
3819
  configOptions;
3150
- constructor(sessionId, client, restoreMethod, configOptions) {
3820
+ resourceReport;
3821
+ constructor(sessionId, client, restoreMethod, configOptions, resourceReport) {
3151
3822
  this.sessionId = sessionId;
3152
3823
  this.client = client;
3153
3824
  this.restoreMethod = restoreMethod;
3154
3825
  this.configOptions = configOptions;
3826
+ this.resourceReport = resourceReport;
3155
3827
  }
3156
3828
  async prompt(promptText, options) {
3157
3829
  return this.client.promptSession(this.sessionId, promptText, options);
@@ -3180,6 +3852,10 @@ class AcpClient {
3180
3852
  clientInfo;
3181
3853
  dataDir;
3182
3854
  extraEnv;
3855
+ configurationScope;
3856
+ sessionConfig = null;
3857
+ resourcesDir;
3858
+ processScopeKey = randomUUID2();
3183
3859
  callbacks;
3184
3860
  terminals = new AcpTerminalManager;
3185
3861
  processHandle = null;
@@ -3187,6 +3863,17 @@ class AcpClient {
3187
3863
  sdkConnection = null;
3188
3864
  streamHandle = null;
3189
3865
  initResponse = null;
3866
+ inflightPrompts = new Set;
3867
+ resourcePrep = null;
3868
+ connectionGen = 0;
3869
+ attachSkillsMcp;
3870
+ sessionLedger = new Map;
3871
+ compatSentKeys = new Set;
3872
+ compatSnapshots = new Map;
3873
+ get resourceReport() {
3874
+ const report = this.resourcePrep?.report;
3875
+ return report ? { ...report, skillsFound: [...report.skillsFound] } : null;
3876
+ }
3190
3877
  constructor(options) {
3191
3878
  this.workspaceRoot = options.workspaceRoot;
3192
3879
  this.clientInfo = {
@@ -3195,6 +3882,14 @@ class AcpClient {
3195
3882
  };
3196
3883
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
3197
3884
  this.extraEnv = options.env ?? {};
3885
+ if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
3886
+ throw new Error("resources.directory 必须是本机绝对路径");
3887
+ }
3888
+ this.configurationScope = options.resources?.configurationScope ?? "overlay";
3889
+ if (!["overlay", "session"].includes(this.configurationScope))
3890
+ throw new Error("Invalid resources.configurationScope");
3891
+ this.resourcesDir = options.resources?.directory ?? null;
3892
+ this.attachSkillsMcp = options.resources?.attachSkillsMcp !== false;
3198
3893
  this.callbacks = options.callbacks ?? {};
3199
3894
  const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
3200
3895
  this.adapter = getAcpRuntimeAdapter(runtimeId);
@@ -3221,6 +3916,14 @@ class AcpClient {
3221
3916
  return this.initResponse;
3222
3917
  }
3223
3918
  async connect() {
3919
+ if (this.inflightPrompts.size > 0)
3920
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
3921
+ if (this.isConnected && this.initResponse)
3922
+ return ok({ status: this.status, init: this.initResponse });
3923
+ if (this.currentStatus === "connecting")
3924
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在连接" });
3925
+ this.connectionGen += 1;
3926
+ const connectGen = this.connectionGen;
3224
3927
  try {
3225
3928
  this.setStatus("connecting");
3226
3929
  const blocker = this.adapter.resolveSpawnBlocker?.();
@@ -3246,16 +3949,105 @@ class AcpClient {
3246
3949
  ...baseEnv,
3247
3950
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
3248
3951
  };
3952
+ let resourceEnv = {};
3953
+ let profileTag = null;
3954
+ if (this.resourcesDir && this.configurationScope === "session") {
3955
+ const profile = await createSessionConfigHome(this.runtimeInfo.id, this.resourcesDir);
3956
+ if (connectGen !== this.connectionGen || this.status !== "connecting") {
3957
+ await profile.dispose();
3958
+ return err({ code: "CANCELLED", message: "连接已取消" });
3959
+ }
3960
+ this.sessionConfig = profile;
3961
+ resourceEnv = this.sessionConfig.env;
3962
+ const load = readAppResourcesDir(this.resourcesDir);
3963
+ this.resourcePrep = { profileTag: null, report: {
3964
+ rulesApplied: false,
3965
+ rulesPrepared: false,
3966
+ skillsApplied: false,
3967
+ rulesChars: load.rules?.chars ?? 0,
3968
+ profileDigest: digestAppResources(load),
3969
+ skillsFound: load.skills.map((s) => s.name),
3970
+ configurationScope: "session",
3971
+ configurationDirectory: this.sessionConfig.directory,
3972
+ configurationRulesFile: this.sessionConfig.rulesFile,
3973
+ reason: this.sessionConfig.nativeRules ? "isolated-config-not-runtime-verified" : "isolated-config-rule-discovery-not-verified"
3974
+ } };
3975
+ } else if (this.resourcesDir && this.adapter.prepareAppResources) {
3976
+ try {
3977
+ const prep = await this.adapter.prepareAppResources({
3978
+ directory: this.resourcesDir,
3979
+ command: effectiveRuntime.command,
3980
+ workspaceRoot: this.workspaceRoot,
3981
+ env: { ...process.env, ...spawnEnv.env }
3982
+ });
3983
+ if (prep.env)
3984
+ resourceEnv = prep.env;
3985
+ prep.report.rulesPrepared = prep.report.rulesPrepared ?? prep.report.rulesApplied;
3986
+ prep.report.rulesApplied = false;
3987
+ prep.report.skillsApplied = false;
3988
+ const digest = prep.report.profileDigest;
3989
+ profileTag = digest ? `${this.runtimeInfo.id}:resources@${digest.slice(0, 16)}` : null;
3990
+ this.resourcePrep = { profileTag, report: prep.report };
3991
+ } catch (error) {
3992
+ this.resourcePrep = {
3993
+ profileTag: null,
3994
+ report: {
3995
+ rulesApplied: false,
3996
+ rulesChars: 0,
3997
+ profileDigest: null,
3998
+ skillsFound: [],
3999
+ reason: "prepare-failed"
4000
+ }
4001
+ };
4002
+ this.callbacks.onLog?.("warn", "应用资源准备失败,已回退兼容", {
4003
+ error: error instanceof Error ? error.message : String(error)
4004
+ });
4005
+ }
4006
+ } else {
4007
+ const load = this.resourcesDir ? readAppResourcesDir(this.resourcesDir) : null;
4008
+ this.resourcePrep = load ? { profileTag: null, report: {
4009
+ rulesApplied: false,
4010
+ rulesPrepared: false,
4011
+ skillsApplied: false,
4012
+ rulesChars: load.rules?.chars ?? 0,
4013
+ profileDigest: digestAppResources(load),
4014
+ skillsFound: load.skills.map((s) => s.name),
4015
+ reason: "runtime-not-supported"
4016
+ } } : null;
4017
+ }
4018
+ const finalEnv = { ...spawnEnv.env, ...resourceEnv };
3249
4019
  await this.adapter.beforeSpawn?.();
3250
- const processHandle = spawnAcpProcess({
4020
+ if (connectGen !== this.connectionGen || this.status !== "connecting")
4021
+ return err({ code: "CANCELLED", message: "连接已取消" });
4022
+ let reuseDegraded = false;
4023
+ let reusedHandle = null;
4024
+ if (profileTag) {
4025
+ const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
4026
+ expectedTag: profileTag,
4027
+ scopeKey: this.processScopeKey,
4028
+ isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
4029
+ });
4030
+ if (reuse.status === "hit") {
4031
+ reusedHandle = reuse.handle;
4032
+ } else if (reuse.status === "busy") {
4033
+ reusedHandle = reuse.handle;
4034
+ reuseDegraded = true;
4035
+ this.callbacks.onLog?.("warn", "应用资源摘要已变更但旧进程正忙,沿用旧进程并降级,新摘要下次冷启动生效");
4036
+ }
4037
+ }
4038
+ const processHandle = reusedHandle ?? spawnAcpProcess({
3251
4039
  runtime: effectiveRuntime,
3252
4040
  cwd: this.workspaceRoot,
3253
- env: spawnEnv.env,
4041
+ scopeKey: this.processScopeKey,
4042
+ env: finalEnv,
3254
4043
  envRemove: spawnEnv.envRemove,
4044
+ profileTag,
3255
4045
  onStderrLine: (line) => {
3256
4046
  this.callbacks.onStderrLine?.(line);
3257
4047
  },
3258
4048
  onExit: (code, signal) => {
4049
+ if (this.connectionGen !== connectGen)
4050
+ return;
3259
4051
  this.callbacks.onLog?.("warn", `Agent 进程已退出 (code: ${code}, signal: ${signal})`);
3260
4052
  if (this.status === "connected" || this.status === "connecting") {
3261
4053
  this.disconnect("Agent 进程异常终止");
@@ -3306,9 +4098,28 @@ class AcpClient {
3306
4098
  }
3307
4099
  });
3308
4100
  this.initResponse = initResp;
4101
+ if (this.resourcePrep) {
4102
+ const agentInfo = initResp?.agentInfo;
4103
+ const bridgeVersion = typeof agentInfo?.version === "string" ? agentInfo.version : undefined;
4104
+ const supported = isSupportedBridgeVersion(this.runtimeInfo.id, bridgeVersion).eligible && (this.adapter.supportedBridgeVersions?.includes(bridgeVersion?.replace(/^v/, "") ?? "") ?? false);
4105
+ this.resourcePrep.report.bridgeVersion = bridgeVersion;
4106
+ this.resourcePrep.report.bridgeSupported = supported;
4107
+ if (this.processHandle)
4108
+ this.processHandle.bridgeVersion = bridgeVersion;
4109
+ if (supported && this.resourcePrep.report.reason === "native-session-version-not-verified")
4110
+ delete this.resourcePrep.report.reason;
4111
+ if (!supported) {
4112
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "unsupported-bridge-version";
4113
+ }
4114
+ if (reuseDegraded) {
4115
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "busy-deferred-stale-rules";
4116
+ }
4117
+ }
3309
4118
  this.setStatus("connected");
3310
4119
  return ok({ status: "connected", init: initResp });
3311
4120
  } catch (e) {
4121
+ if (connectGen !== this.connectionGen)
4122
+ return err({ code: "CANCELLED", message: "连接已被新请求取代" });
3312
4123
  const message = e instanceof Error ? e.message : String(e);
3313
4124
  this.setStatus("error", message);
3314
4125
  await this.disconnect(message);
@@ -3347,6 +4158,29 @@ class AcpClient {
3347
4158
  const resumeSupported = Boolean(init && parseResumeSessionSupported(init.agentCapabilities));
3348
4159
  const loadSupported = Boolean(init && parseLoadSessionSupported(init.agentCapabilities));
3349
4160
  try {
4161
+ let skillsExposed = "none";
4162
+ let mcpServers = options?.mcpServers ?? [];
4163
+ if (this.resourcesDir && this.attachSkillsMcp) {
4164
+ try {
4165
+ const descriptor = buildAppSkillsMcpServer(this.resourcesDir);
4166
+ const callerNames = new Set;
4167
+ for (const entry of mcpServers) {
4168
+ if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
4169
+ callerNames.add(entry.name);
4170
+ }
4171
+ }
4172
+ if (callerNames.has(descriptor.name)) {
4173
+ this.callbacks.onLog?.("warn", "调用方已有同名技能 MCP 服务,保留调用方版本", { name: descriptor.name });
4174
+ } else {
4175
+ mcpServers = [...mcpServers, descriptor];
4176
+ skillsExposed = "mcp-exposed";
4177
+ }
4178
+ } catch (error) {
4179
+ this.callbacks.onLog?.("warn", "技能 MCP 描述符构建失败,本次会话无技能 MCP", {
4180
+ error: error instanceof Error ? error.message : String(error)
4181
+ });
4182
+ }
4183
+ }
3350
4184
  const openResult = await restoreOrCreateAcpSession({
3351
4185
  request: async (method, params) => {
3352
4186
  return sdkRequest(agent, method, params);
@@ -3355,12 +4189,27 @@ class AcpClient {
3355
4189
  resumeSessionId: options?.resumeSessionId ?? null,
3356
4190
  resumeSupported,
3357
4191
  loadSupported,
3358
- mcpServers: options?.mcpServers ?? [],
4192
+ mcpServers,
4193
+ sessionMeta: (!this.sessionConfig || this.runtimeInfo.id === "agy") && this.resourcesDir && this.resourcePrep?.report.bridgeSupported ? this.adapter.appResourceSessionMeta?.(this.resourcesDir) : undefined,
3359
4194
  log: (level, msg, meta) => {
3360
4195
  this.callbacks.onLog?.(level, msg, meta);
3361
4196
  }
3362
4197
  });
3363
- const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions);
4198
+ if (!openResult.mcpServersAccepted)
4199
+ skillsExposed = "none";
4200
+ this.sessionLedger.set(openResult.sessionId, {
4201
+ restoreMethod: openResult.restoreMethod,
4202
+ gen: this.connectionGen,
4203
+ skillsExposed,
4204
+ nativeRules: openResult.nativeSessionAccepted
4205
+ });
4206
+ const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions, this.resourcePrep?.report ? {
4207
+ ...this.resourcePrep.report,
4208
+ skillsFound: [...this.resourcePrep.report.skillsFound],
4209
+ skillsExposed,
4210
+ rulesApplied: openResult.nativeSessionAccepted || !this.adapter.appResourceSessionMeta && openResult.restoreMethod === "new" && this.resourcePrep.report.bridgeSupported === true && this.resourcePrep.report.rulesPrepared === true,
4211
+ ...openResult.restoreMethod !== "new" && !openResult.nativeSessionAccepted ? { reason: "session-restored-not-verified" } : {}
4212
+ } : null);
3364
4213
  return ok(handle);
3365
4214
  } catch (e) {
3366
4215
  const message = e instanceof Error ? e.message : String(e);
@@ -3371,6 +4220,7 @@ class AcpClient {
3371
4220
  if (!this.sdkConnection?.agent) {
3372
4221
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
3373
4222
  }
4223
+ this.inflightPrompts.add(sessionId);
3374
4224
  try {
3375
4225
  const prompt = [{ type: "text", text: promptText }];
3376
4226
  for (const image of options?.images ?? []) {
@@ -3378,16 +4228,52 @@ class AcpClient {
3378
4228
  continue;
3379
4229
  prompt.push({ type: "image", mimeType: image.mimeType, data: image.data });
3380
4230
  }
4231
+ const compat = this.buildCompatPrepend(sessionId);
4232
+ const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
3381
4233
  const response = await sdkRequest(this.sdkConnection.agent, methods2.agent.session.prompt, {
3382
4234
  sessionId,
3383
- prompt
4235
+ prompt: blocks
3384
4236
  }, options?.timeoutMs);
3385
4237
  return ok(response);
3386
4238
  } catch (e) {
3387
4239
  const message = e instanceof Error ? e.message : String(e);
3388
4240
  return err({ code: "ACP_PROTOCOL_ERROR", message });
4241
+ } finally {
4242
+ this.inflightPrompts.delete(sessionId);
3389
4243
  }
3390
4244
  }
4245
+ buildCompatPrepend(sessionId) {
4246
+ if (!this.resourcesDir)
4247
+ return null;
4248
+ if (this.sessionConfig?.nativeRules)
4249
+ return null;
4250
+ const entry = this.sessionLedger.get(sessionId);
4251
+ if (!entry)
4252
+ return null;
4253
+ const connReport = this.resourcePrep?.report;
4254
+ const nativelyDelivered = entry.nativeRules || !this.adapter.appResourceSessionMeta && entry.restoreMethod === "new" && entry.gen === this.connectionGen && connReport?.rulesPrepared === true && connReport?.bridgeSupported === true;
4255
+ if (nativelyDelivered)
4256
+ return null;
4257
+ const load = readAppResourcesDir(this.resourcesDir);
4258
+ const rulesText = readAppRulesText(this.resourcesDir);
4259
+ const digest = digestAppResources(load);
4260
+ const key = compatDeliveryKey(sessionId, this.connectionGen, digest);
4261
+ if (this.compatSentKeys.has(key))
4262
+ return null;
4263
+ const text = buildCompatGuideText({
4264
+ rulesText,
4265
+ skills: load.skills.map((s) => ({ name: s.name, description: s.description })),
4266
+ skillsViaMcp: entry.skillsExposed === "mcp-exposed",
4267
+ digest,
4268
+ sessionId,
4269
+ generation: this.connectionGen
4270
+ });
4271
+ if (!text)
4272
+ return null;
4273
+ this.compatSnapshots.set(key, { text, digest });
4274
+ this.compatSentKeys.add(key);
4275
+ return text;
4276
+ }
3391
4277
  async setSessionConfigOption(sessionId, configId, value) {
3392
4278
  if (!this.sdkConnection?.agent) {
3393
4279
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
@@ -3406,6 +4292,16 @@ class AcpClient {
3406
4292
  }
3407
4293
  async disconnect(reason) {
3408
4294
  this.setStatus("disconnected", reason);
4295
+ this.resourcePrep = null;
4296
+ const capabilities = this.initResponse?.agentCapabilities?.sessionCapabilities;
4297
+ if (capabilities?.close && this.sdkConnection?.agent) {
4298
+ const failed = await closeAcpSessions(this.sdkConnection.agent, this.sessionLedger.keys());
4299
+ if (failed.length)
4300
+ this.callbacks.onLog?.("warn", "Session close failed before process teardown", { count: failed.length });
4301
+ }
4302
+ this.sessionLedger.clear();
4303
+ this.compatSentKeys.clear();
4304
+ this.compatSnapshots.clear();
3409
4305
  try {
3410
4306
  this.streamHandle?.dispose();
3411
4307
  this.sdkConnection?.close();
@@ -3421,6 +4317,15 @@ class AcpClient {
3421
4317
  } catch {}
3422
4318
  this.processHandle = null;
3423
4319
  }
4320
+ const config = this.sessionConfig;
4321
+ this.sessionConfig = null;
4322
+ if (config) {
4323
+ try {
4324
+ await config.dispose();
4325
+ } catch {
4326
+ this.callbacks.onLog?.("warn", "Session configuration cleanup failed; directory retained", { directory: config.directory });
4327
+ }
4328
+ }
3424
4329
  }
3425
4330
  setStatus(status, detail) {
3426
4331
  this.status = status;
@@ -4346,6 +5251,10 @@ export {
4346
5251
  ACP_EARLY_EXIT_WINDOW_MS,
4347
5252
  ACP_SDK_REQUEST_TIMEOUT_MS,
4348
5253
  AGY_ACP_NPM_PACKAGE,
5254
+ APP_RESOURCE_CAPABILITIES,
5255
+ APP_RULES_FILE,
5256
+ APP_SKILLS_DIR,
5257
+ APP_SKILL_FILE,
4349
5258
  AcpClient,
4350
5259
  AcpSessionHandle,
4351
5260
  AcpTerminalManager,
@@ -4364,6 +5273,7 @@ export {
4364
5273
  INKDOWN_VIRTUAL_DIR,
4365
5274
  INKDOWN_VIRTUAL_RESOURCES,
4366
5275
  LEGACY_ZED_CODEX_ACP_NPM_PACKAGE,
5276
+ NATIVE_ELIGIBLE_BRIDGE_VERSIONS,
4367
5277
  OPENCODE_CLI_NPM_PACKAGE,
4368
5278
  QuotaCache,
4369
5279
  acpReadTextFile,
@@ -4379,15 +5289,19 @@ export {
4379
5289
  callInkdownMcpTool,
4380
5290
  callInkdownTocTool,
4381
5291
  claudeAdapter,
5292
+ claudeResourceSessionMeta,
4382
5293
  clearAcpProvider,
4383
5294
  clearCursorCatalogCache,
5295
+ closeAcpSessions,
4384
5296
  codexAdapter,
4385
5297
  connectSdkClient,
4386
5298
  copilotAdapter,
4387
5299
  createSdkStreamHandle,
5300
+ createSessionConfigHome,
4388
5301
  cursorAdapter,
4389
5302
  decideConnectAuth,
4390
5303
  deepseekAdapter,
5304
+ digestAppResources,
4391
5305
  disposeAllAcpProcesses,
4392
5306
  emptyAcpAuthPreflight,
4393
5307
  err,
@@ -4407,6 +5321,7 @@ export {
4407
5321
  getDefaultAgentDataDir,
4408
5322
  getLiveAcpProcess,
4409
5323
  handleInkdownMcpRpc,
5324
+ isAbsolutePathLike,
4410
5325
  isAppError,
4411
5326
  isBinaryDocumentPath,
4412
5327
  isCancelled,
@@ -4416,11 +5331,15 @@ export {
4416
5331
  isInkdownVirtualDirPath,
4417
5332
  isOk,
4418
5333
  isSpawnedAcpProcessAlive,
5334
+ isSupportedBridgeVersion,
4419
5335
  isTransientAcpTransportError,
4420
5336
  isValidCursorAuthFile,
4421
5337
  isValidOpencodeAuthFile,
4422
5338
  listAcpRuntimes,
4423
5339
  listLiveAcpRuntimeIds,
5340
+ mergeCodexConfigJson,
5341
+ mergeConfigTomlPreserving,
5342
+ mergeOpenCodeAppConfig,
4424
5343
  mergeTopLevelModelsIntoConfigOptions,
4425
5344
  ok,
4426
5345
  opencodeAdapter,
@@ -4434,7 +5353,11 @@ export {
4434
5353
  parsePromptCapabilities,
4435
5354
  parseRateLimitsFromStatusText,
4436
5355
  parseResumeSessionSupported,
5356
+ parseSkillFrontmatter,
4437
5357
  pickAllowOptionId,
5358
+ prepareClaudeResources,
5359
+ prepareCompatibilityResources,
5360
+ prepareOpenCodeResources,
4438
5361
  probeAgyAuth,
4439
5362
  probeClaudeAuth,
4440
5363
  probeClaudeQuota,
@@ -4449,6 +5372,8 @@ export {
4449
5372
  probeOpencodeQuota,
4450
5373
  provisionCustomProviderCodexHome,
4451
5374
  readAcpProxySettings,
5375
+ readAppResourcesDir,
5376
+ readAppRulesText,
4452
5377
  readStoredAcpProvider,
4453
5378
  registerAcpClientHandlers,
4454
5379
  resolveClaudeHome,
@@ -4464,6 +5389,7 @@ export {
4464
5389
  resolveOpencodeAuthCandidates,
4465
5390
  resolveOpencodeAuthFile,
4466
5391
  resolveOpencodeAuthPath,
5392
+ resolveRuntimeEligibility,
4467
5393
  restoreOrCreateAcpSession,
4468
5394
  runConnectAuthGate,
4469
5395
  saveAcpProvider,
@@ -4474,5 +5400,6 @@ export {
4474
5400
  synthesizeModelOptionFromTopLevelModels,
4475
5401
  toAppError,
4476
5402
  truncateOutputFromStart,
5403
+ tryReuseLiveAcpProcess,
4477
5404
  withAcpEarlyExitDetail
4478
5405
  };