@yitom/acp-client 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,19 @@ __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,
114
+ closeAcpSessions: () => closeAcpSessions,
108
115
  codexAdapter: () => codexAdapter,
109
116
  connectSdkClient: () => connectSdkClient,
110
117
  copilotAdapter: () => copilotAdapter,
111
118
  createSdkStreamHandle: () => createSdkStreamHandle,
119
+ createSessionConfigHome: () => createSessionConfigHome,
112
120
  cursorAdapter: () => cursorAdapter,
113
121
  decideConnectAuth: () => decideConnectAuth,
114
122
  deepseekAdapter: () => deepseekAdapter,
123
+ digestAppResources: () => digestAppResources,
115
124
  disposeAllAcpProcesses: () => disposeAllAcpProcesses,
116
125
  emptyAcpAuthPreflight: () => emptyAcpAuthPreflight,
117
126
  err: () => err,
@@ -131,6 +140,7 @@ __export(exports_src, {
131
140
  getDefaultAgentDataDir: () => getDefaultAgentDataDir,
132
141
  getLiveAcpProcess: () => getLiveAcpProcess,
133
142
  handleInkdownMcpRpc: () => handleInkdownMcpRpc,
143
+ isAbsolutePathLike: () => isAbsolutePathLike,
134
144
  isAppError: () => isAppError,
135
145
  isBinaryDocumentPath: () => isBinaryDocumentPath,
136
146
  isCancelled: () => isCancelled,
@@ -140,11 +150,15 @@ __export(exports_src, {
140
150
  isInkdownVirtualDirPath: () => isInkdownVirtualDirPath,
141
151
  isOk: () => isOk,
142
152
  isSpawnedAcpProcessAlive: () => isSpawnedAcpProcessAlive,
153
+ isSupportedBridgeVersion: () => isSupportedBridgeVersion,
143
154
  isTransientAcpTransportError: () => isTransientAcpTransportError,
144
155
  isValidCursorAuthFile: () => isValidCursorAuthFile,
145
156
  isValidOpencodeAuthFile: () => isValidOpencodeAuthFile,
146
157
  listAcpRuntimes: () => listAcpRuntimes,
147
158
  listLiveAcpRuntimeIds: () => listLiveAcpRuntimeIds,
159
+ mergeCodexConfigJson: () => mergeCodexConfigJson,
160
+ mergeConfigTomlPreserving: () => mergeConfigTomlPreserving,
161
+ mergeOpenCodeAppConfig: () => mergeOpenCodeAppConfig,
148
162
  mergeTopLevelModelsIntoConfigOptions: () => mergeTopLevelModelsIntoConfigOptions,
149
163
  ok: () => ok,
150
164
  opencodeAdapter: () => opencodeAdapter,
@@ -158,7 +172,11 @@ __export(exports_src, {
158
172
  parsePromptCapabilities: () => parsePromptCapabilities,
159
173
  parseRateLimitsFromStatusText: () => parseRateLimitsFromStatusText,
160
174
  parseResumeSessionSupported: () => parseResumeSessionSupported,
175
+ parseSkillFrontmatter: () => parseSkillFrontmatter,
161
176
  pickAllowOptionId: () => pickAllowOptionId,
177
+ prepareClaudeResources: () => prepareClaudeResources,
178
+ prepareCompatibilityResources: () => prepareCompatibilityResources,
179
+ prepareOpenCodeResources: () => prepareOpenCodeResources,
162
180
  probeAgyAuth: () => probeAgyAuth,
163
181
  probeClaudeAuth: () => probeClaudeAuth,
164
182
  probeClaudeQuota: () => probeClaudeQuota,
@@ -173,6 +191,8 @@ __export(exports_src, {
173
191
  probeOpencodeQuota: () => probeOpencodeQuota,
174
192
  provisionCustomProviderCodexHome: () => provisionCustomProviderCodexHome,
175
193
  readAcpProxySettings: () => readAcpProxySettings,
194
+ readAppResourcesDir: () => readAppResourcesDir,
195
+ readAppRulesText: () => readAppRulesText,
176
196
  readStoredAcpProvider: () => readStoredAcpProvider,
177
197
  registerAcpClientHandlers: () => registerAcpClientHandlers,
178
198
  resolveClaudeHome: () => resolveClaudeHome,
@@ -188,6 +208,7 @@ __export(exports_src, {
188
208
  resolveOpencodeAuthCandidates: () => resolveOpencodeAuthCandidates,
189
209
  resolveOpencodeAuthFile: () => resolveOpencodeAuthFile,
190
210
  resolveOpencodeAuthPath: () => resolveOpencodeAuthPath,
211
+ resolveRuntimeEligibility: () => resolveRuntimeEligibility,
191
212
  restoreOrCreateAcpSession: () => restoreOrCreateAcpSession,
192
213
  runConnectAuthGate: () => runConnectAuthGate,
193
214
  saveAcpProvider: () => saveAcpProvider,
@@ -198,6 +219,7 @@ __export(exports_src, {
198
219
  synthesizeModelOptionFromTopLevelModels: () => synthesizeModelOptionFromTopLevelModels,
199
220
  toAppError: () => toAppError,
200
221
  truncateOutputFromStart: () => truncateOutputFromStart,
222
+ tryReuseLiveAcpProcess: () => tryReuseLiveAcpProcess,
201
223
  withAcpEarlyExitDetail: () => withAcpEarlyExitDetail
202
224
  });
203
225
  module.exports = __toCommonJS(exports_src);
@@ -363,7 +385,320 @@ function findBuiltinAcpRuntime(id) {
363
385
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
364
386
  }
365
387
  // src/version.ts
366
- var ACP_CLIENT_VERSION = "0.1.7";
388
+ var ACP_CLIENT_VERSION = "0.1.9";
389
+ // src/client/sdk-client.ts
390
+ var import_node_stream = require("node:stream");
391
+ var import_sdk = require("@agentclientprotocol/sdk");
392
+ var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
393
+ function createSdkStreamHandle(child) {
394
+ const stdoutBridge = new import_node_stream.PassThrough;
395
+ const stdinBridge = new import_node_stream.PassThrough;
396
+ child.stdout.pipe(stdoutBridge);
397
+ stdinBridge.pipe(child.stdin, { end: false });
398
+ const output = import_node_stream.Writable.toWeb(stdinBridge);
399
+ const input = import_node_stream.Readable.toWeb(stdoutBridge);
400
+ const stream = import_sdk.ndJsonStream(output, input);
401
+ let disposed = false;
402
+ return {
403
+ stream,
404
+ dispose: () => {
405
+ if (disposed)
406
+ return;
407
+ disposed = true;
408
+ try {
409
+ child.stdout.unpipe(stdoutBridge);
410
+ } catch {}
411
+ try {
412
+ stdinBridge.unpipe(child.stdin);
413
+ } catch {}
414
+ try {
415
+ stdoutBridge.destroy();
416
+ } catch {}
417
+ try {
418
+ stdinBridge.destroy();
419
+ } catch {}
420
+ }
421
+ };
422
+ }
423
+ function connectSdkClient(child, configure, runtimeId) {
424
+ if (runtimeId && true) {
425
+ console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
426
+ }
427
+ const app = import_sdk.client({ name: "inkdown" });
428
+ configure(app);
429
+ const streamHandle = createSdkStreamHandle(child);
430
+ const connection = app.connect(streamHandle.stream);
431
+ return { app, connection, streamHandle };
432
+ }
433
+ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
434
+ const controller = new AbortController;
435
+ let timer;
436
+ try {
437
+ const pending = agent.request(method, params, {
438
+ cancellationSignal: controller.signal
439
+ });
440
+ const timeout = new Promise((_, reject) => {
441
+ timer = setTimeout(() => {
442
+ controller.abort();
443
+ reject(new Error(`请求超时: ${method}`));
444
+ }, timeoutMs);
445
+ timer.unref?.();
446
+ });
447
+ return await Promise.race([pending, timeout]);
448
+ } finally {
449
+ if (timer !== undefined)
450
+ clearTimeout(timer);
451
+ }
452
+ }
453
+ async function closeAcpSessions(agent, sessionIds, timeoutMs = 2000) {
454
+ const failed = [];
455
+ await Promise.all([...new Set(sessionIds)].map(async (sessionId) => {
456
+ try {
457
+ await sdkRequest(agent, "session/close", { sessionId }, timeoutMs);
458
+ } catch {
459
+ failed.push(sessionId);
460
+ }
461
+ }));
462
+ return failed;
463
+ }
464
+
465
+ // src/resources/session-config.ts
466
+ var import_node_fs2 = require("node:fs");
467
+ var import_promises = require("node:fs/promises");
468
+ var import_node_os = require("node:os");
469
+ var import_node_path2 = require("node:path");
470
+
471
+ // src/resources/app-resources.ts
472
+ var import_node_crypto = require("node:crypto");
473
+ var import_node_fs = require("node:fs");
474
+ var import_node_path = require("node:path");
475
+ var APP_RULES_FILE = "AGENTS.md";
476
+ var APP_SKILLS_DIR = "skills";
477
+ var APP_SKILL_FILE = "SKILL.md";
478
+ function parseSkillFrontmatter(text) {
479
+ const lines = text.split(`
480
+ `);
481
+ if (lines[0]?.trim() !== "---")
482
+ return {};
483
+ const out = {};
484
+ for (let i = 1;i < lines.length; i += 1) {
485
+ const line = lines[i] ?? "";
486
+ if (line.trim() === "---")
487
+ break;
488
+ const cut = line.indexOf(":");
489
+ if (cut <= 0)
490
+ continue;
491
+ const key = line.slice(0, cut).trim().toLowerCase();
492
+ if (key !== "name" && key !== "description")
493
+ continue;
494
+ const value = line.slice(cut + 1).trim().replace(/^['"]|['"]$/g, "");
495
+ if (value)
496
+ out[key] = value;
497
+ }
498
+ return out;
499
+ }
500
+ function sha256Hex(text) {
501
+ return import_node_crypto.createHash("sha256").update(text, "utf8").digest("hex");
502
+ }
503
+ function readTextFile(path) {
504
+ try {
505
+ if (!import_node_fs.statSync(path).isFile())
506
+ return null;
507
+ const text = import_node_fs.readFileSync(path, "utf8");
508
+ return text.trim() ? text : null;
509
+ } catch {
510
+ return null;
511
+ }
512
+ }
513
+ function readAppResourcesDir(directory) {
514
+ const warnings = [];
515
+ if (!import_node_path.isAbsolute(directory))
516
+ return { directoryReadable: false, rules: null, skills: [], warnings: ["资源目录必须是本机绝对路径"] };
517
+ let directoryReadable = false;
518
+ try {
519
+ directoryReadable = import_node_fs.statSync(directory).isDirectory();
520
+ } catch {
521
+ directoryReadable = false;
522
+ }
523
+ if (!directoryReadable) {
524
+ return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
525
+ }
526
+ let rules = null;
527
+ const rulesText = readTextFile(import_node_path.join(directory, APP_RULES_FILE));
528
+ if (rulesText === null) {
529
+ warnings.push(`缺常驻规则: ${APP_RULES_FILE}`);
530
+ } else {
531
+ rules = { chars: rulesText.length, digest: sha256Hex(`app-rules-v1
532
+ ${rulesText}`) };
533
+ }
534
+ const skills = [];
535
+ const skillsRoot = import_node_path.join(directory, APP_SKILLS_DIR);
536
+ let skillNames = [];
537
+ try {
538
+ if (import_node_fs.statSync(skillsRoot).isDirectory()) {
539
+ skillNames = import_node_fs.readdirSync(skillsRoot).filter((name) => {
540
+ try {
541
+ return import_node_fs.statSync(import_node_path.join(skillsRoot, name)).isDirectory();
542
+ } catch {
543
+ return false;
544
+ }
545
+ });
546
+ }
547
+ } catch {
548
+ skillNames = [];
549
+ }
550
+ for (const name of skillNames.sort()) {
551
+ const rel = `${APP_SKILLS_DIR}/${name}/${APP_SKILL_FILE}`;
552
+ const text = readTextFile(import_node_path.join(directory, rel));
553
+ if (text === null) {
554
+ warnings.push(`技能缺正文已跳过: ${rel}`);
555
+ continue;
556
+ }
557
+ const front = parseSkillFrontmatter(text);
558
+ const skillName = front.name || name;
559
+ if (skills.some((s) => s.name === skillName)) {
560
+ warnings.push(`技能重名已跳过(保留首个): ${skillName}`);
561
+ continue;
562
+ }
563
+ const description = front.description || "";
564
+ skills.push({
565
+ name: skillName,
566
+ description,
567
+ path: rel,
568
+ chars: text.length,
569
+ digest: sha256Hex(`app-skill-v1
570
+ ${skillName}
571
+ ${description}
572
+ ${text}`)
573
+ });
574
+ }
575
+ return { directoryReadable: true, rules, skills, warnings };
576
+ }
577
+ function digestAppResources(load) {
578
+ if (!load.rules)
579
+ return null;
580
+ const skillPart = load.skills.map((s) => `${s.name}:${s.digest}`).join(`
581
+ `);
582
+ return sha256Hex(`app-resources-v1
583
+ ${load.rules.digest}
584
+ ${skillPart}`);
585
+ }
586
+ function readAppRulesText(directory) {
587
+ return readTextFile(import_node_path.join(directory, APP_RULES_FILE));
588
+ }
589
+ function isAbsolutePathLike(path) {
590
+ return import_node_path.isAbsolute(path);
591
+ }
592
+
593
+ // src/resources/session-config.ts
594
+ async function createSessionConfigHome(runtime, resources) {
595
+ if (!import_node_path2.isAbsolute(resources))
596
+ throw new Error("Resources must be an absolute path");
597
+ const id = runtime === "cursor" ? "cursor-cli" : runtime;
598
+ const supported = ["agy", "codex-acp", "claude", "gemini", "copilot", "cursor-cli", "opencode", "opencode-v2"];
599
+ if (!supported.includes(id))
600
+ throw new Error("Session configuration home is not verified for runtime: " + runtime);
601
+ const text = readAppRulesText(resources);
602
+ if (!text)
603
+ throw new Error("Session configuration requires nonempty AGENTS.md");
604
+ const parent = import_node_path2.resolve(import_node_os.tmpdir());
605
+ const directory = await import_promises.mkdtemp(import_node_path2.join(parent, "acp-session-config-"));
606
+ const checkRoot = () => {
607
+ 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-"))
608
+ throw new Error("Unsafe configuration cleanup target");
609
+ };
610
+ const dispose = async () => {
611
+ checkRoot();
612
+ let failure;
613
+ for (let i = 0;i < 30; i++) {
614
+ try {
615
+ await import_promises.rm(directory, { recursive: true, force: true });
616
+ return;
617
+ } catch (error) {
618
+ failure = error;
619
+ await new Promise((r) => setTimeout(r, 100));
620
+ }
621
+ }
622
+ throw failure;
623
+ };
624
+ try {
625
+ const config = import_node_path2.join(directory, "config");
626
+ await import_promises.mkdir(config, { recursive: true, mode: 448 });
627
+ let env;
628
+ let rulesFile;
629
+ let skillsRoot = import_node_path2.join(config, "skills");
630
+ let nativeRules = true;
631
+ if (id === "agy") {
632
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
633
+ env = { AGY_ACP_RESOURCES_DIR: config };
634
+ nativeRules = false;
635
+ } else if (id === "gemini") {
636
+ const root = import_node_path2.join(directory, "home", ".gemini");
637
+ await import_promises.mkdir(root, { recursive: true, mode: 448 });
638
+ rulesFile = import_node_path2.join(root, "GEMINI.md");
639
+ skillsRoot = import_node_path2.join(root, "skills");
640
+ env = { GEMINI_CLI_HOME: import_node_path2.join(directory, "home") };
641
+ } else if (id === "claude") {
642
+ rulesFile = import_node_path2.join(config, "CLAUDE.md");
643
+ env = { CLAUDE_CONFIG_DIR: config };
644
+ } else if (id === "codex-acp") {
645
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
646
+ env = { CODEX_HOME: config };
647
+ } else if (id === "copilot") {
648
+ rulesFile = import_node_path2.join(config, "copilot-instructions.md");
649
+ env = { COPILOT_HOME: config, COPILOT_CUSTOM_INSTRUCTIONS_DIRS: config, COPILOT_SKILLS_DIRS: skillsRoot };
650
+ await import_promises.writeFile(import_node_path2.join(config, "AGENTS.md"), text, { mode: 384 });
651
+ } else if (id === "cursor-cli") {
652
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
653
+ env = { CURSOR_CONFIG_DIR: config };
654
+ nativeRules = false;
655
+ } else {
656
+ const root = import_node_path2.join(directory, "xdg-config", "opencode");
657
+ await import_promises.mkdir(root, { recursive: true, mode: 448 });
658
+ rulesFile = import_node_path2.join(root, "AGENTS.md");
659
+ skillsRoot = import_node_path2.join(root, "skills");
660
+ 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") };
661
+ if (id === "opencode")
662
+ env.OPENCODE_CONFIG_DIR = root;
663
+ const skills = id === "opencode" ? { paths: [skillsRoot] } : [skillsRoot];
664
+ await import_promises.writeFile(import_node_path2.join(root, "opencode.json"), JSON.stringify({ instructions: [rulesFile], skills }), { mode: 384 });
665
+ }
666
+ await import_promises.writeFile(rulesFile, text, { mode: 384 });
667
+ const input = import_node_path2.join(resources, "skills");
668
+ try {
669
+ const info = await import_promises.lstat(input);
670
+ if (info.isSymbolicLink() || !info.isDirectory())
671
+ throw new Error("Skill root must be a regular directory");
672
+ const physical = await import_promises.realpath(input);
673
+ const copy = async (from, to) => {
674
+ await import_promises.mkdir(to, { recursive: true, mode: 448 });
675
+ for (const entry of await import_promises.readdir(from, { withFileTypes: true })) {
676
+ const src = import_node_path2.join(from, entry.name);
677
+ const info = await import_promises.lstat(src);
678
+ if (info.isSymbolicLink())
679
+ throw new Error("Skill symlink is not allowed");
680
+ const actual = await import_promises.realpath(src);
681
+ const rel = import_node_path2.relative(physical, actual);
682
+ if (rel.startsWith(".." + import_node_path2.sep) || rel === ".." || import_node_path2.isAbsolute(rel))
683
+ throw new Error("Skill path escapes resources");
684
+ if (info.isDirectory())
685
+ await copy(src, import_node_path2.join(to, entry.name));
686
+ else if (info.isFile() && entry.name.toLowerCase().endsWith(".md"))
687
+ await import_promises.writeFile(import_node_path2.join(to, entry.name), await import_promises.readFile(src), { mode: 384 });
688
+ }
689
+ };
690
+ await copy(input, skillsRoot);
691
+ } catch (error) {
692
+ if (error.code !== "ENOENT" || import_node_fs2.existsSync(input))
693
+ throw error;
694
+ }
695
+ return { directory, env, rulesFile, nativeRules, dispose };
696
+ } catch (error) {
697
+ await dispose();
698
+ throw error;
699
+ }
700
+ }
701
+
367
702
  // src/session/available-commands.ts
368
703
  function normalizeCommand(raw) {
369
704
  if (!raw || typeof raw !== "object")
@@ -611,15 +946,15 @@ class QuotaCache {
611
946
  var import_sdk4 = require("@agentclientprotocol/sdk");
612
947
 
613
948
  // src/runtimes/codex/quota.ts
614
- var import_node_fs2 = require("node:fs");
615
- var import_node_path2 = require("node:path");
949
+ var import_node_fs4 = require("node:fs");
950
+ var import_node_path4 = require("node:path");
616
951
  var import_node_child_process = require("node:child_process");
617
952
  var import_node_readline = __toESM(require("node:readline"), 1);
618
953
 
619
954
  // 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");
955
+ var import_node_fs3 = require("node:fs");
956
+ var import_node_os2 = require("node:os");
957
+ var import_node_path3 = require("node:path");
623
958
  function emptyAcpAuthPreflight() {
624
959
  return {
625
960
  codexHome: "",
@@ -636,12 +971,12 @@ function resolveCodexHome() {
636
971
  const fromEnv = process.env.CODEX_HOME?.trim();
637
972
  if (fromEnv)
638
973
  return fromEnv;
639
- return import_node_path.join(import_node_os.homedir(), ".codex");
974
+ return import_node_path3.join(import_node_os2.homedir(), ".codex");
640
975
  }
641
976
  function probeCodexAuth() {
642
977
  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"));
978
+ const hasCodexHome = import_node_fs3.existsSync(codexHome);
979
+ const hasAuthFile = import_node_fs3.existsSync(import_node_path3.join(codexHome, "auth.json"));
645
980
  const hasApiKeyEnv = Boolean(process.env.CODEX_API_KEY?.trim() || process.env.OPENAI_API_KEY?.trim());
646
981
  return {
647
982
  codexHome,
@@ -691,7 +1026,7 @@ async function queryCodexAppServer(timeoutMs = 1e4) {
691
1026
  };
692
1027
  timer = setTimeout(() => cleanup(null), timeoutMs);
693
1028
  try {
694
- const cmd = process.platform === "win32" ? "codex" : import_node_fs2.existsSync("/mnt/c/Users") ? "codex.exe" : "codex";
1029
+ const cmd = process.platform === "win32" ? "codex" : import_node_fs4.existsSync("/mnt/c/Users") ? "codex.exe" : "codex";
695
1030
  proc = import_node_child_process.spawn(cmd, ["app-server"], {
696
1031
  stdio: ["pipe", "pipe", "pipe"],
697
1032
  shell: process.platform === "win32",
@@ -762,13 +1097,13 @@ function formatEpochTime(epochSeconds) {
762
1097
  }
763
1098
  async function probeCodexQuota(options) {
764
1099
  const codexHome = resolveCodexHome();
765
- const authPath = import_node_path2.join(codexHome, "auth.json");
1100
+ const authPath = import_node_path4.join(codexHome, "auth.json");
766
1101
  let accountEmail;
767
1102
  let accountPlan = "Codex Free / Local";
768
1103
  let isLoggedIn = false;
769
- if (import_node_fs2.existsSync(authPath)) {
1104
+ if (import_node_fs4.existsSync(authPath)) {
770
1105
  try {
771
- const authData = JSON.parse(import_node_fs2.readFileSync(authPath, "utf8"));
1106
+ const authData = JSON.parse(import_node_fs4.readFileSync(authPath, "utf8"));
772
1107
  if (authData.OPENAI_API_KEY) {
773
1108
  isLoggedIn = true;
774
1109
  accountPlan = "OpenAI API Key";
@@ -859,8 +1194,92 @@ async function probeCodexQuota(options) {
859
1194
  }
860
1195
 
861
1196
  // src/runtimes/codex/index.ts
862
- var import_promises2 = require("node:fs/promises");
863
- var import_node_path5 = require("node:path");
1197
+ var import_promises3 = require("node:fs/promises");
1198
+ var import_node_path7 = require("node:path");
1199
+ var import_node_os4 = require("node:os");
1200
+ var import_node_fs6 = require("node:fs");
1201
+ var import_node_crypto2 = require("node:crypto");
1202
+
1203
+ // src/resources/config-text.ts
1204
+ function mergeCodexConfigJson(input) {
1205
+ const block = (input.hostBlock ?? "").trim();
1206
+ if (!block)
1207
+ return { ok: false, reason: "empty-block" };
1208
+ const raw = (input.existingRaw ?? "").trim();
1209
+ if (!raw) {
1210
+ return { ok: true, json: JSON.stringify({ developer_instructions: block }), preservedUserInstructions: false };
1211
+ }
1212
+ let parsed;
1213
+ try {
1214
+ parsed = JSON.parse(raw);
1215
+ } catch {
1216
+ return { ok: false, reason: "invalid-json" };
1217
+ }
1218
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1219
+ return { ok: false, reason: "invalid-json" };
1220
+ }
1221
+ const merged = { ...parsed };
1222
+ const existing = merged["developer_instructions"];
1223
+ if (existing === undefined) {
1224
+ merged["developer_instructions"] = block;
1225
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: false };
1226
+ }
1227
+ if (typeof existing !== "string") {
1228
+ return { ok: false, reason: "conflicting-value" };
1229
+ }
1230
+ const kept = existing.trim();
1231
+ merged["developer_instructions"] = kept ? `${block}
1232
+
1233
+ ${kept}` : block;
1234
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: kept !== "" };
1235
+ }
1236
+ function mergeConfigTomlPreserving(input) {
1237
+ const block = (input.replacementBlock ?? "").trim() ? `${input.replacementBlock.trim()}
1238
+ ` : "";
1239
+ if (!input.existingText || !input.existingText.trim())
1240
+ return block;
1241
+ if (/"""|'''/.test(input.existingText) || /^\s*\[.*["'].*\]|^\s*\[\[|^\s*["'](?:model|model_provider)["']\s*=/m.test(input.existingText)) {
1242
+ throw new Error("复杂 TOML 配置需要结构化合并,已保留原文件");
1243
+ }
1244
+ const topKeys = new Set(input.managedTopKeys);
1245
+ const tables = new Set(input.managedTables);
1246
+ const out = [];
1247
+ let inManagedTable = false;
1248
+ let inAnyTable = false;
1249
+ for (const line of input.existingText.split(`
1250
+ `)) {
1251
+ const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(line)?.[1]?.trim() ?? null;
1252
+ if (header !== null) {
1253
+ inAnyTable = true;
1254
+ inManagedTable = tables.has(header);
1255
+ if (!inManagedTable)
1256
+ out.push(line);
1257
+ continue;
1258
+ }
1259
+ if (inManagedTable)
1260
+ continue;
1261
+ if (!inAnyTable) {
1262
+ const key = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1];
1263
+ if (key && topKeys.has(key))
1264
+ continue;
1265
+ }
1266
+ out.push(line);
1267
+ }
1268
+ const kept = out.join(`
1269
+ `).trim();
1270
+ if (!kept)
1271
+ return block;
1272
+ const tableAt = block.search(/^\s*\[/m);
1273
+ if (tableAt < 0)
1274
+ return block + `
1275
+ ` + kept + `
1276
+ `;
1277
+ return block.slice(0, tableAt).trimEnd() + `
1278
+
1279
+ ` + kept + `
1280
+
1281
+ ` + block.slice(tableAt);
1282
+ }
864
1283
 
865
1284
  // src/runtimes/codex/codex-provider-home.ts
866
1285
  var INKDOWN_PROVIDER_ID = "inkdown-custom";
@@ -892,13 +1311,13 @@ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
892
1311
  }
893
1312
 
894
1313
  // 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");
1314
+ var import_promises2 = require("node:fs/promises");
1315
+ var import_node_fs5 = require("node:fs");
1316
+ var import_node_path6 = require("node:path");
898
1317
 
899
1318
  // src/client/acp-paths.ts
900
- var import_node_os2 = require("node:os");
901
- var import_node_path3 = require("node:path");
1319
+ var import_node_os3 = require("node:os");
1320
+ var import_node_path5 = require("node:path");
902
1321
  function getDefaultAgentDataDir() {
903
1322
  if (process.env.INKDOWN_DATA_DIR) {
904
1323
  return process.env.INKDOWN_DATA_DIR;
@@ -907,20 +1326,20 @@ function getDefaultAgentDataDir() {
907
1326
  return process.env.ACP_DATA_DIR;
908
1327
  }
909
1328
  if (process.platform === "win32") {
910
- return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path3.join(import_node_os2.homedir(), "AppData", "Local", "inkdown");
1329
+ return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path5.join(import_node_os3.homedir(), "AppData", "Local", "inkdown");
911
1330
  }
912
1331
  if (process.platform === "darwin") {
913
- return import_node_path3.join(import_node_os2.homedir(), "Library", "Application Support", "inkdown");
1332
+ return import_node_path5.join(import_node_os3.homedir(), "Library", "Application Support", "inkdown");
914
1333
  }
915
- return process.env.XDG_DATA_HOME || import_node_path3.join(import_node_os2.homedir(), ".local", "share", "inkdown");
1334
+ return process.env.XDG_DATA_HOME || import_node_path5.join(import_node_os3.homedir(), ".local", "share", "inkdown");
916
1335
  }
917
1336
 
918
1337
  // src/runtimes/codex/codex-provider.ts
919
1338
  function providerFilePath(dir) {
920
- return import_node_path4.join(dir, "agent", "provider.json");
1339
+ return import_node_path6.join(dir, "agent", "provider.json");
921
1340
  }
922
1341
  function providerHomePath(dir) {
923
- return import_node_path4.join(dir, "agent", "codex-home");
1342
+ return import_node_path6.join(dir, "agent", "codex-home");
924
1343
  }
925
1344
  function toStatus(stored) {
926
1345
  if (!stored)
@@ -946,10 +1365,10 @@ function validate(payload) {
946
1365
  }
947
1366
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
948
1367
  const file = providerFilePath(dir);
949
- if (!import_node_fs3.existsSync(file))
1368
+ if (!import_node_fs5.existsSync(file))
950
1369
  return null;
951
1370
  try {
952
- const raw = JSON.parse(await import_promises.readFile(file, "utf8"));
1371
+ const raw = JSON.parse(await import_promises2.readFile(file, "utf8"));
953
1372
  if (typeof raw.baseUrl !== "string" || typeof raw.model !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
954
1373
  return null;
955
1374
  }
@@ -975,7 +1394,7 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
975
1394
  const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
976
1395
  if (!apiKey)
977
1396
  return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
978
- await import_promises.mkdir(import_node_path4.join(dir, "agent"), { recursive: true });
1397
+ await import_promises2.mkdir(import_node_path6.join(dir, "agent"), { recursive: true });
979
1398
  const stored = {
980
1399
  name: payload.name?.trim() || undefined,
981
1400
  baseUrl: payload.baseUrl.trim(),
@@ -983,11 +1402,11 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
983
1402
  apiKey,
984
1403
  wireApi: payload.wireApi === "responses" ? "responses" : "chat"
985
1404
  };
986
- await import_promises.writeFile(file, JSON.stringify(stored, null, 2), "utf8");
1405
+ await import_promises2.writeFile(file, JSON.stringify(stored, null, 2), "utf8");
987
1406
  return ok(toStatus(stored));
988
1407
  }
989
1408
  async function clearAcpProvider(dir = getDefaultAgentDataDir()) {
990
- await import_promises.rm(providerFilePath(dir), { force: true });
1409
+ await import_promises2.rm(providerFilePath(dir), { force: true });
991
1410
  return ok(undefined);
992
1411
  }
993
1412
  function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
@@ -997,8 +1416,20 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
997
1416
  // src/runtimes/codex/index.ts
998
1417
  async function provisionCustomProviderCodexHome(provider, codexHome) {
999
1418
  try {
1000
- await import_promises2.mkdir(codexHome, { recursive: true });
1001
- await import_promises2.writeFile(import_node_path5.join(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
1419
+ await import_promises3.mkdir(codexHome, { recursive: true });
1420
+ let existing = null;
1421
+ try {
1422
+ existing = await import_promises3.readFile(import_node_path7.join(codexHome, "config.toml"), "utf8");
1423
+ } catch (error) {
1424
+ if (error.code !== "ENOENT")
1425
+ throw error;
1426
+ }
1427
+ await import_promises3.writeFile(import_node_path7.join(codexHome, "config.toml"), mergeConfigTomlPreserving({
1428
+ existingText: existing,
1429
+ managedTopKeys: ["model", "model_provider"],
1430
+ managedTables: [`model_providers.${INKDOWN_PROVIDER_ID}`],
1431
+ replacementBlock: buildCustomProviderConfigToml(provider)
1432
+ }), "utf8");
1002
1433
  return true;
1003
1434
  } catch (error) {
1004
1435
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -1008,6 +1439,78 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
1008
1439
  var codexAdapter = {
1009
1440
  id: "codex-acp",
1010
1441
  probeQuota: async (options) => probeCodexQuota(options),
1442
+ supportedBridgeVersions: ["2.2.2"],
1443
+ prepareAppResources: async ({ directory, workspaceRoot, env: overrideEnv }) => {
1444
+ const load = readAppResourcesDir(directory);
1445
+ const skillsFound = load.skills.map((s) => s.name);
1446
+ const rulesText = readAppRulesText(directory);
1447
+ if (!rulesText) {
1448
+ return {
1449
+ report: {
1450
+ rulesApplied: false,
1451
+ rulesChars: 0,
1452
+ profileDigest: null,
1453
+ skillsFound,
1454
+ reason: "rules-missing"
1455
+ }
1456
+ };
1457
+ }
1458
+ const env = { ...process.env, ...overrideEnv };
1459
+ const notApplied = (reason) => ({ report: {
1460
+ rulesApplied: false,
1461
+ rulesPrepared: false,
1462
+ skillsApplied: false,
1463
+ rulesChars: rulesText.length,
1464
+ profileDigest: digestAppResources(load),
1465
+ skillsFound,
1466
+ reason
1467
+ } });
1468
+ if (!load.directoryReadable)
1469
+ return notApplied("invalid-resource-directory");
1470
+ if (env.CODEX_PATH)
1471
+ return notApplied("execution-not-verified");
1472
+ const codexHome = env.CODEX_HOME || import_node_path7.join(import_node_os4.homedir(), ".codex");
1473
+ try {
1474
+ await import_promises3.readFile(import_node_path7.join(codexHome, "config.toml"));
1475
+ return notApplied("effective-config-not-verified");
1476
+ } catch (error) {
1477
+ if (error.code !== "ENOENT")
1478
+ return notApplied("effective-config-not-verified");
1479
+ }
1480
+ for (let dir = workspaceRoot;dir; ) {
1481
+ if (import_node_fs6.existsSync(import_node_path7.join(dir, ".codex", "config.toml")))
1482
+ return notApplied("effective-config-not-verified");
1483
+ if (import_node_fs6.existsSync(import_node_path7.join(dir, ".git")))
1484
+ break;
1485
+ const parent = import_node_path7.dirname(dir);
1486
+ if (parent === dir)
1487
+ break;
1488
+ dir = parent;
1489
+ }
1490
+ const merged = mergeCodexConfigJson({ existingRaw: env["CODEX_CONFIG"], hostBlock: rulesText });
1491
+ if (!merged.ok) {
1492
+ return {
1493
+ report: {
1494
+ rulesApplied: false,
1495
+ rulesChars: rulesText.length,
1496
+ profileDigest: digestAppResources(load),
1497
+ skillsFound,
1498
+ reason: merged.reason === "invalid-json" ? "invalid-codex-config" : "conflicting-codex-config"
1499
+ }
1500
+ };
1501
+ }
1502
+ return {
1503
+ env: { CODEX_CONFIG: merged.json },
1504
+ report: {
1505
+ rulesApplied: false,
1506
+ rulesPrepared: true,
1507
+ skillsApplied: false,
1508
+ rulesChars: rulesText.length,
1509
+ profileDigest: import_node_crypto2.createHash("sha256").update(JSON.stringify([digestAppResources(load), codexHome, workspaceRoot, merged.json])).digest("hex"),
1510
+ skillsFound
1511
+ }
1512
+ };
1513
+ },
1011
1514
  probeAuth: () => {
1012
1515
  return probeCodexAuth();
1013
1516
  },
@@ -1024,11 +1527,84 @@ var codexAdapter = {
1024
1527
  }
1025
1528
  };
1026
1529
 
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");
1530
+ // src/resources/runtime-bindings.ts
1531
+ var import_node_path8 = require("node:path");
1031
1532
  var import_node_child_process2 = require("node:child_process");
1533
+ var import_node_util = require("node:util");
1534
+ var APP_RESOURCE_CAPABILITIES = {
1535
+ "codex-acp": { entry: "CODEX_CONFIG", strategy: "native-overlay", configHome: "CODEX_HOME" },
1536
+ opencode: { entry: "OPENCODE_CONFIG_CONTENT", strategy: "native-overlay", configHome: "OPENCODE_CONFIG_DIR" },
1537
+ "opencode-v2": { entry: null, strategy: "compatibility", configHome: null },
1538
+ claude: { entry: "_meta.systemPrompt + _meta.claudeCode.options.plugins", strategy: "native-session", configHome: "CLAUDE_CONFIG_DIR" },
1539
+ gemini: { entry: null, strategy: "compatibility", configHome: "GEMINI_CLI_HOME" },
1540
+ copilot: { entry: null, strategy: "compatibility", configHome: "COPILOT_HOME", candidateEntry: "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" },
1541
+ "cursor-cli": { entry: null, strategy: "compatibility", configHome: "CURSOR_CONFIG_DIR" },
1542
+ agy: { entry: "_meta.appResources.directory", strategy: "native-session", configHome: null },
1543
+ deepseek: { entry: null, strategy: "compatibility", configHome: null }
1544
+ };
1545
+ function prepareCompatibilityResources(directory, reason) {
1546
+ const load = readAppResourcesDir(directory);
1547
+ return { report: {
1548
+ rulesApplied: false,
1549
+ rulesPrepared: false,
1550
+ skillsApplied: false,
1551
+ rulesChars: load.rules?.chars ?? 0,
1552
+ profileDigest: digestAppResources(load),
1553
+ skillsFound: load.skills.map((s) => s.name),
1554
+ reason
1555
+ } };
1556
+ }
1557
+ function mergeOpenCodeAppConfig(raw, directory) {
1558
+ const value = raw?.trim() ? JSON.parse(raw) : {};
1559
+ if (!value || typeof value !== "object" || Array.isArray(value))
1560
+ throw new Error("invalid-opencode-config");
1561
+ const config = value;
1562
+ if (config.instructions !== undefined && (!Array.isArray(config.instructions) || config.instructions.some((v) => typeof v !== "string")))
1563
+ throw new Error("invalid-opencode-instructions");
1564
+ if (config.skills !== undefined && (!config.skills || typeof config.skills !== "object" || Array.isArray(config.skills)))
1565
+ throw new Error("invalid-opencode-skills");
1566
+ const skills = config.skills ?? {};
1567
+ if (skills.paths !== undefined && (!Array.isArray(skills.paths) || skills.paths.some((v) => typeof v !== "string")))
1568
+ throw new Error("invalid-opencode-skill-paths");
1569
+ return JSON.stringify({
1570
+ ...config,
1571
+ instructions: [...new Set([...config.instructions ?? [], import_node_path8.join(directory, "AGENTS.md")])],
1572
+ skills: { ...skills, paths: [...new Set([...skills.paths ?? [], import_node_path8.join(directory, "skills")])] }
1573
+ });
1574
+ }
1575
+ async function prepareOpenCodeResources(input) {
1576
+ const prep = prepareCompatibilityResources(input.directory, "native-entry-not-verified");
1577
+ if (!input.command || !readAppRulesText(input.directory))
1578
+ return prep;
1579
+ try {
1580
+ const { stdout } = await import_node_util.promisify(import_node_child_process2.execFile)(input.command, ["--version"], { env: input.env, timeout: 8000, windowsHide: true });
1581
+ if (stdout.trim() !== "1.18.35")
1582
+ return prep;
1583
+ const json = mergeOpenCodeAppConfig(input.env?.OPENCODE_CONFIG_CONTENT, input.directory);
1584
+ return { env: { OPENCODE_CONFIG_CONTENT: json }, report: { ...prep.report, rulesPrepared: true, reason: undefined } };
1585
+ } catch {
1586
+ return { ...prep, report: { ...prep.report, reason: "native-config-prepare-failed" } };
1587
+ }
1588
+ }
1589
+ function prepareClaudeResources(directory) {
1590
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
1591
+ return { ...prep, report: { ...prep.report, rulesPrepared: !!readAppRulesText(directory) } };
1592
+ }
1593
+ function claudeResourceSessionMeta(directory) {
1594
+ const text = readAppRulesText(directory);
1595
+ if (!text)
1596
+ return;
1597
+ return {
1598
+ systemPrompt: { type: "preset", preset: "claude_code", append: text },
1599
+ claudeCode: { options: { plugins: [{ type: "local", path: directory }] } }
1600
+ };
1601
+ }
1602
+
1603
+ // src/runtimes/claude/quota.ts
1604
+ var import_node_fs7 = require("node:fs");
1605
+ var import_node_os5 = require("node:os");
1606
+ var import_node_path9 = require("node:path");
1607
+ var import_node_child_process3 = require("node:child_process");
1032
1608
  var cachedClaudeAuth = null;
1033
1609
  async function queryClaudeAuthStatus(timeoutMs = 1200) {
1034
1610
  if (cachedClaudeAuth && Date.now() - cachedClaudeAuth.time < 30000) {
@@ -1036,7 +1612,7 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
1036
1612
  }
1037
1613
  return new Promise((resolve) => {
1038
1614
  try {
1039
- import_node_child_process2.execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
1615
+ import_node_child_process3.execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
1040
1616
  if (!stdout)
1041
1617
  return resolve(null);
1042
1618
  try {
@@ -1054,15 +1630,15 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
1054
1630
  }
1055
1631
  async function probeClaudeQuota(options) {
1056
1632
  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");
1633
+ const claudeJsonPath = import_node_path9.join(import_node_os5.homedir(), ".claude.json");
1634
+ const credsPath = import_node_path9.join(claudeHome, ".credentials.json");
1059
1635
  let isLoggedIn = false;
1060
1636
  let isBanned = false;
1061
1637
  let accountEmail;
1062
1638
  let plan = "Claude Free / Default";
1063
- if (import_node_fs4.existsSync(claudeJsonPath)) {
1639
+ if (import_node_fs7.existsSync(claudeJsonPath)) {
1064
1640
  try {
1065
- const data = JSON.parse(import_node_fs4.readFileSync(claudeJsonPath, "utf8"));
1641
+ const data = JSON.parse(import_node_fs7.readFileSync(claudeJsonPath, "utf8"));
1066
1642
  if (data.oauthAccount) {
1067
1643
  isLoggedIn = true;
1068
1644
  accountEmail = data.oauthAccount.emailAddress;
@@ -1073,9 +1649,9 @@ async function probeClaudeQuota(options) {
1073
1649
  }
1074
1650
  } catch {}
1075
1651
  }
1076
- if (import_node_fs4.existsSync(credsPath)) {
1652
+ if (import_node_fs7.existsSync(credsPath)) {
1077
1653
  try {
1078
- const creds = JSON.parse(import_node_fs4.readFileSync(credsPath, "utf8"));
1654
+ const creds = JSON.parse(import_node_fs7.readFileSync(credsPath, "utf8"));
1079
1655
  if (creds.accessToken || creds.sessionKey)
1080
1656
  isLoggedIn = true;
1081
1657
  } catch {}
@@ -1127,19 +1703,19 @@ async function probeClaudeQuota(options) {
1127
1703
  }
1128
1704
 
1129
1705
  // 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");
1706
+ var import_node_fs8 = require("node:fs");
1707
+ var import_node_os6 = require("node:os");
1708
+ var import_node_path10 = require("node:path");
1133
1709
  function resolveClaudeHome() {
1134
1710
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
1135
1711
  if (fromEnv)
1136
1712
  return fromEnv;
1137
- return import_node_path7.join(import_node_os4.homedir(), ".claude");
1713
+ return import_node_path10.join(import_node_os6.homedir(), ".claude");
1138
1714
  }
1139
1715
  function probeClaudeAuth() {
1140
1716
  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"));
1717
+ const hasCodexHome = import_node_fs8.existsSync(claudeHome);
1718
+ 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
1719
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
1144
1720
  return {
1145
1721
  codexHome: claudeHome,
@@ -1151,6 +1727,9 @@ function probeClaudeAuth() {
1151
1727
  }
1152
1728
  var claudeAdapter = {
1153
1729
  id: "claude",
1730
+ supportedBridgeVersions: ["0.91.0"],
1731
+ prepareAppResources: async ({ directory }) => prepareClaudeResources(directory),
1732
+ appResourceSessionMeta: claudeResourceSessionMeta,
1154
1733
  probeAuth: () => probeClaudeAuth(),
1155
1734
  probeQuota: async (options) => probeClaudeQuota(options),
1156
1735
  orderAuthMethods: (methods) => methods,
@@ -1158,16 +1737,16 @@ var claudeAdapter = {
1158
1737
  };
1159
1738
 
1160
1739
  // 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");
1740
+ var import_node_fs9 = require("node:fs");
1741
+ var import_node_os7 = require("node:os");
1742
+ var import_node_path11 = require("node:path");
1164
1743
  function resolveGeminiHome() {
1165
- return import_node_path8.join(import_node_os5.homedir(), ".gemini");
1744
+ return import_node_path11.join(import_node_os7.homedir(), ".gemini");
1166
1745
  }
1167
1746
  function probeGeminiAuth() {
1168
1747
  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());
1748
+ const hasCodexHome = import_node_fs9.existsSync(geminiHome);
1749
+ const hasAuthFile = import_node_fs9.existsSync(import_node_path11.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
1171
1750
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
1172
1751
  return {
1173
1752
  codexHome: geminiHome,
@@ -1179,24 +1758,25 @@ function probeGeminiAuth() {
1179
1758
  }
1180
1759
  var geminiAdapter = {
1181
1760
  id: "gemini",
1761
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-would-isolate-auth"),
1182
1762
  probeAuth: () => probeGeminiAuth(),
1183
1763
  orderAuthMethods: (methods) => methods,
1184
1764
  canSkipInteractiveAuth: () => false
1185
1765
  };
1186
1766
 
1187
1767
  // 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");
1768
+ var import_node_fs10 = require("node:fs");
1769
+ var import_node_os8 = require("node:os");
1770
+ var import_node_path12 = require("node:path");
1191
1771
  function resolveCopilotHome() {
1192
1772
  const fromEnv = process.env.COPILOT_HOME?.trim();
1193
1773
  if (fromEnv)
1194
1774
  return fromEnv;
1195
- return import_node_path9.join(import_node_os6.homedir(), ".copilot");
1775
+ return import_node_path12.join(import_node_os8.homedir(), ".copilot");
1196
1776
  }
1197
1777
  function hasCopilotLogin(home) {
1198
1778
  try {
1199
- const raw = import_node_fs7.readFileSync(import_node_path9.join(home, "config.json"), "utf8");
1779
+ const raw = import_node_fs10.readFileSync(import_node_path12.join(home, "config.json"), "utf8");
1200
1780
  const parsed = JSON.parse(raw);
1201
1781
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
1202
1782
  } catch {
@@ -1205,7 +1785,7 @@ function hasCopilotLogin(home) {
1205
1785
  }
1206
1786
  function probeCopilotAuth() {
1207
1787
  const copilotHome = resolveCopilotHome();
1208
- const hasCodexHome = import_node_fs7.existsSync(copilotHome);
1788
+ const hasCodexHome = import_node_fs10.existsSync(copilotHome);
1209
1789
  const hasAuthFile = hasCopilotLogin(copilotHome);
1210
1790
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
1211
1791
  return {
@@ -1218,20 +1798,21 @@ function probeCopilotAuth() {
1218
1798
  }
1219
1799
  var copilotAdapter = {
1220
1800
  id: "copilot",
1801
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-entry-not-verified"),
1221
1802
  probeAuth: () => probeCopilotAuth(),
1222
1803
  orderAuthMethods: (methods) => methods,
1223
1804
  canSkipInteractiveAuth: () => false
1224
1805
  };
1225
1806
 
1226
1807
  // src/runtimes/opencode/quota.ts
1227
- var import_node_fs8 = require("node:fs");
1228
- var import_node_child_process3 = require("node:child_process");
1808
+ var import_node_fs11 = require("node:fs");
1809
+ var import_node_child_process4 = require("node:child_process");
1229
1810
  var os = __toESM(require("node:os"), 1);
1230
1811
  var path = __toESM(require("node:path"), 1);
1231
1812
  function resolveOpencodeAuthPath() {
1232
1813
  const candidates = resolveOpencodeAuthCandidates();
1233
1814
  for (const c of candidates) {
1234
- if (import_node_fs8.existsSync(c))
1815
+ if (import_node_fs11.existsSync(c))
1235
1816
  return c;
1236
1817
  }
1237
1818
  return candidates[0] ?? null;
@@ -1243,7 +1824,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
1243
1824
  }
1244
1825
  return new Promise((resolve) => {
1245
1826
  try {
1246
- import_node_child_process3.execFile("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1827
+ import_node_child_process4.execFile("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1247
1828
  if (!stdout)
1248
1829
  return resolve(null);
1249
1830
  try {
@@ -1262,7 +1843,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
1262
1843
  async function queryOpencodeAuthList(timeoutMs = 1200) {
1263
1844
  return new Promise((resolve) => {
1264
1845
  try {
1265
- import_node_child_process3.execFile("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1846
+ import_node_child_process4.execFile("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1266
1847
  if (!stdout)
1267
1848
  return resolve([]);
1268
1849
  const lines = stdout.split(`
@@ -1282,7 +1863,7 @@ function readLocalOpencodeCredentials() {
1282
1863
  path.join(home, ".config", "opencode", "opencode.db")
1283
1864
  ].filter(Boolean);
1284
1865
  for (const dbPath of dbPaths) {
1285
- if (!import_node_fs8.existsSync(dbPath))
1866
+ if (!import_node_fs11.existsSync(dbPath))
1286
1867
  continue;
1287
1868
  try {
1288
1869
  let rows = [];
@@ -1311,7 +1892,7 @@ function readLocalOpencodeCredentials() {
1311
1892
  }
1312
1893
  } catch {
1313
1894
  try {
1314
- const buf = import_node_fs8.readFileSync(dbPath, "utf8");
1895
+ const buf = import_node_fs11.readFileSync(dbPath, "utf8");
1315
1896
  const emailMatch = buf.match(/"email"\s*:\s*"([^"]+)"/);
1316
1897
  const tokenMatch = buf.match(/"access"\s*:\s*"(st_[a-zA-Z0-9_\\-]+)"/);
1317
1898
  const orgMatch = buf.match(/"orgID"\s*:\s*"(wrk_[a-zA-Z0-9_\\-]+)"/);
@@ -1435,9 +2016,9 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1435
2016
  let accountEmail = dbCreds.email;
1436
2017
  let accountName = dbCreds.name;
1437
2018
  let plan = "OpenCode Community";
1438
- if (authPath && import_node_fs8.existsSync(authPath)) {
2019
+ if (authPath && import_node_fs11.existsSync(authPath)) {
1439
2020
  try {
1440
- const data = JSON.parse(import_node_fs8.readFileSync(authPath, "utf8"));
2021
+ const data = JSON.parse(import_node_fs11.readFileSync(authPath, "utf8"));
1441
2022
  if (data && typeof data === "object") {
1442
2023
  const keys = Object.keys(data);
1443
2024
  if (keys.length > 0) {
@@ -1497,16 +2078,16 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1497
2078
  }
1498
2079
 
1499
2080
  // 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");
2081
+ var import_node_fs12 = require("node:fs");
2082
+ var import_node_os9 = require("node:os");
2083
+ var import_node_path13 = require("node:path");
1503
2084
  function pickEnv(env, key) {
1504
2085
  return env?.[key]?.trim() ?? "";
1505
2086
  }
1506
2087
  function resolveOpencodeAuthCandidates(overrides) {
1507
2088
  const platform = overrides?.platform ?? process.platform;
1508
2089
  const env = overrides?.env ?? process.env;
1509
- const home = overrides?.home ?? import_node_os7.homedir();
2090
+ const home = overrides?.home ?? import_node_os9.homedir();
1510
2091
  const seen = new Set;
1511
2092
  const out = [];
1512
2093
  const push = (p) => {
@@ -1517,27 +2098,27 @@ function resolveOpencodeAuthCandidates(overrides) {
1517
2098
  };
1518
2099
  const xdg = pickEnv(env, "XDG_DATA_HOME");
1519
2100
  if (xdg)
1520
- push(import_node_path10.join(xdg, "opencode", "auth.json"));
2101
+ push(import_node_path13.join(xdg, "opencode", "auth.json"));
1521
2102
  if (platform === "win32") {
1522
- const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path10.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
2103
+ const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path13.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
1523
2104
  if (localAppData)
1524
- push(import_node_path10.join(localAppData, "opencode", "auth.json"));
2105
+ push(import_node_path13.join(localAppData, "opencode", "auth.json"));
1525
2106
  const userProfile = pickEnv(env, "USERPROFILE") || home;
1526
2107
  if (userProfile)
1527
- push(import_node_path10.join(userProfile, ".local", "share", "opencode", "auth.json"));
2108
+ push(import_node_path13.join(userProfile, ".local", "share", "opencode", "auth.json"));
1528
2109
  } else if (home) {
1529
- push(import_node_path10.join(home, ".local", "share", "opencode", "auth.json"));
2110
+ push(import_node_path13.join(home, ".local", "share", "opencode", "auth.json"));
1530
2111
  }
1531
2112
  return out;
1532
2113
  }
1533
2114
  function resolveOpencodeAuthFile() {
1534
- return resolveOpencodeAuthCandidates()[0] ?? import_node_path10.join(import_node_os7.homedir(), ".local", "share", "opencode", "auth.json");
2115
+ return resolveOpencodeAuthCandidates()[0] ?? import_node_path13.join(import_node_os9.homedir(), ".local", "share", "opencode", "auth.json");
1535
2116
  }
1536
2117
  function isValidOpencodeAuthFile(authFile) {
1537
2118
  try {
1538
- if (!authFile || !import_node_fs9.existsSync(authFile))
2119
+ if (!authFile || !import_node_fs12.existsSync(authFile))
1539
2120
  return false;
1540
- const raw = import_node_fs9.readFileSync(authFile, "utf8").trim();
2121
+ const raw = import_node_fs12.readFileSync(authFile, "utf8").trim();
1541
2122
  if (!raw)
1542
2123
  return false;
1543
2124
  const parsed = JSON.parse(raw);
@@ -1555,7 +2136,7 @@ function probeOpencodeAuth(overrides) {
1555
2136
  for (const candidate of candidates) {
1556
2137
  let exists = false;
1557
2138
  try {
1558
- exists = import_node_fs9.existsSync(candidate);
2139
+ exists = import_node_fs12.existsSync(candidate);
1559
2140
  } catch {
1560
2141
  exists = false;
1561
2142
  }
@@ -1568,10 +2149,10 @@ function probeOpencodeAuth(overrides) {
1568
2149
  validFile = candidate;
1569
2150
  }
1570
2151
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
1571
- const authDir = import_node_path10.dirname(authFile);
2152
+ const authDir = import_node_path13.dirname(authFile);
1572
2153
  let hasCodexHome = false;
1573
2154
  try {
1574
- hasCodexHome = import_node_fs9.existsSync(authDir);
2155
+ hasCodexHome = import_node_fs12.existsSync(authDir);
1575
2156
  } catch {
1576
2157
  hasCodexHome = false;
1577
2158
  }
@@ -1586,6 +2167,8 @@ function probeOpencodeAuth(overrides) {
1586
2167
  }
1587
2168
  var opencodeAdapter = {
1588
2169
  id: "opencode",
2170
+ supportedBridgeVersions: ["1.18.35"],
2171
+ prepareAppResources: prepareOpenCodeResources,
1589
2172
  probeAuth: () => probeOpencodeAuth(),
1590
2173
  probeQuota: async () => probeOpencodeQuota(),
1591
2174
  orderAuthMethods: (methods) => methods,
@@ -1596,6 +2179,7 @@ var opencodeAdapter = {
1596
2179
  // src/runtimes/opencode-v2/index.ts
1597
2180
  var opencodeV2Adapter = {
1598
2181
  id: "opencode-v2",
2182
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
1599
2183
  probeAuth: () => probeOpencodeAuth(),
1600
2184
  orderAuthMethods: (methods) => methods,
1601
2185
  canSkipInteractiveAuth: () => false,
@@ -1626,28 +2210,28 @@ async function probeCursorQuota() {
1626
2210
  }
1627
2211
 
1628
2212
  // 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");
2213
+ var import_node_child_process5 = require("node:child_process");
2214
+ var import_node_fs13 = require("node:fs");
2215
+ var import_node_os10 = require("node:os");
2216
+ var import_node_path14 = require("node:path");
1633
2217
  function cursorLocalAppData(env) {
1634
2218
  const local = env.LOCALAPPDATA?.trim();
1635
2219
  if (local)
1636
2220
  return local;
1637
2221
  const profile = env.USERPROFILE?.trim();
1638
- return profile ? import_node_path11.join(profile, "AppData", "Local") : "";
2222
+ return profile ? import_node_path14.join(profile, "AppData", "Local") : "";
1639
2223
  }
1640
2224
  function isOnPath(command, env, platform) {
1641
2225
  const pathValue = env.PATH ?? env.Path ?? "";
1642
2226
  if (!pathValue.trim())
1643
2227
  return false;
1644
- const sep = platform === "win32" ? ";" : import_node_path11.delimiter;
2228
+ const sep = platform === "win32" ? ";" : import_node_path14.delimiter;
1645
2229
  for (const dir of pathValue.split(sep)) {
1646
2230
  const trimmed = dir.trim().replace(/^"|"$/g, "");
1647
2231
  if (!trimmed)
1648
2232
  continue;
1649
2233
  try {
1650
- if (import_node_fs10.existsSync(import_node_path11.join(trimmed, command)))
2234
+ if (import_node_fs13.existsSync(import_node_path14.join(trimmed, command)))
1651
2235
  return true;
1652
2236
  } catch {}
1653
2237
  }
@@ -1656,24 +2240,24 @@ function isOnPath(command, env, platform) {
1656
2240
  function resolveDirectCursorCommand(platform, env, home) {
1657
2241
  if (platform === "win32") {
1658
2242
  const localAppData = cursorLocalAppData(env);
1659
- return localAppData ? import_node_path11.join(localAppData, "cursor-agent", "agent.cmd") : "";
2243
+ return localAppData ? import_node_path14.join(localAppData, "cursor-agent", "agent.cmd") : "";
1660
2244
  }
1661
- return home ? import_node_path11.join(home, ".local", "bin", "agent") : "";
2245
+ return home ? import_node_path14.join(home, ".local", "bin", "agent") : "";
1662
2246
  }
1663
2247
  function resolveCursorCommand(overrides) {
1664
2248
  const args = ["acp"];
1665
2249
  const platform = overrides?.platform ?? process.platform;
1666
2250
  const env = overrides?.env ?? process.env;
1667
- const home = overrides?.home ?? import_node_os8.homedir();
2251
+ const home = overrides?.home ?? import_node_os10.homedir();
1668
2252
  if (platform === "win32") {
1669
2253
  const directCmd = resolveDirectCursorCommand(platform, env, home);
1670
- if (directCmd && import_node_fs10.existsSync(directCmd)) {
2254
+ if (directCmd && import_node_fs13.existsSync(directCmd)) {
1671
2255
  return { command: directCmd, args };
1672
2256
  }
1673
2257
  return { command: "agent.cmd", args };
1674
2258
  }
1675
2259
  const directBin = resolveDirectCursorCommand(platform, env, home);
1676
- if (directBin && import_node_fs10.existsSync(directBin)) {
2260
+ if (directBin && import_node_fs13.existsSync(directBin)) {
1677
2261
  return { command: directBin, args };
1678
2262
  }
1679
2263
  return { command: "agent", args };
@@ -1682,11 +2266,11 @@ function resolveCursorSpawnCommand(overrides) {
1682
2266
  const args = ["acp"];
1683
2267
  const platform = overrides?.platform ?? process.platform;
1684
2268
  const env = overrides?.env ?? process.env;
1685
- const home = overrides?.home ?? import_node_os8.homedir();
2269
+ const home = overrides?.home ?? import_node_os10.homedir();
1686
2270
  const binary = platform === "win32" ? "agent.cmd" : "agent";
1687
2271
  const direct = resolveDirectCursorCommand(platform, env, home);
1688
2272
  try {
1689
- if (direct && import_node_fs10.existsSync(direct))
2273
+ if (direct && import_node_fs13.existsSync(direct))
1690
2274
  return { command: direct, args };
1691
2275
  } catch {}
1692
2276
  if (isOnPath(binary, env, platform))
@@ -1708,12 +2292,12 @@ function cursorRoamingAppData(env, home) {
1708
2292
  if (roaming)
1709
2293
  return roaming;
1710
2294
  const profile = pickEnv2(env, "USERPROFILE") || home;
1711
- return profile ? import_node_path11.join(profile, "AppData", "Roaming") : "";
2295
+ return profile ? import_node_path14.join(profile, "AppData", "Roaming") : "";
1712
2296
  }
1713
2297
  function resolveCursorAuthCandidates(overrides) {
1714
2298
  const platform = overrides?.platform ?? process.platform;
1715
2299
  const env = overrides?.env ?? process.env;
1716
- const home = overrides?.home ?? import_node_os8.homedir();
2300
+ const home = overrides?.home ?? import_node_os10.homedir();
1717
2301
  const seen = new Set;
1718
2302
  const out = [];
1719
2303
  const push = (p) => {
@@ -1724,16 +2308,16 @@ function resolveCursorAuthCandidates(overrides) {
1724
2308
  };
1725
2309
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
1726
2310
  if (xdg)
1727
- push(import_node_path11.join(xdg, "cursor", "auth.json"));
2311
+ push(import_node_path14.join(xdg, "cursor", "auth.json"));
1728
2312
  if (platform === "win32") {
1729
2313
  const profile = pickEnv2(env, "USERPROFILE") || home;
1730
2314
  if (profile)
1731
- push(import_node_path11.join(profile, ".config", "cursor", "auth.json"));
2315
+ push(import_node_path14.join(profile, ".config", "cursor", "auth.json"));
1732
2316
  const roaming = cursorRoamingAppData(env, home);
1733
2317
  if (roaming)
1734
- push(import_node_path11.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
2318
+ push(import_node_path14.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
1735
2319
  } else if (home) {
1736
- push(import_node_path11.join(home, ".config", "cursor", "auth.json"));
2320
+ push(import_node_path14.join(home, ".config", "cursor", "auth.json"));
1737
2321
  }
1738
2322
  return out;
1739
2323
  }
@@ -1744,9 +2328,9 @@ function isValidCursorAuthFile(authFile) {
1744
2328
  try {
1745
2329
  if (!authFile || isStorageHintPath(authFile))
1746
2330
  return false;
1747
- if (!import_node_fs10.existsSync(authFile))
2331
+ if (!import_node_fs13.existsSync(authFile))
1748
2332
  return false;
1749
- const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
2333
+ const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
1750
2334
  if (!raw)
1751
2335
  return false;
1752
2336
  const parsed = JSON.parse(raw);
@@ -1764,9 +2348,9 @@ function isHintCursorStorageFile(authFile) {
1764
2348
  try {
1765
2349
  if (!authFile || !isStorageHintPath(authFile))
1766
2350
  return false;
1767
- if (!import_node_fs10.existsSync(authFile))
2351
+ if (!import_node_fs13.existsSync(authFile))
1768
2352
  return false;
1769
- const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
2353
+ const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
1770
2354
  if (!raw)
1771
2355
  return false;
1772
2356
  const parsed = JSON.parse(raw);
@@ -1782,7 +2366,7 @@ function isValidCursorCandidate(authFile) {
1782
2366
  }
1783
2367
  function probeCursorAuth(overrides) {
1784
2368
  const env = overrides?.env ?? process.env;
1785
- const home = overrides?.home ?? import_node_os8.homedir();
2369
+ const home = overrides?.home ?? import_node_os10.homedir();
1786
2370
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
1787
2371
  const candidates = resolveCursorAuthCandidates(overrides);
1788
2372
  let firstExisting = null;
@@ -1790,7 +2374,7 @@ function probeCursorAuth(overrides) {
1790
2374
  for (const candidate of candidates) {
1791
2375
  let exists = false;
1792
2376
  try {
1793
- exists = import_node_fs10.existsSync(candidate);
2377
+ exists = import_node_fs13.existsSync(candidate);
1794
2378
  } catch {
1795
2379
  exists = false;
1796
2380
  }
@@ -1802,12 +2386,12 @@ function probeCursorAuth(overrides) {
1802
2386
  if (isValidCursorCandidate(candidate))
1803
2387
  validFile = candidate;
1804
2388
  }
1805
- const fallback = home ? import_node_path11.join(home, ".config", "cursor", "auth.json") : "";
2389
+ const fallback = home ? import_node_path14.join(home, ".config", "cursor", "auth.json") : "";
1806
2390
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
1807
- const authDir = authFile ? import_node_path11.dirname(authFile) : "";
2391
+ const authDir = authFile ? import_node_path14.dirname(authFile) : "";
1808
2392
  let hasCodexHome = false;
1809
2393
  try {
1810
- hasCodexHome = authDir ? import_node_fs10.existsSync(authDir) : false;
2394
+ hasCodexHome = authDir ? import_node_fs13.existsSync(authDir) : false;
1811
2395
  } catch {
1812
2396
  hasCodexHome = false;
1813
2397
  }
@@ -1821,6 +2405,7 @@ function probeCursorAuth(overrides) {
1821
2405
  }
1822
2406
  var cursorAdapter = {
1823
2407
  id: "cursor-cli",
2408
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-does-not-guarantee-rules"),
1824
2409
  probeAuth: () => probeCursorAuth(),
1825
2410
  probeQuota: async () => probeCursorQuota(),
1826
2411
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
@@ -1871,7 +2456,7 @@ function getCursorCatalogIds(execFile, overrides) {
1871
2456
  }
1872
2457
  try {
1873
2458
  const shell = command.toLowerCase().endsWith(".cmd");
1874
- const result = import_node_child_process4.spawnSync(command, ["--list-models"], {
2459
+ const result = import_node_child_process5.spawnSync(command, ["--list-models"], {
1875
2460
  encoding: "utf8",
1876
2461
  timeout: 6000,
1877
2462
  windowsHide: true,
@@ -1934,6 +2519,7 @@ function probeDeepseekAuth() {
1934
2519
  }
1935
2520
  var deepseekAdapter = {
1936
2521
  id: "deepseek",
2522
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
1937
2523
  probeAuth: () => probeDeepseekAuth(),
1938
2524
  resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
1939
2525
  resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
@@ -1942,13 +2528,13 @@ var deepseekAdapter = {
1942
2528
  };
1943
2529
 
1944
2530
  // 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");
2531
+ var import_node_fs14 = require("node:fs");
2532
+ var import_node_path15 = require("node:path");
2533
+ var import_node_child_process6 = require("node:child_process");
1948
2534
  var os2 = __toESM(require("node:os"), 1);
1949
2535
  function resolveGeminiHome2() {
1950
2536
  const home = process.env.USERPROFILE || process.env.HOME || "";
1951
- return import_node_path12.join(home, ".gemini");
2537
+ return import_node_path15.join(home, ".gemini");
1952
2538
  }
1953
2539
  function resolveAntigravityAccount() {
1954
2540
  if (process.env.GOOGLE_ACCOUNT?.trim()) {
@@ -1961,14 +2547,14 @@ function resolveAntigravityAccount() {
1961
2547
  }
1962
2548
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
1963
2549
  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")
2550
+ process.env.APPDATA ? import_node_path15.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
2551
+ import_node_path15.join(home, ".config", "Antigravity", "app_storage.json"),
2552
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
1967
2553
  ].filter(Boolean);
1968
2554
  for (const file of candidates) {
1969
2555
  try {
1970
- if (import_node_fs11.existsSync(file)) {
1971
- const raw = import_node_fs11.readFileSync(file, "utf8");
2556
+ if (import_node_fs14.existsSync(file)) {
2557
+ const raw = import_node_fs14.readFileSync(file, "utf8");
1972
2558
  const json = JSON.parse(raw);
1973
2559
  const username = json["jetski.onboarding.lastLoginUsername"];
1974
2560
  if (username && typeof username === "string" && username.trim()) {
@@ -1989,30 +2575,30 @@ function resolveAntigravityAccount() {
1989
2575
  }
1990
2576
  function resolveAntigravityLanguageServer() {
1991
2577
  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") : "");
2578
+ const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path15.join(home, "AppData", "Roaming") : "");
1993
2579
  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")
2580
+ appData ? import_node_path15.join(appData, "Antigravity IDE", "logs") : null,
2581
+ appData ? import_node_path15.join(appData, "Antigravity", "logs") : null,
2582
+ import_node_path15.join(home, ".config", "Antigravity IDE", "logs"),
2583
+ import_node_path15.join(home, ".config", "Antigravity", "logs"),
2584
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
2585
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity", "logs")
2000
2586
  ].filter(Boolean);
2001
2587
  for (const base of baseDirs) {
2002
2588
  try {
2003
- if (!import_node_fs11.existsSync(base))
2589
+ if (!import_node_fs14.existsSync(base))
2004
2590
  continue;
2005
- const sessionDirs = import_node_fs11.readdirSync(base).map((d) => {
2591
+ const sessionDirs = import_node_fs14.readdirSync(base).map((d) => {
2006
2592
  try {
2007
- return { name: d, time: import_node_fs11.statSync(import_node_path12.join(base, d)).mtimeMs };
2593
+ return { name: d, time: import_node_fs14.statSync(import_node_path15.join(base, d)).mtimeMs };
2008
2594
  } catch {
2009
2595
  return null;
2010
2596
  }
2011
2597
  }).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
2012
2598
  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");
2599
+ const logFile = import_node_path15.join(base, s.name, "ls-main.log");
2600
+ if (import_node_fs14.existsSync(logFile)) {
2601
+ const content = import_node_fs14.readFileSync(logFile, "utf8");
2016
2602
  const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
2017
2603
  const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
2018
2604
  if (csrfMatch && portMatch) {
@@ -2028,13 +2614,13 @@ function resolveAntigravityLanguageServer() {
2028
2614
  try {
2029
2615
  let out = "";
2030
2616
  if (process.platform === "win32") {
2031
- out = import_node_child_process5.execFileSync("powershell", [
2617
+ out = import_node_child_process6.execFileSync("powershell", [
2032
2618
  "-NoProfile",
2033
2619
  "-Command",
2034
2620
  `Get-CimInstance Win32_Process -Filter "Name like '%language_server%'" | Select-Object -ExpandProperty CommandLine`
2035
2621
  ], { encoding: "utf8", timeout: 4000, windowsHide: true });
2036
2622
  } else {
2037
- out = import_node_child_process5.execFileSync("ps", ["aux"], { encoding: "utf8", timeout: 4000 });
2623
+ out = import_node_child_process6.execFileSync("ps", ["aux"], { encoding: "utf8", timeout: 4000 });
2038
2624
  }
2039
2625
  const lines = out.split(/\r?\n/);
2040
2626
  for (const l of lines) {
@@ -2071,7 +2657,7 @@ async function probeAgyQuota(options) {
2071
2657
  }
2072
2658
  } catch {
2073
2659
  try {
2074
- const raw = import_node_child_process5.execFileSync(process.platform === "win32" ? "curl.exe" : "curl", [
2660
+ const raw = import_node_child_process6.execFileSync(process.platform === "win32" ? "curl.exe" : "curl", [
2075
2661
  "-k",
2076
2662
  "-s",
2077
2663
  "-X",
@@ -2169,7 +2755,7 @@ async function probeAgyQuota(options) {
2169
2755
  } catch {}
2170
2756
  }
2171
2757
  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"));
2758
+ const hasAgyDir = import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity")) || import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity-cli"));
2173
2759
  const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
2174
2760
  const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
2175
2761
  if (!isAvailable) {
@@ -2241,6 +2827,12 @@ function probeAgyAuth() {
2241
2827
  }
2242
2828
  var agyAdapter = {
2243
2829
  id: "agy",
2830
+ prepareAppResources: async ({ directory }) => {
2831
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
2832
+ return { ...prep, env: { AGY_ACP_RESOURCES_DIR: directory }, report: { ...prep.report, rulesPrepared: prep.report.rulesChars > 0 } };
2833
+ },
2834
+ appResourceSessionMeta: (directory) => ({ appResources: { directory } }),
2835
+ supportedBridgeVersions: ["0.1.24"],
2244
2836
  probeAuth: () => probeAgyAuth(),
2245
2837
  probeQuota: (options) => probeAgyQuota(options),
2246
2838
  orderAuthMethods: (methods) => methods,
@@ -2280,7 +2872,10 @@ function getAcpRuntimeAdapter(runtimeId) {
2280
2872
  }
2281
2873
 
2282
2874
  // src/process/process-manager.ts
2283
- var import_node_child_process6 = require("node:child_process");
2875
+ var import_node_child_process7 = require("node:child_process");
2876
+ function processKey(runtimeId, scopeKey) {
2877
+ return scopeKey ? `${scopeKey}:${runtimeId}` : runtimeId;
2878
+ }
2284
2879
  var active = new Map;
2285
2880
  var ACP_EARLY_EXIT_WINDOW_MS = 3000;
2286
2881
  var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
@@ -2292,7 +2887,7 @@ function killProcessTree(pid) {
2292
2887
  if (process.platform !== "win32")
2293
2888
  return;
2294
2889
  try {
2295
- import_node_child_process6.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
2890
+ import_node_child_process7.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
2296
2891
  windowsHide: true,
2297
2892
  timeout: 8000
2298
2893
  });
@@ -2312,7 +2907,8 @@ function spawnAcpProcess(options) {
2312
2907
  if (!options.runtime?.id || !options.runtime.command || !Array.isArray(options.runtime.args)) {
2313
2908
  throw new Error(`ACP 运行时模板缺失 command/args: ${options.runtime?.id ?? "(empty)"}`);
2314
2909
  }
2315
- const existing = active.get(options.runtime.id);
2910
+ const key = processKey(options.runtime.id, options.scopeKey);
2911
+ const existing = active.get(key);
2316
2912
  if (existing) {
2317
2913
  existing.kill();
2318
2914
  }
@@ -2335,7 +2931,7 @@ function spawnAcpProcess(options) {
2335
2931
  } else {
2336
2932
  delete env.NO_BROWSER;
2337
2933
  }
2338
- const child = import_node_child_process6.spawn(file, options.runtime.args, {
2934
+ const child = import_node_child_process7.spawn(file, options.runtime.args, {
2339
2935
  cwd: options.cwd,
2340
2936
  env,
2341
2937
  stdio: ["pipe", "pipe", "pipe"],
@@ -2373,6 +2969,9 @@ function spawnAcpProcess(options) {
2373
2969
  });
2374
2970
  const handle = {
2375
2971
  runtimeId: options.runtime.id,
2972
+ scopeKey: options.scopeKey,
2973
+ executionContext: options.executionContext,
2974
+ profileTag: options.profileTag ?? null,
2376
2975
  child,
2377
2976
  spawnedAt: Date.now(),
2378
2977
  stderrTail,
@@ -2390,7 +2989,7 @@ function spawnAcpProcess(options) {
2390
2989
  } catch {}
2391
2990
  }
2392
2991
  }
2393
- active.delete(options.runtime.id);
2992
+ active.delete(key);
2394
2993
  }
2395
2994
  };
2396
2995
  child.on("exit", (code, signal) => {
@@ -2398,10 +2997,11 @@ function spawnAcpProcess(options) {
2398
2997
  if (rest)
2399
2998
  pushStderrTailLine(rest);
2400
2999
  stderrBuffer = "";
2401
- active.delete(options.runtime.id);
3000
+ if (active.get(key) === handle)
3001
+ active.delete(key);
2402
3002
  options.onExit?.(code, signal);
2403
3003
  });
2404
- active.set(options.runtime.id, handle);
3004
+ active.set(key, handle);
2405
3005
  return handle;
2406
3006
  }
2407
3007
  function getAcpEarlyExitStderrDetail(handle, _now = Date.now()) {
@@ -2429,109 +3029,64 @@ function disposeAllAcpProcesses() {
2429
3029
  }
2430
3030
  active.clear();
2431
3031
  }
2432
- function getActiveAcpProcess(runtimeId) {
2433
- return active.get(runtimeId);
3032
+ function getActiveAcpProcess(runtimeId, scopeKey) {
3033
+ return active.get(processKey(runtimeId, scopeKey));
2434
3034
  }
2435
3035
  function listLiveAcpRuntimeIds() {
2436
- const ids = [];
2437
- for (const [runtimeId, handle] of active) {
3036
+ const ids = new Set;
3037
+ for (const handle of active.values()) {
2438
3038
  if (isSpawnedAcpProcessAlive(handle))
2439
- ids.push(runtimeId);
3039
+ ids.add(handle.runtimeId);
2440
3040
  }
2441
- return ids.sort();
3041
+ return [...ids].sort();
2442
3042
  }
2443
- function getLiveAcpProcess(runtimeId) {
2444
- const handle = active.get(runtimeId);
3043
+ function getLiveAcpProcess(runtimeId, query = {}) {
3044
+ const key = processKey(runtimeId, query.scopeKey);
3045
+ const handle = active.get(key);
2445
3046
  if (!handle)
2446
3047
  return;
2447
3048
  if (!isSpawnedAcpProcessAlive(handle)) {
2448
- active.delete(runtimeId);
3049
+ active.delete(key);
3050
+ return;
3051
+ }
3052
+ if (query.executionContext !== undefined && (handle.executionContext ?? null) !== query.executionContext) {
2449
3053
  return;
2450
3054
  }
3055
+ if (query.expectedTag !== undefined && (handle.profileTag ?? null) !== query.expectedTag)
3056
+ return;
2451
3057
  return handle;
2452
3058
  }
2453
-
2454
- // src/client/sdk-client.ts
2455
- var import_node_stream = require("node:stream");
2456
- var import_sdk = require("@agentclientprotocol/sdk");
2457
- var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
2458
- function createSdkStreamHandle(child) {
2459
- const stdoutBridge = new import_node_stream.PassThrough;
2460
- const stdinBridge = new import_node_stream.PassThrough;
2461
- child.stdout.pipe(stdoutBridge);
2462
- stdinBridge.pipe(child.stdin, { end: false });
2463
- const output = import_node_stream.Writable.toWeb(stdinBridge);
2464
- const input = import_node_stream.Readable.toWeb(stdoutBridge);
2465
- const stream = import_sdk.ndJsonStream(output, input);
2466
- let disposed = false;
2467
- return {
2468
- stream,
2469
- dispose: () => {
2470
- if (disposed)
2471
- return;
2472
- disposed = true;
2473
- try {
2474
- child.stdout.unpipe(stdoutBridge);
2475
- } catch {}
2476
- try {
2477
- stdinBridge.unpipe(child.stdin);
2478
- } catch {}
2479
- try {
2480
- stdoutBridge.destroy();
2481
- } catch {}
2482
- try {
2483
- stdinBridge.destroy();
2484
- } catch {}
2485
- }
2486
- };
2487
- }
2488
- function connectSdkClient(child, configure, runtimeId) {
2489
- if (runtimeId && true) {
2490
- console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
2491
- }
2492
- const app = import_sdk.client({ name: "inkdown" });
2493
- configure(app);
2494
- const streamHandle = createSdkStreamHandle(child);
2495
- const connection = app.connect(streamHandle.stream);
2496
- return { app, connection, streamHandle };
2497
- }
2498
- async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
2499
- const controller = new AbortController;
2500
- let timer;
2501
- try {
2502
- const pending = agent.request(method, params, {
2503
- cancellationSignal: controller.signal
2504
- });
2505
- const timeout = new Promise((_, reject) => {
2506
- timer = setTimeout(() => {
2507
- controller.abort();
2508
- reject(new Error(`请求超时: ${method}`));
2509
- }, timeoutMs);
2510
- timer.unref?.();
2511
- });
2512
- return await Promise.race([pending, timeout]);
2513
- } finally {
2514
- if (timer !== undefined)
2515
- clearTimeout(timer);
2516
- }
3059
+ function tryReuseLiveAcpProcess(runtimeId, query = {}) {
3060
+ const hit = getLiveAcpProcess(runtimeId, query);
3061
+ if (hit)
3062
+ return { status: "hit", handle: hit };
3063
+ if (query.expectedTag === undefined)
3064
+ return { status: "miss" };
3065
+ const stale = getLiveAcpProcess(runtimeId, { scopeKey: query.scopeKey, executionContext: query.executionContext });
3066
+ if (!stale)
3067
+ return { status: "miss" };
3068
+ if (query.isBusy?.(stale))
3069
+ return { status: "busy", handle: stale };
3070
+ stale.kill();
3071
+ return { status: "miss" };
2517
3072
  }
2518
3073
 
2519
3074
  // src/client/client-handlers.ts
2520
3075
  var import_sdk2 = require("@agentclientprotocol/sdk");
2521
3076
 
2522
3077
  // src/client/acp-fs.ts
2523
- var import_promises3 = require("node:fs/promises");
2524
- var import_node_path13 = require("node:path");
2525
3078
  var import_promises4 = require("node:fs/promises");
3079
+ var import_node_path16 = require("node:path");
3080
+ var import_promises5 = require("node:fs/promises");
2526
3081
  var MAX_READ_BYTES = 2 * 1024 * 1024;
2527
3082
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
2528
3083
  function isBinaryDocumentPath(filePath) {
2529
- return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path13.extname(filePath).toLowerCase());
3084
+ return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path16.extname(filePath).toLowerCase());
2530
3085
  }
2531
3086
  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;
3087
+ const root = import_node_path16.resolve(workspaceRoot);
3088
+ const target = import_node_path16.resolve(filePath);
3089
+ const rootWithSep = root.endsWith(import_node_path16.sep) ? root : root + import_node_path16.sep;
2535
3090
  if (target !== root && !target.startsWith(rootWithSep)) {
2536
3091
  throw new Error(`路径不在工作区内: ${filePath}`);
2537
3092
  }
@@ -2542,8 +3097,8 @@ async function acpReadTextFile(params) {
2542
3097
  throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
2543
3098
  }
2544
3099
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
2545
- await import_promises3.access(abs);
2546
- let content = await import_promises3.readFile(abs, "utf-8");
3100
+ await import_promises4.access(abs);
3101
+ let content = await import_promises4.readFile(abs, "utf-8");
2547
3102
  if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
2548
3103
  content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
2549
3104
  content += `
@@ -2562,8 +3117,8 @@ async function acpReadTextFile(params) {
2562
3117
  }
2563
3118
  async function acpWriteTextFile(params) {
2564
3119
  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");
3120
+ await import_promises5.mkdir(import_node_path16.dirname(abs), { recursive: true });
3121
+ await import_promises4.writeFile(abs, params.content, "utf-8");
2567
3122
  return {};
2568
3123
  }
2569
3124
 
@@ -2923,6 +3478,25 @@ function isTransientAcpTransportError(error) {
2923
3478
  async function restoreOrCreateAcpSession(input) {
2924
3479
  const resumeId = input.resumeSessionId?.trim() || null;
2925
3480
  const restoreAttempts = [];
3481
+ let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
3482
+ let nativeSessionAccepted = false;
3483
+ const request = async (method, params) => {
3484
+ if (!input.sessionMeta)
3485
+ return input.request(method, params);
3486
+ try {
3487
+ const result = await input.request(method, { ...params, _meta: input.sessionMeta });
3488
+ nativeSessionAccepted = true;
3489
+ return result;
3490
+ } catch (error) {
3491
+ const rejected = error instanceof import_sdk3.RequestError && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
3492
+ if (!rejected || isTransientAcpTransportError(error))
3493
+ throw error;
3494
+ log("warn", "native resource options failed; retry without extension");
3495
+ const result = await input.request(method, params);
3496
+ nativeSessionAccepted = false;
3497
+ return result;
3498
+ }
3499
+ };
2926
3500
  const delayMs = input.retryDelayMs ?? 250;
2927
3501
  const log = input.log ?? ((level, message, data) => {
2928
3502
  if (level === "info" && false)
@@ -2944,7 +3518,7 @@ async function restoreOrCreateAcpSession(input) {
2944
3518
  maxTries
2945
3519
  });
2946
3520
  try {
2947
- const result = await input.request(rpcMethod, {
3521
+ const result = await request(rpcMethod, {
2948
3522
  sessionId: resumeId,
2949
3523
  cwd: input.cwd,
2950
3524
  mcpServers: input.mcpServers ?? []
@@ -2983,7 +3557,7 @@ async function restoreOrCreateAcpSession(input) {
2983
3557
  mcpServers: input.mcpServers ?? []
2984
3558
  };
2985
3559
  try {
2986
- return await input.request("session/new", baseParams);
3560
+ return await request("session/new", baseParams);
2987
3561
  } catch (firstError) {
2988
3562
  if ((input.mcpServers ?? []).length === 0)
2989
3563
  throw firstError;
@@ -2991,10 +3565,12 @@ async function restoreOrCreateAcpSession(input) {
2991
3565
  error: errorMessage(firstError)
2992
3566
  });
2993
3567
  try {
2994
- return await input.request("session/new", {
3568
+ const result = await request("session/new", {
2995
3569
  cwd: input.cwd,
2996
3570
  mcpServers: []
2997
3571
  });
3572
+ mcpServersAccepted = false;
3573
+ return result;
2998
3574
  } catch {
2999
3575
  throw firstError;
3000
3576
  }
@@ -3010,6 +3586,8 @@ async function restoreOrCreateAcpSession(input) {
3010
3586
  configOptions: withModelsFallback(resumed),
3011
3587
  restoreMethod: "resume",
3012
3588
  sessionRestored: true,
3589
+ mcpServersAccepted,
3590
+ nativeSessionAccepted,
3013
3591
  requestedSessionId: resumeId,
3014
3592
  restoreAttempts
3015
3593
  };
@@ -3028,6 +3606,8 @@ async function restoreOrCreateAcpSession(input) {
3028
3606
  configOptions: withModelsFallback(loaded),
3029
3607
  restoreMethod: "load",
3030
3608
  sessionRestored: true,
3609
+ mcpServersAccepted,
3610
+ nativeSessionAccepted,
3031
3611
  requestedSessionId: resumeId,
3032
3612
  restoreAttempts
3033
3613
  };
@@ -3049,14 +3629,16 @@ async function restoreOrCreateAcpSession(input) {
3049
3629
  configOptions: withModelsFallback(sessionResult),
3050
3630
  restoreMethod: "new",
3051
3631
  sessionRestored: false,
3632
+ mcpServersAccepted,
3633
+ nativeSessionAccepted,
3052
3634
  requestedSessionId: resumeId ?? undefined,
3053
3635
  restoreAttempts
3054
3636
  };
3055
3637
  }
3056
3638
 
3057
3639
  // src/client/acp-terminal.ts
3058
- var import_node_child_process7 = require("node:child_process");
3059
- var import_node_crypto = require("node:crypto");
3640
+ var import_node_child_process8 = require("node:child_process");
3641
+ var import_node_crypto3 = require("node:crypto");
3060
3642
 
3061
3643
  // src/transport/terminal-output-buffer.ts
3062
3644
  function truncateOutputFromStart(text, byteLimit) {
@@ -3108,14 +3690,14 @@ class AcpTerminalManager {
3108
3690
  throw new Error("terminal/create 需要 command");
3109
3691
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
3110
3692
  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 ?? [], {
3693
+ const child = import_node_child_process8.spawn(command, params.args ?? [], {
3112
3694
  cwd,
3113
3695
  env: buildEnv(params.env),
3114
3696
  windowsHide: true,
3115
3697
  shell: false,
3116
3698
  stdio: ["ignore", "pipe", "pipe"]
3117
3699
  });
3118
- const id = `term_${import_node_crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;
3700
+ const id = `term_${import_node_crypto3.randomUUID().replace(/-/g, "").slice(0, 12)}`;
3119
3701
  const record = {
3120
3702
  id,
3121
3703
  sessionId: params.sessionId,
@@ -3204,7 +3786,7 @@ class AcpTerminalManager {
3204
3786
  return;
3205
3787
  if (process.platform === "win32") {
3206
3788
  try {
3207
- import_node_child_process7.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
3789
+ import_node_child_process8.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
3208
3790
  windowsHide: true,
3209
3791
  stdio: "ignore"
3210
3792
  });
@@ -3239,9 +3821,9 @@ class AcpTerminalManager {
3239
3821
  }
3240
3822
 
3241
3823
  // 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");
3824
+ var import_promises6 = require("node:fs/promises");
3825
+ var import_node_fs15 = require("node:fs");
3826
+ var import_node_path17 = require("node:path");
3245
3827
  var DEFAULT_ACP_PROXY_SETTINGS = {
3246
3828
  enabled: false,
3247
3829
  host: "127.0.0.1",
@@ -3250,7 +3832,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
3250
3832
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
3251
3833
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
3252
3834
  function proxyFilePath(dir) {
3253
- return import_node_path14.join(dir, "agent", "proxy.json");
3835
+ return import_node_path17.join(dir, "agent", "proxy.json");
3254
3836
  }
3255
3837
  function validate2(settings) {
3256
3838
  if (!settings.host.trim())
@@ -3262,10 +3844,10 @@ function validate2(settings) {
3262
3844
  }
3263
3845
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
3264
3846
  const file = proxyFilePath(dir);
3265
- if (!import_node_fs12.existsSync(file))
3847
+ if (!import_node_fs15.existsSync(file))
3266
3848
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
3267
3849
  try {
3268
- const raw = JSON.parse(await import_promises5.readFile(file, "utf8"));
3850
+ const raw = JSON.parse(await import_promises6.readFile(file, "utf8"));
3269
3851
  return {
3270
3852
  enabled: raw.enabled === true,
3271
3853
  host: typeof raw.host === "string" && raw.host.trim() ? raw.host : DEFAULT_ACP_PROXY_SETTINGS.host,
@@ -3284,8 +3866,8 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
3284
3866
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
3285
3867
  port: payload.port
3286
3868
  };
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");
3869
+ await import_promises6.mkdir(import_node_path17.join(dir, "agent"), { recursive: true });
3870
+ await import_promises6.writeFile(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
3289
3871
  return ok(stored);
3290
3872
  }
3291
3873
  function buildAcpProxySpawnEnv(settings) {
@@ -3307,6 +3889,116 @@ function buildAcpProxySpawnEnv(settings) {
3307
3889
  };
3308
3890
  }
3309
3891
 
3892
+ // src/session/compat-guide.ts
3893
+ var COMPAT_CONTEXT_TAG = "acp-compat-context";
3894
+ function shortDigest(digest) {
3895
+ return digest ? digest.slice(0, 16) : "none";
3896
+ }
3897
+ function buildCompatGuideText(input) {
3898
+ const hasRules = (input.rulesText ?? "").trim() !== "";
3899
+ const hasSkills = input.skills.length > 0;
3900
+ if (!hasRules && !hasSkills)
3901
+ return null;
3902
+ const lines = [];
3903
+ 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.", "");
3904
+ if (hasRules) {
3905
+ lines.push("--- host rules (same source as the host app, delivered once per session) ---", "");
3906
+ lines.push(input.rulesText.trim(), "");
3907
+ }
3908
+ if (hasSkills) {
3909
+ lines.push("--- host skills catalog (names and descriptions only; read full text on demand) ---", "");
3910
+ for (const skill of input.skills) {
3911
+ lines.push(`- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`);
3912
+ }
3913
+ 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.");
3914
+ lines.push("");
3915
+ }
3916
+ lines.push(`</${COMPAT_CONTEXT_TAG}>`);
3917
+ return lines.join(`
3918
+ `);
3919
+ }
3920
+ function compatDeliveryKey(sessionId, generation, digest) {
3921
+ return `${generation}:${sessionId}:${digest ?? "none"}`;
3922
+ }
3923
+
3924
+ // src/mcp/app-skills-mcp.ts
3925
+ var import_node_path18 = require("node:path");
3926
+ var import_node_url = require("node:url");
3927
+ var import_node_fs16 = require("node:fs");
3928
+ var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
3929
+ var APP_SKILLS_TOOLS = [
3930
+ {
3931
+ name: "app_list_skills",
3932
+ 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.",
3933
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
3934
+ },
3935
+ {
3936
+ name: "app_read_skill",
3937
+ 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).",
3938
+ inputSchema: {
3939
+ type: "object",
3940
+ properties: {
3941
+ name: { type: "string", description: "Exact skill name from app_list_skills" },
3942
+ ref: {
3943
+ type: "string",
3944
+ description: "Optional same-directory relative Markdown file (default SKILL.md)"
3945
+ }
3946
+ },
3947
+ required: ["name"],
3948
+ additionalProperties: false
3949
+ }
3950
+ }
3951
+ ];
3952
+ function buildAppSkillsMcpServer(directory, opts) {
3953
+ return {
3954
+ name: opts?.name ?? APP_SKILLS_MCP_SERVER_NAME,
3955
+ command: process.execPath,
3956
+ env: process.versions.electron ? [{ name: "ELECTRON_RUN_AS_NODE", value: "1" }] : [],
3957
+ args: [opts?.runnerPath ?? resolveAppSkillsRunnerPath(), directory]
3958
+ };
3959
+ }
3960
+ function resolveAppSkillsRunnerPath(fromFile) {
3961
+ const base = fromFile ?? import_node_url.fileURLToPath("file:///home/runner/work/acp-client/acp-client/src/mcp/app-skills-mcp.ts");
3962
+ const candidates = [
3963
+ import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.cjs"),
3964
+ import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.ts")
3965
+ ];
3966
+ for (const candidate of candidates) {
3967
+ if (import_node_fs16.existsSync(candidate))
3968
+ return candidate;
3969
+ }
3970
+ throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
3971
+ }
3972
+
3973
+ // src/client/acp-client.ts
3974
+ var import_node_crypto4 = require("node:crypto");
3975
+
3976
+ // src/resources/eligibility.ts
3977
+ var NATIVE_ELIGIBLE_BRIDGE_VERSIONS = {
3978
+ "codex-acp": ["2.2.2"],
3979
+ opencode: ["1.18.35"],
3980
+ claude: ["0.91.0"],
3981
+ agy: ["0.1.24"]
3982
+ };
3983
+ function resolveRuntimeEligibility(runtimeId) {
3984
+ const id = (runtimeId ?? "").trim();
3985
+ if (!id || !(id in NATIVE_ELIGIBLE_BRIDGE_VERSIONS)) {
3986
+ return { eligible: false, reason: "runtime-not-verified" };
3987
+ }
3988
+ return { eligible: true };
3989
+ }
3990
+ function isSupportedBridgeVersion(runtimeId, version) {
3991
+ const versions = NATIVE_ELIGIBLE_BRIDGE_VERSIONS[(runtimeId ?? "").trim()];
3992
+ if (!versions)
3993
+ return { eligible: false, reason: "runtime-not-verified" };
3994
+ const normalized = version?.trim().replace(/^v/, "");
3995
+ if (!normalized)
3996
+ return { eligible: false, reason: "unknown-bridge-version" };
3997
+ if (!versions.includes(normalized))
3998
+ return { eligible: false, reason: "unsupported-bridge-version" };
3999
+ return { eligible: true };
4000
+ }
4001
+
3310
4002
  // src/session/session-capabilities.ts
3311
4003
  function parseLoadSessionSupported(caps) {
3312
4004
  return caps.loadSession === true;
@@ -3343,11 +4035,13 @@ class AcpSessionHandle {
3343
4035
  client;
3344
4036
  restoreMethod;
3345
4037
  configOptions;
3346
- constructor(sessionId, client, restoreMethod, configOptions) {
4038
+ resourceReport;
4039
+ constructor(sessionId, client, restoreMethod, configOptions, resourceReport) {
3347
4040
  this.sessionId = sessionId;
3348
4041
  this.client = client;
3349
4042
  this.restoreMethod = restoreMethod;
3350
4043
  this.configOptions = configOptions;
4044
+ this.resourceReport = resourceReport;
3351
4045
  }
3352
4046
  async prompt(promptText, options) {
3353
4047
  return this.client.promptSession(this.sessionId, promptText, options);
@@ -3376,6 +4070,10 @@ class AcpClient {
3376
4070
  clientInfo;
3377
4071
  dataDir;
3378
4072
  extraEnv;
4073
+ configurationScope;
4074
+ sessionConfig = null;
4075
+ resourcesDir;
4076
+ processScopeKey = import_node_crypto4.randomUUID();
3379
4077
  callbacks;
3380
4078
  terminals = new AcpTerminalManager;
3381
4079
  processHandle = null;
@@ -3383,6 +4081,17 @@ class AcpClient {
3383
4081
  sdkConnection = null;
3384
4082
  streamHandle = null;
3385
4083
  initResponse = null;
4084
+ inflightPrompts = new Set;
4085
+ resourcePrep = null;
4086
+ connectionGen = 0;
4087
+ attachSkillsMcp;
4088
+ sessionLedger = new Map;
4089
+ compatSentKeys = new Set;
4090
+ compatSnapshots = new Map;
4091
+ get resourceReport() {
4092
+ const report = this.resourcePrep?.report;
4093
+ return report ? { ...report, skillsFound: [...report.skillsFound] } : null;
4094
+ }
3386
4095
  constructor(options) {
3387
4096
  this.workspaceRoot = options.workspaceRoot;
3388
4097
  this.clientInfo = {
@@ -3391,6 +4100,14 @@ class AcpClient {
3391
4100
  };
3392
4101
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
3393
4102
  this.extraEnv = options.env ?? {};
4103
+ if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
4104
+ throw new Error("resources.directory 必须是本机绝对路径");
4105
+ }
4106
+ this.configurationScope = options.resources?.configurationScope ?? "overlay";
4107
+ if (!["overlay", "session"].includes(this.configurationScope))
4108
+ throw new Error("Invalid resources.configurationScope");
4109
+ this.resourcesDir = options.resources?.directory ?? null;
4110
+ this.attachSkillsMcp = options.resources?.attachSkillsMcp !== false;
3394
4111
  this.callbacks = options.callbacks ?? {};
3395
4112
  const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
3396
4113
  this.adapter = getAcpRuntimeAdapter(runtimeId);
@@ -3417,6 +4134,14 @@ class AcpClient {
3417
4134
  return this.initResponse;
3418
4135
  }
3419
4136
  async connect() {
4137
+ if (this.inflightPrompts.size > 0)
4138
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
4139
+ if (this.isConnected && this.initResponse)
4140
+ return ok({ status: this.status, init: this.initResponse });
4141
+ if (this.currentStatus === "connecting")
4142
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在连接" });
4143
+ this.connectionGen += 1;
4144
+ const connectGen = this.connectionGen;
3420
4145
  try {
3421
4146
  this.setStatus("connecting");
3422
4147
  const blocker = this.adapter.resolveSpawnBlocker?.();
@@ -3442,16 +4167,105 @@ class AcpClient {
3442
4167
  ...baseEnv,
3443
4168
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
3444
4169
  };
4170
+ let resourceEnv = {};
4171
+ let profileTag = null;
4172
+ if (this.resourcesDir && this.configurationScope === "session") {
4173
+ const profile = await createSessionConfigHome(this.runtimeInfo.id, this.resourcesDir);
4174
+ if (connectGen !== this.connectionGen || this.status !== "connecting") {
4175
+ await profile.dispose();
4176
+ return err({ code: "CANCELLED", message: "连接已取消" });
4177
+ }
4178
+ this.sessionConfig = profile;
4179
+ resourceEnv = this.sessionConfig.env;
4180
+ const load = readAppResourcesDir(this.resourcesDir);
4181
+ this.resourcePrep = { profileTag: null, report: {
4182
+ rulesApplied: false,
4183
+ rulesPrepared: false,
4184
+ skillsApplied: false,
4185
+ rulesChars: load.rules?.chars ?? 0,
4186
+ profileDigest: digestAppResources(load),
4187
+ skillsFound: load.skills.map((s) => s.name),
4188
+ configurationScope: "session",
4189
+ configurationDirectory: this.sessionConfig.directory,
4190
+ configurationRulesFile: this.sessionConfig.rulesFile,
4191
+ reason: this.sessionConfig.nativeRules ? "isolated-config-not-runtime-verified" : "isolated-config-rule-discovery-not-verified"
4192
+ } };
4193
+ } else if (this.resourcesDir && this.adapter.prepareAppResources) {
4194
+ try {
4195
+ const prep = await this.adapter.prepareAppResources({
4196
+ directory: this.resourcesDir,
4197
+ command: effectiveRuntime.command,
4198
+ workspaceRoot: this.workspaceRoot,
4199
+ env: { ...process.env, ...spawnEnv.env }
4200
+ });
4201
+ if (prep.env)
4202
+ resourceEnv = prep.env;
4203
+ prep.report.rulesPrepared = prep.report.rulesPrepared ?? prep.report.rulesApplied;
4204
+ prep.report.rulesApplied = false;
4205
+ prep.report.skillsApplied = false;
4206
+ const digest = prep.report.profileDigest;
4207
+ profileTag = digest ? `${this.runtimeInfo.id}:resources@${digest.slice(0, 16)}` : null;
4208
+ this.resourcePrep = { profileTag, report: prep.report };
4209
+ } catch (error) {
4210
+ this.resourcePrep = {
4211
+ profileTag: null,
4212
+ report: {
4213
+ rulesApplied: false,
4214
+ rulesChars: 0,
4215
+ profileDigest: null,
4216
+ skillsFound: [],
4217
+ reason: "prepare-failed"
4218
+ }
4219
+ };
4220
+ this.callbacks.onLog?.("warn", "应用资源准备失败,已回退兼容", {
4221
+ error: error instanceof Error ? error.message : String(error)
4222
+ });
4223
+ }
4224
+ } else {
4225
+ const load = this.resourcesDir ? readAppResourcesDir(this.resourcesDir) : null;
4226
+ this.resourcePrep = load ? { profileTag: null, report: {
4227
+ rulesApplied: false,
4228
+ rulesPrepared: false,
4229
+ skillsApplied: false,
4230
+ rulesChars: load.rules?.chars ?? 0,
4231
+ profileDigest: digestAppResources(load),
4232
+ skillsFound: load.skills.map((s) => s.name),
4233
+ reason: "runtime-not-supported"
4234
+ } } : null;
4235
+ }
4236
+ const finalEnv = { ...spawnEnv.env, ...resourceEnv };
3445
4237
  await this.adapter.beforeSpawn?.();
3446
- const processHandle = spawnAcpProcess({
4238
+ if (connectGen !== this.connectionGen || this.status !== "connecting")
4239
+ return err({ code: "CANCELLED", message: "连接已取消" });
4240
+ let reuseDegraded = false;
4241
+ let reusedHandle = null;
4242
+ if (profileTag) {
4243
+ const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
4244
+ expectedTag: profileTag,
4245
+ scopeKey: this.processScopeKey,
4246
+ isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
4247
+ });
4248
+ if (reuse.status === "hit") {
4249
+ reusedHandle = reuse.handle;
4250
+ } else if (reuse.status === "busy") {
4251
+ reusedHandle = reuse.handle;
4252
+ reuseDegraded = true;
4253
+ this.callbacks.onLog?.("warn", "应用资源摘要已变更但旧进程正忙,沿用旧进程并降级,新摘要下次冷启动生效");
4254
+ }
4255
+ }
4256
+ const processHandle = reusedHandle ?? spawnAcpProcess({
3447
4257
  runtime: effectiveRuntime,
3448
4258
  cwd: this.workspaceRoot,
3449
- env: spawnEnv.env,
4259
+ scopeKey: this.processScopeKey,
4260
+ env: finalEnv,
3450
4261
  envRemove: spawnEnv.envRemove,
4262
+ profileTag,
3451
4263
  onStderrLine: (line) => {
3452
4264
  this.callbacks.onStderrLine?.(line);
3453
4265
  },
3454
4266
  onExit: (code, signal) => {
4267
+ if (this.connectionGen !== connectGen)
4268
+ return;
3455
4269
  this.callbacks.onLog?.("warn", `Agent 进程已退出 (code: ${code}, signal: ${signal})`);
3456
4270
  if (this.status === "connected" || this.status === "connecting") {
3457
4271
  this.disconnect("Agent 进程异常终止");
@@ -3502,9 +4316,28 @@ class AcpClient {
3502
4316
  }
3503
4317
  });
3504
4318
  this.initResponse = initResp;
4319
+ if (this.resourcePrep) {
4320
+ const agentInfo = initResp?.agentInfo;
4321
+ const bridgeVersion = typeof agentInfo?.version === "string" ? agentInfo.version : undefined;
4322
+ const supported = isSupportedBridgeVersion(this.runtimeInfo.id, bridgeVersion).eligible && (this.adapter.supportedBridgeVersions?.includes(bridgeVersion?.replace(/^v/, "") ?? "") ?? false);
4323
+ this.resourcePrep.report.bridgeVersion = bridgeVersion;
4324
+ this.resourcePrep.report.bridgeSupported = supported;
4325
+ if (this.processHandle)
4326
+ this.processHandle.bridgeVersion = bridgeVersion;
4327
+ if (supported && this.resourcePrep.report.reason === "native-session-version-not-verified")
4328
+ delete this.resourcePrep.report.reason;
4329
+ if (!supported) {
4330
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "unsupported-bridge-version";
4331
+ }
4332
+ if (reuseDegraded) {
4333
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "busy-deferred-stale-rules";
4334
+ }
4335
+ }
3505
4336
  this.setStatus("connected");
3506
4337
  return ok({ status: "connected", init: initResp });
3507
4338
  } catch (e) {
4339
+ if (connectGen !== this.connectionGen)
4340
+ return err({ code: "CANCELLED", message: "连接已被新请求取代" });
3508
4341
  const message = e instanceof Error ? e.message : String(e);
3509
4342
  this.setStatus("error", message);
3510
4343
  await this.disconnect(message);
@@ -3543,6 +4376,29 @@ class AcpClient {
3543
4376
  const resumeSupported = Boolean(init && parseResumeSessionSupported(init.agentCapabilities));
3544
4377
  const loadSupported = Boolean(init && parseLoadSessionSupported(init.agentCapabilities));
3545
4378
  try {
4379
+ let skillsExposed = "none";
4380
+ let mcpServers = options?.mcpServers ?? [];
4381
+ if (this.resourcesDir && this.attachSkillsMcp) {
4382
+ try {
4383
+ const descriptor = buildAppSkillsMcpServer(this.resourcesDir);
4384
+ const callerNames = new Set;
4385
+ for (const entry of mcpServers) {
4386
+ if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
4387
+ callerNames.add(entry.name);
4388
+ }
4389
+ }
4390
+ if (callerNames.has(descriptor.name)) {
4391
+ this.callbacks.onLog?.("warn", "调用方已有同名技能 MCP 服务,保留调用方版本", { name: descriptor.name });
4392
+ } else {
4393
+ mcpServers = [...mcpServers, descriptor];
4394
+ skillsExposed = "mcp-exposed";
4395
+ }
4396
+ } catch (error) {
4397
+ this.callbacks.onLog?.("warn", "技能 MCP 描述符构建失败,本次会话无技能 MCP", {
4398
+ error: error instanceof Error ? error.message : String(error)
4399
+ });
4400
+ }
4401
+ }
3546
4402
  const openResult = await restoreOrCreateAcpSession({
3547
4403
  request: async (method, params) => {
3548
4404
  return sdkRequest(agent, method, params);
@@ -3551,12 +4407,27 @@ class AcpClient {
3551
4407
  resumeSessionId: options?.resumeSessionId ?? null,
3552
4408
  resumeSupported,
3553
4409
  loadSupported,
3554
- mcpServers: options?.mcpServers ?? [],
4410
+ mcpServers,
4411
+ sessionMeta: (!this.sessionConfig || this.runtimeInfo.id === "agy") && this.resourcesDir && this.resourcePrep?.report.bridgeSupported ? this.adapter.appResourceSessionMeta?.(this.resourcesDir) : undefined,
3555
4412
  log: (level, msg, meta) => {
3556
4413
  this.callbacks.onLog?.(level, msg, meta);
3557
4414
  }
3558
4415
  });
3559
- const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions);
4416
+ if (!openResult.mcpServersAccepted)
4417
+ skillsExposed = "none";
4418
+ this.sessionLedger.set(openResult.sessionId, {
4419
+ restoreMethod: openResult.restoreMethod,
4420
+ gen: this.connectionGen,
4421
+ skillsExposed,
4422
+ nativeRules: openResult.nativeSessionAccepted
4423
+ });
4424
+ const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions, this.resourcePrep?.report ? {
4425
+ ...this.resourcePrep.report,
4426
+ skillsFound: [...this.resourcePrep.report.skillsFound],
4427
+ skillsExposed,
4428
+ rulesApplied: openResult.nativeSessionAccepted || !this.adapter.appResourceSessionMeta && openResult.restoreMethod === "new" && this.resourcePrep.report.bridgeSupported === true && this.resourcePrep.report.rulesPrepared === true,
4429
+ ...openResult.restoreMethod !== "new" && !openResult.nativeSessionAccepted ? { reason: "session-restored-not-verified" } : {}
4430
+ } : null);
3560
4431
  return ok(handle);
3561
4432
  } catch (e) {
3562
4433
  const message = e instanceof Error ? e.message : String(e);
@@ -3567,6 +4438,7 @@ class AcpClient {
3567
4438
  if (!this.sdkConnection?.agent) {
3568
4439
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
3569
4440
  }
4441
+ this.inflightPrompts.add(sessionId);
3570
4442
  try {
3571
4443
  const prompt = [{ type: "text", text: promptText }];
3572
4444
  for (const image of options?.images ?? []) {
@@ -3574,16 +4446,52 @@ class AcpClient {
3574
4446
  continue;
3575
4447
  prompt.push({ type: "image", mimeType: image.mimeType, data: image.data });
3576
4448
  }
4449
+ const compat = this.buildCompatPrepend(sessionId);
4450
+ const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
3577
4451
  const response = await sdkRequest(this.sdkConnection.agent, import_sdk4.methods.agent.session.prompt, {
3578
4452
  sessionId,
3579
- prompt
4453
+ prompt: blocks
3580
4454
  }, options?.timeoutMs);
3581
4455
  return ok(response);
3582
4456
  } catch (e) {
3583
4457
  const message = e instanceof Error ? e.message : String(e);
3584
4458
  return err({ code: "ACP_PROTOCOL_ERROR", message });
4459
+ } finally {
4460
+ this.inflightPrompts.delete(sessionId);
3585
4461
  }
3586
4462
  }
4463
+ buildCompatPrepend(sessionId) {
4464
+ if (!this.resourcesDir)
4465
+ return null;
4466
+ if (this.sessionConfig?.nativeRules)
4467
+ return null;
4468
+ const entry = this.sessionLedger.get(sessionId);
4469
+ if (!entry)
4470
+ return null;
4471
+ const connReport = this.resourcePrep?.report;
4472
+ const nativelyDelivered = entry.nativeRules || !this.adapter.appResourceSessionMeta && entry.restoreMethod === "new" && entry.gen === this.connectionGen && connReport?.rulesPrepared === true && connReport?.bridgeSupported === true;
4473
+ if (nativelyDelivered)
4474
+ return null;
4475
+ const load = readAppResourcesDir(this.resourcesDir);
4476
+ const rulesText = readAppRulesText(this.resourcesDir);
4477
+ const digest = digestAppResources(load);
4478
+ const key = compatDeliveryKey(sessionId, this.connectionGen, digest);
4479
+ if (this.compatSentKeys.has(key))
4480
+ return null;
4481
+ const text = buildCompatGuideText({
4482
+ rulesText,
4483
+ skills: load.skills.map((s) => ({ name: s.name, description: s.description })),
4484
+ skillsViaMcp: entry.skillsExposed === "mcp-exposed",
4485
+ digest,
4486
+ sessionId,
4487
+ generation: this.connectionGen
4488
+ });
4489
+ if (!text)
4490
+ return null;
4491
+ this.compatSnapshots.set(key, { text, digest });
4492
+ this.compatSentKeys.add(key);
4493
+ return text;
4494
+ }
3587
4495
  async setSessionConfigOption(sessionId, configId, value) {
3588
4496
  if (!this.sdkConnection?.agent) {
3589
4497
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
@@ -3602,6 +4510,16 @@ class AcpClient {
3602
4510
  }
3603
4511
  async disconnect(reason) {
3604
4512
  this.setStatus("disconnected", reason);
4513
+ this.resourcePrep = null;
4514
+ const capabilities = this.initResponse?.agentCapabilities?.sessionCapabilities;
4515
+ if (capabilities?.close && this.sdkConnection?.agent) {
4516
+ const failed = await closeAcpSessions(this.sdkConnection.agent, this.sessionLedger.keys());
4517
+ if (failed.length)
4518
+ this.callbacks.onLog?.("warn", "Session close failed before process teardown", { count: failed.length });
4519
+ }
4520
+ this.sessionLedger.clear();
4521
+ this.compatSentKeys.clear();
4522
+ this.compatSnapshots.clear();
3605
4523
  try {
3606
4524
  this.streamHandle?.dispose();
3607
4525
  this.sdkConnection?.close();
@@ -3617,6 +4535,15 @@ class AcpClient {
3617
4535
  } catch {}
3618
4536
  this.processHandle = null;
3619
4537
  }
4538
+ const config = this.sessionConfig;
4539
+ this.sessionConfig = null;
4540
+ if (config) {
4541
+ try {
4542
+ await config.dispose();
4543
+ } catch {
4544
+ this.callbacks.onLog?.("warn", "Session configuration cleanup failed; directory retained", { directory: config.directory });
4545
+ }
4546
+ }
3620
4547
  }
3621
4548
  setStatus(status, detail) {
3622
4549
  this.status = status;