@yitom/acp-client 0.1.7 → 0.1.8

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,244 @@ 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.8";
166
+ // src/resources/session-config.ts
167
+ import { existsSync } from "node:fs";
168
+ import { mkdtemp, mkdir, writeFile, readdir, readFile, lstat, realpath, rm } from "node:fs/promises";
169
+ import { tmpdir } from "node:os";
170
+ import { join as join2, resolve, relative, isAbsolute as isAbsolute2, sep } from "node:path";
171
+
172
+ // src/resources/app-resources.ts
173
+ import { createHash } from "node:crypto";
174
+ import { readdirSync, readFileSync, statSync } from "node:fs";
175
+ import { isAbsolute, join } from "node:path";
176
+ var APP_RULES_FILE = "AGENTS.md";
177
+ var APP_SKILLS_DIR = "skills";
178
+ var APP_SKILL_FILE = "SKILL.md";
179
+ function parseSkillFrontmatter(text) {
180
+ const lines = text.split(`
181
+ `);
182
+ if (lines[0]?.trim() !== "---")
183
+ return {};
184
+ const out = {};
185
+ for (let i = 1;i < lines.length; i += 1) {
186
+ const line = lines[i] ?? "";
187
+ if (line.trim() === "---")
188
+ break;
189
+ const cut = line.indexOf(":");
190
+ if (cut <= 0)
191
+ continue;
192
+ const key = line.slice(0, cut).trim().toLowerCase();
193
+ if (key !== "name" && key !== "description")
194
+ continue;
195
+ const value = line.slice(cut + 1).trim().replace(/^['"]|['"]$/g, "");
196
+ if (value)
197
+ out[key] = value;
198
+ }
199
+ return out;
200
+ }
201
+ function sha256Hex(text) {
202
+ return createHash("sha256").update(text, "utf8").digest("hex");
203
+ }
204
+ function readTextFile(path) {
205
+ try {
206
+ if (!statSync(path).isFile())
207
+ return null;
208
+ const text = readFileSync(path, "utf8");
209
+ return text.trim() ? text : null;
210
+ } catch {
211
+ return null;
212
+ }
213
+ }
214
+ function readAppResourcesDir(directory) {
215
+ const warnings = [];
216
+ if (!isAbsolute(directory))
217
+ return { directoryReadable: false, rules: null, skills: [], warnings: ["资源目录必须是本机绝对路径"] };
218
+ let directoryReadable = false;
219
+ try {
220
+ directoryReadable = statSync(directory).isDirectory();
221
+ } catch {
222
+ directoryReadable = false;
223
+ }
224
+ if (!directoryReadable) {
225
+ return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
226
+ }
227
+ let rules = null;
228
+ const rulesText = readTextFile(join(directory, APP_RULES_FILE));
229
+ if (rulesText === null) {
230
+ warnings.push(`缺常驻规则: ${APP_RULES_FILE}`);
231
+ } else {
232
+ rules = { chars: rulesText.length, digest: sha256Hex(`app-rules-v1
233
+ ${rulesText}`) };
234
+ }
235
+ const skills = [];
236
+ const skillsRoot = join(directory, APP_SKILLS_DIR);
237
+ let skillNames = [];
238
+ try {
239
+ if (statSync(skillsRoot).isDirectory()) {
240
+ skillNames = readdirSync(skillsRoot).filter((name) => {
241
+ try {
242
+ return statSync(join(skillsRoot, name)).isDirectory();
243
+ } catch {
244
+ return false;
245
+ }
246
+ });
247
+ }
248
+ } catch {
249
+ skillNames = [];
250
+ }
251
+ for (const name of skillNames.sort()) {
252
+ const rel = `${APP_SKILLS_DIR}/${name}/${APP_SKILL_FILE}`;
253
+ const text = readTextFile(join(directory, rel));
254
+ if (text === null) {
255
+ warnings.push(`技能缺正文已跳过: ${rel}`);
256
+ continue;
257
+ }
258
+ const front = parseSkillFrontmatter(text);
259
+ const skillName = front.name || name;
260
+ if (skills.some((s) => s.name === skillName)) {
261
+ warnings.push(`技能重名已跳过(保留首个): ${skillName}`);
262
+ continue;
263
+ }
264
+ const description = front.description || "";
265
+ skills.push({
266
+ name: skillName,
267
+ description,
268
+ path: rel,
269
+ chars: text.length,
270
+ digest: sha256Hex(`app-skill-v1
271
+ ${skillName}
272
+ ${description}
273
+ ${text}`)
274
+ });
275
+ }
276
+ return { directoryReadable: true, rules, skills, warnings };
277
+ }
278
+ function digestAppResources(load) {
279
+ if (!load.rules)
280
+ return null;
281
+ const skillPart = load.skills.map((s) => `${s.name}:${s.digest}`).join(`
282
+ `);
283
+ return sha256Hex(`app-resources-v1
284
+ ${load.rules.digest}
285
+ ${skillPart}`);
286
+ }
287
+ function readAppRulesText(directory) {
288
+ return readTextFile(join(directory, APP_RULES_FILE));
289
+ }
290
+ function isAbsolutePathLike(path) {
291
+ return isAbsolute(path);
292
+ }
293
+
294
+ // src/resources/session-config.ts
295
+ async function createSessionConfigHome(runtime, resources) {
296
+ if (!isAbsolute2(resources))
297
+ throw new Error("Resources must be an absolute path");
298
+ const id = runtime === "cursor" ? "cursor-cli" : runtime;
299
+ const supported = ["agy", "codex-acp", "claude", "gemini", "copilot", "cursor-cli", "opencode", "opencode-v2"];
300
+ if (!supported.includes(id))
301
+ throw new Error("Session configuration home is not verified for runtime: " + runtime);
302
+ const text = readAppRulesText(resources);
303
+ if (!text)
304
+ throw new Error("Session configuration requires nonempty AGENTS.md");
305
+ const parent = resolve(tmpdir());
306
+ const directory = await mkdtemp(join2(parent, "acp-session-config-"));
307
+ const checkRoot = () => {
308
+ if (resolve(directory) === parent || !resolve(directory).startsWith(parent + sep) || !relative(parent, directory).startsWith("acp-session-config-"))
309
+ throw new Error("Unsafe configuration cleanup target");
310
+ };
311
+ const dispose = async () => {
312
+ checkRoot();
313
+ let failure;
314
+ for (let i = 0;i < 30; i++) {
315
+ try {
316
+ await rm(directory, { recursive: true, force: true });
317
+ return;
318
+ } catch (error) {
319
+ failure = error;
320
+ await new Promise((r) => setTimeout(r, 100));
321
+ }
322
+ }
323
+ throw failure;
324
+ };
325
+ try {
326
+ const config = join2(directory, "config");
327
+ await mkdir(config, { recursive: true, mode: 448 });
328
+ let env;
329
+ let rulesFile;
330
+ let skillsRoot = join2(config, "skills");
331
+ let nativeRules = true;
332
+ if (id === "agy") {
333
+ rulesFile = join2(config, "AGENTS.md");
334
+ env = { AGY_ACP_RESOURCES_DIR: config };
335
+ nativeRules = false;
336
+ } else if (id === "gemini") {
337
+ const root = join2(directory, "home", ".gemini");
338
+ await mkdir(root, { recursive: true, mode: 448 });
339
+ rulesFile = join2(root, "GEMINI.md");
340
+ skillsRoot = join2(root, "skills");
341
+ env = { GEMINI_CLI_HOME: join2(directory, "home") };
342
+ } else if (id === "claude") {
343
+ rulesFile = join2(config, "CLAUDE.md");
344
+ env = { CLAUDE_CONFIG_DIR: config };
345
+ } else if (id === "codex-acp") {
346
+ rulesFile = join2(config, "AGENTS.md");
347
+ env = { CODEX_HOME: config };
348
+ } else if (id === "copilot") {
349
+ rulesFile = join2(config, "copilot-instructions.md");
350
+ env = { COPILOT_HOME: config, COPILOT_CUSTOM_INSTRUCTIONS_DIRS: config, COPILOT_SKILLS_DIRS: skillsRoot };
351
+ await writeFile(join2(config, "AGENTS.md"), text, { mode: 384 });
352
+ } else if (id === "cursor-cli") {
353
+ rulesFile = join2(config, "AGENTS.md");
354
+ env = { CURSOR_CONFIG_DIR: config };
355
+ nativeRules = false;
356
+ } else {
357
+ const root = join2(directory, "xdg-config", "opencode");
358
+ await mkdir(root, { recursive: true, mode: 448 });
359
+ rulesFile = join2(root, "AGENTS.md");
360
+ skillsRoot = join2(root, "skills");
361
+ 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") };
362
+ if (id === "opencode")
363
+ env.OPENCODE_CONFIG_DIR = root;
364
+ const skills = id === "opencode" ? { paths: [skillsRoot] } : [skillsRoot];
365
+ await writeFile(join2(root, "opencode.json"), JSON.stringify({ instructions: [rulesFile], skills }), { mode: 384 });
366
+ }
367
+ await writeFile(rulesFile, text, { mode: 384 });
368
+ const input = join2(resources, "skills");
369
+ try {
370
+ const info = await lstat(input);
371
+ if (info.isSymbolicLink() || !info.isDirectory())
372
+ throw new Error("Skill root must be a regular directory");
373
+ const physical = await realpath(input);
374
+ const copy = async (from, to) => {
375
+ await mkdir(to, { recursive: true, mode: 448 });
376
+ for (const entry of await readdir(from, { withFileTypes: true })) {
377
+ const src = join2(from, entry.name);
378
+ const info = await lstat(src);
379
+ if (info.isSymbolicLink())
380
+ throw new Error("Skill symlink is not allowed");
381
+ const actual = await realpath(src);
382
+ const rel = relative(physical, actual);
383
+ if (rel.startsWith(".." + sep) || rel === ".." || isAbsolute2(rel))
384
+ throw new Error("Skill path escapes resources");
385
+ if (info.isDirectory())
386
+ await copy(src, join2(to, entry.name));
387
+ else if (info.isFile() && entry.name.toLowerCase().endsWith(".md"))
388
+ await writeFile(join2(to, entry.name), await readFile(src), { mode: 384 });
389
+ }
390
+ };
391
+ await copy(input, skillsRoot);
392
+ } catch (error) {
393
+ if (error.code !== "ENOENT" || existsSync(input))
394
+ throw error;
395
+ }
396
+ return { directory, env, rulesFile, nativeRules, dispose };
397
+ } catch (error) {
398
+ await dispose();
399
+ throw error;
400
+ }
401
+ }
402
+
166
403
  // src/session/available-commands.ts
167
404
  function normalizeCommand(raw) {
168
405
  if (!raw || typeof raw !== "object")
@@ -412,15 +649,15 @@ import {
412
649
  } from "@agentclientprotocol/sdk";
413
650
 
414
651
  // src/runtimes/codex/quota.ts
415
- import { existsSync as existsSync2, readFileSync } from "node:fs";
416
- import { join as join2 } from "node:path";
652
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
653
+ import { join as join4 } from "node:path";
417
654
  import { spawn } from "node:child_process";
418
655
  import readline from "node:readline";
419
656
 
420
657
  // src/runtimes/codex/codex-auth-preflight.ts
421
- import { existsSync } from "node:fs";
658
+ import { existsSync as existsSync2 } from "node:fs";
422
659
  import { homedir } from "node:os";
423
- import { join } from "node:path";
660
+ import { join as join3 } from "node:path";
424
661
  function emptyAcpAuthPreflight() {
425
662
  return {
426
663
  codexHome: "",
@@ -437,12 +674,12 @@ function resolveCodexHome() {
437
674
  const fromEnv = process.env.CODEX_HOME?.trim();
438
675
  if (fromEnv)
439
676
  return fromEnv;
440
- return join(homedir(), ".codex");
677
+ return join3(homedir(), ".codex");
441
678
  }
442
679
  function probeCodexAuth() {
443
680
  const codexHome = resolveCodexHome();
444
- const hasCodexHome = existsSync(codexHome);
445
- const hasAuthFile = existsSync(join(codexHome, "auth.json"));
681
+ const hasCodexHome = existsSync2(codexHome);
682
+ const hasAuthFile = existsSync2(join3(codexHome, "auth.json"));
446
683
  const hasApiKeyEnv = Boolean(process.env.CODEX_API_KEY?.trim() || process.env.OPENAI_API_KEY?.trim());
447
684
  return {
448
685
  codexHome,
@@ -492,7 +729,7 @@ async function queryCodexAppServer(timeoutMs = 1e4) {
492
729
  };
493
730
  timer = setTimeout(() => cleanup(null), timeoutMs);
494
731
  try {
495
- const cmd = process.platform === "win32" ? "codex" : existsSync2("/mnt/c/Users") ? "codex.exe" : "codex";
732
+ const cmd = process.platform === "win32" ? "codex" : existsSync3("/mnt/c/Users") ? "codex.exe" : "codex";
496
733
  proc = spawn(cmd, ["app-server"], {
497
734
  stdio: ["pipe", "pipe", "pipe"],
498
735
  shell: process.platform === "win32",
@@ -563,13 +800,13 @@ function formatEpochTime(epochSeconds) {
563
800
  }
564
801
  async function probeCodexQuota(options) {
565
802
  const codexHome = resolveCodexHome();
566
- const authPath = join2(codexHome, "auth.json");
803
+ const authPath = join4(codexHome, "auth.json");
567
804
  let accountEmail;
568
805
  let accountPlan = "Codex Free / Local";
569
806
  let isLoggedIn = false;
570
- if (existsSync2(authPath)) {
807
+ if (existsSync3(authPath)) {
571
808
  try {
572
- const authData = JSON.parse(readFileSync(authPath, "utf8"));
809
+ const authData = JSON.parse(readFileSync2(authPath, "utf8"));
573
810
  if (authData.OPENAI_API_KEY) {
574
811
  isLoggedIn = true;
575
812
  accountPlan = "OpenAI API Key";
@@ -660,8 +897,92 @@ async function probeCodexQuota(options) {
660
897
  }
661
898
 
662
899
  // 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";
900
+ import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "node:fs/promises";
901
+ import { dirname, join as join7 } from "node:path";
902
+ import { homedir as homedir3 } from "node:os";
903
+ import { existsSync as existsSync5 } from "node:fs";
904
+ import { createHash as createHash2 } from "node:crypto";
905
+
906
+ // src/resources/config-text.ts
907
+ function mergeCodexConfigJson(input) {
908
+ const block = (input.hostBlock ?? "").trim();
909
+ if (!block)
910
+ return { ok: false, reason: "empty-block" };
911
+ const raw = (input.existingRaw ?? "").trim();
912
+ if (!raw) {
913
+ return { ok: true, json: JSON.stringify({ developer_instructions: block }), preservedUserInstructions: false };
914
+ }
915
+ let parsed;
916
+ try {
917
+ parsed = JSON.parse(raw);
918
+ } catch {
919
+ return { ok: false, reason: "invalid-json" };
920
+ }
921
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
922
+ return { ok: false, reason: "invalid-json" };
923
+ }
924
+ const merged = { ...parsed };
925
+ const existing = merged["developer_instructions"];
926
+ if (existing === undefined) {
927
+ merged["developer_instructions"] = block;
928
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: false };
929
+ }
930
+ if (typeof existing !== "string") {
931
+ return { ok: false, reason: "conflicting-value" };
932
+ }
933
+ const kept = existing.trim();
934
+ merged["developer_instructions"] = kept ? `${block}
935
+
936
+ ${kept}` : block;
937
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: kept !== "" };
938
+ }
939
+ function mergeConfigTomlPreserving(input) {
940
+ const block = (input.replacementBlock ?? "").trim() ? `${input.replacementBlock.trim()}
941
+ ` : "";
942
+ if (!input.existingText || !input.existingText.trim())
943
+ return block;
944
+ if (/"""|'''/.test(input.existingText) || /^\s*\[.*["'].*\]|^\s*\[\[|^\s*["'](?:model|model_provider)["']\s*=/m.test(input.existingText)) {
945
+ throw new Error("复杂 TOML 配置需要结构化合并,已保留原文件");
946
+ }
947
+ const topKeys = new Set(input.managedTopKeys);
948
+ const tables = new Set(input.managedTables);
949
+ const out = [];
950
+ let inManagedTable = false;
951
+ let inAnyTable = false;
952
+ for (const line of input.existingText.split(`
953
+ `)) {
954
+ const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(line)?.[1]?.trim() ?? null;
955
+ if (header !== null) {
956
+ inAnyTable = true;
957
+ inManagedTable = tables.has(header);
958
+ if (!inManagedTable)
959
+ out.push(line);
960
+ continue;
961
+ }
962
+ if (inManagedTable)
963
+ continue;
964
+ if (!inAnyTable) {
965
+ const key = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1];
966
+ if (key && topKeys.has(key))
967
+ continue;
968
+ }
969
+ out.push(line);
970
+ }
971
+ const kept = out.join(`
972
+ `).trim();
973
+ if (!kept)
974
+ return block;
975
+ const tableAt = block.search(/^\s*\[/m);
976
+ if (tableAt < 0)
977
+ return block + `
978
+ ` + kept + `
979
+ `;
980
+ return block.slice(0, tableAt).trimEnd() + `
981
+
982
+ ` + kept + `
983
+
984
+ ` + block.slice(tableAt);
985
+ }
665
986
 
666
987
  // src/runtimes/codex/codex-provider-home.ts
667
988
  var INKDOWN_PROVIDER_ID = "inkdown-custom";
@@ -693,13 +1014,13 @@ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
693
1014
  }
694
1015
 
695
1016
  // 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";
1017
+ import { mkdir as mkdir2, readFile as readFile2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
1018
+ import { existsSync as existsSync4 } from "node:fs";
1019
+ import { join as join6 } from "node:path";
699
1020
 
700
1021
  // src/client/acp-paths.ts
701
1022
  import { homedir as homedir2 } from "node:os";
702
- import { join as join3 } from "node:path";
1023
+ import { join as join5 } from "node:path";
703
1024
  function getDefaultAgentDataDir() {
704
1025
  if (process.env.INKDOWN_DATA_DIR) {
705
1026
  return process.env.INKDOWN_DATA_DIR;
@@ -708,20 +1029,20 @@ function getDefaultAgentDataDir() {
708
1029
  return process.env.ACP_DATA_DIR;
709
1030
  }
710
1031
  if (process.platform === "win32") {
711
- return process.env.LOCALAPPDATA || process.env.APPDATA || join3(homedir2(), "AppData", "Local", "inkdown");
1032
+ return process.env.LOCALAPPDATA || process.env.APPDATA || join5(homedir2(), "AppData", "Local", "inkdown");
712
1033
  }
713
1034
  if (process.platform === "darwin") {
714
- return join3(homedir2(), "Library", "Application Support", "inkdown");
1035
+ return join5(homedir2(), "Library", "Application Support", "inkdown");
715
1036
  }
716
- return process.env.XDG_DATA_HOME || join3(homedir2(), ".local", "share", "inkdown");
1037
+ return process.env.XDG_DATA_HOME || join5(homedir2(), ".local", "share", "inkdown");
717
1038
  }
718
1039
 
719
1040
  // src/runtimes/codex/codex-provider.ts
720
1041
  function providerFilePath(dir) {
721
- return join4(dir, "agent", "provider.json");
1042
+ return join6(dir, "agent", "provider.json");
722
1043
  }
723
1044
  function providerHomePath(dir) {
724
- return join4(dir, "agent", "codex-home");
1045
+ return join6(dir, "agent", "codex-home");
725
1046
  }
726
1047
  function toStatus(stored) {
727
1048
  if (!stored)
@@ -747,10 +1068,10 @@ function validate(payload) {
747
1068
  }
748
1069
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
749
1070
  const file = providerFilePath(dir);
750
- if (!existsSync3(file))
1071
+ if (!existsSync4(file))
751
1072
  return null;
752
1073
  try {
753
- const raw = JSON.parse(await readFile(file, "utf8"));
1074
+ const raw = JSON.parse(await readFile2(file, "utf8"));
754
1075
  if (typeof raw.baseUrl !== "string" || typeof raw.model !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
755
1076
  return null;
756
1077
  }
@@ -776,7 +1097,7 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
776
1097
  const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
777
1098
  if (!apiKey)
778
1099
  return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
779
- await mkdir(join4(dir, "agent"), { recursive: true });
1100
+ await mkdir2(join6(dir, "agent"), { recursive: true });
780
1101
  const stored = {
781
1102
  name: payload.name?.trim() || undefined,
782
1103
  baseUrl: payload.baseUrl.trim(),
@@ -784,11 +1105,11 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
784
1105
  apiKey,
785
1106
  wireApi: payload.wireApi === "responses" ? "responses" : "chat"
786
1107
  };
787
- await writeFile(file, JSON.stringify(stored, null, 2), "utf8");
1108
+ await writeFile2(file, JSON.stringify(stored, null, 2), "utf8");
788
1109
  return ok(toStatus(stored));
789
1110
  }
790
1111
  async function clearAcpProvider(dir = getDefaultAgentDataDir()) {
791
- await rm(providerFilePath(dir), { force: true });
1112
+ await rm2(providerFilePath(dir), { force: true });
792
1113
  return ok(undefined);
793
1114
  }
794
1115
  function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
@@ -798,8 +1119,20 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
798
1119
  // src/runtimes/codex/index.ts
799
1120
  async function provisionCustomProviderCodexHome(provider, codexHome) {
800
1121
  try {
801
- await mkdir2(codexHome, { recursive: true });
802
- await writeFile2(join5(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
1122
+ await mkdir3(codexHome, { recursive: true });
1123
+ let existing = null;
1124
+ try {
1125
+ existing = await readFile3(join7(codexHome, "config.toml"), "utf8");
1126
+ } catch (error) {
1127
+ if (error.code !== "ENOENT")
1128
+ throw error;
1129
+ }
1130
+ await writeFile3(join7(codexHome, "config.toml"), mergeConfigTomlPreserving({
1131
+ existingText: existing,
1132
+ managedTopKeys: ["model", "model_provider"],
1133
+ managedTables: [`model_providers.${INKDOWN_PROVIDER_ID}`],
1134
+ replacementBlock: buildCustomProviderConfigToml(provider)
1135
+ }), "utf8");
803
1136
  return true;
804
1137
  } catch (error) {
805
1138
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -809,6 +1142,78 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
809
1142
  var codexAdapter = {
810
1143
  id: "codex-acp",
811
1144
  probeQuota: async (options) => probeCodexQuota(options),
1145
+ supportedBridgeVersions: ["2.2.2"],
1146
+ prepareAppResources: async ({ directory, workspaceRoot, env: overrideEnv }) => {
1147
+ const load = readAppResourcesDir(directory);
1148
+ const skillsFound = load.skills.map((s) => s.name);
1149
+ const rulesText = readAppRulesText(directory);
1150
+ if (!rulesText) {
1151
+ return {
1152
+ report: {
1153
+ rulesApplied: false,
1154
+ rulesChars: 0,
1155
+ profileDigest: null,
1156
+ skillsFound,
1157
+ reason: "rules-missing"
1158
+ }
1159
+ };
1160
+ }
1161
+ const env = { ...process.env, ...overrideEnv };
1162
+ const notApplied = (reason) => ({ report: {
1163
+ rulesApplied: false,
1164
+ rulesPrepared: false,
1165
+ skillsApplied: false,
1166
+ rulesChars: rulesText.length,
1167
+ profileDigest: digestAppResources(load),
1168
+ skillsFound,
1169
+ reason
1170
+ } });
1171
+ if (!load.directoryReadable)
1172
+ return notApplied("invalid-resource-directory");
1173
+ if (env.CODEX_PATH)
1174
+ return notApplied("execution-not-verified");
1175
+ const codexHome = env.CODEX_HOME || join7(homedir3(), ".codex");
1176
+ try {
1177
+ await readFile3(join7(codexHome, "config.toml"));
1178
+ return notApplied("effective-config-not-verified");
1179
+ } catch (error) {
1180
+ if (error.code !== "ENOENT")
1181
+ return notApplied("effective-config-not-verified");
1182
+ }
1183
+ for (let dir = workspaceRoot;dir; ) {
1184
+ if (existsSync5(join7(dir, ".codex", "config.toml")))
1185
+ return notApplied("effective-config-not-verified");
1186
+ if (existsSync5(join7(dir, ".git")))
1187
+ break;
1188
+ const parent = dirname(dir);
1189
+ if (parent === dir)
1190
+ break;
1191
+ dir = parent;
1192
+ }
1193
+ const merged = mergeCodexConfigJson({ existingRaw: env["CODEX_CONFIG"], hostBlock: rulesText });
1194
+ if (!merged.ok) {
1195
+ return {
1196
+ report: {
1197
+ rulesApplied: false,
1198
+ rulesChars: rulesText.length,
1199
+ profileDigest: digestAppResources(load),
1200
+ skillsFound,
1201
+ reason: merged.reason === "invalid-json" ? "invalid-codex-config" : "conflicting-codex-config"
1202
+ }
1203
+ };
1204
+ }
1205
+ return {
1206
+ env: { CODEX_CONFIG: merged.json },
1207
+ report: {
1208
+ rulesApplied: false,
1209
+ rulesPrepared: true,
1210
+ skillsApplied: false,
1211
+ rulesChars: rulesText.length,
1212
+ profileDigest: createHash2("sha256").update(JSON.stringify([digestAppResources(load), codexHome, workspaceRoot, merged.json])).digest("hex"),
1213
+ skillsFound
1214
+ }
1215
+ };
1216
+ },
812
1217
  probeAuth: () => {
813
1218
  return probeCodexAuth();
814
1219
  },
@@ -825,11 +1230,84 @@ var codexAdapter = {
825
1230
  }
826
1231
  };
827
1232
 
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";
1233
+ // src/resources/runtime-bindings.ts
1234
+ import { join as join8 } from "node:path";
832
1235
  import { execFile } from "node:child_process";
1236
+ import { promisify } from "node:util";
1237
+ var APP_RESOURCE_CAPABILITIES = {
1238
+ "codex-acp": { entry: "CODEX_CONFIG", strategy: "native-overlay", configHome: "CODEX_HOME" },
1239
+ opencode: { entry: "OPENCODE_CONFIG_CONTENT", strategy: "native-overlay", configHome: "OPENCODE_CONFIG_DIR" },
1240
+ "opencode-v2": { entry: null, strategy: "compatibility", configHome: null },
1241
+ claude: { entry: "_meta.systemPrompt + _meta.claudeCode.options.plugins", strategy: "native-session", configHome: "CLAUDE_CONFIG_DIR" },
1242
+ gemini: { entry: null, strategy: "compatibility", configHome: "GEMINI_CLI_HOME" },
1243
+ copilot: { entry: null, strategy: "compatibility", configHome: "COPILOT_HOME", candidateEntry: "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" },
1244
+ "cursor-cli": { entry: null, strategy: "compatibility", configHome: "CURSOR_CONFIG_DIR" },
1245
+ agy: { entry: "_meta.appResources.directory", strategy: "native-session", configHome: null },
1246
+ deepseek: { entry: null, strategy: "compatibility", configHome: null }
1247
+ };
1248
+ function prepareCompatibilityResources(directory, reason) {
1249
+ const load = readAppResourcesDir(directory);
1250
+ return { report: {
1251
+ rulesApplied: false,
1252
+ rulesPrepared: false,
1253
+ skillsApplied: false,
1254
+ rulesChars: load.rules?.chars ?? 0,
1255
+ profileDigest: digestAppResources(load),
1256
+ skillsFound: load.skills.map((s) => s.name),
1257
+ reason
1258
+ } };
1259
+ }
1260
+ function mergeOpenCodeAppConfig(raw, directory) {
1261
+ const value = raw?.trim() ? JSON.parse(raw) : {};
1262
+ if (!value || typeof value !== "object" || Array.isArray(value))
1263
+ throw new Error("invalid-opencode-config");
1264
+ const config = value;
1265
+ if (config.instructions !== undefined && (!Array.isArray(config.instructions) || config.instructions.some((v) => typeof v !== "string")))
1266
+ throw new Error("invalid-opencode-instructions");
1267
+ if (config.skills !== undefined && (!config.skills || typeof config.skills !== "object" || Array.isArray(config.skills)))
1268
+ throw new Error("invalid-opencode-skills");
1269
+ const skills = config.skills ?? {};
1270
+ if (skills.paths !== undefined && (!Array.isArray(skills.paths) || skills.paths.some((v) => typeof v !== "string")))
1271
+ throw new Error("invalid-opencode-skill-paths");
1272
+ return JSON.stringify({
1273
+ ...config,
1274
+ instructions: [...new Set([...config.instructions ?? [], join8(directory, "AGENTS.md")])],
1275
+ skills: { ...skills, paths: [...new Set([...skills.paths ?? [], join8(directory, "skills")])] }
1276
+ });
1277
+ }
1278
+ async function prepareOpenCodeResources(input) {
1279
+ const prep = prepareCompatibilityResources(input.directory, "native-entry-not-verified");
1280
+ if (!input.command || !readAppRulesText(input.directory))
1281
+ return prep;
1282
+ try {
1283
+ const { stdout } = await promisify(execFile)(input.command, ["--version"], { env: input.env, timeout: 8000, windowsHide: true });
1284
+ if (stdout.trim() !== "1.18.35")
1285
+ return prep;
1286
+ const json = mergeOpenCodeAppConfig(input.env?.OPENCODE_CONFIG_CONTENT, input.directory);
1287
+ return { env: { OPENCODE_CONFIG_CONTENT: json }, report: { ...prep.report, rulesPrepared: true, reason: undefined } };
1288
+ } catch {
1289
+ return { ...prep, report: { ...prep.report, reason: "native-config-prepare-failed" } };
1290
+ }
1291
+ }
1292
+ function prepareClaudeResources(directory) {
1293
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
1294
+ return { ...prep, report: { ...prep.report, rulesPrepared: !!readAppRulesText(directory) } };
1295
+ }
1296
+ function claudeResourceSessionMeta(directory) {
1297
+ const text = readAppRulesText(directory);
1298
+ if (!text)
1299
+ return;
1300
+ return {
1301
+ systemPrompt: { type: "preset", preset: "claude_code", append: text },
1302
+ claudeCode: { options: { plugins: [{ type: "local", path: directory }] } }
1303
+ };
1304
+ }
1305
+
1306
+ // src/runtimes/claude/quota.ts
1307
+ import { existsSync as existsSync6, readFileSync as readFileSync3 } from "node:fs";
1308
+ import { homedir as homedir4 } from "node:os";
1309
+ import { join as join9 } from "node:path";
1310
+ import { execFile as execFile2 } from "node:child_process";
833
1311
  var cachedClaudeAuth = null;
834
1312
  async function queryClaudeAuthStatus(timeoutMs = 1200) {
835
1313
  if (cachedClaudeAuth && Date.now() - cachedClaudeAuth.time < 30000) {
@@ -837,7 +1315,7 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
837
1315
  }
838
1316
  return new Promise((resolve) => {
839
1317
  try {
840
- execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
1318
+ execFile2("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
841
1319
  if (!stdout)
842
1320
  return resolve(null);
843
1321
  try {
@@ -855,15 +1333,15 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
855
1333
  }
856
1334
  async function probeClaudeQuota(options) {
857
1335
  const claudeHome = resolveClaudeHome();
858
- const claudeJsonPath = join6(homedir3(), ".claude.json");
859
- const credsPath = join6(claudeHome, ".credentials.json");
1336
+ const claudeJsonPath = join9(homedir4(), ".claude.json");
1337
+ const credsPath = join9(claudeHome, ".credentials.json");
860
1338
  let isLoggedIn = false;
861
1339
  let isBanned = false;
862
1340
  let accountEmail;
863
1341
  let plan = "Claude Free / Default";
864
- if (existsSync4(claudeJsonPath)) {
1342
+ if (existsSync6(claudeJsonPath)) {
865
1343
  try {
866
- const data = JSON.parse(readFileSync2(claudeJsonPath, "utf8"));
1344
+ const data = JSON.parse(readFileSync3(claudeJsonPath, "utf8"));
867
1345
  if (data.oauthAccount) {
868
1346
  isLoggedIn = true;
869
1347
  accountEmail = data.oauthAccount.emailAddress;
@@ -874,9 +1352,9 @@ async function probeClaudeQuota(options) {
874
1352
  }
875
1353
  } catch {}
876
1354
  }
877
- if (existsSync4(credsPath)) {
1355
+ if (existsSync6(credsPath)) {
878
1356
  try {
879
- const creds = JSON.parse(readFileSync2(credsPath, "utf8"));
1357
+ const creds = JSON.parse(readFileSync3(credsPath, "utf8"));
880
1358
  if (creds.accessToken || creds.sessionKey)
881
1359
  isLoggedIn = true;
882
1360
  } catch {}
@@ -928,19 +1406,19 @@ async function probeClaudeQuota(options) {
928
1406
  }
929
1407
 
930
1408
  // 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";
1409
+ import { existsSync as existsSync7 } from "node:fs";
1410
+ import { homedir as homedir5 } from "node:os";
1411
+ import { join as join10 } from "node:path";
934
1412
  function resolveClaudeHome() {
935
1413
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
936
1414
  if (fromEnv)
937
1415
  return fromEnv;
938
- return join7(homedir4(), ".claude");
1416
+ return join10(homedir5(), ".claude");
939
1417
  }
940
1418
  function probeClaudeAuth() {
941
1419
  const claudeHome = resolveClaudeHome();
942
- const hasCodexHome = existsSync5(claudeHome);
943
- const hasAuthFile = existsSync5(join7(homedir4(), ".claude.json")) || existsSync5(join7(claudeHome, ".credentials.json"));
1420
+ const hasCodexHome = existsSync7(claudeHome);
1421
+ const hasAuthFile = existsSync7(join10(homedir5(), ".claude.json")) || existsSync7(join10(claudeHome, ".credentials.json"));
944
1422
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
945
1423
  return {
946
1424
  codexHome: claudeHome,
@@ -952,6 +1430,9 @@ function probeClaudeAuth() {
952
1430
  }
953
1431
  var claudeAdapter = {
954
1432
  id: "claude",
1433
+ supportedBridgeVersions: ["0.91.0"],
1434
+ prepareAppResources: async ({ directory }) => prepareClaudeResources(directory),
1435
+ appResourceSessionMeta: claudeResourceSessionMeta,
955
1436
  probeAuth: () => probeClaudeAuth(),
956
1437
  probeQuota: async (options) => probeClaudeQuota(options),
957
1438
  orderAuthMethods: (methods) => methods,
@@ -959,16 +1440,16 @@ var claudeAdapter = {
959
1440
  };
960
1441
 
961
1442
  // 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";
1443
+ import { existsSync as existsSync8 } from "node:fs";
1444
+ import { homedir as homedir6 } from "node:os";
1445
+ import { join as join11 } from "node:path";
965
1446
  function resolveGeminiHome() {
966
- return join8(homedir5(), ".gemini");
1447
+ return join11(homedir6(), ".gemini");
967
1448
  }
968
1449
  function probeGeminiAuth() {
969
1450
  const geminiHome = resolveGeminiHome();
970
- const hasCodexHome = existsSync6(geminiHome);
971
- const hasAuthFile = existsSync6(join8(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
1451
+ const hasCodexHome = existsSync8(geminiHome);
1452
+ const hasAuthFile = existsSync8(join11(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
972
1453
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
973
1454
  return {
974
1455
  codexHome: geminiHome,
@@ -980,24 +1461,25 @@ function probeGeminiAuth() {
980
1461
  }
981
1462
  var geminiAdapter = {
982
1463
  id: "gemini",
1464
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-would-isolate-auth"),
983
1465
  probeAuth: () => probeGeminiAuth(),
984
1466
  orderAuthMethods: (methods) => methods,
985
1467
  canSkipInteractiveAuth: () => false
986
1468
  };
987
1469
 
988
1470
  // 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";
1471
+ import { existsSync as existsSync9, readFileSync as readFileSync4 } from "node:fs";
1472
+ import { homedir as homedir7 } from "node:os";
1473
+ import { join as join12 } from "node:path";
992
1474
  function resolveCopilotHome() {
993
1475
  const fromEnv = process.env.COPILOT_HOME?.trim();
994
1476
  if (fromEnv)
995
1477
  return fromEnv;
996
- return join9(homedir6(), ".copilot");
1478
+ return join12(homedir7(), ".copilot");
997
1479
  }
998
1480
  function hasCopilotLogin(home) {
999
1481
  try {
1000
- const raw = readFileSync3(join9(home, "config.json"), "utf8");
1482
+ const raw = readFileSync4(join12(home, "config.json"), "utf8");
1001
1483
  const parsed = JSON.parse(raw);
1002
1484
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
1003
1485
  } catch {
@@ -1006,7 +1488,7 @@ function hasCopilotLogin(home) {
1006
1488
  }
1007
1489
  function probeCopilotAuth() {
1008
1490
  const copilotHome = resolveCopilotHome();
1009
- const hasCodexHome = existsSync7(copilotHome);
1491
+ const hasCodexHome = existsSync9(copilotHome);
1010
1492
  const hasAuthFile = hasCopilotLogin(copilotHome);
1011
1493
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
1012
1494
  return {
@@ -1019,20 +1501,21 @@ function probeCopilotAuth() {
1019
1501
  }
1020
1502
  var copilotAdapter = {
1021
1503
  id: "copilot",
1504
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-entry-not-verified"),
1022
1505
  probeAuth: () => probeCopilotAuth(),
1023
1506
  orderAuthMethods: (methods) => methods,
1024
1507
  canSkipInteractiveAuth: () => false
1025
1508
  };
1026
1509
 
1027
1510
  // 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";
1511
+ import { existsSync as existsSync10, readFileSync as readFileSync5 } from "node:fs";
1512
+ import { execFile as execFile3 } from "node:child_process";
1030
1513
  import * as os from "node:os";
1031
1514
  import * as path from "node:path";
1032
1515
  function resolveOpencodeAuthPath() {
1033
1516
  const candidates = resolveOpencodeAuthCandidates();
1034
1517
  for (const c of candidates) {
1035
- if (existsSync8(c))
1518
+ if (existsSync10(c))
1036
1519
  return c;
1037
1520
  }
1038
1521
  return candidates[0] ?? null;
@@ -1044,7 +1527,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
1044
1527
  }
1045
1528
  return new Promise((resolve) => {
1046
1529
  try {
1047
- execFile2("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1530
+ execFile3("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1048
1531
  if (!stdout)
1049
1532
  return resolve(null);
1050
1533
  try {
@@ -1063,7 +1546,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
1063
1546
  async function queryOpencodeAuthList(timeoutMs = 1200) {
1064
1547
  return new Promise((resolve) => {
1065
1548
  try {
1066
- execFile2("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1549
+ execFile3("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1067
1550
  if (!stdout)
1068
1551
  return resolve([]);
1069
1552
  const lines = stdout.split(`
@@ -1083,7 +1566,7 @@ function readLocalOpencodeCredentials() {
1083
1566
  path.join(home, ".config", "opencode", "opencode.db")
1084
1567
  ].filter(Boolean);
1085
1568
  for (const dbPath of dbPaths) {
1086
- if (!existsSync8(dbPath))
1569
+ if (!existsSync10(dbPath))
1087
1570
  continue;
1088
1571
  try {
1089
1572
  let rows = [];
@@ -1112,7 +1595,7 @@ function readLocalOpencodeCredentials() {
1112
1595
  }
1113
1596
  } catch {
1114
1597
  try {
1115
- const buf = readFileSync4(dbPath, "utf8");
1598
+ const buf = readFileSync5(dbPath, "utf8");
1116
1599
  const emailMatch = buf.match(/"email"\s*:\s*"([^"]+)"/);
1117
1600
  const tokenMatch = buf.match(/"access"\s*:\s*"(st_[a-zA-Z0-9_\\-]+)"/);
1118
1601
  const orgMatch = buf.match(/"orgID"\s*:\s*"(wrk_[a-zA-Z0-9_\\-]+)"/);
@@ -1236,9 +1719,9 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1236
1719
  let accountEmail = dbCreds.email;
1237
1720
  let accountName = dbCreds.name;
1238
1721
  let plan = "OpenCode Community";
1239
- if (authPath && existsSync8(authPath)) {
1722
+ if (authPath && existsSync10(authPath)) {
1240
1723
  try {
1241
- const data = JSON.parse(readFileSync4(authPath, "utf8"));
1724
+ const data = JSON.parse(readFileSync5(authPath, "utf8"));
1242
1725
  if (data && typeof data === "object") {
1243
1726
  const keys = Object.keys(data);
1244
1727
  if (keys.length > 0) {
@@ -1298,16 +1781,16 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1298
1781
  }
1299
1782
 
1300
1783
  // 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";
1784
+ import { existsSync as existsSync11, readFileSync as readFileSync6 } from "node:fs";
1785
+ import { homedir as homedir9 } from "node:os";
1786
+ import { dirname as dirname2, join as join14 } from "node:path";
1304
1787
  function pickEnv(env, key) {
1305
1788
  return env?.[key]?.trim() ?? "";
1306
1789
  }
1307
1790
  function resolveOpencodeAuthCandidates(overrides) {
1308
1791
  const platform = overrides?.platform ?? process.platform;
1309
1792
  const env = overrides?.env ?? process.env;
1310
- const home = overrides?.home ?? homedir8();
1793
+ const home = overrides?.home ?? homedir9();
1311
1794
  const seen = new Set;
1312
1795
  const out = [];
1313
1796
  const push = (p) => {
@@ -1318,27 +1801,27 @@ function resolveOpencodeAuthCandidates(overrides) {
1318
1801
  };
1319
1802
  const xdg = pickEnv(env, "XDG_DATA_HOME");
1320
1803
  if (xdg)
1321
- push(join11(xdg, "opencode", "auth.json"));
1804
+ push(join14(xdg, "opencode", "auth.json"));
1322
1805
  if (platform === "win32") {
1323
- const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? join11(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
1806
+ const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? join14(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
1324
1807
  if (localAppData)
1325
- push(join11(localAppData, "opencode", "auth.json"));
1808
+ push(join14(localAppData, "opencode", "auth.json"));
1326
1809
  const userProfile = pickEnv(env, "USERPROFILE") || home;
1327
1810
  if (userProfile)
1328
- push(join11(userProfile, ".local", "share", "opencode", "auth.json"));
1811
+ push(join14(userProfile, ".local", "share", "opencode", "auth.json"));
1329
1812
  } else if (home) {
1330
- push(join11(home, ".local", "share", "opencode", "auth.json"));
1813
+ push(join14(home, ".local", "share", "opencode", "auth.json"));
1331
1814
  }
1332
1815
  return out;
1333
1816
  }
1334
1817
  function resolveOpencodeAuthFile() {
1335
- return resolveOpencodeAuthCandidates()[0] ?? join11(homedir8(), ".local", "share", "opencode", "auth.json");
1818
+ return resolveOpencodeAuthCandidates()[0] ?? join14(homedir9(), ".local", "share", "opencode", "auth.json");
1336
1819
  }
1337
1820
  function isValidOpencodeAuthFile(authFile) {
1338
1821
  try {
1339
- if (!authFile || !existsSync9(authFile))
1822
+ if (!authFile || !existsSync11(authFile))
1340
1823
  return false;
1341
- const raw = readFileSync5(authFile, "utf8").trim();
1824
+ const raw = readFileSync6(authFile, "utf8").trim();
1342
1825
  if (!raw)
1343
1826
  return false;
1344
1827
  const parsed = JSON.parse(raw);
@@ -1356,7 +1839,7 @@ function probeOpencodeAuth(overrides) {
1356
1839
  for (const candidate of candidates) {
1357
1840
  let exists = false;
1358
1841
  try {
1359
- exists = existsSync9(candidate);
1842
+ exists = existsSync11(candidate);
1360
1843
  } catch {
1361
1844
  exists = false;
1362
1845
  }
@@ -1369,10 +1852,10 @@ function probeOpencodeAuth(overrides) {
1369
1852
  validFile = candidate;
1370
1853
  }
1371
1854
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
1372
- const authDir = dirname(authFile);
1855
+ const authDir = dirname2(authFile);
1373
1856
  let hasCodexHome = false;
1374
1857
  try {
1375
- hasCodexHome = existsSync9(authDir);
1858
+ hasCodexHome = existsSync11(authDir);
1376
1859
  } catch {
1377
1860
  hasCodexHome = false;
1378
1861
  }
@@ -1387,6 +1870,8 @@ function probeOpencodeAuth(overrides) {
1387
1870
  }
1388
1871
  var opencodeAdapter = {
1389
1872
  id: "opencode",
1873
+ supportedBridgeVersions: ["1.18.35"],
1874
+ prepareAppResources: prepareOpenCodeResources,
1390
1875
  probeAuth: () => probeOpencodeAuth(),
1391
1876
  probeQuota: async () => probeOpencodeQuota(),
1392
1877
  orderAuthMethods: (methods) => methods,
@@ -1397,6 +1882,7 @@ var opencodeAdapter = {
1397
1882
  // src/runtimes/opencode-v2/index.ts
1398
1883
  var opencodeV2Adapter = {
1399
1884
  id: "opencode-v2",
1885
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
1400
1886
  probeAuth: () => probeOpencodeAuth(),
1401
1887
  orderAuthMethods: (methods) => methods,
1402
1888
  canSkipInteractiveAuth: () => false,
@@ -1428,15 +1914,15 @@ async function probeCursorQuota() {
1428
1914
 
1429
1915
  // src/runtimes/cursor/index.ts
1430
1916
  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";
1917
+ import { existsSync as existsSync12, readFileSync as readFileSync7 } from "node:fs";
1918
+ import { homedir as homedir10 } from "node:os";
1919
+ import { delimiter, dirname as dirname3, join as join15 } from "node:path";
1434
1920
  function cursorLocalAppData(env) {
1435
1921
  const local = env.LOCALAPPDATA?.trim();
1436
1922
  if (local)
1437
1923
  return local;
1438
1924
  const profile = env.USERPROFILE?.trim();
1439
- return profile ? join12(profile, "AppData", "Local") : "";
1925
+ return profile ? join15(profile, "AppData", "Local") : "";
1440
1926
  }
1441
1927
  function isOnPath(command, env, platform) {
1442
1928
  const pathValue = env.PATH ?? env.Path ?? "";
@@ -1448,7 +1934,7 @@ function isOnPath(command, env, platform) {
1448
1934
  if (!trimmed)
1449
1935
  continue;
1450
1936
  try {
1451
- if (existsSync10(join12(trimmed, command)))
1937
+ if (existsSync12(join15(trimmed, command)))
1452
1938
  return true;
1453
1939
  } catch {}
1454
1940
  }
@@ -1457,24 +1943,24 @@ function isOnPath(command, env, platform) {
1457
1943
  function resolveDirectCursorCommand(platform, env, home) {
1458
1944
  if (platform === "win32") {
1459
1945
  const localAppData = cursorLocalAppData(env);
1460
- return localAppData ? join12(localAppData, "cursor-agent", "agent.cmd") : "";
1946
+ return localAppData ? join15(localAppData, "cursor-agent", "agent.cmd") : "";
1461
1947
  }
1462
- return home ? join12(home, ".local", "bin", "agent") : "";
1948
+ return home ? join15(home, ".local", "bin", "agent") : "";
1463
1949
  }
1464
1950
  function resolveCursorCommand(overrides) {
1465
1951
  const args = ["acp"];
1466
1952
  const platform = overrides?.platform ?? process.platform;
1467
1953
  const env = overrides?.env ?? process.env;
1468
- const home = overrides?.home ?? homedir9();
1954
+ const home = overrides?.home ?? homedir10();
1469
1955
  if (platform === "win32") {
1470
1956
  const directCmd = resolveDirectCursorCommand(platform, env, home);
1471
- if (directCmd && existsSync10(directCmd)) {
1957
+ if (directCmd && existsSync12(directCmd)) {
1472
1958
  return { command: directCmd, args };
1473
1959
  }
1474
1960
  return { command: "agent.cmd", args };
1475
1961
  }
1476
1962
  const directBin = resolveDirectCursorCommand(platform, env, home);
1477
- if (directBin && existsSync10(directBin)) {
1963
+ if (directBin && existsSync12(directBin)) {
1478
1964
  return { command: directBin, args };
1479
1965
  }
1480
1966
  return { command: "agent", args };
@@ -1483,11 +1969,11 @@ function resolveCursorSpawnCommand(overrides) {
1483
1969
  const args = ["acp"];
1484
1970
  const platform = overrides?.platform ?? process.platform;
1485
1971
  const env = overrides?.env ?? process.env;
1486
- const home = overrides?.home ?? homedir9();
1972
+ const home = overrides?.home ?? homedir10();
1487
1973
  const binary = platform === "win32" ? "agent.cmd" : "agent";
1488
1974
  const direct = resolveDirectCursorCommand(platform, env, home);
1489
1975
  try {
1490
- if (direct && existsSync10(direct))
1976
+ if (direct && existsSync12(direct))
1491
1977
  return { command: direct, args };
1492
1978
  } catch {}
1493
1979
  if (isOnPath(binary, env, platform))
@@ -1509,12 +1995,12 @@ function cursorRoamingAppData(env, home) {
1509
1995
  if (roaming)
1510
1996
  return roaming;
1511
1997
  const profile = pickEnv2(env, "USERPROFILE") || home;
1512
- return profile ? join12(profile, "AppData", "Roaming") : "";
1998
+ return profile ? join15(profile, "AppData", "Roaming") : "";
1513
1999
  }
1514
2000
  function resolveCursorAuthCandidates(overrides) {
1515
2001
  const platform = overrides?.platform ?? process.platform;
1516
2002
  const env = overrides?.env ?? process.env;
1517
- const home = overrides?.home ?? homedir9();
2003
+ const home = overrides?.home ?? homedir10();
1518
2004
  const seen = new Set;
1519
2005
  const out = [];
1520
2006
  const push = (p) => {
@@ -1525,16 +2011,16 @@ function resolveCursorAuthCandidates(overrides) {
1525
2011
  };
1526
2012
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
1527
2013
  if (xdg)
1528
- push(join12(xdg, "cursor", "auth.json"));
2014
+ push(join15(xdg, "cursor", "auth.json"));
1529
2015
  if (platform === "win32") {
1530
2016
  const profile = pickEnv2(env, "USERPROFILE") || home;
1531
2017
  if (profile)
1532
- push(join12(profile, ".config", "cursor", "auth.json"));
2018
+ push(join15(profile, ".config", "cursor", "auth.json"));
1533
2019
  const roaming = cursorRoamingAppData(env, home);
1534
2020
  if (roaming)
1535
- push(join12(roaming, "Cursor", "User", "globalStorage", "storage.json"));
2021
+ push(join15(roaming, "Cursor", "User", "globalStorage", "storage.json"));
1536
2022
  } else if (home) {
1537
- push(join12(home, ".config", "cursor", "auth.json"));
2023
+ push(join15(home, ".config", "cursor", "auth.json"));
1538
2024
  }
1539
2025
  return out;
1540
2026
  }
@@ -1545,9 +2031,9 @@ function isValidCursorAuthFile(authFile) {
1545
2031
  try {
1546
2032
  if (!authFile || isStorageHintPath(authFile))
1547
2033
  return false;
1548
- if (!existsSync10(authFile))
2034
+ if (!existsSync12(authFile))
1549
2035
  return false;
1550
- const raw = readFileSync6(authFile, "utf8").trim();
2036
+ const raw = readFileSync7(authFile, "utf8").trim();
1551
2037
  if (!raw)
1552
2038
  return false;
1553
2039
  const parsed = JSON.parse(raw);
@@ -1565,9 +2051,9 @@ function isHintCursorStorageFile(authFile) {
1565
2051
  try {
1566
2052
  if (!authFile || !isStorageHintPath(authFile))
1567
2053
  return false;
1568
- if (!existsSync10(authFile))
2054
+ if (!existsSync12(authFile))
1569
2055
  return false;
1570
- const raw = readFileSync6(authFile, "utf8").trim();
2056
+ const raw = readFileSync7(authFile, "utf8").trim();
1571
2057
  if (!raw)
1572
2058
  return false;
1573
2059
  const parsed = JSON.parse(raw);
@@ -1583,7 +2069,7 @@ function isValidCursorCandidate(authFile) {
1583
2069
  }
1584
2070
  function probeCursorAuth(overrides) {
1585
2071
  const env = overrides?.env ?? process.env;
1586
- const home = overrides?.home ?? homedir9();
2072
+ const home = overrides?.home ?? homedir10();
1587
2073
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
1588
2074
  const candidates = resolveCursorAuthCandidates(overrides);
1589
2075
  let firstExisting = null;
@@ -1591,7 +2077,7 @@ function probeCursorAuth(overrides) {
1591
2077
  for (const candidate of candidates) {
1592
2078
  let exists = false;
1593
2079
  try {
1594
- exists = existsSync10(candidate);
2080
+ exists = existsSync12(candidate);
1595
2081
  } catch {
1596
2082
  exists = false;
1597
2083
  }
@@ -1603,12 +2089,12 @@ function probeCursorAuth(overrides) {
1603
2089
  if (isValidCursorCandidate(candidate))
1604
2090
  validFile = candidate;
1605
2091
  }
1606
- const fallback = home ? join12(home, ".config", "cursor", "auth.json") : "";
2092
+ const fallback = home ? join15(home, ".config", "cursor", "auth.json") : "";
1607
2093
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
1608
- const authDir = authFile ? dirname2(authFile) : "";
2094
+ const authDir = authFile ? dirname3(authFile) : "";
1609
2095
  let hasCodexHome = false;
1610
2096
  try {
1611
- hasCodexHome = authDir ? existsSync10(authDir) : false;
2097
+ hasCodexHome = authDir ? existsSync12(authDir) : false;
1612
2098
  } catch {
1613
2099
  hasCodexHome = false;
1614
2100
  }
@@ -1622,6 +2108,7 @@ function probeCursorAuth(overrides) {
1622
2108
  }
1623
2109
  var cursorAdapter = {
1624
2110
  id: "cursor-cli",
2111
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-does-not-guarantee-rules"),
1625
2112
  probeAuth: () => probeCursorAuth(),
1626
2113
  probeQuota: async () => probeCursorQuota(),
1627
2114
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
@@ -1735,6 +2222,7 @@ function probeDeepseekAuth() {
1735
2222
  }
1736
2223
  var deepseekAdapter = {
1737
2224
  id: "deepseek",
2225
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
1738
2226
  probeAuth: () => probeDeepseekAuth(),
1739
2227
  resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
1740
2228
  resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
@@ -1743,13 +2231,13 @@ var deepseekAdapter = {
1743
2231
  };
1744
2232
 
1745
2233
  // 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";
2234
+ import { existsSync as existsSync13, readFileSync as readFileSync8, readdirSync as readdirSync2, statSync as statSync2 } from "node:fs";
2235
+ import { join as join16 } from "node:path";
1748
2236
  import { execFileSync } from "node:child_process";
1749
2237
  import * as os2 from "node:os";
1750
2238
  function resolveGeminiHome2() {
1751
2239
  const home = process.env.USERPROFILE || process.env.HOME || "";
1752
- return join13(home, ".gemini");
2240
+ return join16(home, ".gemini");
1753
2241
  }
1754
2242
  function resolveAntigravityAccount() {
1755
2243
  if (process.env.GOOGLE_ACCOUNT?.trim()) {
@@ -1762,14 +2250,14 @@ function resolveAntigravityAccount() {
1762
2250
  }
1763
2251
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
1764
2252
  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")
2253
+ process.env.APPDATA ? join16(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
2254
+ join16(home, ".config", "Antigravity", "app_storage.json"),
2255
+ join16(home, "Library", "Application Support", "Antigravity", "app_storage.json")
1768
2256
  ].filter(Boolean);
1769
2257
  for (const file of candidates) {
1770
2258
  try {
1771
- if (existsSync11(file)) {
1772
- const raw = readFileSync7(file, "utf8");
2259
+ if (existsSync13(file)) {
2260
+ const raw = readFileSync8(file, "utf8");
1773
2261
  const json = JSON.parse(raw);
1774
2262
  const username = json["jetski.onboarding.lastLoginUsername"];
1775
2263
  if (username && typeof username === "string" && username.trim()) {
@@ -1790,30 +2278,30 @@ function resolveAntigravityAccount() {
1790
2278
  }
1791
2279
  function resolveAntigravityLanguageServer() {
1792
2280
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
1793
- const appData = process.env.APPDATA || (process.platform === "win32" ? join13(home, "AppData", "Roaming") : "");
2281
+ const appData = process.env.APPDATA || (process.platform === "win32" ? join16(home, "AppData", "Roaming") : "");
1794
2282
  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")
2283
+ appData ? join16(appData, "Antigravity IDE", "logs") : null,
2284
+ appData ? join16(appData, "Antigravity", "logs") : null,
2285
+ join16(home, ".config", "Antigravity IDE", "logs"),
2286
+ join16(home, ".config", "Antigravity", "logs"),
2287
+ join16(home, "Library", "Application Support", "Antigravity IDE", "logs"),
2288
+ join16(home, "Library", "Application Support", "Antigravity", "logs")
1801
2289
  ].filter(Boolean);
1802
2290
  for (const base of baseDirs) {
1803
2291
  try {
1804
- if (!existsSync11(base))
2292
+ if (!existsSync13(base))
1805
2293
  continue;
1806
- const sessionDirs = readdirSync(base).map((d) => {
2294
+ const sessionDirs = readdirSync2(base).map((d) => {
1807
2295
  try {
1808
- return { name: d, time: statSync(join13(base, d)).mtimeMs };
2296
+ return { name: d, time: statSync2(join16(base, d)).mtimeMs };
1809
2297
  } catch {
1810
2298
  return null;
1811
2299
  }
1812
2300
  }).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
1813
2301
  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");
2302
+ const logFile = join16(base, s.name, "ls-main.log");
2303
+ if (existsSync13(logFile)) {
2304
+ const content = readFileSync8(logFile, "utf8");
1817
2305
  const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
1818
2306
  const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
1819
2307
  if (csrfMatch && portMatch) {
@@ -1970,7 +2458,7 @@ async function probeAgyQuota(options) {
1970
2458
  } catch {}
1971
2459
  }
1972
2460
  const geminiHome = resolveGeminiHome2();
1973
- const hasAgyDir = existsSync11(join13(geminiHome, "antigravity")) || existsSync11(join13(geminiHome, "antigravity-cli"));
2461
+ const hasAgyDir = existsSync13(join16(geminiHome, "antigravity")) || existsSync13(join16(geminiHome, "antigravity-cli"));
1974
2462
  const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
1975
2463
  const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
1976
2464
  if (!isAvailable) {
@@ -2042,6 +2530,12 @@ function probeAgyAuth() {
2042
2530
  }
2043
2531
  var agyAdapter = {
2044
2532
  id: "agy",
2533
+ prepareAppResources: async ({ directory }) => {
2534
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
2535
+ return { ...prep, env: { AGY_ACP_RESOURCES_DIR: directory }, report: { ...prep.report, rulesPrepared: prep.report.rulesChars > 0 } };
2536
+ },
2537
+ appResourceSessionMeta: (directory) => ({ appResources: { directory } }),
2538
+ supportedBridgeVersions: ["0.1.24"],
2045
2539
  probeAuth: () => probeAgyAuth(),
2046
2540
  probeQuota: (options) => probeAgyQuota(options),
2047
2541
  orderAuthMethods: (methods) => methods,
@@ -2082,6 +2576,9 @@ function getAcpRuntimeAdapter(runtimeId) {
2082
2576
 
2083
2577
  // src/process/process-manager.ts
2084
2578
  import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
2579
+ function processKey(runtimeId, scopeKey) {
2580
+ return scopeKey ? `${scopeKey}:${runtimeId}` : runtimeId;
2581
+ }
2085
2582
  var active = new Map;
2086
2583
  var ACP_EARLY_EXIT_WINDOW_MS = 3000;
2087
2584
  var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
@@ -2113,7 +2610,8 @@ function spawnAcpProcess(options) {
2113
2610
  if (!options.runtime?.id || !options.runtime.command || !Array.isArray(options.runtime.args)) {
2114
2611
  throw new Error(`ACP 运行时模板缺失 command/args: ${options.runtime?.id ?? "(empty)"}`);
2115
2612
  }
2116
- const existing = active.get(options.runtime.id);
2613
+ const key = processKey(options.runtime.id, options.scopeKey);
2614
+ const existing = active.get(key);
2117
2615
  if (existing) {
2118
2616
  existing.kill();
2119
2617
  }
@@ -2174,6 +2672,9 @@ function spawnAcpProcess(options) {
2174
2672
  });
2175
2673
  const handle = {
2176
2674
  runtimeId: options.runtime.id,
2675
+ scopeKey: options.scopeKey,
2676
+ executionContext: options.executionContext,
2677
+ profileTag: options.profileTag ?? null,
2177
2678
  child,
2178
2679
  spawnedAt: Date.now(),
2179
2680
  stderrTail,
@@ -2191,7 +2692,7 @@ function spawnAcpProcess(options) {
2191
2692
  } catch {}
2192
2693
  }
2193
2694
  }
2194
- active.delete(options.runtime.id);
2695
+ active.delete(key);
2195
2696
  }
2196
2697
  };
2197
2698
  child.on("exit", (code, signal) => {
@@ -2199,10 +2700,11 @@ function spawnAcpProcess(options) {
2199
2700
  if (rest)
2200
2701
  pushStderrTailLine(rest);
2201
2702
  stderrBuffer = "";
2202
- active.delete(options.runtime.id);
2703
+ if (active.get(key) === handle)
2704
+ active.delete(key);
2203
2705
  options.onExit?.(code, signal);
2204
2706
  });
2205
- active.set(options.runtime.id, handle);
2707
+ active.set(key, handle);
2206
2708
  return handle;
2207
2709
  }
2208
2710
  function getAcpEarlyExitStderrDetail(handle, _now = Date.now()) {
@@ -2230,27 +2732,47 @@ function disposeAllAcpProcesses() {
2230
2732
  }
2231
2733
  active.clear();
2232
2734
  }
2233
- function getActiveAcpProcess(runtimeId) {
2234
- return active.get(runtimeId);
2735
+ function getActiveAcpProcess(runtimeId, scopeKey) {
2736
+ return active.get(processKey(runtimeId, scopeKey));
2235
2737
  }
2236
2738
  function listLiveAcpRuntimeIds() {
2237
- const ids = [];
2238
- for (const [runtimeId, handle] of active) {
2739
+ const ids = new Set;
2740
+ for (const handle of active.values()) {
2239
2741
  if (isSpawnedAcpProcessAlive(handle))
2240
- ids.push(runtimeId);
2742
+ ids.add(handle.runtimeId);
2241
2743
  }
2242
- return ids.sort();
2744
+ return [...ids].sort();
2243
2745
  }
2244
- function getLiveAcpProcess(runtimeId) {
2245
- const handle = active.get(runtimeId);
2746
+ function getLiveAcpProcess(runtimeId, query = {}) {
2747
+ const key = processKey(runtimeId, query.scopeKey);
2748
+ const handle = active.get(key);
2246
2749
  if (!handle)
2247
2750
  return;
2248
2751
  if (!isSpawnedAcpProcessAlive(handle)) {
2249
- active.delete(runtimeId);
2752
+ active.delete(key);
2250
2753
  return;
2251
2754
  }
2755
+ if (query.executionContext !== undefined && (handle.executionContext ?? null) !== query.executionContext) {
2756
+ return;
2757
+ }
2758
+ if (query.expectedTag !== undefined && (handle.profileTag ?? null) !== query.expectedTag)
2759
+ return;
2252
2760
  return handle;
2253
2761
  }
2762
+ function tryReuseLiveAcpProcess(runtimeId, query = {}) {
2763
+ const hit = getLiveAcpProcess(runtimeId, query);
2764
+ if (hit)
2765
+ return { status: "hit", handle: hit };
2766
+ if (query.expectedTag === undefined)
2767
+ return { status: "miss" };
2768
+ const stale = getLiveAcpProcess(runtimeId, { scopeKey: query.scopeKey, executionContext: query.executionContext });
2769
+ if (!stale)
2770
+ return { status: "miss" };
2771
+ if (query.isBusy?.(stale))
2772
+ return { status: "busy", handle: stale };
2773
+ stale.kill();
2774
+ return { status: "miss" };
2775
+ }
2254
2776
 
2255
2777
  // src/client/sdk-client.ts
2256
2778
  import { PassThrough, Readable, Writable } from "node:stream";
@@ -2324,18 +2846,18 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
2324
2846
  import { methods, RequestError } from "@agentclientprotocol/sdk";
2325
2847
 
2326
2848
  // 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";
2849
+ import { access, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
2850
+ import { dirname as dirname4, extname, resolve as resolve2, sep as sep2 } from "node:path";
2851
+ import { mkdir as mkdir4 } from "node:fs/promises";
2330
2852
  var MAX_READ_BYTES = 2 * 1024 * 1024;
2331
2853
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
2332
2854
  function isBinaryDocumentPath(filePath) {
2333
2855
  return BINARY_DOCUMENT_EXTENSIONS.has(extname(filePath).toLowerCase());
2334
2856
  }
2335
2857
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
2336
- const root = resolve(workspaceRoot);
2337
- const target = resolve(filePath);
2338
- const rootWithSep = root.endsWith(sep) ? root : root + sep;
2858
+ const root = resolve2(workspaceRoot);
2859
+ const target = resolve2(filePath);
2860
+ const rootWithSep = root.endsWith(sep2) ? root : root + sep2;
2339
2861
  if (target !== root && !target.startsWith(rootWithSep)) {
2340
2862
  throw new Error(`路径不在工作区内: ${filePath}`);
2341
2863
  }
@@ -2347,7 +2869,7 @@ async function acpReadTextFile(params) {
2347
2869
  }
2348
2870
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
2349
2871
  await access(abs);
2350
- let content = await readFile2(abs, "utf-8");
2872
+ let content = await readFile4(abs, "utf-8");
2351
2873
  if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
2352
2874
  content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
2353
2875
  content += `
@@ -2366,8 +2888,8 @@ async function acpReadTextFile(params) {
2366
2888
  }
2367
2889
  async function acpWriteTextFile(params) {
2368
2890
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
2369
- await mkdir3(dirname3(abs), { recursive: true });
2370
- await writeFile3(abs, params.content, "utf-8");
2891
+ await mkdir4(dirname4(abs), { recursive: true });
2892
+ await writeFile4(abs, params.content, "utf-8");
2371
2893
  return {};
2372
2894
  }
2373
2895
 
@@ -2727,6 +3249,25 @@ function isTransientAcpTransportError(error) {
2727
3249
  async function restoreOrCreateAcpSession(input) {
2728
3250
  const resumeId = input.resumeSessionId?.trim() || null;
2729
3251
  const restoreAttempts = [];
3252
+ let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
3253
+ let nativeSessionAccepted = false;
3254
+ const request = async (method, params) => {
3255
+ if (!input.sessionMeta)
3256
+ return input.request(method, params);
3257
+ try {
3258
+ const result = await input.request(method, { ...params, _meta: input.sessionMeta });
3259
+ nativeSessionAccepted = true;
3260
+ return result;
3261
+ } catch (error) {
3262
+ const rejected = error instanceof RequestError2 && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
3263
+ if (!rejected || isTransientAcpTransportError(error))
3264
+ throw error;
3265
+ log("warn", "native resource options failed; retry without extension");
3266
+ const result = await input.request(method, params);
3267
+ nativeSessionAccepted = false;
3268
+ return result;
3269
+ }
3270
+ };
2730
3271
  const delayMs = input.retryDelayMs ?? 250;
2731
3272
  const log = input.log ?? ((level, message, data) => {
2732
3273
  if (level === "info" && false)
@@ -2748,7 +3289,7 @@ async function restoreOrCreateAcpSession(input) {
2748
3289
  maxTries
2749
3290
  });
2750
3291
  try {
2751
- const result = await input.request(rpcMethod, {
3292
+ const result = await request(rpcMethod, {
2752
3293
  sessionId: resumeId,
2753
3294
  cwd: input.cwd,
2754
3295
  mcpServers: input.mcpServers ?? []
@@ -2787,7 +3328,7 @@ async function restoreOrCreateAcpSession(input) {
2787
3328
  mcpServers: input.mcpServers ?? []
2788
3329
  };
2789
3330
  try {
2790
- return await input.request("session/new", baseParams);
3331
+ return await request("session/new", baseParams);
2791
3332
  } catch (firstError) {
2792
3333
  if ((input.mcpServers ?? []).length === 0)
2793
3334
  throw firstError;
@@ -2795,10 +3336,12 @@ async function restoreOrCreateAcpSession(input) {
2795
3336
  error: errorMessage(firstError)
2796
3337
  });
2797
3338
  try {
2798
- return await input.request("session/new", {
3339
+ const result = await request("session/new", {
2799
3340
  cwd: input.cwd,
2800
3341
  mcpServers: []
2801
3342
  });
3343
+ mcpServersAccepted = false;
3344
+ return result;
2802
3345
  } catch {
2803
3346
  throw firstError;
2804
3347
  }
@@ -2814,6 +3357,8 @@ async function restoreOrCreateAcpSession(input) {
2814
3357
  configOptions: withModelsFallback(resumed),
2815
3358
  restoreMethod: "resume",
2816
3359
  sessionRestored: true,
3360
+ mcpServersAccepted,
3361
+ nativeSessionAccepted,
2817
3362
  requestedSessionId: resumeId,
2818
3363
  restoreAttempts
2819
3364
  };
@@ -2832,6 +3377,8 @@ async function restoreOrCreateAcpSession(input) {
2832
3377
  configOptions: withModelsFallback(loaded),
2833
3378
  restoreMethod: "load",
2834
3379
  sessionRestored: true,
3380
+ mcpServersAccepted,
3381
+ nativeSessionAccepted,
2835
3382
  requestedSessionId: resumeId,
2836
3383
  restoreAttempts
2837
3384
  };
@@ -2853,6 +3400,8 @@ async function restoreOrCreateAcpSession(input) {
2853
3400
  configOptions: withModelsFallback(sessionResult),
2854
3401
  restoreMethod: "new",
2855
3402
  sessionRestored: false,
3403
+ mcpServersAccepted,
3404
+ nativeSessionAccepted,
2856
3405
  requestedSessionId: resumeId ?? undefined,
2857
3406
  restoreAttempts
2858
3407
  };
@@ -3043,9 +3592,9 @@ class AcpTerminalManager {
3043
3592
  }
3044
3593
 
3045
3594
  // 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";
3595
+ import { mkdir as mkdir5, readFile as readFile5, writeFile as writeFile5 } from "node:fs/promises";
3596
+ import { existsSync as existsSync14 } from "node:fs";
3597
+ import { join as join17 } from "node:path";
3049
3598
  var DEFAULT_ACP_PROXY_SETTINGS = {
3050
3599
  enabled: false,
3051
3600
  host: "127.0.0.1",
@@ -3054,7 +3603,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
3054
3603
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
3055
3604
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
3056
3605
  function proxyFilePath(dir) {
3057
- return join14(dir, "agent", "proxy.json");
3606
+ return join17(dir, "agent", "proxy.json");
3058
3607
  }
3059
3608
  function validate2(settings) {
3060
3609
  if (!settings.host.trim())
@@ -3066,10 +3615,10 @@ function validate2(settings) {
3066
3615
  }
3067
3616
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
3068
3617
  const file = proxyFilePath(dir);
3069
- if (!existsSync12(file))
3618
+ if (!existsSync14(file))
3070
3619
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
3071
3620
  try {
3072
- const raw = JSON.parse(await readFile3(file, "utf8"));
3621
+ const raw = JSON.parse(await readFile5(file, "utf8"));
3073
3622
  return {
3074
3623
  enabled: raw.enabled === true,
3075
3624
  host: typeof raw.host === "string" && raw.host.trim() ? raw.host : DEFAULT_ACP_PROXY_SETTINGS.host,
@@ -3088,8 +3637,8 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
3088
3637
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
3089
3638
  port: payload.port
3090
3639
  };
3091
- await mkdir4(join14(dir, "agent"), { recursive: true });
3092
- await writeFile4(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
3640
+ await mkdir5(join17(dir, "agent"), { recursive: true });
3641
+ await writeFile5(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
3093
3642
  return ok(stored);
3094
3643
  }
3095
3644
  function buildAcpProxySpawnEnv(settings) {
@@ -3111,6 +3660,116 @@ function buildAcpProxySpawnEnv(settings) {
3111
3660
  };
3112
3661
  }
3113
3662
 
3663
+ // src/session/compat-guide.ts
3664
+ var COMPAT_CONTEXT_TAG = "acp-compat-context";
3665
+ function shortDigest(digest) {
3666
+ return digest ? digest.slice(0, 16) : "none";
3667
+ }
3668
+ function buildCompatGuideText(input) {
3669
+ const hasRules = (input.rulesText ?? "").trim() !== "";
3670
+ const hasSkills = input.skills.length > 0;
3671
+ if (!hasRules && !hasSkills)
3672
+ return null;
3673
+ const lines = [];
3674
+ 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.", "");
3675
+ if (hasRules) {
3676
+ lines.push("--- host rules (same source as the host app, delivered once per session) ---", "");
3677
+ lines.push(input.rulesText.trim(), "");
3678
+ }
3679
+ if (hasSkills) {
3680
+ lines.push("--- host skills catalog (names and descriptions only; read full text on demand) ---", "");
3681
+ for (const skill of input.skills) {
3682
+ lines.push(`- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`);
3683
+ }
3684
+ 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.");
3685
+ lines.push("");
3686
+ }
3687
+ lines.push(`</${COMPAT_CONTEXT_TAG}>`);
3688
+ return lines.join(`
3689
+ `);
3690
+ }
3691
+ function compatDeliveryKey(sessionId, generation, digest) {
3692
+ return `${generation}:${sessionId}:${digest ?? "none"}`;
3693
+ }
3694
+
3695
+ // src/mcp/app-skills-mcp.ts
3696
+ import { dirname as dirname5, join as join18 } from "node:path";
3697
+ import { fileURLToPath } from "node:url";
3698
+ import { existsSync as existsSync15, readFileSync as readFileSync9, statSync as statSync3 } from "node:fs";
3699
+ var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
3700
+ var APP_SKILLS_TOOLS = [
3701
+ {
3702
+ name: "app_list_skills",
3703
+ 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.",
3704
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
3705
+ },
3706
+ {
3707
+ name: "app_read_skill",
3708
+ 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).",
3709
+ inputSchema: {
3710
+ type: "object",
3711
+ properties: {
3712
+ name: { type: "string", description: "Exact skill name from app_list_skills" },
3713
+ ref: {
3714
+ type: "string",
3715
+ description: "Optional same-directory relative Markdown file (default SKILL.md)"
3716
+ }
3717
+ },
3718
+ required: ["name"],
3719
+ additionalProperties: false
3720
+ }
3721
+ }
3722
+ ];
3723
+ function buildAppSkillsMcpServer(directory, opts) {
3724
+ return {
3725
+ name: opts?.name ?? APP_SKILLS_MCP_SERVER_NAME,
3726
+ command: process.execPath,
3727
+ env: process.versions.electron ? [{ name: "ELECTRON_RUN_AS_NODE", value: "1" }] : [],
3728
+ args: [opts?.runnerPath ?? resolveAppSkillsRunnerPath(), directory]
3729
+ };
3730
+ }
3731
+ function resolveAppSkillsRunnerPath(fromFile) {
3732
+ const base = fromFile ?? fileURLToPath(import.meta.url);
3733
+ const candidates = [
3734
+ join18(dirname5(base), "app-skills-mcp-serve.cjs"),
3735
+ join18(dirname5(base), "app-skills-mcp-serve.ts")
3736
+ ];
3737
+ for (const candidate of candidates) {
3738
+ if (existsSync15(candidate))
3739
+ return candidate;
3740
+ }
3741
+ throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
3742
+ }
3743
+
3744
+ // src/client/acp-client.ts
3745
+ import { randomUUID as randomUUID2 } from "node:crypto";
3746
+
3747
+ // src/resources/eligibility.ts
3748
+ var NATIVE_ELIGIBLE_BRIDGE_VERSIONS = {
3749
+ "codex-acp": ["2.2.2"],
3750
+ opencode: ["1.18.35"],
3751
+ claude: ["0.91.0"],
3752
+ agy: ["0.1.24"]
3753
+ };
3754
+ function resolveRuntimeEligibility(runtimeId) {
3755
+ const id = (runtimeId ?? "").trim();
3756
+ if (!id || !(id in NATIVE_ELIGIBLE_BRIDGE_VERSIONS)) {
3757
+ return { eligible: false, reason: "runtime-not-verified" };
3758
+ }
3759
+ return { eligible: true };
3760
+ }
3761
+ function isSupportedBridgeVersion(runtimeId, version) {
3762
+ const versions = NATIVE_ELIGIBLE_BRIDGE_VERSIONS[(runtimeId ?? "").trim()];
3763
+ if (!versions)
3764
+ return { eligible: false, reason: "runtime-not-verified" };
3765
+ const normalized = version?.trim().replace(/^v/, "");
3766
+ if (!normalized)
3767
+ return { eligible: false, reason: "unknown-bridge-version" };
3768
+ if (!versions.includes(normalized))
3769
+ return { eligible: false, reason: "unsupported-bridge-version" };
3770
+ return { eligible: true };
3771
+ }
3772
+
3114
3773
  // src/session/session-capabilities.ts
3115
3774
  function parseLoadSessionSupported(caps) {
3116
3775
  return caps.loadSession === true;
@@ -3147,11 +3806,13 @@ class AcpSessionHandle {
3147
3806
  client;
3148
3807
  restoreMethod;
3149
3808
  configOptions;
3150
- constructor(sessionId, client, restoreMethod, configOptions) {
3809
+ resourceReport;
3810
+ constructor(sessionId, client, restoreMethod, configOptions, resourceReport) {
3151
3811
  this.sessionId = sessionId;
3152
3812
  this.client = client;
3153
3813
  this.restoreMethod = restoreMethod;
3154
3814
  this.configOptions = configOptions;
3815
+ this.resourceReport = resourceReport;
3155
3816
  }
3156
3817
  async prompt(promptText, options) {
3157
3818
  return this.client.promptSession(this.sessionId, promptText, options);
@@ -3180,6 +3841,10 @@ class AcpClient {
3180
3841
  clientInfo;
3181
3842
  dataDir;
3182
3843
  extraEnv;
3844
+ configurationScope;
3845
+ sessionConfig = null;
3846
+ resourcesDir;
3847
+ processScopeKey = randomUUID2();
3183
3848
  callbacks;
3184
3849
  terminals = new AcpTerminalManager;
3185
3850
  processHandle = null;
@@ -3187,6 +3852,17 @@ class AcpClient {
3187
3852
  sdkConnection = null;
3188
3853
  streamHandle = null;
3189
3854
  initResponse = null;
3855
+ inflightPrompts = new Set;
3856
+ resourcePrep = null;
3857
+ connectionGen = 0;
3858
+ attachSkillsMcp;
3859
+ sessionLedger = new Map;
3860
+ compatSentKeys = new Set;
3861
+ compatSnapshots = new Map;
3862
+ get resourceReport() {
3863
+ const report = this.resourcePrep?.report;
3864
+ return report ? { ...report, skillsFound: [...report.skillsFound] } : null;
3865
+ }
3190
3866
  constructor(options) {
3191
3867
  this.workspaceRoot = options.workspaceRoot;
3192
3868
  this.clientInfo = {
@@ -3195,6 +3871,14 @@ class AcpClient {
3195
3871
  };
3196
3872
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
3197
3873
  this.extraEnv = options.env ?? {};
3874
+ if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
3875
+ throw new Error("resources.directory 必须是本机绝对路径");
3876
+ }
3877
+ this.configurationScope = options.resources?.configurationScope ?? "overlay";
3878
+ if (!["overlay", "session"].includes(this.configurationScope))
3879
+ throw new Error("Invalid resources.configurationScope");
3880
+ this.resourcesDir = options.resources?.directory ?? null;
3881
+ this.attachSkillsMcp = options.resources?.attachSkillsMcp !== false;
3198
3882
  this.callbacks = options.callbacks ?? {};
3199
3883
  const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
3200
3884
  this.adapter = getAcpRuntimeAdapter(runtimeId);
@@ -3221,6 +3905,14 @@ class AcpClient {
3221
3905
  return this.initResponse;
3222
3906
  }
3223
3907
  async connect() {
3908
+ if (this.inflightPrompts.size > 0)
3909
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
3910
+ if (this.isConnected && this.initResponse)
3911
+ return ok({ status: this.status, init: this.initResponse });
3912
+ if (this.currentStatus === "connecting")
3913
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在连接" });
3914
+ this.connectionGen += 1;
3915
+ const connectGen = this.connectionGen;
3224
3916
  try {
3225
3917
  this.setStatus("connecting");
3226
3918
  const blocker = this.adapter.resolveSpawnBlocker?.();
@@ -3246,16 +3938,105 @@ class AcpClient {
3246
3938
  ...baseEnv,
3247
3939
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
3248
3940
  };
3941
+ let resourceEnv = {};
3942
+ let profileTag = null;
3943
+ if (this.resourcesDir && this.configurationScope === "session") {
3944
+ const profile = await createSessionConfigHome(this.runtimeInfo.id, this.resourcesDir);
3945
+ if (connectGen !== this.connectionGen || this.status !== "connecting") {
3946
+ await profile.dispose();
3947
+ return err({ code: "CANCELLED", message: "连接已取消" });
3948
+ }
3949
+ this.sessionConfig = profile;
3950
+ resourceEnv = this.sessionConfig.env;
3951
+ const load = readAppResourcesDir(this.resourcesDir);
3952
+ this.resourcePrep = { profileTag: null, report: {
3953
+ rulesApplied: false,
3954
+ rulesPrepared: false,
3955
+ skillsApplied: false,
3956
+ rulesChars: load.rules?.chars ?? 0,
3957
+ profileDigest: digestAppResources(load),
3958
+ skillsFound: load.skills.map((s) => s.name),
3959
+ configurationScope: "session",
3960
+ configurationDirectory: this.sessionConfig.directory,
3961
+ configurationRulesFile: this.sessionConfig.rulesFile,
3962
+ reason: this.sessionConfig.nativeRules ? "isolated-config-not-runtime-verified" : "isolated-config-rule-discovery-not-verified"
3963
+ } };
3964
+ } else if (this.resourcesDir && this.adapter.prepareAppResources) {
3965
+ try {
3966
+ const prep = await this.adapter.prepareAppResources({
3967
+ directory: this.resourcesDir,
3968
+ command: effectiveRuntime.command,
3969
+ workspaceRoot: this.workspaceRoot,
3970
+ env: { ...process.env, ...spawnEnv.env }
3971
+ });
3972
+ if (prep.env)
3973
+ resourceEnv = prep.env;
3974
+ prep.report.rulesPrepared = prep.report.rulesPrepared ?? prep.report.rulesApplied;
3975
+ prep.report.rulesApplied = false;
3976
+ prep.report.skillsApplied = false;
3977
+ const digest = prep.report.profileDigest;
3978
+ profileTag = digest ? `${this.runtimeInfo.id}:resources@${digest.slice(0, 16)}` : null;
3979
+ this.resourcePrep = { profileTag, report: prep.report };
3980
+ } catch (error) {
3981
+ this.resourcePrep = {
3982
+ profileTag: null,
3983
+ report: {
3984
+ rulesApplied: false,
3985
+ rulesChars: 0,
3986
+ profileDigest: null,
3987
+ skillsFound: [],
3988
+ reason: "prepare-failed"
3989
+ }
3990
+ };
3991
+ this.callbacks.onLog?.("warn", "应用资源准备失败,已回退兼容", {
3992
+ error: error instanceof Error ? error.message : String(error)
3993
+ });
3994
+ }
3995
+ } else {
3996
+ const load = this.resourcesDir ? readAppResourcesDir(this.resourcesDir) : null;
3997
+ this.resourcePrep = load ? { profileTag: null, report: {
3998
+ rulesApplied: false,
3999
+ rulesPrepared: false,
4000
+ skillsApplied: false,
4001
+ rulesChars: load.rules?.chars ?? 0,
4002
+ profileDigest: digestAppResources(load),
4003
+ skillsFound: load.skills.map((s) => s.name),
4004
+ reason: "runtime-not-supported"
4005
+ } } : null;
4006
+ }
4007
+ const finalEnv = { ...spawnEnv.env, ...resourceEnv };
3249
4008
  await this.adapter.beforeSpawn?.();
3250
- const processHandle = spawnAcpProcess({
4009
+ if (connectGen !== this.connectionGen || this.status !== "connecting")
4010
+ return err({ code: "CANCELLED", message: "连接已取消" });
4011
+ let reuseDegraded = false;
4012
+ let reusedHandle = null;
4013
+ if (profileTag) {
4014
+ const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
4015
+ expectedTag: profileTag,
4016
+ scopeKey: this.processScopeKey,
4017
+ isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
4018
+ });
4019
+ if (reuse.status === "hit") {
4020
+ reusedHandle = reuse.handle;
4021
+ } else if (reuse.status === "busy") {
4022
+ reusedHandle = reuse.handle;
4023
+ reuseDegraded = true;
4024
+ this.callbacks.onLog?.("warn", "应用资源摘要已变更但旧进程正忙,沿用旧进程并降级,新摘要下次冷启动生效");
4025
+ }
4026
+ }
4027
+ const processHandle = reusedHandle ?? spawnAcpProcess({
3251
4028
  runtime: effectiveRuntime,
3252
4029
  cwd: this.workspaceRoot,
3253
- env: spawnEnv.env,
4030
+ scopeKey: this.processScopeKey,
4031
+ env: finalEnv,
3254
4032
  envRemove: spawnEnv.envRemove,
4033
+ profileTag,
3255
4034
  onStderrLine: (line) => {
3256
4035
  this.callbacks.onStderrLine?.(line);
3257
4036
  },
3258
4037
  onExit: (code, signal) => {
4038
+ if (this.connectionGen !== connectGen)
4039
+ return;
3259
4040
  this.callbacks.onLog?.("warn", `Agent 进程已退出 (code: ${code}, signal: ${signal})`);
3260
4041
  if (this.status === "connected" || this.status === "connecting") {
3261
4042
  this.disconnect("Agent 进程异常终止");
@@ -3306,9 +4087,28 @@ class AcpClient {
3306
4087
  }
3307
4088
  });
3308
4089
  this.initResponse = initResp;
4090
+ if (this.resourcePrep) {
4091
+ const agentInfo = initResp?.agentInfo;
4092
+ const bridgeVersion = typeof agentInfo?.version === "string" ? agentInfo.version : undefined;
4093
+ const supported = isSupportedBridgeVersion(this.runtimeInfo.id, bridgeVersion).eligible && (this.adapter.supportedBridgeVersions?.includes(bridgeVersion?.replace(/^v/, "") ?? "") ?? false);
4094
+ this.resourcePrep.report.bridgeVersion = bridgeVersion;
4095
+ this.resourcePrep.report.bridgeSupported = supported;
4096
+ if (this.processHandle)
4097
+ this.processHandle.bridgeVersion = bridgeVersion;
4098
+ if (supported && this.resourcePrep.report.reason === "native-session-version-not-verified")
4099
+ delete this.resourcePrep.report.reason;
4100
+ if (!supported) {
4101
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "unsupported-bridge-version";
4102
+ }
4103
+ if (reuseDegraded) {
4104
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "busy-deferred-stale-rules";
4105
+ }
4106
+ }
3309
4107
  this.setStatus("connected");
3310
4108
  return ok({ status: "connected", init: initResp });
3311
4109
  } catch (e) {
4110
+ if (connectGen !== this.connectionGen)
4111
+ return err({ code: "CANCELLED", message: "连接已被新请求取代" });
3312
4112
  const message = e instanceof Error ? e.message : String(e);
3313
4113
  this.setStatus("error", message);
3314
4114
  await this.disconnect(message);
@@ -3347,6 +4147,29 @@ class AcpClient {
3347
4147
  const resumeSupported = Boolean(init && parseResumeSessionSupported(init.agentCapabilities));
3348
4148
  const loadSupported = Boolean(init && parseLoadSessionSupported(init.agentCapabilities));
3349
4149
  try {
4150
+ let skillsExposed = "none";
4151
+ let mcpServers = options?.mcpServers ?? [];
4152
+ if (this.resourcesDir && this.attachSkillsMcp) {
4153
+ try {
4154
+ const descriptor = buildAppSkillsMcpServer(this.resourcesDir);
4155
+ const callerNames = new Set;
4156
+ for (const entry of mcpServers) {
4157
+ if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
4158
+ callerNames.add(entry.name);
4159
+ }
4160
+ }
4161
+ if (callerNames.has(descriptor.name)) {
4162
+ this.callbacks.onLog?.("warn", "调用方已有同名技能 MCP 服务,保留调用方版本", { name: descriptor.name });
4163
+ } else {
4164
+ mcpServers = [...mcpServers, descriptor];
4165
+ skillsExposed = "mcp-exposed";
4166
+ }
4167
+ } catch (error) {
4168
+ this.callbacks.onLog?.("warn", "技能 MCP 描述符构建失败,本次会话无技能 MCP", {
4169
+ error: error instanceof Error ? error.message : String(error)
4170
+ });
4171
+ }
4172
+ }
3350
4173
  const openResult = await restoreOrCreateAcpSession({
3351
4174
  request: async (method, params) => {
3352
4175
  return sdkRequest(agent, method, params);
@@ -3355,12 +4178,27 @@ class AcpClient {
3355
4178
  resumeSessionId: options?.resumeSessionId ?? null,
3356
4179
  resumeSupported,
3357
4180
  loadSupported,
3358
- mcpServers: options?.mcpServers ?? [],
4181
+ mcpServers,
4182
+ sessionMeta: (!this.sessionConfig || this.runtimeInfo.id === "agy") && this.resourcesDir && this.resourcePrep?.report.bridgeSupported ? this.adapter.appResourceSessionMeta?.(this.resourcesDir) : undefined,
3359
4183
  log: (level, msg, meta) => {
3360
4184
  this.callbacks.onLog?.(level, msg, meta);
3361
4185
  }
3362
4186
  });
3363
- const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions);
4187
+ if (!openResult.mcpServersAccepted)
4188
+ skillsExposed = "none";
4189
+ this.sessionLedger.set(openResult.sessionId, {
4190
+ restoreMethod: openResult.restoreMethod,
4191
+ gen: this.connectionGen,
4192
+ skillsExposed,
4193
+ nativeRules: openResult.nativeSessionAccepted
4194
+ });
4195
+ const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions, this.resourcePrep?.report ? {
4196
+ ...this.resourcePrep.report,
4197
+ skillsFound: [...this.resourcePrep.report.skillsFound],
4198
+ skillsExposed,
4199
+ rulesApplied: openResult.nativeSessionAccepted || !this.adapter.appResourceSessionMeta && openResult.restoreMethod === "new" && this.resourcePrep.report.bridgeSupported === true && this.resourcePrep.report.rulesPrepared === true,
4200
+ ...openResult.restoreMethod !== "new" && !openResult.nativeSessionAccepted ? { reason: "session-restored-not-verified" } : {}
4201
+ } : null);
3364
4202
  return ok(handle);
3365
4203
  } catch (e) {
3366
4204
  const message = e instanceof Error ? e.message : String(e);
@@ -3371,6 +4209,7 @@ class AcpClient {
3371
4209
  if (!this.sdkConnection?.agent) {
3372
4210
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
3373
4211
  }
4212
+ this.inflightPrompts.add(sessionId);
3374
4213
  try {
3375
4214
  const prompt = [{ type: "text", text: promptText }];
3376
4215
  for (const image of options?.images ?? []) {
@@ -3378,16 +4217,52 @@ class AcpClient {
3378
4217
  continue;
3379
4218
  prompt.push({ type: "image", mimeType: image.mimeType, data: image.data });
3380
4219
  }
4220
+ const compat = this.buildCompatPrepend(sessionId);
4221
+ const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
3381
4222
  const response = await sdkRequest(this.sdkConnection.agent, methods2.agent.session.prompt, {
3382
4223
  sessionId,
3383
- prompt
4224
+ prompt: blocks
3384
4225
  }, options?.timeoutMs);
3385
4226
  return ok(response);
3386
4227
  } catch (e) {
3387
4228
  const message = e instanceof Error ? e.message : String(e);
3388
4229
  return err({ code: "ACP_PROTOCOL_ERROR", message });
4230
+ } finally {
4231
+ this.inflightPrompts.delete(sessionId);
3389
4232
  }
3390
4233
  }
4234
+ buildCompatPrepend(sessionId) {
4235
+ if (!this.resourcesDir)
4236
+ return null;
4237
+ if (this.sessionConfig?.nativeRules)
4238
+ return null;
4239
+ const entry = this.sessionLedger.get(sessionId);
4240
+ if (!entry)
4241
+ return null;
4242
+ const connReport = this.resourcePrep?.report;
4243
+ const nativelyDelivered = entry.nativeRules || !this.adapter.appResourceSessionMeta && entry.restoreMethod === "new" && entry.gen === this.connectionGen && connReport?.rulesPrepared === true && connReport?.bridgeSupported === true;
4244
+ if (nativelyDelivered)
4245
+ return null;
4246
+ const load = readAppResourcesDir(this.resourcesDir);
4247
+ const rulesText = readAppRulesText(this.resourcesDir);
4248
+ const digest = digestAppResources(load);
4249
+ const key = compatDeliveryKey(sessionId, this.connectionGen, digest);
4250
+ if (this.compatSentKeys.has(key))
4251
+ return null;
4252
+ const text = buildCompatGuideText({
4253
+ rulesText,
4254
+ skills: load.skills.map((s) => ({ name: s.name, description: s.description })),
4255
+ skillsViaMcp: entry.skillsExposed === "mcp-exposed",
4256
+ digest,
4257
+ sessionId,
4258
+ generation: this.connectionGen
4259
+ });
4260
+ if (!text)
4261
+ return null;
4262
+ this.compatSnapshots.set(key, { text, digest });
4263
+ this.compatSentKeys.add(key);
4264
+ return text;
4265
+ }
3391
4266
  async setSessionConfigOption(sessionId, configId, value) {
3392
4267
  if (!this.sdkConnection?.agent) {
3393
4268
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
@@ -3406,6 +4281,10 @@ class AcpClient {
3406
4281
  }
3407
4282
  async disconnect(reason) {
3408
4283
  this.setStatus("disconnected", reason);
4284
+ this.resourcePrep = null;
4285
+ this.sessionLedger.clear();
4286
+ this.compatSentKeys.clear();
4287
+ this.compatSnapshots.clear();
3409
4288
  try {
3410
4289
  this.streamHandle?.dispose();
3411
4290
  this.sdkConnection?.close();
@@ -3421,6 +4300,15 @@ class AcpClient {
3421
4300
  } catch {}
3422
4301
  this.processHandle = null;
3423
4302
  }
4303
+ const config = this.sessionConfig;
4304
+ this.sessionConfig = null;
4305
+ if (config) {
4306
+ try {
4307
+ await config.dispose();
4308
+ } catch {
4309
+ this.callbacks.onLog?.("warn", "Session configuration cleanup failed; directory retained", { directory: config.directory });
4310
+ }
4311
+ }
3424
4312
  }
3425
4313
  setStatus(status, detail) {
3426
4314
  this.status = status;
@@ -4346,6 +5234,10 @@ export {
4346
5234
  ACP_EARLY_EXIT_WINDOW_MS,
4347
5235
  ACP_SDK_REQUEST_TIMEOUT_MS,
4348
5236
  AGY_ACP_NPM_PACKAGE,
5237
+ APP_RESOURCE_CAPABILITIES,
5238
+ APP_RULES_FILE,
5239
+ APP_SKILLS_DIR,
5240
+ APP_SKILL_FILE,
4349
5241
  AcpClient,
4350
5242
  AcpSessionHandle,
4351
5243
  AcpTerminalManager,
@@ -4364,6 +5256,7 @@ export {
4364
5256
  INKDOWN_VIRTUAL_DIR,
4365
5257
  INKDOWN_VIRTUAL_RESOURCES,
4366
5258
  LEGACY_ZED_CODEX_ACP_NPM_PACKAGE,
5259
+ NATIVE_ELIGIBLE_BRIDGE_VERSIONS,
4367
5260
  OPENCODE_CLI_NPM_PACKAGE,
4368
5261
  QuotaCache,
4369
5262
  acpReadTextFile,
@@ -4379,15 +5272,18 @@ export {
4379
5272
  callInkdownMcpTool,
4380
5273
  callInkdownTocTool,
4381
5274
  claudeAdapter,
5275
+ claudeResourceSessionMeta,
4382
5276
  clearAcpProvider,
4383
5277
  clearCursorCatalogCache,
4384
5278
  codexAdapter,
4385
5279
  connectSdkClient,
4386
5280
  copilotAdapter,
4387
5281
  createSdkStreamHandle,
5282
+ createSessionConfigHome,
4388
5283
  cursorAdapter,
4389
5284
  decideConnectAuth,
4390
5285
  deepseekAdapter,
5286
+ digestAppResources,
4391
5287
  disposeAllAcpProcesses,
4392
5288
  emptyAcpAuthPreflight,
4393
5289
  err,
@@ -4407,6 +5303,7 @@ export {
4407
5303
  getDefaultAgentDataDir,
4408
5304
  getLiveAcpProcess,
4409
5305
  handleInkdownMcpRpc,
5306
+ isAbsolutePathLike,
4410
5307
  isAppError,
4411
5308
  isBinaryDocumentPath,
4412
5309
  isCancelled,
@@ -4416,11 +5313,15 @@ export {
4416
5313
  isInkdownVirtualDirPath,
4417
5314
  isOk,
4418
5315
  isSpawnedAcpProcessAlive,
5316
+ isSupportedBridgeVersion,
4419
5317
  isTransientAcpTransportError,
4420
5318
  isValidCursorAuthFile,
4421
5319
  isValidOpencodeAuthFile,
4422
5320
  listAcpRuntimes,
4423
5321
  listLiveAcpRuntimeIds,
5322
+ mergeCodexConfigJson,
5323
+ mergeConfigTomlPreserving,
5324
+ mergeOpenCodeAppConfig,
4424
5325
  mergeTopLevelModelsIntoConfigOptions,
4425
5326
  ok,
4426
5327
  opencodeAdapter,
@@ -4434,7 +5335,11 @@ export {
4434
5335
  parsePromptCapabilities,
4435
5336
  parseRateLimitsFromStatusText,
4436
5337
  parseResumeSessionSupported,
5338
+ parseSkillFrontmatter,
4437
5339
  pickAllowOptionId,
5340
+ prepareClaudeResources,
5341
+ prepareCompatibilityResources,
5342
+ prepareOpenCodeResources,
4438
5343
  probeAgyAuth,
4439
5344
  probeClaudeAuth,
4440
5345
  probeClaudeQuota,
@@ -4449,6 +5354,8 @@ export {
4449
5354
  probeOpencodeQuota,
4450
5355
  provisionCustomProviderCodexHome,
4451
5356
  readAcpProxySettings,
5357
+ readAppResourcesDir,
5358
+ readAppRulesText,
4452
5359
  readStoredAcpProvider,
4453
5360
  registerAcpClientHandlers,
4454
5361
  resolveClaudeHome,
@@ -4464,6 +5371,7 @@ export {
4464
5371
  resolveOpencodeAuthCandidates,
4465
5372
  resolveOpencodeAuthFile,
4466
5373
  resolveOpencodeAuthPath,
5374
+ resolveRuntimeEligibility,
4467
5375
  restoreOrCreateAcpSession,
4468
5376
  runConnectAuthGate,
4469
5377
  saveAcpProvider,
@@ -4474,5 +5382,6 @@ export {
4474
5382
  synthesizeModelOptionFromTopLevelModels,
4475
5383
  toAppError,
4476
5384
  truncateOutputFromStart,
5385
+ tryReuseLiveAcpProcess,
4477
5386
  withAcpEarlyExitDetail
4478
5387
  };