@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.cjs CHANGED
@@ -70,6 +70,10 @@ __export(exports_src, {
70
70
  ACP_EARLY_EXIT_WINDOW_MS: () => ACP_EARLY_EXIT_WINDOW_MS,
71
71
  ACP_SDK_REQUEST_TIMEOUT_MS: () => ACP_SDK_REQUEST_TIMEOUT_MS,
72
72
  AGY_ACP_NPM_PACKAGE: () => AGY_ACP_NPM_PACKAGE,
73
+ APP_RESOURCE_CAPABILITIES: () => APP_RESOURCE_CAPABILITIES,
74
+ APP_RULES_FILE: () => APP_RULES_FILE,
75
+ APP_SKILLS_DIR: () => APP_SKILLS_DIR,
76
+ APP_SKILL_FILE: () => APP_SKILL_FILE,
73
77
  AcpClient: () => AcpClient,
74
78
  AcpSessionHandle: () => AcpSessionHandle,
75
79
  AcpTerminalManager: () => AcpTerminalManager,
@@ -88,6 +92,7 @@ __export(exports_src, {
88
92
  INKDOWN_VIRTUAL_DIR: () => INKDOWN_VIRTUAL_DIR,
89
93
  INKDOWN_VIRTUAL_RESOURCES: () => INKDOWN_VIRTUAL_RESOURCES,
90
94
  LEGACY_ZED_CODEX_ACP_NPM_PACKAGE: () => LEGACY_ZED_CODEX_ACP_NPM_PACKAGE,
95
+ NATIVE_ELIGIBLE_BRIDGE_VERSIONS: () => NATIVE_ELIGIBLE_BRIDGE_VERSIONS,
91
96
  OPENCODE_CLI_NPM_PACKAGE: () => OPENCODE_CLI_NPM_PACKAGE,
92
97
  QuotaCache: () => QuotaCache,
93
98
  acpReadTextFile: () => acpReadTextFile,
@@ -103,15 +108,18 @@ __export(exports_src, {
103
108
  callInkdownMcpTool: () => callInkdownMcpTool,
104
109
  callInkdownTocTool: () => callInkdownTocTool,
105
110
  claudeAdapter: () => claudeAdapter,
111
+ claudeResourceSessionMeta: () => claudeResourceSessionMeta,
106
112
  clearAcpProvider: () => clearAcpProvider,
107
113
  clearCursorCatalogCache: () => clearCursorCatalogCache,
108
114
  codexAdapter: () => codexAdapter,
109
115
  connectSdkClient: () => connectSdkClient,
110
116
  copilotAdapter: () => copilotAdapter,
111
117
  createSdkStreamHandle: () => createSdkStreamHandle,
118
+ createSessionConfigHome: () => createSessionConfigHome,
112
119
  cursorAdapter: () => cursorAdapter,
113
120
  decideConnectAuth: () => decideConnectAuth,
114
121
  deepseekAdapter: () => deepseekAdapter,
122
+ digestAppResources: () => digestAppResources,
115
123
  disposeAllAcpProcesses: () => disposeAllAcpProcesses,
116
124
  emptyAcpAuthPreflight: () => emptyAcpAuthPreflight,
117
125
  err: () => err,
@@ -131,6 +139,7 @@ __export(exports_src, {
131
139
  getDefaultAgentDataDir: () => getDefaultAgentDataDir,
132
140
  getLiveAcpProcess: () => getLiveAcpProcess,
133
141
  handleInkdownMcpRpc: () => handleInkdownMcpRpc,
142
+ isAbsolutePathLike: () => isAbsolutePathLike,
134
143
  isAppError: () => isAppError,
135
144
  isBinaryDocumentPath: () => isBinaryDocumentPath,
136
145
  isCancelled: () => isCancelled,
@@ -140,11 +149,15 @@ __export(exports_src, {
140
149
  isInkdownVirtualDirPath: () => isInkdownVirtualDirPath,
141
150
  isOk: () => isOk,
142
151
  isSpawnedAcpProcessAlive: () => isSpawnedAcpProcessAlive,
152
+ isSupportedBridgeVersion: () => isSupportedBridgeVersion,
143
153
  isTransientAcpTransportError: () => isTransientAcpTransportError,
144
154
  isValidCursorAuthFile: () => isValidCursorAuthFile,
145
155
  isValidOpencodeAuthFile: () => isValidOpencodeAuthFile,
146
156
  listAcpRuntimes: () => listAcpRuntimes,
147
157
  listLiveAcpRuntimeIds: () => listLiveAcpRuntimeIds,
158
+ mergeCodexConfigJson: () => mergeCodexConfigJson,
159
+ mergeConfigTomlPreserving: () => mergeConfigTomlPreserving,
160
+ mergeOpenCodeAppConfig: () => mergeOpenCodeAppConfig,
148
161
  mergeTopLevelModelsIntoConfigOptions: () => mergeTopLevelModelsIntoConfigOptions,
149
162
  ok: () => ok,
150
163
  opencodeAdapter: () => opencodeAdapter,
@@ -158,7 +171,11 @@ __export(exports_src, {
158
171
  parsePromptCapabilities: () => parsePromptCapabilities,
159
172
  parseRateLimitsFromStatusText: () => parseRateLimitsFromStatusText,
160
173
  parseResumeSessionSupported: () => parseResumeSessionSupported,
174
+ parseSkillFrontmatter: () => parseSkillFrontmatter,
161
175
  pickAllowOptionId: () => pickAllowOptionId,
176
+ prepareClaudeResources: () => prepareClaudeResources,
177
+ prepareCompatibilityResources: () => prepareCompatibilityResources,
178
+ prepareOpenCodeResources: () => prepareOpenCodeResources,
162
179
  probeAgyAuth: () => probeAgyAuth,
163
180
  probeClaudeAuth: () => probeClaudeAuth,
164
181
  probeClaudeQuota: () => probeClaudeQuota,
@@ -173,6 +190,8 @@ __export(exports_src, {
173
190
  probeOpencodeQuota: () => probeOpencodeQuota,
174
191
  provisionCustomProviderCodexHome: () => provisionCustomProviderCodexHome,
175
192
  readAcpProxySettings: () => readAcpProxySettings,
193
+ readAppResourcesDir: () => readAppResourcesDir,
194
+ readAppRulesText: () => readAppRulesText,
176
195
  readStoredAcpProvider: () => readStoredAcpProvider,
177
196
  registerAcpClientHandlers: () => registerAcpClientHandlers,
178
197
  resolveClaudeHome: () => resolveClaudeHome,
@@ -188,6 +207,7 @@ __export(exports_src, {
188
207
  resolveOpencodeAuthCandidates: () => resolveOpencodeAuthCandidates,
189
208
  resolveOpencodeAuthFile: () => resolveOpencodeAuthFile,
190
209
  resolveOpencodeAuthPath: () => resolveOpencodeAuthPath,
210
+ resolveRuntimeEligibility: () => resolveRuntimeEligibility,
191
211
  restoreOrCreateAcpSession: () => restoreOrCreateAcpSession,
192
212
  runConnectAuthGate: () => runConnectAuthGate,
193
213
  saveAcpProvider: () => saveAcpProvider,
@@ -198,6 +218,7 @@ __export(exports_src, {
198
218
  synthesizeModelOptionFromTopLevelModels: () => synthesizeModelOptionFromTopLevelModels,
199
219
  toAppError: () => toAppError,
200
220
  truncateOutputFromStart: () => truncateOutputFromStart,
221
+ tryReuseLiveAcpProcess: () => tryReuseLiveAcpProcess,
201
222
  withAcpEarlyExitDetail: () => withAcpEarlyExitDetail
202
223
  });
203
224
  module.exports = __toCommonJS(exports_src);
@@ -363,7 +384,244 @@ function findBuiltinAcpRuntime(id) {
363
384
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
364
385
  }
365
386
  // src/version.ts
366
- var ACP_CLIENT_VERSION = "0.1.7";
387
+ var ACP_CLIENT_VERSION = "0.1.8";
388
+ // src/resources/session-config.ts
389
+ var import_node_fs2 = require("node:fs");
390
+ var import_promises = require("node:fs/promises");
391
+ var import_node_os = require("node:os");
392
+ var import_node_path2 = require("node:path");
393
+
394
+ // src/resources/app-resources.ts
395
+ var import_node_crypto = require("node:crypto");
396
+ var import_node_fs = require("node:fs");
397
+ var import_node_path = require("node:path");
398
+ var APP_RULES_FILE = "AGENTS.md";
399
+ var APP_SKILLS_DIR = "skills";
400
+ var APP_SKILL_FILE = "SKILL.md";
401
+ function parseSkillFrontmatter(text) {
402
+ const lines = text.split(`
403
+ `);
404
+ if (lines[0]?.trim() !== "---")
405
+ return {};
406
+ const out = {};
407
+ for (let i = 1;i < lines.length; i += 1) {
408
+ const line = lines[i] ?? "";
409
+ if (line.trim() === "---")
410
+ break;
411
+ const cut = line.indexOf(":");
412
+ if (cut <= 0)
413
+ continue;
414
+ const key = line.slice(0, cut).trim().toLowerCase();
415
+ if (key !== "name" && key !== "description")
416
+ continue;
417
+ const value = line.slice(cut + 1).trim().replace(/^['"]|['"]$/g, "");
418
+ if (value)
419
+ out[key] = value;
420
+ }
421
+ return out;
422
+ }
423
+ function sha256Hex(text) {
424
+ return import_node_crypto.createHash("sha256").update(text, "utf8").digest("hex");
425
+ }
426
+ function readTextFile(path) {
427
+ try {
428
+ if (!import_node_fs.statSync(path).isFile())
429
+ return null;
430
+ const text = import_node_fs.readFileSync(path, "utf8");
431
+ return text.trim() ? text : null;
432
+ } catch {
433
+ return null;
434
+ }
435
+ }
436
+ function readAppResourcesDir(directory) {
437
+ const warnings = [];
438
+ if (!import_node_path.isAbsolute(directory))
439
+ return { directoryReadable: false, rules: null, skills: [], warnings: ["资源目录必须是本机绝对路径"] };
440
+ let directoryReadable = false;
441
+ try {
442
+ directoryReadable = import_node_fs.statSync(directory).isDirectory();
443
+ } catch {
444
+ directoryReadable = false;
445
+ }
446
+ if (!directoryReadable) {
447
+ return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
448
+ }
449
+ let rules = null;
450
+ const rulesText = readTextFile(import_node_path.join(directory, APP_RULES_FILE));
451
+ if (rulesText === null) {
452
+ warnings.push(`缺常驻规则: ${APP_RULES_FILE}`);
453
+ } else {
454
+ rules = { chars: rulesText.length, digest: sha256Hex(`app-rules-v1
455
+ ${rulesText}`) };
456
+ }
457
+ const skills = [];
458
+ const skillsRoot = import_node_path.join(directory, APP_SKILLS_DIR);
459
+ let skillNames = [];
460
+ try {
461
+ if (import_node_fs.statSync(skillsRoot).isDirectory()) {
462
+ skillNames = import_node_fs.readdirSync(skillsRoot).filter((name) => {
463
+ try {
464
+ return import_node_fs.statSync(import_node_path.join(skillsRoot, name)).isDirectory();
465
+ } catch {
466
+ return false;
467
+ }
468
+ });
469
+ }
470
+ } catch {
471
+ skillNames = [];
472
+ }
473
+ for (const name of skillNames.sort()) {
474
+ const rel = `${APP_SKILLS_DIR}/${name}/${APP_SKILL_FILE}`;
475
+ const text = readTextFile(import_node_path.join(directory, rel));
476
+ if (text === null) {
477
+ warnings.push(`技能缺正文已跳过: ${rel}`);
478
+ continue;
479
+ }
480
+ const front = parseSkillFrontmatter(text);
481
+ const skillName = front.name || name;
482
+ if (skills.some((s) => s.name === skillName)) {
483
+ warnings.push(`技能重名已跳过(保留首个): ${skillName}`);
484
+ continue;
485
+ }
486
+ const description = front.description || "";
487
+ skills.push({
488
+ name: skillName,
489
+ description,
490
+ path: rel,
491
+ chars: text.length,
492
+ digest: sha256Hex(`app-skill-v1
493
+ ${skillName}
494
+ ${description}
495
+ ${text}`)
496
+ });
497
+ }
498
+ return { directoryReadable: true, rules, skills, warnings };
499
+ }
500
+ function digestAppResources(load) {
501
+ if (!load.rules)
502
+ return null;
503
+ const skillPart = load.skills.map((s) => `${s.name}:${s.digest}`).join(`
504
+ `);
505
+ return sha256Hex(`app-resources-v1
506
+ ${load.rules.digest}
507
+ ${skillPart}`);
508
+ }
509
+ function readAppRulesText(directory) {
510
+ return readTextFile(import_node_path.join(directory, APP_RULES_FILE));
511
+ }
512
+ function isAbsolutePathLike(path) {
513
+ return import_node_path.isAbsolute(path);
514
+ }
515
+
516
+ // src/resources/session-config.ts
517
+ async function createSessionConfigHome(runtime, resources) {
518
+ if (!import_node_path2.isAbsolute(resources))
519
+ throw new Error("Resources must be an absolute path");
520
+ const id = runtime === "cursor" ? "cursor-cli" : runtime;
521
+ const supported = ["agy", "codex-acp", "claude", "gemini", "copilot", "cursor-cli", "opencode", "opencode-v2"];
522
+ if (!supported.includes(id))
523
+ throw new Error("Session configuration home is not verified for runtime: " + runtime);
524
+ const text = readAppRulesText(resources);
525
+ if (!text)
526
+ throw new Error("Session configuration requires nonempty AGENTS.md");
527
+ const parent = import_node_path2.resolve(import_node_os.tmpdir());
528
+ const directory = await import_promises.mkdtemp(import_node_path2.join(parent, "acp-session-config-"));
529
+ const checkRoot = () => {
530
+ if (import_node_path2.resolve(directory) === parent || !import_node_path2.resolve(directory).startsWith(parent + import_node_path2.sep) || !import_node_path2.relative(parent, directory).startsWith("acp-session-config-"))
531
+ throw new Error("Unsafe configuration cleanup target");
532
+ };
533
+ const dispose = async () => {
534
+ checkRoot();
535
+ let failure;
536
+ for (let i = 0;i < 30; i++) {
537
+ try {
538
+ await import_promises.rm(directory, { recursive: true, force: true });
539
+ return;
540
+ } catch (error) {
541
+ failure = error;
542
+ await new Promise((r) => setTimeout(r, 100));
543
+ }
544
+ }
545
+ throw failure;
546
+ };
547
+ try {
548
+ const config = import_node_path2.join(directory, "config");
549
+ await import_promises.mkdir(config, { recursive: true, mode: 448 });
550
+ let env;
551
+ let rulesFile;
552
+ let skillsRoot = import_node_path2.join(config, "skills");
553
+ let nativeRules = true;
554
+ if (id === "agy") {
555
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
556
+ env = { AGY_ACP_RESOURCES_DIR: config };
557
+ nativeRules = false;
558
+ } else if (id === "gemini") {
559
+ const root = import_node_path2.join(directory, "home", ".gemini");
560
+ await import_promises.mkdir(root, { recursive: true, mode: 448 });
561
+ rulesFile = import_node_path2.join(root, "GEMINI.md");
562
+ skillsRoot = import_node_path2.join(root, "skills");
563
+ env = { GEMINI_CLI_HOME: import_node_path2.join(directory, "home") };
564
+ } else if (id === "claude") {
565
+ rulesFile = import_node_path2.join(config, "CLAUDE.md");
566
+ env = { CLAUDE_CONFIG_DIR: config };
567
+ } else if (id === "codex-acp") {
568
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
569
+ env = { CODEX_HOME: config };
570
+ } else if (id === "copilot") {
571
+ rulesFile = import_node_path2.join(config, "copilot-instructions.md");
572
+ env = { COPILOT_HOME: config, COPILOT_CUSTOM_INSTRUCTIONS_DIRS: config, COPILOT_SKILLS_DIRS: skillsRoot };
573
+ await import_promises.writeFile(import_node_path2.join(config, "AGENTS.md"), text, { mode: 384 });
574
+ } else if (id === "cursor-cli") {
575
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
576
+ env = { CURSOR_CONFIG_DIR: config };
577
+ nativeRules = false;
578
+ } else {
579
+ const root = import_node_path2.join(directory, "xdg-config", "opencode");
580
+ await import_promises.mkdir(root, { recursive: true, mode: 448 });
581
+ rulesFile = import_node_path2.join(root, "AGENTS.md");
582
+ skillsRoot = import_node_path2.join(root, "skills");
583
+ env = { XDG_CONFIG_HOME: import_node_path2.join(directory, "xdg-config"), XDG_DATA_HOME: import_node_path2.join(directory, "xdg-data"), XDG_CACHE_HOME: import_node_path2.join(directory, "xdg-cache"), XDG_STATE_HOME: import_node_path2.join(directory, "xdg-state") };
584
+ if (id === "opencode")
585
+ env.OPENCODE_CONFIG_DIR = root;
586
+ const skills = id === "opencode" ? { paths: [skillsRoot] } : [skillsRoot];
587
+ await import_promises.writeFile(import_node_path2.join(root, "opencode.json"), JSON.stringify({ instructions: [rulesFile], skills }), { mode: 384 });
588
+ }
589
+ await import_promises.writeFile(rulesFile, text, { mode: 384 });
590
+ const input = import_node_path2.join(resources, "skills");
591
+ try {
592
+ const info = await import_promises.lstat(input);
593
+ if (info.isSymbolicLink() || !info.isDirectory())
594
+ throw new Error("Skill root must be a regular directory");
595
+ const physical = await import_promises.realpath(input);
596
+ const copy = async (from, to) => {
597
+ await import_promises.mkdir(to, { recursive: true, mode: 448 });
598
+ for (const entry of await import_promises.readdir(from, { withFileTypes: true })) {
599
+ const src = import_node_path2.join(from, entry.name);
600
+ const info = await import_promises.lstat(src);
601
+ if (info.isSymbolicLink())
602
+ throw new Error("Skill symlink is not allowed");
603
+ const actual = await import_promises.realpath(src);
604
+ const rel = import_node_path2.relative(physical, actual);
605
+ if (rel.startsWith(".." + import_node_path2.sep) || rel === ".." || import_node_path2.isAbsolute(rel))
606
+ throw new Error("Skill path escapes resources");
607
+ if (info.isDirectory())
608
+ await copy(src, import_node_path2.join(to, entry.name));
609
+ else if (info.isFile() && entry.name.toLowerCase().endsWith(".md"))
610
+ await import_promises.writeFile(import_node_path2.join(to, entry.name), await import_promises.readFile(src), { mode: 384 });
611
+ }
612
+ };
613
+ await copy(input, skillsRoot);
614
+ } catch (error) {
615
+ if (error.code !== "ENOENT" || import_node_fs2.existsSync(input))
616
+ throw error;
617
+ }
618
+ return { directory, env, rulesFile, nativeRules, dispose };
619
+ } catch (error) {
620
+ await dispose();
621
+ throw error;
622
+ }
623
+ }
624
+
367
625
  // src/session/available-commands.ts
368
626
  function normalizeCommand(raw) {
369
627
  if (!raw || typeof raw !== "object")
@@ -611,15 +869,15 @@ class QuotaCache {
611
869
  var import_sdk4 = require("@agentclientprotocol/sdk");
612
870
 
613
871
  // src/runtimes/codex/quota.ts
614
- var import_node_fs2 = require("node:fs");
615
- var import_node_path2 = require("node:path");
872
+ var import_node_fs4 = require("node:fs");
873
+ var import_node_path4 = require("node:path");
616
874
  var import_node_child_process = require("node:child_process");
617
875
  var import_node_readline = __toESM(require("node:readline"), 1);
618
876
 
619
877
  // src/runtimes/codex/codex-auth-preflight.ts
620
- var import_node_fs = require("node:fs");
621
- var import_node_os = require("node:os");
622
- var import_node_path = require("node:path");
878
+ var import_node_fs3 = require("node:fs");
879
+ var import_node_os2 = require("node:os");
880
+ var import_node_path3 = require("node:path");
623
881
  function emptyAcpAuthPreflight() {
624
882
  return {
625
883
  codexHome: "",
@@ -636,12 +894,12 @@ function resolveCodexHome() {
636
894
  const fromEnv = process.env.CODEX_HOME?.trim();
637
895
  if (fromEnv)
638
896
  return fromEnv;
639
- return import_node_path.join(import_node_os.homedir(), ".codex");
897
+ return import_node_path3.join(import_node_os2.homedir(), ".codex");
640
898
  }
641
899
  function probeCodexAuth() {
642
900
  const codexHome = resolveCodexHome();
643
- const hasCodexHome = import_node_fs.existsSync(codexHome);
644
- const hasAuthFile = import_node_fs.existsSync(import_node_path.join(codexHome, "auth.json"));
901
+ const hasCodexHome = import_node_fs3.existsSync(codexHome);
902
+ const hasAuthFile = import_node_fs3.existsSync(import_node_path3.join(codexHome, "auth.json"));
645
903
  const hasApiKeyEnv = Boolean(process.env.CODEX_API_KEY?.trim() || process.env.OPENAI_API_KEY?.trim());
646
904
  return {
647
905
  codexHome,
@@ -691,7 +949,7 @@ async function queryCodexAppServer(timeoutMs = 1e4) {
691
949
  };
692
950
  timer = setTimeout(() => cleanup(null), timeoutMs);
693
951
  try {
694
- const cmd = process.platform === "win32" ? "codex" : import_node_fs2.existsSync("/mnt/c/Users") ? "codex.exe" : "codex";
952
+ const cmd = process.platform === "win32" ? "codex" : import_node_fs4.existsSync("/mnt/c/Users") ? "codex.exe" : "codex";
695
953
  proc = import_node_child_process.spawn(cmd, ["app-server"], {
696
954
  stdio: ["pipe", "pipe", "pipe"],
697
955
  shell: process.platform === "win32",
@@ -762,13 +1020,13 @@ function formatEpochTime(epochSeconds) {
762
1020
  }
763
1021
  async function probeCodexQuota(options) {
764
1022
  const codexHome = resolveCodexHome();
765
- const authPath = import_node_path2.join(codexHome, "auth.json");
1023
+ const authPath = import_node_path4.join(codexHome, "auth.json");
766
1024
  let accountEmail;
767
1025
  let accountPlan = "Codex Free / Local";
768
1026
  let isLoggedIn = false;
769
- if (import_node_fs2.existsSync(authPath)) {
1027
+ if (import_node_fs4.existsSync(authPath)) {
770
1028
  try {
771
- const authData = JSON.parse(import_node_fs2.readFileSync(authPath, "utf8"));
1029
+ const authData = JSON.parse(import_node_fs4.readFileSync(authPath, "utf8"));
772
1030
  if (authData.OPENAI_API_KEY) {
773
1031
  isLoggedIn = true;
774
1032
  accountPlan = "OpenAI API Key";
@@ -859,8 +1117,92 @@ async function probeCodexQuota(options) {
859
1117
  }
860
1118
 
861
1119
  // src/runtimes/codex/index.ts
862
- var import_promises2 = require("node:fs/promises");
863
- var import_node_path5 = require("node:path");
1120
+ var import_promises3 = require("node:fs/promises");
1121
+ var import_node_path7 = require("node:path");
1122
+ var import_node_os4 = require("node:os");
1123
+ var import_node_fs6 = require("node:fs");
1124
+ var import_node_crypto2 = require("node:crypto");
1125
+
1126
+ // src/resources/config-text.ts
1127
+ function mergeCodexConfigJson(input) {
1128
+ const block = (input.hostBlock ?? "").trim();
1129
+ if (!block)
1130
+ return { ok: false, reason: "empty-block" };
1131
+ const raw = (input.existingRaw ?? "").trim();
1132
+ if (!raw) {
1133
+ return { ok: true, json: JSON.stringify({ developer_instructions: block }), preservedUserInstructions: false };
1134
+ }
1135
+ let parsed;
1136
+ try {
1137
+ parsed = JSON.parse(raw);
1138
+ } catch {
1139
+ return { ok: false, reason: "invalid-json" };
1140
+ }
1141
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1142
+ return { ok: false, reason: "invalid-json" };
1143
+ }
1144
+ const merged = { ...parsed };
1145
+ const existing = merged["developer_instructions"];
1146
+ if (existing === undefined) {
1147
+ merged["developer_instructions"] = block;
1148
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: false };
1149
+ }
1150
+ if (typeof existing !== "string") {
1151
+ return { ok: false, reason: "conflicting-value" };
1152
+ }
1153
+ const kept = existing.trim();
1154
+ merged["developer_instructions"] = kept ? `${block}
1155
+
1156
+ ${kept}` : block;
1157
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: kept !== "" };
1158
+ }
1159
+ function mergeConfigTomlPreserving(input) {
1160
+ const block = (input.replacementBlock ?? "").trim() ? `${input.replacementBlock.trim()}
1161
+ ` : "";
1162
+ if (!input.existingText || !input.existingText.trim())
1163
+ return block;
1164
+ if (/"""|'''/.test(input.existingText) || /^\s*\[.*["'].*\]|^\s*\[\[|^\s*["'](?:model|model_provider)["']\s*=/m.test(input.existingText)) {
1165
+ throw new Error("复杂 TOML 配置需要结构化合并,已保留原文件");
1166
+ }
1167
+ const topKeys = new Set(input.managedTopKeys);
1168
+ const tables = new Set(input.managedTables);
1169
+ const out = [];
1170
+ let inManagedTable = false;
1171
+ let inAnyTable = false;
1172
+ for (const line of input.existingText.split(`
1173
+ `)) {
1174
+ const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(line)?.[1]?.trim() ?? null;
1175
+ if (header !== null) {
1176
+ inAnyTable = true;
1177
+ inManagedTable = tables.has(header);
1178
+ if (!inManagedTable)
1179
+ out.push(line);
1180
+ continue;
1181
+ }
1182
+ if (inManagedTable)
1183
+ continue;
1184
+ if (!inAnyTable) {
1185
+ const key = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1];
1186
+ if (key && topKeys.has(key))
1187
+ continue;
1188
+ }
1189
+ out.push(line);
1190
+ }
1191
+ const kept = out.join(`
1192
+ `).trim();
1193
+ if (!kept)
1194
+ return block;
1195
+ const tableAt = block.search(/^\s*\[/m);
1196
+ if (tableAt < 0)
1197
+ return block + `
1198
+ ` + kept + `
1199
+ `;
1200
+ return block.slice(0, tableAt).trimEnd() + `
1201
+
1202
+ ` + kept + `
1203
+
1204
+ ` + block.slice(tableAt);
1205
+ }
864
1206
 
865
1207
  // src/runtimes/codex/codex-provider-home.ts
866
1208
  var INKDOWN_PROVIDER_ID = "inkdown-custom";
@@ -892,13 +1234,13 @@ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
892
1234
  }
893
1235
 
894
1236
  // src/runtimes/codex/codex-provider.ts
895
- var import_promises = require("node:fs/promises");
896
- var import_node_fs3 = require("node:fs");
897
- var import_node_path4 = require("node:path");
1237
+ var import_promises2 = require("node:fs/promises");
1238
+ var import_node_fs5 = require("node:fs");
1239
+ var import_node_path6 = require("node:path");
898
1240
 
899
1241
  // src/client/acp-paths.ts
900
- var import_node_os2 = require("node:os");
901
- var import_node_path3 = require("node:path");
1242
+ var import_node_os3 = require("node:os");
1243
+ var import_node_path5 = require("node:path");
902
1244
  function getDefaultAgentDataDir() {
903
1245
  if (process.env.INKDOWN_DATA_DIR) {
904
1246
  return process.env.INKDOWN_DATA_DIR;
@@ -907,20 +1249,20 @@ function getDefaultAgentDataDir() {
907
1249
  return process.env.ACP_DATA_DIR;
908
1250
  }
909
1251
  if (process.platform === "win32") {
910
- return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path3.join(import_node_os2.homedir(), "AppData", "Local", "inkdown");
1252
+ return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path5.join(import_node_os3.homedir(), "AppData", "Local", "inkdown");
911
1253
  }
912
1254
  if (process.platform === "darwin") {
913
- return import_node_path3.join(import_node_os2.homedir(), "Library", "Application Support", "inkdown");
1255
+ return import_node_path5.join(import_node_os3.homedir(), "Library", "Application Support", "inkdown");
914
1256
  }
915
- return process.env.XDG_DATA_HOME || import_node_path3.join(import_node_os2.homedir(), ".local", "share", "inkdown");
1257
+ return process.env.XDG_DATA_HOME || import_node_path5.join(import_node_os3.homedir(), ".local", "share", "inkdown");
916
1258
  }
917
1259
 
918
1260
  // src/runtimes/codex/codex-provider.ts
919
1261
  function providerFilePath(dir) {
920
- return import_node_path4.join(dir, "agent", "provider.json");
1262
+ return import_node_path6.join(dir, "agent", "provider.json");
921
1263
  }
922
1264
  function providerHomePath(dir) {
923
- return import_node_path4.join(dir, "agent", "codex-home");
1265
+ return import_node_path6.join(dir, "agent", "codex-home");
924
1266
  }
925
1267
  function toStatus(stored) {
926
1268
  if (!stored)
@@ -946,10 +1288,10 @@ function validate(payload) {
946
1288
  }
947
1289
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
948
1290
  const file = providerFilePath(dir);
949
- if (!import_node_fs3.existsSync(file))
1291
+ if (!import_node_fs5.existsSync(file))
950
1292
  return null;
951
1293
  try {
952
- const raw = JSON.parse(await import_promises.readFile(file, "utf8"));
1294
+ const raw = JSON.parse(await import_promises2.readFile(file, "utf8"));
953
1295
  if (typeof raw.baseUrl !== "string" || typeof raw.model !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
954
1296
  return null;
955
1297
  }
@@ -975,7 +1317,7 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
975
1317
  const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
976
1318
  if (!apiKey)
977
1319
  return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
978
- await import_promises.mkdir(import_node_path4.join(dir, "agent"), { recursive: true });
1320
+ await import_promises2.mkdir(import_node_path6.join(dir, "agent"), { recursive: true });
979
1321
  const stored = {
980
1322
  name: payload.name?.trim() || undefined,
981
1323
  baseUrl: payload.baseUrl.trim(),
@@ -983,11 +1325,11 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
983
1325
  apiKey,
984
1326
  wireApi: payload.wireApi === "responses" ? "responses" : "chat"
985
1327
  };
986
- await import_promises.writeFile(file, JSON.stringify(stored, null, 2), "utf8");
1328
+ await import_promises2.writeFile(file, JSON.stringify(stored, null, 2), "utf8");
987
1329
  return ok(toStatus(stored));
988
1330
  }
989
1331
  async function clearAcpProvider(dir = getDefaultAgentDataDir()) {
990
- await import_promises.rm(providerFilePath(dir), { force: true });
1332
+ await import_promises2.rm(providerFilePath(dir), { force: true });
991
1333
  return ok(undefined);
992
1334
  }
993
1335
  function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
@@ -997,8 +1339,20 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
997
1339
  // src/runtimes/codex/index.ts
998
1340
  async function provisionCustomProviderCodexHome(provider, codexHome) {
999
1341
  try {
1000
- await import_promises2.mkdir(codexHome, { recursive: true });
1001
- await import_promises2.writeFile(import_node_path5.join(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
1342
+ await import_promises3.mkdir(codexHome, { recursive: true });
1343
+ let existing = null;
1344
+ try {
1345
+ existing = await import_promises3.readFile(import_node_path7.join(codexHome, "config.toml"), "utf8");
1346
+ } catch (error) {
1347
+ if (error.code !== "ENOENT")
1348
+ throw error;
1349
+ }
1350
+ await import_promises3.writeFile(import_node_path7.join(codexHome, "config.toml"), mergeConfigTomlPreserving({
1351
+ existingText: existing,
1352
+ managedTopKeys: ["model", "model_provider"],
1353
+ managedTables: [`model_providers.${INKDOWN_PROVIDER_ID}`],
1354
+ replacementBlock: buildCustomProviderConfigToml(provider)
1355
+ }), "utf8");
1002
1356
  return true;
1003
1357
  } catch (error) {
1004
1358
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -1008,6 +1362,78 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
1008
1362
  var codexAdapter = {
1009
1363
  id: "codex-acp",
1010
1364
  probeQuota: async (options) => probeCodexQuota(options),
1365
+ supportedBridgeVersions: ["2.2.2"],
1366
+ prepareAppResources: async ({ directory, workspaceRoot, env: overrideEnv }) => {
1367
+ const load = readAppResourcesDir(directory);
1368
+ const skillsFound = load.skills.map((s) => s.name);
1369
+ const rulesText = readAppRulesText(directory);
1370
+ if (!rulesText) {
1371
+ return {
1372
+ report: {
1373
+ rulesApplied: false,
1374
+ rulesChars: 0,
1375
+ profileDigest: null,
1376
+ skillsFound,
1377
+ reason: "rules-missing"
1378
+ }
1379
+ };
1380
+ }
1381
+ const env = { ...process.env, ...overrideEnv };
1382
+ const notApplied = (reason) => ({ report: {
1383
+ rulesApplied: false,
1384
+ rulesPrepared: false,
1385
+ skillsApplied: false,
1386
+ rulesChars: rulesText.length,
1387
+ profileDigest: digestAppResources(load),
1388
+ skillsFound,
1389
+ reason
1390
+ } });
1391
+ if (!load.directoryReadable)
1392
+ return notApplied("invalid-resource-directory");
1393
+ if (env.CODEX_PATH)
1394
+ return notApplied("execution-not-verified");
1395
+ const codexHome = env.CODEX_HOME || import_node_path7.join(import_node_os4.homedir(), ".codex");
1396
+ try {
1397
+ await import_promises3.readFile(import_node_path7.join(codexHome, "config.toml"));
1398
+ return notApplied("effective-config-not-verified");
1399
+ } catch (error) {
1400
+ if (error.code !== "ENOENT")
1401
+ return notApplied("effective-config-not-verified");
1402
+ }
1403
+ for (let dir = workspaceRoot;dir; ) {
1404
+ if (import_node_fs6.existsSync(import_node_path7.join(dir, ".codex", "config.toml")))
1405
+ return notApplied("effective-config-not-verified");
1406
+ if (import_node_fs6.existsSync(import_node_path7.join(dir, ".git")))
1407
+ break;
1408
+ const parent = import_node_path7.dirname(dir);
1409
+ if (parent === dir)
1410
+ break;
1411
+ dir = parent;
1412
+ }
1413
+ const merged = mergeCodexConfigJson({ existingRaw: env["CODEX_CONFIG"], hostBlock: rulesText });
1414
+ if (!merged.ok) {
1415
+ return {
1416
+ report: {
1417
+ rulesApplied: false,
1418
+ rulesChars: rulesText.length,
1419
+ profileDigest: digestAppResources(load),
1420
+ skillsFound,
1421
+ reason: merged.reason === "invalid-json" ? "invalid-codex-config" : "conflicting-codex-config"
1422
+ }
1423
+ };
1424
+ }
1425
+ return {
1426
+ env: { CODEX_CONFIG: merged.json },
1427
+ report: {
1428
+ rulesApplied: false,
1429
+ rulesPrepared: true,
1430
+ skillsApplied: false,
1431
+ rulesChars: rulesText.length,
1432
+ profileDigest: import_node_crypto2.createHash("sha256").update(JSON.stringify([digestAppResources(load), codexHome, workspaceRoot, merged.json])).digest("hex"),
1433
+ skillsFound
1434
+ }
1435
+ };
1436
+ },
1011
1437
  probeAuth: () => {
1012
1438
  return probeCodexAuth();
1013
1439
  },
@@ -1024,11 +1450,84 @@ var codexAdapter = {
1024
1450
  }
1025
1451
  };
1026
1452
 
1027
- // src/runtimes/claude/quota.ts
1028
- var import_node_fs4 = require("node:fs");
1029
- var import_node_os3 = require("node:os");
1030
- var import_node_path6 = require("node:path");
1453
+ // src/resources/runtime-bindings.ts
1454
+ var import_node_path8 = require("node:path");
1031
1455
  var import_node_child_process2 = require("node:child_process");
1456
+ var import_node_util = require("node:util");
1457
+ var APP_RESOURCE_CAPABILITIES = {
1458
+ "codex-acp": { entry: "CODEX_CONFIG", strategy: "native-overlay", configHome: "CODEX_HOME" },
1459
+ opencode: { entry: "OPENCODE_CONFIG_CONTENT", strategy: "native-overlay", configHome: "OPENCODE_CONFIG_DIR" },
1460
+ "opencode-v2": { entry: null, strategy: "compatibility", configHome: null },
1461
+ claude: { entry: "_meta.systemPrompt + _meta.claudeCode.options.plugins", strategy: "native-session", configHome: "CLAUDE_CONFIG_DIR" },
1462
+ gemini: { entry: null, strategy: "compatibility", configHome: "GEMINI_CLI_HOME" },
1463
+ copilot: { entry: null, strategy: "compatibility", configHome: "COPILOT_HOME", candidateEntry: "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" },
1464
+ "cursor-cli": { entry: null, strategy: "compatibility", configHome: "CURSOR_CONFIG_DIR" },
1465
+ agy: { entry: "_meta.appResources.directory", strategy: "native-session", configHome: null },
1466
+ deepseek: { entry: null, strategy: "compatibility", configHome: null }
1467
+ };
1468
+ function prepareCompatibilityResources(directory, reason) {
1469
+ const load = readAppResourcesDir(directory);
1470
+ return { report: {
1471
+ rulesApplied: false,
1472
+ rulesPrepared: false,
1473
+ skillsApplied: false,
1474
+ rulesChars: load.rules?.chars ?? 0,
1475
+ profileDigest: digestAppResources(load),
1476
+ skillsFound: load.skills.map((s) => s.name),
1477
+ reason
1478
+ } };
1479
+ }
1480
+ function mergeOpenCodeAppConfig(raw, directory) {
1481
+ const value = raw?.trim() ? JSON.parse(raw) : {};
1482
+ if (!value || typeof value !== "object" || Array.isArray(value))
1483
+ throw new Error("invalid-opencode-config");
1484
+ const config = value;
1485
+ if (config.instructions !== undefined && (!Array.isArray(config.instructions) || config.instructions.some((v) => typeof v !== "string")))
1486
+ throw new Error("invalid-opencode-instructions");
1487
+ if (config.skills !== undefined && (!config.skills || typeof config.skills !== "object" || Array.isArray(config.skills)))
1488
+ throw new Error("invalid-opencode-skills");
1489
+ const skills = config.skills ?? {};
1490
+ if (skills.paths !== undefined && (!Array.isArray(skills.paths) || skills.paths.some((v) => typeof v !== "string")))
1491
+ throw new Error("invalid-opencode-skill-paths");
1492
+ return JSON.stringify({
1493
+ ...config,
1494
+ instructions: [...new Set([...config.instructions ?? [], import_node_path8.join(directory, "AGENTS.md")])],
1495
+ skills: { ...skills, paths: [...new Set([...skills.paths ?? [], import_node_path8.join(directory, "skills")])] }
1496
+ });
1497
+ }
1498
+ async function prepareOpenCodeResources(input) {
1499
+ const prep = prepareCompatibilityResources(input.directory, "native-entry-not-verified");
1500
+ if (!input.command || !readAppRulesText(input.directory))
1501
+ return prep;
1502
+ try {
1503
+ const { stdout } = await import_node_util.promisify(import_node_child_process2.execFile)(input.command, ["--version"], { env: input.env, timeout: 8000, windowsHide: true });
1504
+ if (stdout.trim() !== "1.18.35")
1505
+ return prep;
1506
+ const json = mergeOpenCodeAppConfig(input.env?.OPENCODE_CONFIG_CONTENT, input.directory);
1507
+ return { env: { OPENCODE_CONFIG_CONTENT: json }, report: { ...prep.report, rulesPrepared: true, reason: undefined } };
1508
+ } catch {
1509
+ return { ...prep, report: { ...prep.report, reason: "native-config-prepare-failed" } };
1510
+ }
1511
+ }
1512
+ function prepareClaudeResources(directory) {
1513
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
1514
+ return { ...prep, report: { ...prep.report, rulesPrepared: !!readAppRulesText(directory) } };
1515
+ }
1516
+ function claudeResourceSessionMeta(directory) {
1517
+ const text = readAppRulesText(directory);
1518
+ if (!text)
1519
+ return;
1520
+ return {
1521
+ systemPrompt: { type: "preset", preset: "claude_code", append: text },
1522
+ claudeCode: { options: { plugins: [{ type: "local", path: directory }] } }
1523
+ };
1524
+ }
1525
+
1526
+ // src/runtimes/claude/quota.ts
1527
+ var import_node_fs7 = require("node:fs");
1528
+ var import_node_os5 = require("node:os");
1529
+ var import_node_path9 = require("node:path");
1530
+ var import_node_child_process3 = require("node:child_process");
1032
1531
  var cachedClaudeAuth = null;
1033
1532
  async function queryClaudeAuthStatus(timeoutMs = 1200) {
1034
1533
  if (cachedClaudeAuth && Date.now() - cachedClaudeAuth.time < 30000) {
@@ -1036,7 +1535,7 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
1036
1535
  }
1037
1536
  return new Promise((resolve) => {
1038
1537
  try {
1039
- import_node_child_process2.execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
1538
+ import_node_child_process3.execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
1040
1539
  if (!stdout)
1041
1540
  return resolve(null);
1042
1541
  try {
@@ -1054,15 +1553,15 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
1054
1553
  }
1055
1554
  async function probeClaudeQuota(options) {
1056
1555
  const claudeHome = resolveClaudeHome();
1057
- const claudeJsonPath = import_node_path6.join(import_node_os3.homedir(), ".claude.json");
1058
- const credsPath = import_node_path6.join(claudeHome, ".credentials.json");
1556
+ const claudeJsonPath = import_node_path9.join(import_node_os5.homedir(), ".claude.json");
1557
+ const credsPath = import_node_path9.join(claudeHome, ".credentials.json");
1059
1558
  let isLoggedIn = false;
1060
1559
  let isBanned = false;
1061
1560
  let accountEmail;
1062
1561
  let plan = "Claude Free / Default";
1063
- if (import_node_fs4.existsSync(claudeJsonPath)) {
1562
+ if (import_node_fs7.existsSync(claudeJsonPath)) {
1064
1563
  try {
1065
- const data = JSON.parse(import_node_fs4.readFileSync(claudeJsonPath, "utf8"));
1564
+ const data = JSON.parse(import_node_fs7.readFileSync(claudeJsonPath, "utf8"));
1066
1565
  if (data.oauthAccount) {
1067
1566
  isLoggedIn = true;
1068
1567
  accountEmail = data.oauthAccount.emailAddress;
@@ -1073,9 +1572,9 @@ async function probeClaudeQuota(options) {
1073
1572
  }
1074
1573
  } catch {}
1075
1574
  }
1076
- if (import_node_fs4.existsSync(credsPath)) {
1575
+ if (import_node_fs7.existsSync(credsPath)) {
1077
1576
  try {
1078
- const creds = JSON.parse(import_node_fs4.readFileSync(credsPath, "utf8"));
1577
+ const creds = JSON.parse(import_node_fs7.readFileSync(credsPath, "utf8"));
1079
1578
  if (creds.accessToken || creds.sessionKey)
1080
1579
  isLoggedIn = true;
1081
1580
  } catch {}
@@ -1127,19 +1626,19 @@ async function probeClaudeQuota(options) {
1127
1626
  }
1128
1627
 
1129
1628
  // src/runtimes/claude/index.ts
1130
- var import_node_fs5 = require("node:fs");
1131
- var import_node_os4 = require("node:os");
1132
- var import_node_path7 = require("node:path");
1629
+ var import_node_fs8 = require("node:fs");
1630
+ var import_node_os6 = require("node:os");
1631
+ var import_node_path10 = require("node:path");
1133
1632
  function resolveClaudeHome() {
1134
1633
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
1135
1634
  if (fromEnv)
1136
1635
  return fromEnv;
1137
- return import_node_path7.join(import_node_os4.homedir(), ".claude");
1636
+ return import_node_path10.join(import_node_os6.homedir(), ".claude");
1138
1637
  }
1139
1638
  function probeClaudeAuth() {
1140
1639
  const claudeHome = resolveClaudeHome();
1141
- const hasCodexHome = import_node_fs5.existsSync(claudeHome);
1142
- const hasAuthFile = import_node_fs5.existsSync(import_node_path7.join(import_node_os4.homedir(), ".claude.json")) || import_node_fs5.existsSync(import_node_path7.join(claudeHome, ".credentials.json"));
1640
+ const hasCodexHome = import_node_fs8.existsSync(claudeHome);
1641
+ const hasAuthFile = import_node_fs8.existsSync(import_node_path10.join(import_node_os6.homedir(), ".claude.json")) || import_node_fs8.existsSync(import_node_path10.join(claudeHome, ".credentials.json"));
1143
1642
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
1144
1643
  return {
1145
1644
  codexHome: claudeHome,
@@ -1151,6 +1650,9 @@ function probeClaudeAuth() {
1151
1650
  }
1152
1651
  var claudeAdapter = {
1153
1652
  id: "claude",
1653
+ supportedBridgeVersions: ["0.91.0"],
1654
+ prepareAppResources: async ({ directory }) => prepareClaudeResources(directory),
1655
+ appResourceSessionMeta: claudeResourceSessionMeta,
1154
1656
  probeAuth: () => probeClaudeAuth(),
1155
1657
  probeQuota: async (options) => probeClaudeQuota(options),
1156
1658
  orderAuthMethods: (methods) => methods,
@@ -1158,16 +1660,16 @@ var claudeAdapter = {
1158
1660
  };
1159
1661
 
1160
1662
  // src/runtimes/gemini/index.ts
1161
- var import_node_fs6 = require("node:fs");
1162
- var import_node_os5 = require("node:os");
1163
- var import_node_path8 = require("node:path");
1663
+ var import_node_fs9 = require("node:fs");
1664
+ var import_node_os7 = require("node:os");
1665
+ var import_node_path11 = require("node:path");
1164
1666
  function resolveGeminiHome() {
1165
- return import_node_path8.join(import_node_os5.homedir(), ".gemini");
1667
+ return import_node_path11.join(import_node_os7.homedir(), ".gemini");
1166
1668
  }
1167
1669
  function probeGeminiAuth() {
1168
1670
  const geminiHome = resolveGeminiHome();
1169
- const hasCodexHome = import_node_fs6.existsSync(geminiHome);
1170
- const hasAuthFile = import_node_fs6.existsSync(import_node_path8.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
1671
+ const hasCodexHome = import_node_fs9.existsSync(geminiHome);
1672
+ const hasAuthFile = import_node_fs9.existsSync(import_node_path11.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
1171
1673
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
1172
1674
  return {
1173
1675
  codexHome: geminiHome,
@@ -1179,24 +1681,25 @@ function probeGeminiAuth() {
1179
1681
  }
1180
1682
  var geminiAdapter = {
1181
1683
  id: "gemini",
1684
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-would-isolate-auth"),
1182
1685
  probeAuth: () => probeGeminiAuth(),
1183
1686
  orderAuthMethods: (methods) => methods,
1184
1687
  canSkipInteractiveAuth: () => false
1185
1688
  };
1186
1689
 
1187
1690
  // src/runtimes/copilot/index.ts
1188
- var import_node_fs7 = require("node:fs");
1189
- var import_node_os6 = require("node:os");
1190
- var import_node_path9 = require("node:path");
1691
+ var import_node_fs10 = require("node:fs");
1692
+ var import_node_os8 = require("node:os");
1693
+ var import_node_path12 = require("node:path");
1191
1694
  function resolveCopilotHome() {
1192
1695
  const fromEnv = process.env.COPILOT_HOME?.trim();
1193
1696
  if (fromEnv)
1194
1697
  return fromEnv;
1195
- return import_node_path9.join(import_node_os6.homedir(), ".copilot");
1698
+ return import_node_path12.join(import_node_os8.homedir(), ".copilot");
1196
1699
  }
1197
1700
  function hasCopilotLogin(home) {
1198
1701
  try {
1199
- const raw = import_node_fs7.readFileSync(import_node_path9.join(home, "config.json"), "utf8");
1702
+ const raw = import_node_fs10.readFileSync(import_node_path12.join(home, "config.json"), "utf8");
1200
1703
  const parsed = JSON.parse(raw);
1201
1704
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
1202
1705
  } catch {
@@ -1205,7 +1708,7 @@ function hasCopilotLogin(home) {
1205
1708
  }
1206
1709
  function probeCopilotAuth() {
1207
1710
  const copilotHome = resolveCopilotHome();
1208
- const hasCodexHome = import_node_fs7.existsSync(copilotHome);
1711
+ const hasCodexHome = import_node_fs10.existsSync(copilotHome);
1209
1712
  const hasAuthFile = hasCopilotLogin(copilotHome);
1210
1713
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
1211
1714
  return {
@@ -1218,20 +1721,21 @@ function probeCopilotAuth() {
1218
1721
  }
1219
1722
  var copilotAdapter = {
1220
1723
  id: "copilot",
1724
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-entry-not-verified"),
1221
1725
  probeAuth: () => probeCopilotAuth(),
1222
1726
  orderAuthMethods: (methods) => methods,
1223
1727
  canSkipInteractiveAuth: () => false
1224
1728
  };
1225
1729
 
1226
1730
  // src/runtimes/opencode/quota.ts
1227
- var import_node_fs8 = require("node:fs");
1228
- var import_node_child_process3 = require("node:child_process");
1731
+ var import_node_fs11 = require("node:fs");
1732
+ var import_node_child_process4 = require("node:child_process");
1229
1733
  var os = __toESM(require("node:os"), 1);
1230
1734
  var path = __toESM(require("node:path"), 1);
1231
1735
  function resolveOpencodeAuthPath() {
1232
1736
  const candidates = resolveOpencodeAuthCandidates();
1233
1737
  for (const c of candidates) {
1234
- if (import_node_fs8.existsSync(c))
1738
+ if (import_node_fs11.existsSync(c))
1235
1739
  return c;
1236
1740
  }
1237
1741
  return candidates[0] ?? null;
@@ -1243,7 +1747,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
1243
1747
  }
1244
1748
  return new Promise((resolve) => {
1245
1749
  try {
1246
- import_node_child_process3.execFile("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1750
+ import_node_child_process4.execFile("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1247
1751
  if (!stdout)
1248
1752
  return resolve(null);
1249
1753
  try {
@@ -1262,7 +1766,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
1262
1766
  async function queryOpencodeAuthList(timeoutMs = 1200) {
1263
1767
  return new Promise((resolve) => {
1264
1768
  try {
1265
- import_node_child_process3.execFile("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1769
+ import_node_child_process4.execFile("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1266
1770
  if (!stdout)
1267
1771
  return resolve([]);
1268
1772
  const lines = stdout.split(`
@@ -1282,7 +1786,7 @@ function readLocalOpencodeCredentials() {
1282
1786
  path.join(home, ".config", "opencode", "opencode.db")
1283
1787
  ].filter(Boolean);
1284
1788
  for (const dbPath of dbPaths) {
1285
- if (!import_node_fs8.existsSync(dbPath))
1789
+ if (!import_node_fs11.existsSync(dbPath))
1286
1790
  continue;
1287
1791
  try {
1288
1792
  let rows = [];
@@ -1311,7 +1815,7 @@ function readLocalOpencodeCredentials() {
1311
1815
  }
1312
1816
  } catch {
1313
1817
  try {
1314
- const buf = import_node_fs8.readFileSync(dbPath, "utf8");
1818
+ const buf = import_node_fs11.readFileSync(dbPath, "utf8");
1315
1819
  const emailMatch = buf.match(/"email"\s*:\s*"([^"]+)"/);
1316
1820
  const tokenMatch = buf.match(/"access"\s*:\s*"(st_[a-zA-Z0-9_\\-]+)"/);
1317
1821
  const orgMatch = buf.match(/"orgID"\s*:\s*"(wrk_[a-zA-Z0-9_\\-]+)"/);
@@ -1435,9 +1939,9 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1435
1939
  let accountEmail = dbCreds.email;
1436
1940
  let accountName = dbCreds.name;
1437
1941
  let plan = "OpenCode Community";
1438
- if (authPath && import_node_fs8.existsSync(authPath)) {
1942
+ if (authPath && import_node_fs11.existsSync(authPath)) {
1439
1943
  try {
1440
- const data = JSON.parse(import_node_fs8.readFileSync(authPath, "utf8"));
1944
+ const data = JSON.parse(import_node_fs11.readFileSync(authPath, "utf8"));
1441
1945
  if (data && typeof data === "object") {
1442
1946
  const keys = Object.keys(data);
1443
1947
  if (keys.length > 0) {
@@ -1497,16 +2001,16 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1497
2001
  }
1498
2002
 
1499
2003
  // src/runtimes/opencode/index.ts
1500
- var import_node_fs9 = require("node:fs");
1501
- var import_node_os7 = require("node:os");
1502
- var import_node_path10 = require("node:path");
2004
+ var import_node_fs12 = require("node:fs");
2005
+ var import_node_os9 = require("node:os");
2006
+ var import_node_path13 = require("node:path");
1503
2007
  function pickEnv(env, key) {
1504
2008
  return env?.[key]?.trim() ?? "";
1505
2009
  }
1506
2010
  function resolveOpencodeAuthCandidates(overrides) {
1507
2011
  const platform = overrides?.platform ?? process.platform;
1508
2012
  const env = overrides?.env ?? process.env;
1509
- const home = overrides?.home ?? import_node_os7.homedir();
2013
+ const home = overrides?.home ?? import_node_os9.homedir();
1510
2014
  const seen = new Set;
1511
2015
  const out = [];
1512
2016
  const push = (p) => {
@@ -1517,27 +2021,27 @@ function resolveOpencodeAuthCandidates(overrides) {
1517
2021
  };
1518
2022
  const xdg = pickEnv(env, "XDG_DATA_HOME");
1519
2023
  if (xdg)
1520
- push(import_node_path10.join(xdg, "opencode", "auth.json"));
2024
+ push(import_node_path13.join(xdg, "opencode", "auth.json"));
1521
2025
  if (platform === "win32") {
1522
- const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path10.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
2026
+ const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path13.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
1523
2027
  if (localAppData)
1524
- push(import_node_path10.join(localAppData, "opencode", "auth.json"));
2028
+ push(import_node_path13.join(localAppData, "opencode", "auth.json"));
1525
2029
  const userProfile = pickEnv(env, "USERPROFILE") || home;
1526
2030
  if (userProfile)
1527
- push(import_node_path10.join(userProfile, ".local", "share", "opencode", "auth.json"));
2031
+ push(import_node_path13.join(userProfile, ".local", "share", "opencode", "auth.json"));
1528
2032
  } else if (home) {
1529
- push(import_node_path10.join(home, ".local", "share", "opencode", "auth.json"));
2033
+ push(import_node_path13.join(home, ".local", "share", "opencode", "auth.json"));
1530
2034
  }
1531
2035
  return out;
1532
2036
  }
1533
2037
  function resolveOpencodeAuthFile() {
1534
- return resolveOpencodeAuthCandidates()[0] ?? import_node_path10.join(import_node_os7.homedir(), ".local", "share", "opencode", "auth.json");
2038
+ return resolveOpencodeAuthCandidates()[0] ?? import_node_path13.join(import_node_os9.homedir(), ".local", "share", "opencode", "auth.json");
1535
2039
  }
1536
2040
  function isValidOpencodeAuthFile(authFile) {
1537
2041
  try {
1538
- if (!authFile || !import_node_fs9.existsSync(authFile))
2042
+ if (!authFile || !import_node_fs12.existsSync(authFile))
1539
2043
  return false;
1540
- const raw = import_node_fs9.readFileSync(authFile, "utf8").trim();
2044
+ const raw = import_node_fs12.readFileSync(authFile, "utf8").trim();
1541
2045
  if (!raw)
1542
2046
  return false;
1543
2047
  const parsed = JSON.parse(raw);
@@ -1555,7 +2059,7 @@ function probeOpencodeAuth(overrides) {
1555
2059
  for (const candidate of candidates) {
1556
2060
  let exists = false;
1557
2061
  try {
1558
- exists = import_node_fs9.existsSync(candidate);
2062
+ exists = import_node_fs12.existsSync(candidate);
1559
2063
  } catch {
1560
2064
  exists = false;
1561
2065
  }
@@ -1568,10 +2072,10 @@ function probeOpencodeAuth(overrides) {
1568
2072
  validFile = candidate;
1569
2073
  }
1570
2074
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
1571
- const authDir = import_node_path10.dirname(authFile);
2075
+ const authDir = import_node_path13.dirname(authFile);
1572
2076
  let hasCodexHome = false;
1573
2077
  try {
1574
- hasCodexHome = import_node_fs9.existsSync(authDir);
2078
+ hasCodexHome = import_node_fs12.existsSync(authDir);
1575
2079
  } catch {
1576
2080
  hasCodexHome = false;
1577
2081
  }
@@ -1586,6 +2090,8 @@ function probeOpencodeAuth(overrides) {
1586
2090
  }
1587
2091
  var opencodeAdapter = {
1588
2092
  id: "opencode",
2093
+ supportedBridgeVersions: ["1.18.35"],
2094
+ prepareAppResources: prepareOpenCodeResources,
1589
2095
  probeAuth: () => probeOpencodeAuth(),
1590
2096
  probeQuota: async () => probeOpencodeQuota(),
1591
2097
  orderAuthMethods: (methods) => methods,
@@ -1596,6 +2102,7 @@ var opencodeAdapter = {
1596
2102
  // src/runtimes/opencode-v2/index.ts
1597
2103
  var opencodeV2Adapter = {
1598
2104
  id: "opencode-v2",
2105
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
1599
2106
  probeAuth: () => probeOpencodeAuth(),
1600
2107
  orderAuthMethods: (methods) => methods,
1601
2108
  canSkipInteractiveAuth: () => false,
@@ -1626,28 +2133,28 @@ async function probeCursorQuota() {
1626
2133
  }
1627
2134
 
1628
2135
  // src/runtimes/cursor/index.ts
1629
- var import_node_child_process4 = require("node:child_process");
1630
- var import_node_fs10 = require("node:fs");
1631
- var import_node_os8 = require("node:os");
1632
- var import_node_path11 = require("node:path");
2136
+ var import_node_child_process5 = require("node:child_process");
2137
+ var import_node_fs13 = require("node:fs");
2138
+ var import_node_os10 = require("node:os");
2139
+ var import_node_path14 = require("node:path");
1633
2140
  function cursorLocalAppData(env) {
1634
2141
  const local = env.LOCALAPPDATA?.trim();
1635
2142
  if (local)
1636
2143
  return local;
1637
2144
  const profile = env.USERPROFILE?.trim();
1638
- return profile ? import_node_path11.join(profile, "AppData", "Local") : "";
2145
+ return profile ? import_node_path14.join(profile, "AppData", "Local") : "";
1639
2146
  }
1640
2147
  function isOnPath(command, env, platform) {
1641
2148
  const pathValue = env.PATH ?? env.Path ?? "";
1642
2149
  if (!pathValue.trim())
1643
2150
  return false;
1644
- const sep = platform === "win32" ? ";" : import_node_path11.delimiter;
2151
+ const sep = platform === "win32" ? ";" : import_node_path14.delimiter;
1645
2152
  for (const dir of pathValue.split(sep)) {
1646
2153
  const trimmed = dir.trim().replace(/^"|"$/g, "");
1647
2154
  if (!trimmed)
1648
2155
  continue;
1649
2156
  try {
1650
- if (import_node_fs10.existsSync(import_node_path11.join(trimmed, command)))
2157
+ if (import_node_fs13.existsSync(import_node_path14.join(trimmed, command)))
1651
2158
  return true;
1652
2159
  } catch {}
1653
2160
  }
@@ -1656,24 +2163,24 @@ function isOnPath(command, env, platform) {
1656
2163
  function resolveDirectCursorCommand(platform, env, home) {
1657
2164
  if (platform === "win32") {
1658
2165
  const localAppData = cursorLocalAppData(env);
1659
- return localAppData ? import_node_path11.join(localAppData, "cursor-agent", "agent.cmd") : "";
2166
+ return localAppData ? import_node_path14.join(localAppData, "cursor-agent", "agent.cmd") : "";
1660
2167
  }
1661
- return home ? import_node_path11.join(home, ".local", "bin", "agent") : "";
2168
+ return home ? import_node_path14.join(home, ".local", "bin", "agent") : "";
1662
2169
  }
1663
2170
  function resolveCursorCommand(overrides) {
1664
2171
  const args = ["acp"];
1665
2172
  const platform = overrides?.platform ?? process.platform;
1666
2173
  const env = overrides?.env ?? process.env;
1667
- const home = overrides?.home ?? import_node_os8.homedir();
2174
+ const home = overrides?.home ?? import_node_os10.homedir();
1668
2175
  if (platform === "win32") {
1669
2176
  const directCmd = resolveDirectCursorCommand(platform, env, home);
1670
- if (directCmd && import_node_fs10.existsSync(directCmd)) {
2177
+ if (directCmd && import_node_fs13.existsSync(directCmd)) {
1671
2178
  return { command: directCmd, args };
1672
2179
  }
1673
2180
  return { command: "agent.cmd", args };
1674
2181
  }
1675
2182
  const directBin = resolveDirectCursorCommand(platform, env, home);
1676
- if (directBin && import_node_fs10.existsSync(directBin)) {
2183
+ if (directBin && import_node_fs13.existsSync(directBin)) {
1677
2184
  return { command: directBin, args };
1678
2185
  }
1679
2186
  return { command: "agent", args };
@@ -1682,11 +2189,11 @@ function resolveCursorSpawnCommand(overrides) {
1682
2189
  const args = ["acp"];
1683
2190
  const platform = overrides?.platform ?? process.platform;
1684
2191
  const env = overrides?.env ?? process.env;
1685
- const home = overrides?.home ?? import_node_os8.homedir();
2192
+ const home = overrides?.home ?? import_node_os10.homedir();
1686
2193
  const binary = platform === "win32" ? "agent.cmd" : "agent";
1687
2194
  const direct = resolveDirectCursorCommand(platform, env, home);
1688
2195
  try {
1689
- if (direct && import_node_fs10.existsSync(direct))
2196
+ if (direct && import_node_fs13.existsSync(direct))
1690
2197
  return { command: direct, args };
1691
2198
  } catch {}
1692
2199
  if (isOnPath(binary, env, platform))
@@ -1708,12 +2215,12 @@ function cursorRoamingAppData(env, home) {
1708
2215
  if (roaming)
1709
2216
  return roaming;
1710
2217
  const profile = pickEnv2(env, "USERPROFILE") || home;
1711
- return profile ? import_node_path11.join(profile, "AppData", "Roaming") : "";
2218
+ return profile ? import_node_path14.join(profile, "AppData", "Roaming") : "";
1712
2219
  }
1713
2220
  function resolveCursorAuthCandidates(overrides) {
1714
2221
  const platform = overrides?.platform ?? process.platform;
1715
2222
  const env = overrides?.env ?? process.env;
1716
- const home = overrides?.home ?? import_node_os8.homedir();
2223
+ const home = overrides?.home ?? import_node_os10.homedir();
1717
2224
  const seen = new Set;
1718
2225
  const out = [];
1719
2226
  const push = (p) => {
@@ -1724,16 +2231,16 @@ function resolveCursorAuthCandidates(overrides) {
1724
2231
  };
1725
2232
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
1726
2233
  if (xdg)
1727
- push(import_node_path11.join(xdg, "cursor", "auth.json"));
2234
+ push(import_node_path14.join(xdg, "cursor", "auth.json"));
1728
2235
  if (platform === "win32") {
1729
2236
  const profile = pickEnv2(env, "USERPROFILE") || home;
1730
2237
  if (profile)
1731
- push(import_node_path11.join(profile, ".config", "cursor", "auth.json"));
2238
+ push(import_node_path14.join(profile, ".config", "cursor", "auth.json"));
1732
2239
  const roaming = cursorRoamingAppData(env, home);
1733
2240
  if (roaming)
1734
- push(import_node_path11.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
2241
+ push(import_node_path14.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
1735
2242
  } else if (home) {
1736
- push(import_node_path11.join(home, ".config", "cursor", "auth.json"));
2243
+ push(import_node_path14.join(home, ".config", "cursor", "auth.json"));
1737
2244
  }
1738
2245
  return out;
1739
2246
  }
@@ -1744,9 +2251,9 @@ function isValidCursorAuthFile(authFile) {
1744
2251
  try {
1745
2252
  if (!authFile || isStorageHintPath(authFile))
1746
2253
  return false;
1747
- if (!import_node_fs10.existsSync(authFile))
2254
+ if (!import_node_fs13.existsSync(authFile))
1748
2255
  return false;
1749
- const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
2256
+ const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
1750
2257
  if (!raw)
1751
2258
  return false;
1752
2259
  const parsed = JSON.parse(raw);
@@ -1764,9 +2271,9 @@ function isHintCursorStorageFile(authFile) {
1764
2271
  try {
1765
2272
  if (!authFile || !isStorageHintPath(authFile))
1766
2273
  return false;
1767
- if (!import_node_fs10.existsSync(authFile))
2274
+ if (!import_node_fs13.existsSync(authFile))
1768
2275
  return false;
1769
- const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
2276
+ const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
1770
2277
  if (!raw)
1771
2278
  return false;
1772
2279
  const parsed = JSON.parse(raw);
@@ -1782,7 +2289,7 @@ function isValidCursorCandidate(authFile) {
1782
2289
  }
1783
2290
  function probeCursorAuth(overrides) {
1784
2291
  const env = overrides?.env ?? process.env;
1785
- const home = overrides?.home ?? import_node_os8.homedir();
2292
+ const home = overrides?.home ?? import_node_os10.homedir();
1786
2293
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
1787
2294
  const candidates = resolveCursorAuthCandidates(overrides);
1788
2295
  let firstExisting = null;
@@ -1790,7 +2297,7 @@ function probeCursorAuth(overrides) {
1790
2297
  for (const candidate of candidates) {
1791
2298
  let exists = false;
1792
2299
  try {
1793
- exists = import_node_fs10.existsSync(candidate);
2300
+ exists = import_node_fs13.existsSync(candidate);
1794
2301
  } catch {
1795
2302
  exists = false;
1796
2303
  }
@@ -1802,12 +2309,12 @@ function probeCursorAuth(overrides) {
1802
2309
  if (isValidCursorCandidate(candidate))
1803
2310
  validFile = candidate;
1804
2311
  }
1805
- const fallback = home ? import_node_path11.join(home, ".config", "cursor", "auth.json") : "";
2312
+ const fallback = home ? import_node_path14.join(home, ".config", "cursor", "auth.json") : "";
1806
2313
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
1807
- const authDir = authFile ? import_node_path11.dirname(authFile) : "";
2314
+ const authDir = authFile ? import_node_path14.dirname(authFile) : "";
1808
2315
  let hasCodexHome = false;
1809
2316
  try {
1810
- hasCodexHome = authDir ? import_node_fs10.existsSync(authDir) : false;
2317
+ hasCodexHome = authDir ? import_node_fs13.existsSync(authDir) : false;
1811
2318
  } catch {
1812
2319
  hasCodexHome = false;
1813
2320
  }
@@ -1821,6 +2328,7 @@ function probeCursorAuth(overrides) {
1821
2328
  }
1822
2329
  var cursorAdapter = {
1823
2330
  id: "cursor-cli",
2331
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-does-not-guarantee-rules"),
1824
2332
  probeAuth: () => probeCursorAuth(),
1825
2333
  probeQuota: async () => probeCursorQuota(),
1826
2334
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
@@ -1871,7 +2379,7 @@ function getCursorCatalogIds(execFile, overrides) {
1871
2379
  }
1872
2380
  try {
1873
2381
  const shell = command.toLowerCase().endsWith(".cmd");
1874
- const result = import_node_child_process4.spawnSync(command, ["--list-models"], {
2382
+ const result = import_node_child_process5.spawnSync(command, ["--list-models"], {
1875
2383
  encoding: "utf8",
1876
2384
  timeout: 6000,
1877
2385
  windowsHide: true,
@@ -1934,6 +2442,7 @@ function probeDeepseekAuth() {
1934
2442
  }
1935
2443
  var deepseekAdapter = {
1936
2444
  id: "deepseek",
2445
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
1937
2446
  probeAuth: () => probeDeepseekAuth(),
1938
2447
  resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
1939
2448
  resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
@@ -1942,13 +2451,13 @@ var deepseekAdapter = {
1942
2451
  };
1943
2452
 
1944
2453
  // src/runtimes/agy/quota.ts
1945
- var import_node_fs11 = require("node:fs");
1946
- var import_node_path12 = require("node:path");
1947
- var import_node_child_process5 = require("node:child_process");
2454
+ var import_node_fs14 = require("node:fs");
2455
+ var import_node_path15 = require("node:path");
2456
+ var import_node_child_process6 = require("node:child_process");
1948
2457
  var os2 = __toESM(require("node:os"), 1);
1949
2458
  function resolveGeminiHome2() {
1950
2459
  const home = process.env.USERPROFILE || process.env.HOME || "";
1951
- return import_node_path12.join(home, ".gemini");
2460
+ return import_node_path15.join(home, ".gemini");
1952
2461
  }
1953
2462
  function resolveAntigravityAccount() {
1954
2463
  if (process.env.GOOGLE_ACCOUNT?.trim()) {
@@ -1961,14 +2470,14 @@ function resolveAntigravityAccount() {
1961
2470
  }
1962
2471
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
1963
2472
  const candidates = [
1964
- process.env.APPDATA ? import_node_path12.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
1965
- import_node_path12.join(home, ".config", "Antigravity", "app_storage.json"),
1966
- import_node_path12.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
2473
+ process.env.APPDATA ? import_node_path15.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
2474
+ import_node_path15.join(home, ".config", "Antigravity", "app_storage.json"),
2475
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
1967
2476
  ].filter(Boolean);
1968
2477
  for (const file of candidates) {
1969
2478
  try {
1970
- if (import_node_fs11.existsSync(file)) {
1971
- const raw = import_node_fs11.readFileSync(file, "utf8");
2479
+ if (import_node_fs14.existsSync(file)) {
2480
+ const raw = import_node_fs14.readFileSync(file, "utf8");
1972
2481
  const json = JSON.parse(raw);
1973
2482
  const username = json["jetski.onboarding.lastLoginUsername"];
1974
2483
  if (username && typeof username === "string" && username.trim()) {
@@ -1989,30 +2498,30 @@ function resolveAntigravityAccount() {
1989
2498
  }
1990
2499
  function resolveAntigravityLanguageServer() {
1991
2500
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
1992
- const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path12.join(home, "AppData", "Roaming") : "");
2501
+ const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path15.join(home, "AppData", "Roaming") : "");
1993
2502
  const baseDirs = [
1994
- appData ? import_node_path12.join(appData, "Antigravity IDE", "logs") : null,
1995
- appData ? import_node_path12.join(appData, "Antigravity", "logs") : null,
1996
- import_node_path12.join(home, ".config", "Antigravity IDE", "logs"),
1997
- import_node_path12.join(home, ".config", "Antigravity", "logs"),
1998
- import_node_path12.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
1999
- import_node_path12.join(home, "Library", "Application Support", "Antigravity", "logs")
2503
+ appData ? import_node_path15.join(appData, "Antigravity IDE", "logs") : null,
2504
+ appData ? import_node_path15.join(appData, "Antigravity", "logs") : null,
2505
+ import_node_path15.join(home, ".config", "Antigravity IDE", "logs"),
2506
+ import_node_path15.join(home, ".config", "Antigravity", "logs"),
2507
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
2508
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity", "logs")
2000
2509
  ].filter(Boolean);
2001
2510
  for (const base of baseDirs) {
2002
2511
  try {
2003
- if (!import_node_fs11.existsSync(base))
2512
+ if (!import_node_fs14.existsSync(base))
2004
2513
  continue;
2005
- const sessionDirs = import_node_fs11.readdirSync(base).map((d) => {
2514
+ const sessionDirs = import_node_fs14.readdirSync(base).map((d) => {
2006
2515
  try {
2007
- return { name: d, time: import_node_fs11.statSync(import_node_path12.join(base, d)).mtimeMs };
2516
+ return { name: d, time: import_node_fs14.statSync(import_node_path15.join(base, d)).mtimeMs };
2008
2517
  } catch {
2009
2518
  return null;
2010
2519
  }
2011
2520
  }).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
2012
2521
  for (const s of sessionDirs) {
2013
- const logFile = import_node_path12.join(base, s.name, "ls-main.log");
2014
- if (import_node_fs11.existsSync(logFile)) {
2015
- const content = import_node_fs11.readFileSync(logFile, "utf8");
2522
+ const logFile = import_node_path15.join(base, s.name, "ls-main.log");
2523
+ if (import_node_fs14.existsSync(logFile)) {
2524
+ const content = import_node_fs14.readFileSync(logFile, "utf8");
2016
2525
  const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
2017
2526
  const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
2018
2527
  if (csrfMatch && portMatch) {
@@ -2028,13 +2537,13 @@ function resolveAntigravityLanguageServer() {
2028
2537
  try {
2029
2538
  let out = "";
2030
2539
  if (process.platform === "win32") {
2031
- out = import_node_child_process5.execFileSync("powershell", [
2540
+ out = import_node_child_process6.execFileSync("powershell", [
2032
2541
  "-NoProfile",
2033
2542
  "-Command",
2034
2543
  `Get-CimInstance Win32_Process -Filter "Name like '%language_server%'" | Select-Object -ExpandProperty CommandLine`
2035
2544
  ], { encoding: "utf8", timeout: 4000, windowsHide: true });
2036
2545
  } else {
2037
- out = import_node_child_process5.execFileSync("ps", ["aux"], { encoding: "utf8", timeout: 4000 });
2546
+ out = import_node_child_process6.execFileSync("ps", ["aux"], { encoding: "utf8", timeout: 4000 });
2038
2547
  }
2039
2548
  const lines = out.split(/\r?\n/);
2040
2549
  for (const l of lines) {
@@ -2071,7 +2580,7 @@ async function probeAgyQuota(options) {
2071
2580
  }
2072
2581
  } catch {
2073
2582
  try {
2074
- const raw = import_node_child_process5.execFileSync(process.platform === "win32" ? "curl.exe" : "curl", [
2583
+ const raw = import_node_child_process6.execFileSync(process.platform === "win32" ? "curl.exe" : "curl", [
2075
2584
  "-k",
2076
2585
  "-s",
2077
2586
  "-X",
@@ -2169,7 +2678,7 @@ async function probeAgyQuota(options) {
2169
2678
  } catch {}
2170
2679
  }
2171
2680
  const geminiHome = resolveGeminiHome2();
2172
- const hasAgyDir = import_node_fs11.existsSync(import_node_path12.join(geminiHome, "antigravity")) || import_node_fs11.existsSync(import_node_path12.join(geminiHome, "antigravity-cli"));
2681
+ const hasAgyDir = import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity")) || import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity-cli"));
2173
2682
  const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
2174
2683
  const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
2175
2684
  if (!isAvailable) {
@@ -2241,6 +2750,12 @@ function probeAgyAuth() {
2241
2750
  }
2242
2751
  var agyAdapter = {
2243
2752
  id: "agy",
2753
+ prepareAppResources: async ({ directory }) => {
2754
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
2755
+ return { ...prep, env: { AGY_ACP_RESOURCES_DIR: directory }, report: { ...prep.report, rulesPrepared: prep.report.rulesChars > 0 } };
2756
+ },
2757
+ appResourceSessionMeta: (directory) => ({ appResources: { directory } }),
2758
+ supportedBridgeVersions: ["0.1.24"],
2244
2759
  probeAuth: () => probeAgyAuth(),
2245
2760
  probeQuota: (options) => probeAgyQuota(options),
2246
2761
  orderAuthMethods: (methods) => methods,
@@ -2280,7 +2795,10 @@ function getAcpRuntimeAdapter(runtimeId) {
2280
2795
  }
2281
2796
 
2282
2797
  // src/process/process-manager.ts
2283
- var import_node_child_process6 = require("node:child_process");
2798
+ var import_node_child_process7 = require("node:child_process");
2799
+ function processKey(runtimeId, scopeKey) {
2800
+ return scopeKey ? `${scopeKey}:${runtimeId}` : runtimeId;
2801
+ }
2284
2802
  var active = new Map;
2285
2803
  var ACP_EARLY_EXIT_WINDOW_MS = 3000;
2286
2804
  var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
@@ -2292,7 +2810,7 @@ function killProcessTree(pid) {
2292
2810
  if (process.platform !== "win32")
2293
2811
  return;
2294
2812
  try {
2295
- import_node_child_process6.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
2813
+ import_node_child_process7.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
2296
2814
  windowsHide: true,
2297
2815
  timeout: 8000
2298
2816
  });
@@ -2312,7 +2830,8 @@ function spawnAcpProcess(options) {
2312
2830
  if (!options.runtime?.id || !options.runtime.command || !Array.isArray(options.runtime.args)) {
2313
2831
  throw new Error(`ACP 运行时模板缺失 command/args: ${options.runtime?.id ?? "(empty)"}`);
2314
2832
  }
2315
- const existing = active.get(options.runtime.id);
2833
+ const key = processKey(options.runtime.id, options.scopeKey);
2834
+ const existing = active.get(key);
2316
2835
  if (existing) {
2317
2836
  existing.kill();
2318
2837
  }
@@ -2335,7 +2854,7 @@ function spawnAcpProcess(options) {
2335
2854
  } else {
2336
2855
  delete env.NO_BROWSER;
2337
2856
  }
2338
- const child = import_node_child_process6.spawn(file, options.runtime.args, {
2857
+ const child = import_node_child_process7.spawn(file, options.runtime.args, {
2339
2858
  cwd: options.cwd,
2340
2859
  env,
2341
2860
  stdio: ["pipe", "pipe", "pipe"],
@@ -2373,6 +2892,9 @@ function spawnAcpProcess(options) {
2373
2892
  });
2374
2893
  const handle = {
2375
2894
  runtimeId: options.runtime.id,
2895
+ scopeKey: options.scopeKey,
2896
+ executionContext: options.executionContext,
2897
+ profileTag: options.profileTag ?? null,
2376
2898
  child,
2377
2899
  spawnedAt: Date.now(),
2378
2900
  stderrTail,
@@ -2390,7 +2912,7 @@ function spawnAcpProcess(options) {
2390
2912
  } catch {}
2391
2913
  }
2392
2914
  }
2393
- active.delete(options.runtime.id);
2915
+ active.delete(key);
2394
2916
  }
2395
2917
  };
2396
2918
  child.on("exit", (code, signal) => {
@@ -2398,10 +2920,11 @@ function spawnAcpProcess(options) {
2398
2920
  if (rest)
2399
2921
  pushStderrTailLine(rest);
2400
2922
  stderrBuffer = "";
2401
- active.delete(options.runtime.id);
2923
+ if (active.get(key) === handle)
2924
+ active.delete(key);
2402
2925
  options.onExit?.(code, signal);
2403
2926
  });
2404
- active.set(options.runtime.id, handle);
2927
+ active.set(key, handle);
2405
2928
  return handle;
2406
2929
  }
2407
2930
  function getAcpEarlyExitStderrDetail(handle, _now = Date.now()) {
@@ -2429,27 +2952,47 @@ function disposeAllAcpProcesses() {
2429
2952
  }
2430
2953
  active.clear();
2431
2954
  }
2432
- function getActiveAcpProcess(runtimeId) {
2433
- return active.get(runtimeId);
2955
+ function getActiveAcpProcess(runtimeId, scopeKey) {
2956
+ return active.get(processKey(runtimeId, scopeKey));
2434
2957
  }
2435
2958
  function listLiveAcpRuntimeIds() {
2436
- const ids = [];
2437
- for (const [runtimeId, handle] of active) {
2959
+ const ids = new Set;
2960
+ for (const handle of active.values()) {
2438
2961
  if (isSpawnedAcpProcessAlive(handle))
2439
- ids.push(runtimeId);
2962
+ ids.add(handle.runtimeId);
2440
2963
  }
2441
- return ids.sort();
2964
+ return [...ids].sort();
2442
2965
  }
2443
- function getLiveAcpProcess(runtimeId) {
2444
- const handle = active.get(runtimeId);
2966
+ function getLiveAcpProcess(runtimeId, query = {}) {
2967
+ const key = processKey(runtimeId, query.scopeKey);
2968
+ const handle = active.get(key);
2445
2969
  if (!handle)
2446
2970
  return;
2447
2971
  if (!isSpawnedAcpProcessAlive(handle)) {
2448
- active.delete(runtimeId);
2972
+ active.delete(key);
2973
+ return;
2974
+ }
2975
+ if (query.executionContext !== undefined && (handle.executionContext ?? null) !== query.executionContext) {
2449
2976
  return;
2450
2977
  }
2978
+ if (query.expectedTag !== undefined && (handle.profileTag ?? null) !== query.expectedTag)
2979
+ return;
2451
2980
  return handle;
2452
2981
  }
2982
+ function tryReuseLiveAcpProcess(runtimeId, query = {}) {
2983
+ const hit = getLiveAcpProcess(runtimeId, query);
2984
+ if (hit)
2985
+ return { status: "hit", handle: hit };
2986
+ if (query.expectedTag === undefined)
2987
+ return { status: "miss" };
2988
+ const stale = getLiveAcpProcess(runtimeId, { scopeKey: query.scopeKey, executionContext: query.executionContext });
2989
+ if (!stale)
2990
+ return { status: "miss" };
2991
+ if (query.isBusy?.(stale))
2992
+ return { status: "busy", handle: stale };
2993
+ stale.kill();
2994
+ return { status: "miss" };
2995
+ }
2453
2996
 
2454
2997
  // src/client/sdk-client.ts
2455
2998
  var import_node_stream = require("node:stream");
@@ -2520,18 +3063,18 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
2520
3063
  var import_sdk2 = require("@agentclientprotocol/sdk");
2521
3064
 
2522
3065
  // src/client/acp-fs.ts
2523
- var import_promises3 = require("node:fs/promises");
2524
- var import_node_path13 = require("node:path");
2525
3066
  var import_promises4 = require("node:fs/promises");
3067
+ var import_node_path16 = require("node:path");
3068
+ var import_promises5 = require("node:fs/promises");
2526
3069
  var MAX_READ_BYTES = 2 * 1024 * 1024;
2527
3070
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
2528
3071
  function isBinaryDocumentPath(filePath) {
2529
- return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path13.extname(filePath).toLowerCase());
3072
+ return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path16.extname(filePath).toLowerCase());
2530
3073
  }
2531
3074
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
2532
- const root = import_node_path13.resolve(workspaceRoot);
2533
- const target = import_node_path13.resolve(filePath);
2534
- const rootWithSep = root.endsWith(import_node_path13.sep) ? root : root + import_node_path13.sep;
3075
+ const root = import_node_path16.resolve(workspaceRoot);
3076
+ const target = import_node_path16.resolve(filePath);
3077
+ const rootWithSep = root.endsWith(import_node_path16.sep) ? root : root + import_node_path16.sep;
2535
3078
  if (target !== root && !target.startsWith(rootWithSep)) {
2536
3079
  throw new Error(`路径不在工作区内: ${filePath}`);
2537
3080
  }
@@ -2542,8 +3085,8 @@ async function acpReadTextFile(params) {
2542
3085
  throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
2543
3086
  }
2544
3087
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
2545
- await import_promises3.access(abs);
2546
- let content = await import_promises3.readFile(abs, "utf-8");
3088
+ await import_promises4.access(abs);
3089
+ let content = await import_promises4.readFile(abs, "utf-8");
2547
3090
  if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
2548
3091
  content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
2549
3092
  content += `
@@ -2562,8 +3105,8 @@ async function acpReadTextFile(params) {
2562
3105
  }
2563
3106
  async function acpWriteTextFile(params) {
2564
3107
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
2565
- await import_promises4.mkdir(import_node_path13.dirname(abs), { recursive: true });
2566
- await import_promises3.writeFile(abs, params.content, "utf-8");
3108
+ await import_promises5.mkdir(import_node_path16.dirname(abs), { recursive: true });
3109
+ await import_promises4.writeFile(abs, params.content, "utf-8");
2567
3110
  return {};
2568
3111
  }
2569
3112
 
@@ -2923,6 +3466,25 @@ function isTransientAcpTransportError(error) {
2923
3466
  async function restoreOrCreateAcpSession(input) {
2924
3467
  const resumeId = input.resumeSessionId?.trim() || null;
2925
3468
  const restoreAttempts = [];
3469
+ let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
3470
+ let nativeSessionAccepted = false;
3471
+ const request = async (method, params) => {
3472
+ if (!input.sessionMeta)
3473
+ return input.request(method, params);
3474
+ try {
3475
+ const result = await input.request(method, { ...params, _meta: input.sessionMeta });
3476
+ nativeSessionAccepted = true;
3477
+ return result;
3478
+ } catch (error) {
3479
+ const rejected = error instanceof import_sdk3.RequestError && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
3480
+ if (!rejected || isTransientAcpTransportError(error))
3481
+ throw error;
3482
+ log("warn", "native resource options failed; retry without extension");
3483
+ const result = await input.request(method, params);
3484
+ nativeSessionAccepted = false;
3485
+ return result;
3486
+ }
3487
+ };
2926
3488
  const delayMs = input.retryDelayMs ?? 250;
2927
3489
  const log = input.log ?? ((level, message, data) => {
2928
3490
  if (level === "info" && false)
@@ -2944,7 +3506,7 @@ async function restoreOrCreateAcpSession(input) {
2944
3506
  maxTries
2945
3507
  });
2946
3508
  try {
2947
- const result = await input.request(rpcMethod, {
3509
+ const result = await request(rpcMethod, {
2948
3510
  sessionId: resumeId,
2949
3511
  cwd: input.cwd,
2950
3512
  mcpServers: input.mcpServers ?? []
@@ -2983,7 +3545,7 @@ async function restoreOrCreateAcpSession(input) {
2983
3545
  mcpServers: input.mcpServers ?? []
2984
3546
  };
2985
3547
  try {
2986
- return await input.request("session/new", baseParams);
3548
+ return await request("session/new", baseParams);
2987
3549
  } catch (firstError) {
2988
3550
  if ((input.mcpServers ?? []).length === 0)
2989
3551
  throw firstError;
@@ -2991,10 +3553,12 @@ async function restoreOrCreateAcpSession(input) {
2991
3553
  error: errorMessage(firstError)
2992
3554
  });
2993
3555
  try {
2994
- return await input.request("session/new", {
3556
+ const result = await request("session/new", {
2995
3557
  cwd: input.cwd,
2996
3558
  mcpServers: []
2997
3559
  });
3560
+ mcpServersAccepted = false;
3561
+ return result;
2998
3562
  } catch {
2999
3563
  throw firstError;
3000
3564
  }
@@ -3010,6 +3574,8 @@ async function restoreOrCreateAcpSession(input) {
3010
3574
  configOptions: withModelsFallback(resumed),
3011
3575
  restoreMethod: "resume",
3012
3576
  sessionRestored: true,
3577
+ mcpServersAccepted,
3578
+ nativeSessionAccepted,
3013
3579
  requestedSessionId: resumeId,
3014
3580
  restoreAttempts
3015
3581
  };
@@ -3028,6 +3594,8 @@ async function restoreOrCreateAcpSession(input) {
3028
3594
  configOptions: withModelsFallback(loaded),
3029
3595
  restoreMethod: "load",
3030
3596
  sessionRestored: true,
3597
+ mcpServersAccepted,
3598
+ nativeSessionAccepted,
3031
3599
  requestedSessionId: resumeId,
3032
3600
  restoreAttempts
3033
3601
  };
@@ -3049,14 +3617,16 @@ async function restoreOrCreateAcpSession(input) {
3049
3617
  configOptions: withModelsFallback(sessionResult),
3050
3618
  restoreMethod: "new",
3051
3619
  sessionRestored: false,
3620
+ mcpServersAccepted,
3621
+ nativeSessionAccepted,
3052
3622
  requestedSessionId: resumeId ?? undefined,
3053
3623
  restoreAttempts
3054
3624
  };
3055
3625
  }
3056
3626
 
3057
3627
  // src/client/acp-terminal.ts
3058
- var import_node_child_process7 = require("node:child_process");
3059
- var import_node_crypto = require("node:crypto");
3628
+ var import_node_child_process8 = require("node:child_process");
3629
+ var import_node_crypto3 = require("node:crypto");
3060
3630
 
3061
3631
  // src/transport/terminal-output-buffer.ts
3062
3632
  function truncateOutputFromStart(text, byteLimit) {
@@ -3108,14 +3678,14 @@ class AcpTerminalManager {
3108
3678
  throw new Error("terminal/create 需要 command");
3109
3679
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
3110
3680
  const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : DEFAULT_OUTPUT_BYTE_LIMIT;
3111
- const child = import_node_child_process7.spawn(command, params.args ?? [], {
3681
+ const child = import_node_child_process8.spawn(command, params.args ?? [], {
3112
3682
  cwd,
3113
3683
  env: buildEnv(params.env),
3114
3684
  windowsHide: true,
3115
3685
  shell: false,
3116
3686
  stdio: ["ignore", "pipe", "pipe"]
3117
3687
  });
3118
- const id = `term_${import_node_crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;
3688
+ const id = `term_${import_node_crypto3.randomUUID().replace(/-/g, "").slice(0, 12)}`;
3119
3689
  const record = {
3120
3690
  id,
3121
3691
  sessionId: params.sessionId,
@@ -3204,7 +3774,7 @@ class AcpTerminalManager {
3204
3774
  return;
3205
3775
  if (process.platform === "win32") {
3206
3776
  try {
3207
- import_node_child_process7.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
3777
+ import_node_child_process8.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
3208
3778
  windowsHide: true,
3209
3779
  stdio: "ignore"
3210
3780
  });
@@ -3239,9 +3809,9 @@ class AcpTerminalManager {
3239
3809
  }
3240
3810
 
3241
3811
  // src/client/acp-proxy-service.ts
3242
- var import_promises5 = require("node:fs/promises");
3243
- var import_node_fs12 = require("node:fs");
3244
- var import_node_path14 = require("node:path");
3812
+ var import_promises6 = require("node:fs/promises");
3813
+ var import_node_fs15 = require("node:fs");
3814
+ var import_node_path17 = require("node:path");
3245
3815
  var DEFAULT_ACP_PROXY_SETTINGS = {
3246
3816
  enabled: false,
3247
3817
  host: "127.0.0.1",
@@ -3250,7 +3820,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
3250
3820
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
3251
3821
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
3252
3822
  function proxyFilePath(dir) {
3253
- return import_node_path14.join(dir, "agent", "proxy.json");
3823
+ return import_node_path17.join(dir, "agent", "proxy.json");
3254
3824
  }
3255
3825
  function validate2(settings) {
3256
3826
  if (!settings.host.trim())
@@ -3262,10 +3832,10 @@ function validate2(settings) {
3262
3832
  }
3263
3833
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
3264
3834
  const file = proxyFilePath(dir);
3265
- if (!import_node_fs12.existsSync(file))
3835
+ if (!import_node_fs15.existsSync(file))
3266
3836
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
3267
3837
  try {
3268
- const raw = JSON.parse(await import_promises5.readFile(file, "utf8"));
3838
+ const raw = JSON.parse(await import_promises6.readFile(file, "utf8"));
3269
3839
  return {
3270
3840
  enabled: raw.enabled === true,
3271
3841
  host: typeof raw.host === "string" && raw.host.trim() ? raw.host : DEFAULT_ACP_PROXY_SETTINGS.host,
@@ -3284,8 +3854,8 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
3284
3854
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
3285
3855
  port: payload.port
3286
3856
  };
3287
- await import_promises5.mkdir(import_node_path14.join(dir, "agent"), { recursive: true });
3288
- await import_promises5.writeFile(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
3857
+ await import_promises6.mkdir(import_node_path17.join(dir, "agent"), { recursive: true });
3858
+ await import_promises6.writeFile(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
3289
3859
  return ok(stored);
3290
3860
  }
3291
3861
  function buildAcpProxySpawnEnv(settings) {
@@ -3307,6 +3877,116 @@ function buildAcpProxySpawnEnv(settings) {
3307
3877
  };
3308
3878
  }
3309
3879
 
3880
+ // src/session/compat-guide.ts
3881
+ var COMPAT_CONTEXT_TAG = "acp-compat-context";
3882
+ function shortDigest(digest) {
3883
+ return digest ? digest.slice(0, 16) : "none";
3884
+ }
3885
+ function buildCompatGuideText(input) {
3886
+ const hasRules = (input.rulesText ?? "").trim() !== "";
3887
+ const hasSkills = input.skills.length > 0;
3888
+ if (!hasRules && !hasSkills)
3889
+ return null;
3890
+ const lines = [];
3891
+ 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.", "");
3892
+ if (hasRules) {
3893
+ lines.push("--- host rules (same source as the host app, delivered once per session) ---", "");
3894
+ lines.push(input.rulesText.trim(), "");
3895
+ }
3896
+ if (hasSkills) {
3897
+ lines.push("--- host skills catalog (names and descriptions only; read full text on demand) ---", "");
3898
+ for (const skill of input.skills) {
3899
+ lines.push(`- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`);
3900
+ }
3901
+ 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.");
3902
+ lines.push("");
3903
+ }
3904
+ lines.push(`</${COMPAT_CONTEXT_TAG}>`);
3905
+ return lines.join(`
3906
+ `);
3907
+ }
3908
+ function compatDeliveryKey(sessionId, generation, digest) {
3909
+ return `${generation}:${sessionId}:${digest ?? "none"}`;
3910
+ }
3911
+
3912
+ // src/mcp/app-skills-mcp.ts
3913
+ var import_node_path18 = require("node:path");
3914
+ var import_node_url = require("node:url");
3915
+ var import_node_fs16 = require("node:fs");
3916
+ var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
3917
+ var APP_SKILLS_TOOLS = [
3918
+ {
3919
+ name: "app_list_skills",
3920
+ 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.",
3921
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
3922
+ },
3923
+ {
3924
+ name: "app_read_skill",
3925
+ 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).",
3926
+ inputSchema: {
3927
+ type: "object",
3928
+ properties: {
3929
+ name: { type: "string", description: "Exact skill name from app_list_skills" },
3930
+ ref: {
3931
+ type: "string",
3932
+ description: "Optional same-directory relative Markdown file (default SKILL.md)"
3933
+ }
3934
+ },
3935
+ required: ["name"],
3936
+ additionalProperties: false
3937
+ }
3938
+ }
3939
+ ];
3940
+ function buildAppSkillsMcpServer(directory, opts) {
3941
+ return {
3942
+ name: opts?.name ?? APP_SKILLS_MCP_SERVER_NAME,
3943
+ command: process.execPath,
3944
+ env: process.versions.electron ? [{ name: "ELECTRON_RUN_AS_NODE", value: "1" }] : [],
3945
+ args: [opts?.runnerPath ?? resolveAppSkillsRunnerPath(), directory]
3946
+ };
3947
+ }
3948
+ function resolveAppSkillsRunnerPath(fromFile) {
3949
+ const base = fromFile ?? import_node_url.fileURLToPath("file:///home/runner/work/acp-client/acp-client/src/mcp/app-skills-mcp.ts");
3950
+ const candidates = [
3951
+ import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.cjs"),
3952
+ import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.ts")
3953
+ ];
3954
+ for (const candidate of candidates) {
3955
+ if (import_node_fs16.existsSync(candidate))
3956
+ return candidate;
3957
+ }
3958
+ throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
3959
+ }
3960
+
3961
+ // src/client/acp-client.ts
3962
+ var import_node_crypto4 = require("node:crypto");
3963
+
3964
+ // src/resources/eligibility.ts
3965
+ var NATIVE_ELIGIBLE_BRIDGE_VERSIONS = {
3966
+ "codex-acp": ["2.2.2"],
3967
+ opencode: ["1.18.35"],
3968
+ claude: ["0.91.0"],
3969
+ agy: ["0.1.24"]
3970
+ };
3971
+ function resolveRuntimeEligibility(runtimeId) {
3972
+ const id = (runtimeId ?? "").trim();
3973
+ if (!id || !(id in NATIVE_ELIGIBLE_BRIDGE_VERSIONS)) {
3974
+ return { eligible: false, reason: "runtime-not-verified" };
3975
+ }
3976
+ return { eligible: true };
3977
+ }
3978
+ function isSupportedBridgeVersion(runtimeId, version) {
3979
+ const versions = NATIVE_ELIGIBLE_BRIDGE_VERSIONS[(runtimeId ?? "").trim()];
3980
+ if (!versions)
3981
+ return { eligible: false, reason: "runtime-not-verified" };
3982
+ const normalized = version?.trim().replace(/^v/, "");
3983
+ if (!normalized)
3984
+ return { eligible: false, reason: "unknown-bridge-version" };
3985
+ if (!versions.includes(normalized))
3986
+ return { eligible: false, reason: "unsupported-bridge-version" };
3987
+ return { eligible: true };
3988
+ }
3989
+
3310
3990
  // src/session/session-capabilities.ts
3311
3991
  function parseLoadSessionSupported(caps) {
3312
3992
  return caps.loadSession === true;
@@ -3343,11 +4023,13 @@ class AcpSessionHandle {
3343
4023
  client;
3344
4024
  restoreMethod;
3345
4025
  configOptions;
3346
- constructor(sessionId, client, restoreMethod, configOptions) {
4026
+ resourceReport;
4027
+ constructor(sessionId, client, restoreMethod, configOptions, resourceReport) {
3347
4028
  this.sessionId = sessionId;
3348
4029
  this.client = client;
3349
4030
  this.restoreMethod = restoreMethod;
3350
4031
  this.configOptions = configOptions;
4032
+ this.resourceReport = resourceReport;
3351
4033
  }
3352
4034
  async prompt(promptText, options) {
3353
4035
  return this.client.promptSession(this.sessionId, promptText, options);
@@ -3376,6 +4058,10 @@ class AcpClient {
3376
4058
  clientInfo;
3377
4059
  dataDir;
3378
4060
  extraEnv;
4061
+ configurationScope;
4062
+ sessionConfig = null;
4063
+ resourcesDir;
4064
+ processScopeKey = import_node_crypto4.randomUUID();
3379
4065
  callbacks;
3380
4066
  terminals = new AcpTerminalManager;
3381
4067
  processHandle = null;
@@ -3383,6 +4069,17 @@ class AcpClient {
3383
4069
  sdkConnection = null;
3384
4070
  streamHandle = null;
3385
4071
  initResponse = null;
4072
+ inflightPrompts = new Set;
4073
+ resourcePrep = null;
4074
+ connectionGen = 0;
4075
+ attachSkillsMcp;
4076
+ sessionLedger = new Map;
4077
+ compatSentKeys = new Set;
4078
+ compatSnapshots = new Map;
4079
+ get resourceReport() {
4080
+ const report = this.resourcePrep?.report;
4081
+ return report ? { ...report, skillsFound: [...report.skillsFound] } : null;
4082
+ }
3386
4083
  constructor(options) {
3387
4084
  this.workspaceRoot = options.workspaceRoot;
3388
4085
  this.clientInfo = {
@@ -3391,6 +4088,14 @@ class AcpClient {
3391
4088
  };
3392
4089
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
3393
4090
  this.extraEnv = options.env ?? {};
4091
+ if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
4092
+ throw new Error("resources.directory 必须是本机绝对路径");
4093
+ }
4094
+ this.configurationScope = options.resources?.configurationScope ?? "overlay";
4095
+ if (!["overlay", "session"].includes(this.configurationScope))
4096
+ throw new Error("Invalid resources.configurationScope");
4097
+ this.resourcesDir = options.resources?.directory ?? null;
4098
+ this.attachSkillsMcp = options.resources?.attachSkillsMcp !== false;
3394
4099
  this.callbacks = options.callbacks ?? {};
3395
4100
  const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
3396
4101
  this.adapter = getAcpRuntimeAdapter(runtimeId);
@@ -3417,6 +4122,14 @@ class AcpClient {
3417
4122
  return this.initResponse;
3418
4123
  }
3419
4124
  async connect() {
4125
+ if (this.inflightPrompts.size > 0)
4126
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
4127
+ if (this.isConnected && this.initResponse)
4128
+ return ok({ status: this.status, init: this.initResponse });
4129
+ if (this.currentStatus === "connecting")
4130
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在连接" });
4131
+ this.connectionGen += 1;
4132
+ const connectGen = this.connectionGen;
3420
4133
  try {
3421
4134
  this.setStatus("connecting");
3422
4135
  const blocker = this.adapter.resolveSpawnBlocker?.();
@@ -3442,16 +4155,105 @@ class AcpClient {
3442
4155
  ...baseEnv,
3443
4156
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
3444
4157
  };
4158
+ let resourceEnv = {};
4159
+ let profileTag = null;
4160
+ if (this.resourcesDir && this.configurationScope === "session") {
4161
+ const profile = await createSessionConfigHome(this.runtimeInfo.id, this.resourcesDir);
4162
+ if (connectGen !== this.connectionGen || this.status !== "connecting") {
4163
+ await profile.dispose();
4164
+ return err({ code: "CANCELLED", message: "连接已取消" });
4165
+ }
4166
+ this.sessionConfig = profile;
4167
+ resourceEnv = this.sessionConfig.env;
4168
+ const load = readAppResourcesDir(this.resourcesDir);
4169
+ this.resourcePrep = { profileTag: null, report: {
4170
+ rulesApplied: false,
4171
+ rulesPrepared: false,
4172
+ skillsApplied: false,
4173
+ rulesChars: load.rules?.chars ?? 0,
4174
+ profileDigest: digestAppResources(load),
4175
+ skillsFound: load.skills.map((s) => s.name),
4176
+ configurationScope: "session",
4177
+ configurationDirectory: this.sessionConfig.directory,
4178
+ configurationRulesFile: this.sessionConfig.rulesFile,
4179
+ reason: this.sessionConfig.nativeRules ? "isolated-config-not-runtime-verified" : "isolated-config-rule-discovery-not-verified"
4180
+ } };
4181
+ } else if (this.resourcesDir && this.adapter.prepareAppResources) {
4182
+ try {
4183
+ const prep = await this.adapter.prepareAppResources({
4184
+ directory: this.resourcesDir,
4185
+ command: effectiveRuntime.command,
4186
+ workspaceRoot: this.workspaceRoot,
4187
+ env: { ...process.env, ...spawnEnv.env }
4188
+ });
4189
+ if (prep.env)
4190
+ resourceEnv = prep.env;
4191
+ prep.report.rulesPrepared = prep.report.rulesPrepared ?? prep.report.rulesApplied;
4192
+ prep.report.rulesApplied = false;
4193
+ prep.report.skillsApplied = false;
4194
+ const digest = prep.report.profileDigest;
4195
+ profileTag = digest ? `${this.runtimeInfo.id}:resources@${digest.slice(0, 16)}` : null;
4196
+ this.resourcePrep = { profileTag, report: prep.report };
4197
+ } catch (error) {
4198
+ this.resourcePrep = {
4199
+ profileTag: null,
4200
+ report: {
4201
+ rulesApplied: false,
4202
+ rulesChars: 0,
4203
+ profileDigest: null,
4204
+ skillsFound: [],
4205
+ reason: "prepare-failed"
4206
+ }
4207
+ };
4208
+ this.callbacks.onLog?.("warn", "应用资源准备失败,已回退兼容", {
4209
+ error: error instanceof Error ? error.message : String(error)
4210
+ });
4211
+ }
4212
+ } else {
4213
+ const load = this.resourcesDir ? readAppResourcesDir(this.resourcesDir) : null;
4214
+ this.resourcePrep = load ? { profileTag: null, report: {
4215
+ rulesApplied: false,
4216
+ rulesPrepared: false,
4217
+ skillsApplied: false,
4218
+ rulesChars: load.rules?.chars ?? 0,
4219
+ profileDigest: digestAppResources(load),
4220
+ skillsFound: load.skills.map((s) => s.name),
4221
+ reason: "runtime-not-supported"
4222
+ } } : null;
4223
+ }
4224
+ const finalEnv = { ...spawnEnv.env, ...resourceEnv };
3445
4225
  await this.adapter.beforeSpawn?.();
3446
- const processHandle = spawnAcpProcess({
4226
+ if (connectGen !== this.connectionGen || this.status !== "connecting")
4227
+ return err({ code: "CANCELLED", message: "连接已取消" });
4228
+ let reuseDegraded = false;
4229
+ let reusedHandle = null;
4230
+ if (profileTag) {
4231
+ const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
4232
+ expectedTag: profileTag,
4233
+ scopeKey: this.processScopeKey,
4234
+ isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
4235
+ });
4236
+ if (reuse.status === "hit") {
4237
+ reusedHandle = reuse.handle;
4238
+ } else if (reuse.status === "busy") {
4239
+ reusedHandle = reuse.handle;
4240
+ reuseDegraded = true;
4241
+ this.callbacks.onLog?.("warn", "应用资源摘要已变更但旧进程正忙,沿用旧进程并降级,新摘要下次冷启动生效");
4242
+ }
4243
+ }
4244
+ const processHandle = reusedHandle ?? spawnAcpProcess({
3447
4245
  runtime: effectiveRuntime,
3448
4246
  cwd: this.workspaceRoot,
3449
- env: spawnEnv.env,
4247
+ scopeKey: this.processScopeKey,
4248
+ env: finalEnv,
3450
4249
  envRemove: spawnEnv.envRemove,
4250
+ profileTag,
3451
4251
  onStderrLine: (line) => {
3452
4252
  this.callbacks.onStderrLine?.(line);
3453
4253
  },
3454
4254
  onExit: (code, signal) => {
4255
+ if (this.connectionGen !== connectGen)
4256
+ return;
3455
4257
  this.callbacks.onLog?.("warn", `Agent 进程已退出 (code: ${code}, signal: ${signal})`);
3456
4258
  if (this.status === "connected" || this.status === "connecting") {
3457
4259
  this.disconnect("Agent 进程异常终止");
@@ -3502,9 +4304,28 @@ class AcpClient {
3502
4304
  }
3503
4305
  });
3504
4306
  this.initResponse = initResp;
4307
+ if (this.resourcePrep) {
4308
+ const agentInfo = initResp?.agentInfo;
4309
+ const bridgeVersion = typeof agentInfo?.version === "string" ? agentInfo.version : undefined;
4310
+ const supported = isSupportedBridgeVersion(this.runtimeInfo.id, bridgeVersion).eligible && (this.adapter.supportedBridgeVersions?.includes(bridgeVersion?.replace(/^v/, "") ?? "") ?? false);
4311
+ this.resourcePrep.report.bridgeVersion = bridgeVersion;
4312
+ this.resourcePrep.report.bridgeSupported = supported;
4313
+ if (this.processHandle)
4314
+ this.processHandle.bridgeVersion = bridgeVersion;
4315
+ if (supported && this.resourcePrep.report.reason === "native-session-version-not-verified")
4316
+ delete this.resourcePrep.report.reason;
4317
+ if (!supported) {
4318
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "unsupported-bridge-version";
4319
+ }
4320
+ if (reuseDegraded) {
4321
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "busy-deferred-stale-rules";
4322
+ }
4323
+ }
3505
4324
  this.setStatus("connected");
3506
4325
  return ok({ status: "connected", init: initResp });
3507
4326
  } catch (e) {
4327
+ if (connectGen !== this.connectionGen)
4328
+ return err({ code: "CANCELLED", message: "连接已被新请求取代" });
3508
4329
  const message = e instanceof Error ? e.message : String(e);
3509
4330
  this.setStatus("error", message);
3510
4331
  await this.disconnect(message);
@@ -3543,6 +4364,29 @@ class AcpClient {
3543
4364
  const resumeSupported = Boolean(init && parseResumeSessionSupported(init.agentCapabilities));
3544
4365
  const loadSupported = Boolean(init && parseLoadSessionSupported(init.agentCapabilities));
3545
4366
  try {
4367
+ let skillsExposed = "none";
4368
+ let mcpServers = options?.mcpServers ?? [];
4369
+ if (this.resourcesDir && this.attachSkillsMcp) {
4370
+ try {
4371
+ const descriptor = buildAppSkillsMcpServer(this.resourcesDir);
4372
+ const callerNames = new Set;
4373
+ for (const entry of mcpServers) {
4374
+ if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
4375
+ callerNames.add(entry.name);
4376
+ }
4377
+ }
4378
+ if (callerNames.has(descriptor.name)) {
4379
+ this.callbacks.onLog?.("warn", "调用方已有同名技能 MCP 服务,保留调用方版本", { name: descriptor.name });
4380
+ } else {
4381
+ mcpServers = [...mcpServers, descriptor];
4382
+ skillsExposed = "mcp-exposed";
4383
+ }
4384
+ } catch (error) {
4385
+ this.callbacks.onLog?.("warn", "技能 MCP 描述符构建失败,本次会话无技能 MCP", {
4386
+ error: error instanceof Error ? error.message : String(error)
4387
+ });
4388
+ }
4389
+ }
3546
4390
  const openResult = await restoreOrCreateAcpSession({
3547
4391
  request: async (method, params) => {
3548
4392
  return sdkRequest(agent, method, params);
@@ -3551,12 +4395,27 @@ class AcpClient {
3551
4395
  resumeSessionId: options?.resumeSessionId ?? null,
3552
4396
  resumeSupported,
3553
4397
  loadSupported,
3554
- mcpServers: options?.mcpServers ?? [],
4398
+ mcpServers,
4399
+ sessionMeta: (!this.sessionConfig || this.runtimeInfo.id === "agy") && this.resourcesDir && this.resourcePrep?.report.bridgeSupported ? this.adapter.appResourceSessionMeta?.(this.resourcesDir) : undefined,
3555
4400
  log: (level, msg, meta) => {
3556
4401
  this.callbacks.onLog?.(level, msg, meta);
3557
4402
  }
3558
4403
  });
3559
- const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions);
4404
+ if (!openResult.mcpServersAccepted)
4405
+ skillsExposed = "none";
4406
+ this.sessionLedger.set(openResult.sessionId, {
4407
+ restoreMethod: openResult.restoreMethod,
4408
+ gen: this.connectionGen,
4409
+ skillsExposed,
4410
+ nativeRules: openResult.nativeSessionAccepted
4411
+ });
4412
+ const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions, this.resourcePrep?.report ? {
4413
+ ...this.resourcePrep.report,
4414
+ skillsFound: [...this.resourcePrep.report.skillsFound],
4415
+ skillsExposed,
4416
+ rulesApplied: openResult.nativeSessionAccepted || !this.adapter.appResourceSessionMeta && openResult.restoreMethod === "new" && this.resourcePrep.report.bridgeSupported === true && this.resourcePrep.report.rulesPrepared === true,
4417
+ ...openResult.restoreMethod !== "new" && !openResult.nativeSessionAccepted ? { reason: "session-restored-not-verified" } : {}
4418
+ } : null);
3560
4419
  return ok(handle);
3561
4420
  } catch (e) {
3562
4421
  const message = e instanceof Error ? e.message : String(e);
@@ -3567,6 +4426,7 @@ class AcpClient {
3567
4426
  if (!this.sdkConnection?.agent) {
3568
4427
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
3569
4428
  }
4429
+ this.inflightPrompts.add(sessionId);
3570
4430
  try {
3571
4431
  const prompt = [{ type: "text", text: promptText }];
3572
4432
  for (const image of options?.images ?? []) {
@@ -3574,16 +4434,52 @@ class AcpClient {
3574
4434
  continue;
3575
4435
  prompt.push({ type: "image", mimeType: image.mimeType, data: image.data });
3576
4436
  }
4437
+ const compat = this.buildCompatPrepend(sessionId);
4438
+ const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
3577
4439
  const response = await sdkRequest(this.sdkConnection.agent, import_sdk4.methods.agent.session.prompt, {
3578
4440
  sessionId,
3579
- prompt
4441
+ prompt: blocks
3580
4442
  }, options?.timeoutMs);
3581
4443
  return ok(response);
3582
4444
  } catch (e) {
3583
4445
  const message = e instanceof Error ? e.message : String(e);
3584
4446
  return err({ code: "ACP_PROTOCOL_ERROR", message });
4447
+ } finally {
4448
+ this.inflightPrompts.delete(sessionId);
3585
4449
  }
3586
4450
  }
4451
+ buildCompatPrepend(sessionId) {
4452
+ if (!this.resourcesDir)
4453
+ return null;
4454
+ if (this.sessionConfig?.nativeRules)
4455
+ return null;
4456
+ const entry = this.sessionLedger.get(sessionId);
4457
+ if (!entry)
4458
+ return null;
4459
+ const connReport = this.resourcePrep?.report;
4460
+ const nativelyDelivered = entry.nativeRules || !this.adapter.appResourceSessionMeta && entry.restoreMethod === "new" && entry.gen === this.connectionGen && connReport?.rulesPrepared === true && connReport?.bridgeSupported === true;
4461
+ if (nativelyDelivered)
4462
+ return null;
4463
+ const load = readAppResourcesDir(this.resourcesDir);
4464
+ const rulesText = readAppRulesText(this.resourcesDir);
4465
+ const digest = digestAppResources(load);
4466
+ const key = compatDeliveryKey(sessionId, this.connectionGen, digest);
4467
+ if (this.compatSentKeys.has(key))
4468
+ return null;
4469
+ const text = buildCompatGuideText({
4470
+ rulesText,
4471
+ skills: load.skills.map((s) => ({ name: s.name, description: s.description })),
4472
+ skillsViaMcp: entry.skillsExposed === "mcp-exposed",
4473
+ digest,
4474
+ sessionId,
4475
+ generation: this.connectionGen
4476
+ });
4477
+ if (!text)
4478
+ return null;
4479
+ this.compatSnapshots.set(key, { text, digest });
4480
+ this.compatSentKeys.add(key);
4481
+ return text;
4482
+ }
3587
4483
  async setSessionConfigOption(sessionId, configId, value) {
3588
4484
  if (!this.sdkConnection?.agent) {
3589
4485
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
@@ -3602,6 +4498,10 @@ class AcpClient {
3602
4498
  }
3603
4499
  async disconnect(reason) {
3604
4500
  this.setStatus("disconnected", reason);
4501
+ this.resourcePrep = null;
4502
+ this.sessionLedger.clear();
4503
+ this.compatSentKeys.clear();
4504
+ this.compatSnapshots.clear();
3605
4505
  try {
3606
4506
  this.streamHandle?.dispose();
3607
4507
  this.sdkConnection?.close();
@@ -3617,6 +4517,15 @@ class AcpClient {
3617
4517
  } catch {}
3618
4518
  this.processHandle = null;
3619
4519
  }
4520
+ const config = this.sessionConfig;
4521
+ this.sessionConfig = null;
4522
+ if (config) {
4523
+ try {
4524
+ await config.dispose();
4525
+ } catch {
4526
+ this.callbacks.onLog?.("warn", "Session configuration cleanup failed; directory retained", { directory: config.directory });
4527
+ }
4528
+ }
3620
4529
  }
3621
4530
  setStatus(status, detail) {
3622
4531
  this.status = status;