@yitom/acp-client 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
1
4
  // src/contracts/index.ts
2
5
  function isCancelled(error) {
3
6
  return error.code === "CANCELLED";
@@ -159,7 +162,244 @@ function findBuiltinAcpRuntime(id) {
159
162
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
160
163
  }
161
164
  // src/version.ts
162
- var ACP_CLIENT_VERSION = "0.1.6";
165
+ var ACP_CLIENT_VERSION = "0.1.8";
166
+ // src/resources/session-config.ts
167
+ import { existsSync } from "node:fs";
168
+ import { mkdtemp, mkdir, writeFile, readdir, readFile, lstat, realpath, rm } from "node:fs/promises";
169
+ import { tmpdir } from "node:os";
170
+ import { join as join2, resolve, relative, isAbsolute as isAbsolute2, sep } from "node:path";
171
+
172
+ // src/resources/app-resources.ts
173
+ import { createHash } from "node:crypto";
174
+ import { readdirSync, readFileSync, statSync } from "node:fs";
175
+ import { isAbsolute, join } from "node:path";
176
+ var APP_RULES_FILE = "AGENTS.md";
177
+ var APP_SKILLS_DIR = "skills";
178
+ var APP_SKILL_FILE = "SKILL.md";
179
+ function parseSkillFrontmatter(text) {
180
+ const lines = text.split(`
181
+ `);
182
+ if (lines[0]?.trim() !== "---")
183
+ return {};
184
+ const out = {};
185
+ for (let i = 1;i < lines.length; i += 1) {
186
+ const line = lines[i] ?? "";
187
+ if (line.trim() === "---")
188
+ break;
189
+ const cut = line.indexOf(":");
190
+ if (cut <= 0)
191
+ continue;
192
+ const key = line.slice(0, cut).trim().toLowerCase();
193
+ if (key !== "name" && key !== "description")
194
+ continue;
195
+ const value = line.slice(cut + 1).trim().replace(/^['"]|['"]$/g, "");
196
+ if (value)
197
+ out[key] = value;
198
+ }
199
+ return out;
200
+ }
201
+ function sha256Hex(text) {
202
+ return createHash("sha256").update(text, "utf8").digest("hex");
203
+ }
204
+ function readTextFile(path) {
205
+ try {
206
+ if (!statSync(path).isFile())
207
+ return null;
208
+ const text = readFileSync(path, "utf8");
209
+ return text.trim() ? text : null;
210
+ } catch {
211
+ return null;
212
+ }
213
+ }
214
+ function readAppResourcesDir(directory) {
215
+ const warnings = [];
216
+ if (!isAbsolute(directory))
217
+ return { directoryReadable: false, rules: null, skills: [], warnings: ["资源目录必须是本机绝对路径"] };
218
+ let directoryReadable = false;
219
+ try {
220
+ directoryReadable = statSync(directory).isDirectory();
221
+ } catch {
222
+ directoryReadable = false;
223
+ }
224
+ if (!directoryReadable) {
225
+ return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
226
+ }
227
+ let rules = null;
228
+ const rulesText = readTextFile(join(directory, APP_RULES_FILE));
229
+ if (rulesText === null) {
230
+ warnings.push(`缺常驻规则: ${APP_RULES_FILE}`);
231
+ } else {
232
+ rules = { chars: rulesText.length, digest: sha256Hex(`app-rules-v1
233
+ ${rulesText}`) };
234
+ }
235
+ const skills = [];
236
+ const skillsRoot = join(directory, APP_SKILLS_DIR);
237
+ let skillNames = [];
238
+ try {
239
+ if (statSync(skillsRoot).isDirectory()) {
240
+ skillNames = readdirSync(skillsRoot).filter((name) => {
241
+ try {
242
+ return statSync(join(skillsRoot, name)).isDirectory();
243
+ } catch {
244
+ return false;
245
+ }
246
+ });
247
+ }
248
+ } catch {
249
+ skillNames = [];
250
+ }
251
+ for (const name of skillNames.sort()) {
252
+ const rel = `${APP_SKILLS_DIR}/${name}/${APP_SKILL_FILE}`;
253
+ const text = readTextFile(join(directory, rel));
254
+ if (text === null) {
255
+ warnings.push(`技能缺正文已跳过: ${rel}`);
256
+ continue;
257
+ }
258
+ const front = parseSkillFrontmatter(text);
259
+ const skillName = front.name || name;
260
+ if (skills.some((s) => s.name === skillName)) {
261
+ warnings.push(`技能重名已跳过(保留首个): ${skillName}`);
262
+ continue;
263
+ }
264
+ const description = front.description || "";
265
+ skills.push({
266
+ name: skillName,
267
+ description,
268
+ path: rel,
269
+ chars: text.length,
270
+ digest: sha256Hex(`app-skill-v1
271
+ ${skillName}
272
+ ${description}
273
+ ${text}`)
274
+ });
275
+ }
276
+ return { directoryReadable: true, rules, skills, warnings };
277
+ }
278
+ function digestAppResources(load) {
279
+ if (!load.rules)
280
+ return null;
281
+ const skillPart = load.skills.map((s) => `${s.name}:${s.digest}`).join(`
282
+ `);
283
+ return sha256Hex(`app-resources-v1
284
+ ${load.rules.digest}
285
+ ${skillPart}`);
286
+ }
287
+ function readAppRulesText(directory) {
288
+ return readTextFile(join(directory, APP_RULES_FILE));
289
+ }
290
+ function isAbsolutePathLike(path) {
291
+ return isAbsolute(path);
292
+ }
293
+
294
+ // src/resources/session-config.ts
295
+ async function createSessionConfigHome(runtime, resources) {
296
+ if (!isAbsolute2(resources))
297
+ throw new Error("Resources must be an absolute path");
298
+ const id = runtime === "cursor" ? "cursor-cli" : runtime;
299
+ const supported = ["agy", "codex-acp", "claude", "gemini", "copilot", "cursor-cli", "opencode", "opencode-v2"];
300
+ if (!supported.includes(id))
301
+ throw new Error("Session configuration home is not verified for runtime: " + runtime);
302
+ const text = readAppRulesText(resources);
303
+ if (!text)
304
+ throw new Error("Session configuration requires nonempty AGENTS.md");
305
+ const parent = resolve(tmpdir());
306
+ const directory = await mkdtemp(join2(parent, "acp-session-config-"));
307
+ const checkRoot = () => {
308
+ if (resolve(directory) === parent || !resolve(directory).startsWith(parent + sep) || !relative(parent, directory).startsWith("acp-session-config-"))
309
+ throw new Error("Unsafe configuration cleanup target");
310
+ };
311
+ const dispose = async () => {
312
+ checkRoot();
313
+ let failure;
314
+ for (let i = 0;i < 30; i++) {
315
+ try {
316
+ await rm(directory, { recursive: true, force: true });
317
+ return;
318
+ } catch (error) {
319
+ failure = error;
320
+ await new Promise((r) => setTimeout(r, 100));
321
+ }
322
+ }
323
+ throw failure;
324
+ };
325
+ try {
326
+ const config = join2(directory, "config");
327
+ await mkdir(config, { recursive: true, mode: 448 });
328
+ let env;
329
+ let rulesFile;
330
+ let skillsRoot = join2(config, "skills");
331
+ let nativeRules = true;
332
+ if (id === "agy") {
333
+ rulesFile = join2(config, "AGENTS.md");
334
+ env = { AGY_ACP_RESOURCES_DIR: config };
335
+ nativeRules = false;
336
+ } else if (id === "gemini") {
337
+ const root = join2(directory, "home", ".gemini");
338
+ await mkdir(root, { recursive: true, mode: 448 });
339
+ rulesFile = join2(root, "GEMINI.md");
340
+ skillsRoot = join2(root, "skills");
341
+ env = { GEMINI_CLI_HOME: join2(directory, "home") };
342
+ } else if (id === "claude") {
343
+ rulesFile = join2(config, "CLAUDE.md");
344
+ env = { CLAUDE_CONFIG_DIR: config };
345
+ } else if (id === "codex-acp") {
346
+ rulesFile = join2(config, "AGENTS.md");
347
+ env = { CODEX_HOME: config };
348
+ } else if (id === "copilot") {
349
+ rulesFile = join2(config, "copilot-instructions.md");
350
+ env = { COPILOT_HOME: config, COPILOT_CUSTOM_INSTRUCTIONS_DIRS: config, COPILOT_SKILLS_DIRS: skillsRoot };
351
+ await writeFile(join2(config, "AGENTS.md"), text, { mode: 384 });
352
+ } else if (id === "cursor-cli") {
353
+ rulesFile = join2(config, "AGENTS.md");
354
+ env = { CURSOR_CONFIG_DIR: config };
355
+ nativeRules = false;
356
+ } else {
357
+ const root = join2(directory, "xdg-config", "opencode");
358
+ await mkdir(root, { recursive: true, mode: 448 });
359
+ rulesFile = join2(root, "AGENTS.md");
360
+ skillsRoot = join2(root, "skills");
361
+ env = { XDG_CONFIG_HOME: join2(directory, "xdg-config"), XDG_DATA_HOME: join2(directory, "xdg-data"), XDG_CACHE_HOME: join2(directory, "xdg-cache"), XDG_STATE_HOME: join2(directory, "xdg-state") };
362
+ if (id === "opencode")
363
+ env.OPENCODE_CONFIG_DIR = root;
364
+ const skills = id === "opencode" ? { paths: [skillsRoot] } : [skillsRoot];
365
+ await writeFile(join2(root, "opencode.json"), JSON.stringify({ instructions: [rulesFile], skills }), { mode: 384 });
366
+ }
367
+ await writeFile(rulesFile, text, { mode: 384 });
368
+ const input = join2(resources, "skills");
369
+ try {
370
+ const info = await lstat(input);
371
+ if (info.isSymbolicLink() || !info.isDirectory())
372
+ throw new Error("Skill root must be a regular directory");
373
+ const physical = await realpath(input);
374
+ const copy = async (from, to) => {
375
+ await mkdir(to, { recursive: true, mode: 448 });
376
+ for (const entry of await readdir(from, { withFileTypes: true })) {
377
+ const src = join2(from, entry.name);
378
+ const info = await lstat(src);
379
+ if (info.isSymbolicLink())
380
+ throw new Error("Skill symlink is not allowed");
381
+ const actual = await realpath(src);
382
+ const rel = relative(physical, actual);
383
+ if (rel.startsWith(".." + sep) || rel === ".." || isAbsolute2(rel))
384
+ throw new Error("Skill path escapes resources");
385
+ if (info.isDirectory())
386
+ await copy(src, join2(to, entry.name));
387
+ else if (info.isFile() && entry.name.toLowerCase().endsWith(".md"))
388
+ await writeFile(join2(to, entry.name), await readFile(src), { mode: 384 });
389
+ }
390
+ };
391
+ await copy(input, skillsRoot);
392
+ } catch (error) {
393
+ if (error.code !== "ENOENT" || existsSync(input))
394
+ throw error;
395
+ }
396
+ return { directory, env, rulesFile, nativeRules, dispose };
397
+ } catch (error) {
398
+ await dispose();
399
+ throw error;
400
+ }
401
+ }
402
+
163
403
  // src/session/available-commands.ts
164
404
  function normalizeCommand(raw) {
165
405
  if (!raw || typeof raw !== "object")
@@ -409,15 +649,15 @@ import {
409
649
  } from "@agentclientprotocol/sdk";
410
650
 
411
651
  // src/runtimes/codex/quota.ts
412
- import { existsSync as existsSync2, readFileSync } from "node:fs";
413
- import { join as join2 } from "node:path";
652
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
653
+ import { join as join4 } from "node:path";
414
654
  import { spawn } from "node:child_process";
415
655
  import readline from "node:readline";
416
656
 
417
657
  // src/runtimes/codex/codex-auth-preflight.ts
418
- import { existsSync } from "node:fs";
658
+ import { existsSync as existsSync2 } from "node:fs";
419
659
  import { homedir } from "node:os";
420
- import { join } from "node:path";
660
+ import { join as join3 } from "node:path";
421
661
  function emptyAcpAuthPreflight() {
422
662
  return {
423
663
  codexHome: "",
@@ -434,12 +674,12 @@ function resolveCodexHome() {
434
674
  const fromEnv = process.env.CODEX_HOME?.trim();
435
675
  if (fromEnv)
436
676
  return fromEnv;
437
- return join(homedir(), ".codex");
677
+ return join3(homedir(), ".codex");
438
678
  }
439
679
  function probeCodexAuth() {
440
680
  const codexHome = resolveCodexHome();
441
- const hasCodexHome = existsSync(codexHome);
442
- const hasAuthFile = existsSync(join(codexHome, "auth.json"));
681
+ const hasCodexHome = existsSync2(codexHome);
682
+ const hasAuthFile = existsSync2(join3(codexHome, "auth.json"));
443
683
  const hasApiKeyEnv = Boolean(process.env.CODEX_API_KEY?.trim() || process.env.OPENAI_API_KEY?.trim());
444
684
  return {
445
685
  codexHome,
@@ -463,8 +703,8 @@ function decodeJwtPayload(token) {
463
703
  }
464
704
  }
465
705
  var cachedDynamicResult = null;
466
- async function queryCodexAppServer(timeoutMs = 4000) {
467
- if (cachedDynamicResult && Date.now() - cachedDynamicResult.time < 15000) {
706
+ async function queryCodexAppServer(timeoutMs = 1e4) {
707
+ if (cachedDynamicResult && Date.now() - cachedDynamicResult.time < 120000) {
468
708
  return cachedDynamicResult.res;
469
709
  }
470
710
  return new Promise((resolve) => {
@@ -489,7 +729,8 @@ async function queryCodexAppServer(timeoutMs = 4000) {
489
729
  };
490
730
  timer = setTimeout(() => cleanup(null), timeoutMs);
491
731
  try {
492
- proc = spawn("codex", ["app-server"], {
732
+ const cmd = process.platform === "win32" ? "codex" : existsSync3("/mnt/c/Users") ? "codex.exe" : "codex";
733
+ proc = spawn(cmd, ["app-server"], {
493
734
  stdio: ["pipe", "pipe", "pipe"],
494
735
  shell: process.platform === "win32",
495
736
  windowsHide: true
@@ -559,13 +800,13 @@ function formatEpochTime(epochSeconds) {
559
800
  }
560
801
  async function probeCodexQuota(options) {
561
802
  const codexHome = resolveCodexHome();
562
- const authPath = join2(codexHome, "auth.json");
803
+ const authPath = join4(codexHome, "auth.json");
563
804
  let accountEmail;
564
805
  let accountPlan = "Codex Free / Local";
565
806
  let isLoggedIn = false;
566
- if (existsSync2(authPath)) {
807
+ if (existsSync3(authPath)) {
567
808
  try {
568
- const authData = JSON.parse(readFileSync(authPath, "utf8"));
809
+ const authData = JSON.parse(readFileSync2(authPath, "utf8"));
569
810
  if (authData.OPENAI_API_KEY) {
570
811
  isLoggedIn = true;
571
812
  accountPlan = "OpenAI API Key";
@@ -590,7 +831,7 @@ async function probeCodexQuota(options) {
590
831
  isLoggedIn = true;
591
832
  accountPlan = "API Key (Env)";
592
833
  }
593
- const dynamic = await queryCodexAppServer(4000);
834
+ const dynamic = await queryCodexAppServer(1e4);
594
835
  if (dynamic) {
595
836
  isLoggedIn = true;
596
837
  if (dynamic.account?.email)
@@ -656,8 +897,92 @@ async function probeCodexQuota(options) {
656
897
  }
657
898
 
658
899
  // src/runtimes/codex/index.ts
659
- import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
660
- import { join as join5 } from "node:path";
900
+ import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "node:fs/promises";
901
+ import { dirname, join as join7 } from "node:path";
902
+ import { homedir as homedir3 } from "node:os";
903
+ import { existsSync as existsSync5 } from "node:fs";
904
+ import { createHash as createHash2 } from "node:crypto";
905
+
906
+ // src/resources/config-text.ts
907
+ function mergeCodexConfigJson(input) {
908
+ const block = (input.hostBlock ?? "").trim();
909
+ if (!block)
910
+ return { ok: false, reason: "empty-block" };
911
+ const raw = (input.existingRaw ?? "").trim();
912
+ if (!raw) {
913
+ return { ok: true, json: JSON.stringify({ developer_instructions: block }), preservedUserInstructions: false };
914
+ }
915
+ let parsed;
916
+ try {
917
+ parsed = JSON.parse(raw);
918
+ } catch {
919
+ return { ok: false, reason: "invalid-json" };
920
+ }
921
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
922
+ return { ok: false, reason: "invalid-json" };
923
+ }
924
+ const merged = { ...parsed };
925
+ const existing = merged["developer_instructions"];
926
+ if (existing === undefined) {
927
+ merged["developer_instructions"] = block;
928
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: false };
929
+ }
930
+ if (typeof existing !== "string") {
931
+ return { ok: false, reason: "conflicting-value" };
932
+ }
933
+ const kept = existing.trim();
934
+ merged["developer_instructions"] = kept ? `${block}
935
+
936
+ ${kept}` : block;
937
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: kept !== "" };
938
+ }
939
+ function mergeConfigTomlPreserving(input) {
940
+ const block = (input.replacementBlock ?? "").trim() ? `${input.replacementBlock.trim()}
941
+ ` : "";
942
+ if (!input.existingText || !input.existingText.trim())
943
+ return block;
944
+ if (/"""|'''/.test(input.existingText) || /^\s*\[.*["'].*\]|^\s*\[\[|^\s*["'](?:model|model_provider)["']\s*=/m.test(input.existingText)) {
945
+ throw new Error("复杂 TOML 配置需要结构化合并,已保留原文件");
946
+ }
947
+ const topKeys = new Set(input.managedTopKeys);
948
+ const tables = new Set(input.managedTables);
949
+ const out = [];
950
+ let inManagedTable = false;
951
+ let inAnyTable = false;
952
+ for (const line of input.existingText.split(`
953
+ `)) {
954
+ const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(line)?.[1]?.trim() ?? null;
955
+ if (header !== null) {
956
+ inAnyTable = true;
957
+ inManagedTable = tables.has(header);
958
+ if (!inManagedTable)
959
+ out.push(line);
960
+ continue;
961
+ }
962
+ if (inManagedTable)
963
+ continue;
964
+ if (!inAnyTable) {
965
+ const key = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1];
966
+ if (key && topKeys.has(key))
967
+ continue;
968
+ }
969
+ out.push(line);
970
+ }
971
+ const kept = out.join(`
972
+ `).trim();
973
+ if (!kept)
974
+ return block;
975
+ const tableAt = block.search(/^\s*\[/m);
976
+ if (tableAt < 0)
977
+ return block + `
978
+ ` + kept + `
979
+ `;
980
+ return block.slice(0, tableAt).trimEnd() + `
981
+
982
+ ` + kept + `
983
+
984
+ ` + block.slice(tableAt);
985
+ }
661
986
 
662
987
  // src/runtimes/codex/codex-provider-home.ts
663
988
  var INKDOWN_PROVIDER_ID = "inkdown-custom";
@@ -689,13 +1014,13 @@ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
689
1014
  }
690
1015
 
691
1016
  // src/runtimes/codex/codex-provider.ts
692
- import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
693
- import { existsSync as existsSync3 } from "node:fs";
694
- import { join as join4 } from "node:path";
1017
+ import { mkdir as mkdir2, readFile as readFile2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
1018
+ import { existsSync as existsSync4 } from "node:fs";
1019
+ import { join as join6 } from "node:path";
695
1020
 
696
1021
  // src/client/acp-paths.ts
697
1022
  import { homedir as homedir2 } from "node:os";
698
- import { join as join3 } from "node:path";
1023
+ import { join as join5 } from "node:path";
699
1024
  function getDefaultAgentDataDir() {
700
1025
  if (process.env.INKDOWN_DATA_DIR) {
701
1026
  return process.env.INKDOWN_DATA_DIR;
@@ -704,20 +1029,20 @@ function getDefaultAgentDataDir() {
704
1029
  return process.env.ACP_DATA_DIR;
705
1030
  }
706
1031
  if (process.platform === "win32") {
707
- return process.env.LOCALAPPDATA || process.env.APPDATA || join3(homedir2(), "AppData", "Local", "inkdown");
1032
+ return process.env.LOCALAPPDATA || process.env.APPDATA || join5(homedir2(), "AppData", "Local", "inkdown");
708
1033
  }
709
1034
  if (process.platform === "darwin") {
710
- return join3(homedir2(), "Library", "Application Support", "inkdown");
1035
+ return join5(homedir2(), "Library", "Application Support", "inkdown");
711
1036
  }
712
- return process.env.XDG_DATA_HOME || join3(homedir2(), ".local", "share", "inkdown");
1037
+ return process.env.XDG_DATA_HOME || join5(homedir2(), ".local", "share", "inkdown");
713
1038
  }
714
1039
 
715
1040
  // src/runtimes/codex/codex-provider.ts
716
1041
  function providerFilePath(dir) {
717
- return join4(dir, "agent", "provider.json");
1042
+ return join6(dir, "agent", "provider.json");
718
1043
  }
719
1044
  function providerHomePath(dir) {
720
- return join4(dir, "agent", "codex-home");
1045
+ return join6(dir, "agent", "codex-home");
721
1046
  }
722
1047
  function toStatus(stored) {
723
1048
  if (!stored)
@@ -743,10 +1068,10 @@ function validate(payload) {
743
1068
  }
744
1069
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
745
1070
  const file = providerFilePath(dir);
746
- if (!existsSync3(file))
1071
+ if (!existsSync4(file))
747
1072
  return null;
748
1073
  try {
749
- const raw = JSON.parse(await readFile(file, "utf8"));
1074
+ const raw = JSON.parse(await readFile2(file, "utf8"));
750
1075
  if (typeof raw.baseUrl !== "string" || typeof raw.model !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
751
1076
  return null;
752
1077
  }
@@ -772,7 +1097,7 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
772
1097
  const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
773
1098
  if (!apiKey)
774
1099
  return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
775
- await mkdir(join4(dir, "agent"), { recursive: true });
1100
+ await mkdir2(join6(dir, "agent"), { recursive: true });
776
1101
  const stored = {
777
1102
  name: payload.name?.trim() || undefined,
778
1103
  baseUrl: payload.baseUrl.trim(),
@@ -780,11 +1105,11 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
780
1105
  apiKey,
781
1106
  wireApi: payload.wireApi === "responses" ? "responses" : "chat"
782
1107
  };
783
- await writeFile(file, JSON.stringify(stored, null, 2), "utf8");
1108
+ await writeFile2(file, JSON.stringify(stored, null, 2), "utf8");
784
1109
  return ok(toStatus(stored));
785
1110
  }
786
1111
  async function clearAcpProvider(dir = getDefaultAgentDataDir()) {
787
- await rm(providerFilePath(dir), { force: true });
1112
+ await rm2(providerFilePath(dir), { force: true });
788
1113
  return ok(undefined);
789
1114
  }
790
1115
  function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
@@ -794,8 +1119,20 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
794
1119
  // src/runtimes/codex/index.ts
795
1120
  async function provisionCustomProviderCodexHome(provider, codexHome) {
796
1121
  try {
797
- await mkdir2(codexHome, { recursive: true });
798
- await writeFile2(join5(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
1122
+ await mkdir3(codexHome, { recursive: true });
1123
+ let existing = null;
1124
+ try {
1125
+ existing = await readFile3(join7(codexHome, "config.toml"), "utf8");
1126
+ } catch (error) {
1127
+ if (error.code !== "ENOENT")
1128
+ throw error;
1129
+ }
1130
+ await writeFile3(join7(codexHome, "config.toml"), mergeConfigTomlPreserving({
1131
+ existingText: existing,
1132
+ managedTopKeys: ["model", "model_provider"],
1133
+ managedTables: [`model_providers.${INKDOWN_PROVIDER_ID}`],
1134
+ replacementBlock: buildCustomProviderConfigToml(provider)
1135
+ }), "utf8");
799
1136
  return true;
800
1137
  } catch (error) {
801
1138
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -805,6 +1142,78 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
805
1142
  var codexAdapter = {
806
1143
  id: "codex-acp",
807
1144
  probeQuota: async (options) => probeCodexQuota(options),
1145
+ supportedBridgeVersions: ["2.2.2"],
1146
+ prepareAppResources: async ({ directory, workspaceRoot, env: overrideEnv }) => {
1147
+ const load = readAppResourcesDir(directory);
1148
+ const skillsFound = load.skills.map((s) => s.name);
1149
+ const rulesText = readAppRulesText(directory);
1150
+ if (!rulesText) {
1151
+ return {
1152
+ report: {
1153
+ rulesApplied: false,
1154
+ rulesChars: 0,
1155
+ profileDigest: null,
1156
+ skillsFound,
1157
+ reason: "rules-missing"
1158
+ }
1159
+ };
1160
+ }
1161
+ const env = { ...process.env, ...overrideEnv };
1162
+ const notApplied = (reason) => ({ report: {
1163
+ rulesApplied: false,
1164
+ rulesPrepared: false,
1165
+ skillsApplied: false,
1166
+ rulesChars: rulesText.length,
1167
+ profileDigest: digestAppResources(load),
1168
+ skillsFound,
1169
+ reason
1170
+ } });
1171
+ if (!load.directoryReadable)
1172
+ return notApplied("invalid-resource-directory");
1173
+ if (env.CODEX_PATH)
1174
+ return notApplied("execution-not-verified");
1175
+ const codexHome = env.CODEX_HOME || join7(homedir3(), ".codex");
1176
+ try {
1177
+ await readFile3(join7(codexHome, "config.toml"));
1178
+ return notApplied("effective-config-not-verified");
1179
+ } catch (error) {
1180
+ if (error.code !== "ENOENT")
1181
+ return notApplied("effective-config-not-verified");
1182
+ }
1183
+ for (let dir = workspaceRoot;dir; ) {
1184
+ if (existsSync5(join7(dir, ".codex", "config.toml")))
1185
+ return notApplied("effective-config-not-verified");
1186
+ if (existsSync5(join7(dir, ".git")))
1187
+ break;
1188
+ const parent = dirname(dir);
1189
+ if (parent === dir)
1190
+ break;
1191
+ dir = parent;
1192
+ }
1193
+ const merged = mergeCodexConfigJson({ existingRaw: env["CODEX_CONFIG"], hostBlock: rulesText });
1194
+ if (!merged.ok) {
1195
+ return {
1196
+ report: {
1197
+ rulesApplied: false,
1198
+ rulesChars: rulesText.length,
1199
+ profileDigest: digestAppResources(load),
1200
+ skillsFound,
1201
+ reason: merged.reason === "invalid-json" ? "invalid-codex-config" : "conflicting-codex-config"
1202
+ }
1203
+ };
1204
+ }
1205
+ return {
1206
+ env: { CODEX_CONFIG: merged.json },
1207
+ report: {
1208
+ rulesApplied: false,
1209
+ rulesPrepared: true,
1210
+ skillsApplied: false,
1211
+ rulesChars: rulesText.length,
1212
+ profileDigest: createHash2("sha256").update(JSON.stringify([digestAppResources(load), codexHome, workspaceRoot, merged.json])).digest("hex"),
1213
+ skillsFound
1214
+ }
1215
+ };
1216
+ },
808
1217
  probeAuth: () => {
809
1218
  return probeCodexAuth();
810
1219
  },
@@ -821,11 +1230,84 @@ var codexAdapter = {
821
1230
  }
822
1231
  };
823
1232
 
824
- // src/runtimes/claude/quota.ts
825
- import { existsSync as existsSync4, readFileSync as readFileSync2 } from "node:fs";
826
- import { homedir as homedir3 } from "node:os";
827
- import { join as join6 } from "node:path";
1233
+ // src/resources/runtime-bindings.ts
1234
+ import { join as join8 } from "node:path";
828
1235
  import { execFile } from "node:child_process";
1236
+ import { promisify } from "node:util";
1237
+ var APP_RESOURCE_CAPABILITIES = {
1238
+ "codex-acp": { entry: "CODEX_CONFIG", strategy: "native-overlay", configHome: "CODEX_HOME" },
1239
+ opencode: { entry: "OPENCODE_CONFIG_CONTENT", strategy: "native-overlay", configHome: "OPENCODE_CONFIG_DIR" },
1240
+ "opencode-v2": { entry: null, strategy: "compatibility", configHome: null },
1241
+ claude: { entry: "_meta.systemPrompt + _meta.claudeCode.options.plugins", strategy: "native-session", configHome: "CLAUDE_CONFIG_DIR" },
1242
+ gemini: { entry: null, strategy: "compatibility", configHome: "GEMINI_CLI_HOME" },
1243
+ copilot: { entry: null, strategy: "compatibility", configHome: "COPILOT_HOME", candidateEntry: "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" },
1244
+ "cursor-cli": { entry: null, strategy: "compatibility", configHome: "CURSOR_CONFIG_DIR" },
1245
+ agy: { entry: "_meta.appResources.directory", strategy: "native-session", configHome: null },
1246
+ deepseek: { entry: null, strategy: "compatibility", configHome: null }
1247
+ };
1248
+ function prepareCompatibilityResources(directory, reason) {
1249
+ const load = readAppResourcesDir(directory);
1250
+ return { report: {
1251
+ rulesApplied: false,
1252
+ rulesPrepared: false,
1253
+ skillsApplied: false,
1254
+ rulesChars: load.rules?.chars ?? 0,
1255
+ profileDigest: digestAppResources(load),
1256
+ skillsFound: load.skills.map((s) => s.name),
1257
+ reason
1258
+ } };
1259
+ }
1260
+ function mergeOpenCodeAppConfig(raw, directory) {
1261
+ const value = raw?.trim() ? JSON.parse(raw) : {};
1262
+ if (!value || typeof value !== "object" || Array.isArray(value))
1263
+ throw new Error("invalid-opencode-config");
1264
+ const config = value;
1265
+ if (config.instructions !== undefined && (!Array.isArray(config.instructions) || config.instructions.some((v) => typeof v !== "string")))
1266
+ throw new Error("invalid-opencode-instructions");
1267
+ if (config.skills !== undefined && (!config.skills || typeof config.skills !== "object" || Array.isArray(config.skills)))
1268
+ throw new Error("invalid-opencode-skills");
1269
+ const skills = config.skills ?? {};
1270
+ if (skills.paths !== undefined && (!Array.isArray(skills.paths) || skills.paths.some((v) => typeof v !== "string")))
1271
+ throw new Error("invalid-opencode-skill-paths");
1272
+ return JSON.stringify({
1273
+ ...config,
1274
+ instructions: [...new Set([...config.instructions ?? [], join8(directory, "AGENTS.md")])],
1275
+ skills: { ...skills, paths: [...new Set([...skills.paths ?? [], join8(directory, "skills")])] }
1276
+ });
1277
+ }
1278
+ async function prepareOpenCodeResources(input) {
1279
+ const prep = prepareCompatibilityResources(input.directory, "native-entry-not-verified");
1280
+ if (!input.command || !readAppRulesText(input.directory))
1281
+ return prep;
1282
+ try {
1283
+ const { stdout } = await promisify(execFile)(input.command, ["--version"], { env: input.env, timeout: 8000, windowsHide: true });
1284
+ if (stdout.trim() !== "1.18.35")
1285
+ return prep;
1286
+ const json = mergeOpenCodeAppConfig(input.env?.OPENCODE_CONFIG_CONTENT, input.directory);
1287
+ return { env: { OPENCODE_CONFIG_CONTENT: json }, report: { ...prep.report, rulesPrepared: true, reason: undefined } };
1288
+ } catch {
1289
+ return { ...prep, report: { ...prep.report, reason: "native-config-prepare-failed" } };
1290
+ }
1291
+ }
1292
+ function prepareClaudeResources(directory) {
1293
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
1294
+ return { ...prep, report: { ...prep.report, rulesPrepared: !!readAppRulesText(directory) } };
1295
+ }
1296
+ function claudeResourceSessionMeta(directory) {
1297
+ const text = readAppRulesText(directory);
1298
+ if (!text)
1299
+ return;
1300
+ return {
1301
+ systemPrompt: { type: "preset", preset: "claude_code", append: text },
1302
+ claudeCode: { options: { plugins: [{ type: "local", path: directory }] } }
1303
+ };
1304
+ }
1305
+
1306
+ // src/runtimes/claude/quota.ts
1307
+ import { existsSync as existsSync6, readFileSync as readFileSync3 } from "node:fs";
1308
+ import { homedir as homedir4 } from "node:os";
1309
+ import { join as join9 } from "node:path";
1310
+ import { execFile as execFile2 } from "node:child_process";
829
1311
  var cachedClaudeAuth = null;
830
1312
  async function queryClaudeAuthStatus(timeoutMs = 1200) {
831
1313
  if (cachedClaudeAuth && Date.now() - cachedClaudeAuth.time < 30000) {
@@ -833,7 +1315,7 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
833
1315
  }
834
1316
  return new Promise((resolve) => {
835
1317
  try {
836
- execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
1318
+ execFile2("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
837
1319
  if (!stdout)
838
1320
  return resolve(null);
839
1321
  try {
@@ -851,15 +1333,15 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
851
1333
  }
852
1334
  async function probeClaudeQuota(options) {
853
1335
  const claudeHome = resolveClaudeHome();
854
- const claudeJsonPath = join6(homedir3(), ".claude.json");
855
- const credsPath = join6(claudeHome, ".credentials.json");
1336
+ const claudeJsonPath = join9(homedir4(), ".claude.json");
1337
+ const credsPath = join9(claudeHome, ".credentials.json");
856
1338
  let isLoggedIn = false;
857
1339
  let isBanned = false;
858
1340
  let accountEmail;
859
1341
  let plan = "Claude Free / Default";
860
- if (existsSync4(claudeJsonPath)) {
1342
+ if (existsSync6(claudeJsonPath)) {
861
1343
  try {
862
- const data = JSON.parse(readFileSync2(claudeJsonPath, "utf8"));
1344
+ const data = JSON.parse(readFileSync3(claudeJsonPath, "utf8"));
863
1345
  if (data.oauthAccount) {
864
1346
  isLoggedIn = true;
865
1347
  accountEmail = data.oauthAccount.emailAddress;
@@ -870,9 +1352,9 @@ async function probeClaudeQuota(options) {
870
1352
  }
871
1353
  } catch {}
872
1354
  }
873
- if (existsSync4(credsPath)) {
1355
+ if (existsSync6(credsPath)) {
874
1356
  try {
875
- const creds = JSON.parse(readFileSync2(credsPath, "utf8"));
1357
+ const creds = JSON.parse(readFileSync3(credsPath, "utf8"));
876
1358
  if (creds.accessToken || creds.sessionKey)
877
1359
  isLoggedIn = true;
878
1360
  } catch {}
@@ -924,19 +1406,19 @@ async function probeClaudeQuota(options) {
924
1406
  }
925
1407
 
926
1408
  // src/runtimes/claude/index.ts
927
- import { existsSync as existsSync5 } from "node:fs";
928
- import { homedir as homedir4 } from "node:os";
929
- import { join as join7 } from "node:path";
1409
+ import { existsSync as existsSync7 } from "node:fs";
1410
+ import { homedir as homedir5 } from "node:os";
1411
+ import { join as join10 } from "node:path";
930
1412
  function resolveClaudeHome() {
931
1413
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
932
1414
  if (fromEnv)
933
1415
  return fromEnv;
934
- return join7(homedir4(), ".claude");
1416
+ return join10(homedir5(), ".claude");
935
1417
  }
936
1418
  function probeClaudeAuth() {
937
1419
  const claudeHome = resolveClaudeHome();
938
- const hasCodexHome = existsSync5(claudeHome);
939
- const hasAuthFile = existsSync5(join7(homedir4(), ".claude.json")) || existsSync5(join7(claudeHome, ".credentials.json"));
1420
+ const hasCodexHome = existsSync7(claudeHome);
1421
+ const hasAuthFile = existsSync7(join10(homedir5(), ".claude.json")) || existsSync7(join10(claudeHome, ".credentials.json"));
940
1422
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
941
1423
  return {
942
1424
  codexHome: claudeHome,
@@ -948,6 +1430,9 @@ function probeClaudeAuth() {
948
1430
  }
949
1431
  var claudeAdapter = {
950
1432
  id: "claude",
1433
+ supportedBridgeVersions: ["0.91.0"],
1434
+ prepareAppResources: async ({ directory }) => prepareClaudeResources(directory),
1435
+ appResourceSessionMeta: claudeResourceSessionMeta,
951
1436
  probeAuth: () => probeClaudeAuth(),
952
1437
  probeQuota: async (options) => probeClaudeQuota(options),
953
1438
  orderAuthMethods: (methods) => methods,
@@ -955,16 +1440,16 @@ var claudeAdapter = {
955
1440
  };
956
1441
 
957
1442
  // src/runtimes/gemini/index.ts
958
- import { existsSync as existsSync6 } from "node:fs";
959
- import { homedir as homedir5 } from "node:os";
960
- import { join as join8 } from "node:path";
1443
+ import { existsSync as existsSync8 } from "node:fs";
1444
+ import { homedir as homedir6 } from "node:os";
1445
+ import { join as join11 } from "node:path";
961
1446
  function resolveGeminiHome() {
962
- return join8(homedir5(), ".gemini");
1447
+ return join11(homedir6(), ".gemini");
963
1448
  }
964
1449
  function probeGeminiAuth() {
965
1450
  const geminiHome = resolveGeminiHome();
966
- const hasCodexHome = existsSync6(geminiHome);
967
- const hasAuthFile = existsSync6(join8(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
1451
+ const hasCodexHome = existsSync8(geminiHome);
1452
+ const hasAuthFile = existsSync8(join11(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
968
1453
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
969
1454
  return {
970
1455
  codexHome: geminiHome,
@@ -976,24 +1461,25 @@ function probeGeminiAuth() {
976
1461
  }
977
1462
  var geminiAdapter = {
978
1463
  id: "gemini",
1464
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-would-isolate-auth"),
979
1465
  probeAuth: () => probeGeminiAuth(),
980
1466
  orderAuthMethods: (methods) => methods,
981
1467
  canSkipInteractiveAuth: () => false
982
1468
  };
983
1469
 
984
1470
  // src/runtimes/copilot/index.ts
985
- import { existsSync as existsSync7, readFileSync as readFileSync3 } from "node:fs";
986
- import { homedir as homedir6 } from "node:os";
987
- import { join as join9 } from "node:path";
1471
+ import { existsSync as existsSync9, readFileSync as readFileSync4 } from "node:fs";
1472
+ import { homedir as homedir7 } from "node:os";
1473
+ import { join as join12 } from "node:path";
988
1474
  function resolveCopilotHome() {
989
1475
  const fromEnv = process.env.COPILOT_HOME?.trim();
990
1476
  if (fromEnv)
991
1477
  return fromEnv;
992
- return join9(homedir6(), ".copilot");
1478
+ return join12(homedir7(), ".copilot");
993
1479
  }
994
1480
  function hasCopilotLogin(home) {
995
1481
  try {
996
- const raw = readFileSync3(join9(home, "config.json"), "utf8");
1482
+ const raw = readFileSync4(join12(home, "config.json"), "utf8");
997
1483
  const parsed = JSON.parse(raw);
998
1484
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
999
1485
  } catch {
@@ -1002,7 +1488,7 @@ function hasCopilotLogin(home) {
1002
1488
  }
1003
1489
  function probeCopilotAuth() {
1004
1490
  const copilotHome = resolveCopilotHome();
1005
- const hasCodexHome = existsSync7(copilotHome);
1491
+ const hasCodexHome = existsSync9(copilotHome);
1006
1492
  const hasAuthFile = hasCopilotLogin(copilotHome);
1007
1493
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
1008
1494
  return {
@@ -1015,18 +1501,21 @@ function probeCopilotAuth() {
1015
1501
  }
1016
1502
  var copilotAdapter = {
1017
1503
  id: "copilot",
1504
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-entry-not-verified"),
1018
1505
  probeAuth: () => probeCopilotAuth(),
1019
1506
  orderAuthMethods: (methods) => methods,
1020
1507
  canSkipInteractiveAuth: () => false
1021
1508
  };
1022
1509
 
1023
1510
  // src/runtimes/opencode/quota.ts
1024
- import { existsSync as existsSync8, readFileSync as readFileSync4 } from "node:fs";
1025
- import { execFile as execFile2 } from "node:child_process";
1511
+ import { existsSync as existsSync10, readFileSync as readFileSync5 } from "node:fs";
1512
+ import { execFile as execFile3 } from "node:child_process";
1513
+ import * as os from "node:os";
1514
+ import * as path from "node:path";
1026
1515
  function resolveOpencodeAuthPath() {
1027
1516
  const candidates = resolveOpencodeAuthCandidates();
1028
1517
  for (const c of candidates) {
1029
- if (existsSync8(c))
1518
+ if (existsSync10(c))
1030
1519
  return c;
1031
1520
  }
1032
1521
  return candidates[0] ?? null;
@@ -1038,7 +1527,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
1038
1527
  }
1039
1528
  return new Promise((resolve) => {
1040
1529
  try {
1041
- execFile2("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1530
+ execFile3("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1042
1531
  if (!stdout)
1043
1532
  return resolve(null);
1044
1533
  try {
@@ -1057,7 +1546,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
1057
1546
  async function queryOpencodeAuthList(timeoutMs = 1200) {
1058
1547
  return new Promise((resolve) => {
1059
1548
  try {
1060
- execFile2("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1549
+ execFile3("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
1061
1550
  if (!stdout)
1062
1551
  return resolve([]);
1063
1552
  const lines = stdout.split(`
@@ -1069,14 +1558,170 @@ async function queryOpencodeAuthList(timeoutMs = 1200) {
1069
1558
  }
1070
1559
  });
1071
1560
  }
1561
+ function readLocalOpencodeCredentials() {
1562
+ const home = os.homedir();
1563
+ const dbPaths = [
1564
+ path.join(home, ".local", "share", "opencode", "opencode.db"),
1565
+ process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "opencode", "opencode.db") : null,
1566
+ path.join(home, ".config", "opencode", "opencode.db")
1567
+ ].filter(Boolean);
1568
+ for (const dbPath of dbPaths) {
1569
+ if (!existsSync10(dbPath))
1570
+ continue;
1571
+ try {
1572
+ let rows = [];
1573
+ if (typeof process.versions?.bun !== "undefined") {
1574
+ const { Database } = __require("bun:sqlite");
1575
+ const db = new Database(dbPath, { readonly: true });
1576
+ rows = db.query("SELECT integration_id, value FROM credential").all();
1577
+ db.close();
1578
+ } else {
1579
+ const { DatabaseSync } = __require("node:sqlite");
1580
+ const db = new DatabaseSync(dbPath, { readOnly: true });
1581
+ rows = db.prepare("SELECT integration_id, value FROM credential").all();
1582
+ db.close();
1583
+ }
1584
+ const opencodeCred = rows.find((r) => r.integration_id === "opencode");
1585
+ if (opencodeCred?.value) {
1586
+ const parsed = JSON.parse(opencodeCred.value);
1587
+ const meta = parsed.metadata || {};
1588
+ return {
1589
+ email: meta.email || undefined,
1590
+ name: meta.email ? meta.email.split("@")[0] : meta.orgName || undefined,
1591
+ token: parsed.access || undefined,
1592
+ orgId: meta.orgID || undefined,
1593
+ accountId: meta.accountID || undefined
1594
+ };
1595
+ }
1596
+ } catch {
1597
+ try {
1598
+ const buf = readFileSync5(dbPath, "utf8");
1599
+ const emailMatch = buf.match(/"email"\s*:\s*"([^"]+)"/);
1600
+ const tokenMatch = buf.match(/"access"\s*:\s*"(st_[a-zA-Z0-9_\\-]+)"/);
1601
+ const orgMatch = buf.match(/"orgID"\s*:\s*"(wrk_[a-zA-Z0-9_\\-]+)"/);
1602
+ const accMatch = buf.match(/"accountID"\s*:\s*"(acc_[a-zA-Z0-9_\\-]+)"/);
1603
+ if (emailMatch || tokenMatch) {
1604
+ return {
1605
+ email: emailMatch?.[1],
1606
+ name: emailMatch?.[1]?.split("@")[0],
1607
+ token: tokenMatch?.[1],
1608
+ orgId: orgMatch?.[1],
1609
+ accountId: accMatch?.[1]
1610
+ };
1611
+ }
1612
+ } catch {}
1613
+ }
1614
+ }
1615
+ return {};
1616
+ }
1617
+ async function probeOpencodeGoOnlineQuota(creds, runtimeId = "opencode") {
1618
+ if (!creds.token || !creds.orgId)
1619
+ return null;
1620
+ try {
1621
+ const res = await fetch("https://opencode.ai/console/api/go/status", {
1622
+ headers: {
1623
+ Authorization: `Bearer ${creds.token}`,
1624
+ "x-opencode-org-id": creds.orgId,
1625
+ "x-opencode-account-id": creds.accountId || ""
1626
+ },
1627
+ signal: AbortSignal.timeout(3500)
1628
+ });
1629
+ if (!res.ok)
1630
+ return null;
1631
+ const data = await res.json();
1632
+ const meters = data?.access?.meters;
1633
+ if (!meters)
1634
+ return null;
1635
+ const formatReset = (isoStr) => {
1636
+ if (!isoStr)
1637
+ return;
1638
+ const diffMs = new Date(isoStr).getTime() - Date.now();
1639
+ if (diffMs <= 0)
1640
+ return "已重置";
1641
+ const totalMins = Math.floor(diffMs / 60000);
1642
+ const hours = Math.floor(totalMins / 60);
1643
+ const days = Math.floor(hours / 24);
1644
+ if (days > 0) {
1645
+ const remH = hours % 24;
1646
+ return `Resets in ${days}d ${remH}h`;
1647
+ }
1648
+ const remM = totalMins % 60;
1649
+ return `Resets in ${hours}h ${remM}m`;
1650
+ };
1651
+ const calcWindow = (m, label, durMins) => {
1652
+ if (!m || !m.limitMicroCents)
1653
+ return;
1654
+ const limit = Number(m.limitMicroCents);
1655
+ const used = Number(m.usedMicroCents || 0);
1656
+ const usedPercent = limit > 0 ? Math.round(used / limit * 100) : 0;
1657
+ const percentLeft = Math.max(0, 100 - usedPercent);
1658
+ return {
1659
+ label,
1660
+ usedPercent,
1661
+ percentLeft,
1662
+ windowDurationMins: durMins,
1663
+ resetsAt: formatReset(m.resetsAt)
1664
+ };
1665
+ };
1666
+ const rolling = calcWindow(meters.fiveHour, "Rolling", 300);
1667
+ const weekly = calcWindow(meters.week, "Weekly", 10080);
1668
+ const monthly = calcWindow(meters.month, "Monthly", 43200);
1669
+ let creditBalance = "$0.00";
1670
+ try {
1671
+ const bRes = await fetch("https://opencode.ai/console/api/billing/status", {
1672
+ headers: {
1673
+ Authorization: `Bearer ${creds.token}`,
1674
+ "x-opencode-org-id": creds.orgId,
1675
+ "x-opencode-account-id": creds.accountId || ""
1676
+ },
1677
+ signal: AbortSignal.timeout(2000)
1678
+ });
1679
+ if (bRes.ok) {
1680
+ const bData = await bRes.json();
1681
+ const availMicro = Number(bData.availableMicroCents || 0);
1682
+ creditBalance = `$${(availMicro / 1e8).toFixed(2)}`;
1683
+ }
1684
+ } catch {}
1685
+ const quota = {
1686
+ runtimeId,
1687
+ provider: "OpenCode",
1688
+ account: {
1689
+ email: creds.email,
1690
+ name: creds.name || "OpenCode User",
1691
+ plan: "OpenCode Go",
1692
+ type: "opencode"
1693
+ },
1694
+ primaryWindow: rolling,
1695
+ secondaryWindow: weekly,
1696
+ extraWindows: monthly ? [monthly] : undefined,
1697
+ credits: {
1698
+ balance: creditBalance,
1699
+ currency: "USD",
1700
+ unlimited: false
1701
+ },
1702
+ status: "ok",
1703
+ updatedAt: Date.now()
1704
+ };
1705
+ return quota;
1706
+ } catch {
1707
+ return null;
1708
+ }
1709
+ }
1072
1710
  async function probeOpencodeQuota(runtimeId = "opencode") {
1711
+ const dbCreds = readLocalOpencodeCredentials();
1712
+ if (dbCreds.token) {
1713
+ const goQuota = await probeOpencodeGoOnlineQuota(dbCreds, runtimeId);
1714
+ if (goQuota)
1715
+ return goQuota;
1716
+ }
1073
1717
  const authPath = resolveOpencodeAuthPath();
1074
- let isLoggedIn = false;
1075
- let accountEmail;
1718
+ let isLoggedIn = Boolean(dbCreds.token || dbCreds.email);
1719
+ let accountEmail = dbCreds.email;
1720
+ let accountName = dbCreds.name;
1076
1721
  let plan = "OpenCode Community";
1077
- if (authPath && existsSync8(authPath)) {
1722
+ if (authPath && existsSync10(authPath)) {
1078
1723
  try {
1079
- const data = JSON.parse(readFileSync4(authPath, "utf8"));
1724
+ const data = JSON.parse(readFileSync5(authPath, "utf8"));
1080
1725
  if (data && typeof data === "object") {
1081
1726
  const keys = Object.keys(data);
1082
1727
  if (keys.length > 0) {
@@ -1096,7 +1741,9 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1096
1741
  if (authList.length > 0) {
1097
1742
  isLoggedIn = true;
1098
1743
  const providers = authList.map((l) => l.split(/\s{2,}/)[0]).filter(Boolean);
1099
- if (providers.length > 0) {
1744
+ if (providers.some((p) => p.toLowerCase().includes("go"))) {
1745
+ plan = "OpenCode Go";
1746
+ } else if (providers.length > 0) {
1100
1747
  plan = `OpenCode (${providers.join(", ")})`;
1101
1748
  }
1102
1749
  }
@@ -1115,7 +1762,7 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1115
1762
  let credits;
1116
1763
  if (stats && typeof stats.cost === "number") {
1117
1764
  credits = {
1118
- balance: stats.cost > 0 ? `$${stats.cost.toFixed(2)} spent` : "0.00"
1765
+ balance: stats.cost > 0 ? `$${stats.cost.toFixed(2)} spent` : "$0.00"
1119
1766
  };
1120
1767
  }
1121
1768
  return {
@@ -1123,6 +1770,7 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1123
1770
  provider: "OpenCode",
1124
1771
  account: {
1125
1772
  email: accountEmail,
1773
+ name: accountName,
1126
1774
  plan,
1127
1775
  type: "provider_oauth"
1128
1776
  },
@@ -1133,16 +1781,16 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
1133
1781
  }
1134
1782
 
1135
1783
  // src/runtimes/opencode/index.ts
1136
- import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
1137
- import { homedir as homedir7 } from "node:os";
1138
- import { dirname, join as join10 } from "node:path";
1784
+ import { existsSync as existsSync11, readFileSync as readFileSync6 } from "node:fs";
1785
+ import { homedir as homedir9 } from "node:os";
1786
+ import { dirname as dirname2, join as join14 } from "node:path";
1139
1787
  function pickEnv(env, key) {
1140
1788
  return env?.[key]?.trim() ?? "";
1141
1789
  }
1142
1790
  function resolveOpencodeAuthCandidates(overrides) {
1143
1791
  const platform = overrides?.platform ?? process.platform;
1144
1792
  const env = overrides?.env ?? process.env;
1145
- const home = overrides?.home ?? homedir7();
1793
+ const home = overrides?.home ?? homedir9();
1146
1794
  const seen = new Set;
1147
1795
  const out = [];
1148
1796
  const push = (p) => {
@@ -1153,27 +1801,27 @@ function resolveOpencodeAuthCandidates(overrides) {
1153
1801
  };
1154
1802
  const xdg = pickEnv(env, "XDG_DATA_HOME");
1155
1803
  if (xdg)
1156
- push(join10(xdg, "opencode", "auth.json"));
1804
+ push(join14(xdg, "opencode", "auth.json"));
1157
1805
  if (platform === "win32") {
1158
- const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? join10(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
1806
+ const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? join14(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
1159
1807
  if (localAppData)
1160
- push(join10(localAppData, "opencode", "auth.json"));
1808
+ push(join14(localAppData, "opencode", "auth.json"));
1161
1809
  const userProfile = pickEnv(env, "USERPROFILE") || home;
1162
1810
  if (userProfile)
1163
- push(join10(userProfile, ".local", "share", "opencode", "auth.json"));
1811
+ push(join14(userProfile, ".local", "share", "opencode", "auth.json"));
1164
1812
  } else if (home) {
1165
- push(join10(home, ".local", "share", "opencode", "auth.json"));
1813
+ push(join14(home, ".local", "share", "opencode", "auth.json"));
1166
1814
  }
1167
1815
  return out;
1168
1816
  }
1169
1817
  function resolveOpencodeAuthFile() {
1170
- return resolveOpencodeAuthCandidates()[0] ?? join10(homedir7(), ".local", "share", "opencode", "auth.json");
1818
+ return resolveOpencodeAuthCandidates()[0] ?? join14(homedir9(), ".local", "share", "opencode", "auth.json");
1171
1819
  }
1172
1820
  function isValidOpencodeAuthFile(authFile) {
1173
1821
  try {
1174
- if (!authFile || !existsSync9(authFile))
1822
+ if (!authFile || !existsSync11(authFile))
1175
1823
  return false;
1176
- const raw = readFileSync5(authFile, "utf8").trim();
1824
+ const raw = readFileSync6(authFile, "utf8").trim();
1177
1825
  if (!raw)
1178
1826
  return false;
1179
1827
  const parsed = JSON.parse(raw);
@@ -1191,7 +1839,7 @@ function probeOpencodeAuth(overrides) {
1191
1839
  for (const candidate of candidates) {
1192
1840
  let exists = false;
1193
1841
  try {
1194
- exists = existsSync9(candidate);
1842
+ exists = existsSync11(candidate);
1195
1843
  } catch {
1196
1844
  exists = false;
1197
1845
  }
@@ -1204,10 +1852,10 @@ function probeOpencodeAuth(overrides) {
1204
1852
  validFile = candidate;
1205
1853
  }
1206
1854
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
1207
- const authDir = dirname(authFile);
1855
+ const authDir = dirname2(authFile);
1208
1856
  let hasCodexHome = false;
1209
1857
  try {
1210
- hasCodexHome = existsSync9(authDir);
1858
+ hasCodexHome = existsSync11(authDir);
1211
1859
  } catch {
1212
1860
  hasCodexHome = false;
1213
1861
  }
@@ -1222,6 +1870,8 @@ function probeOpencodeAuth(overrides) {
1222
1870
  }
1223
1871
  var opencodeAdapter = {
1224
1872
  id: "opencode",
1873
+ supportedBridgeVersions: ["1.18.35"],
1874
+ prepareAppResources: prepareOpenCodeResources,
1225
1875
  probeAuth: () => probeOpencodeAuth(),
1226
1876
  probeQuota: async () => probeOpencodeQuota(),
1227
1877
  orderAuthMethods: (methods) => methods,
@@ -1232,6 +1882,7 @@ var opencodeAdapter = {
1232
1882
  // src/runtimes/opencode-v2/index.ts
1233
1883
  var opencodeV2Adapter = {
1234
1884
  id: "opencode-v2",
1885
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
1235
1886
  probeAuth: () => probeOpencodeAuth(),
1236
1887
  orderAuthMethods: (methods) => methods,
1237
1888
  canSkipInteractiveAuth: () => false,
@@ -1263,15 +1914,15 @@ async function probeCursorQuota() {
1263
1914
 
1264
1915
  // src/runtimes/cursor/index.ts
1265
1916
  import { spawnSync } from "node:child_process";
1266
- import { existsSync as existsSync10, readFileSync as readFileSync6 } from "node:fs";
1267
- import { homedir as homedir8 } from "node:os";
1268
- import { delimiter, dirname as dirname2, join as join11 } from "node:path";
1917
+ import { existsSync as existsSync12, readFileSync as readFileSync7 } from "node:fs";
1918
+ import { homedir as homedir10 } from "node:os";
1919
+ import { delimiter, dirname as dirname3, join as join15 } from "node:path";
1269
1920
  function cursorLocalAppData(env) {
1270
1921
  const local = env.LOCALAPPDATA?.trim();
1271
1922
  if (local)
1272
1923
  return local;
1273
1924
  const profile = env.USERPROFILE?.trim();
1274
- return profile ? join11(profile, "AppData", "Local") : "";
1925
+ return profile ? join15(profile, "AppData", "Local") : "";
1275
1926
  }
1276
1927
  function isOnPath(command, env, platform) {
1277
1928
  const pathValue = env.PATH ?? env.Path ?? "";
@@ -1283,7 +1934,7 @@ function isOnPath(command, env, platform) {
1283
1934
  if (!trimmed)
1284
1935
  continue;
1285
1936
  try {
1286
- if (existsSync10(join11(trimmed, command)))
1937
+ if (existsSync12(join15(trimmed, command)))
1287
1938
  return true;
1288
1939
  } catch {}
1289
1940
  }
@@ -1292,24 +1943,24 @@ function isOnPath(command, env, platform) {
1292
1943
  function resolveDirectCursorCommand(platform, env, home) {
1293
1944
  if (platform === "win32") {
1294
1945
  const localAppData = cursorLocalAppData(env);
1295
- return localAppData ? join11(localAppData, "cursor-agent", "agent.cmd") : "";
1946
+ return localAppData ? join15(localAppData, "cursor-agent", "agent.cmd") : "";
1296
1947
  }
1297
- return home ? join11(home, ".local", "bin", "agent") : "";
1948
+ return home ? join15(home, ".local", "bin", "agent") : "";
1298
1949
  }
1299
1950
  function resolveCursorCommand(overrides) {
1300
1951
  const args = ["acp"];
1301
1952
  const platform = overrides?.platform ?? process.platform;
1302
1953
  const env = overrides?.env ?? process.env;
1303
- const home = overrides?.home ?? homedir8();
1954
+ const home = overrides?.home ?? homedir10();
1304
1955
  if (platform === "win32") {
1305
1956
  const directCmd = resolveDirectCursorCommand(platform, env, home);
1306
- if (directCmd && existsSync10(directCmd)) {
1957
+ if (directCmd && existsSync12(directCmd)) {
1307
1958
  return { command: directCmd, args };
1308
1959
  }
1309
1960
  return { command: "agent.cmd", args };
1310
1961
  }
1311
1962
  const directBin = resolveDirectCursorCommand(platform, env, home);
1312
- if (directBin && existsSync10(directBin)) {
1963
+ if (directBin && existsSync12(directBin)) {
1313
1964
  return { command: directBin, args };
1314
1965
  }
1315
1966
  return { command: "agent", args };
@@ -1318,11 +1969,11 @@ function resolveCursorSpawnCommand(overrides) {
1318
1969
  const args = ["acp"];
1319
1970
  const platform = overrides?.platform ?? process.platform;
1320
1971
  const env = overrides?.env ?? process.env;
1321
- const home = overrides?.home ?? homedir8();
1972
+ const home = overrides?.home ?? homedir10();
1322
1973
  const binary = platform === "win32" ? "agent.cmd" : "agent";
1323
1974
  const direct = resolveDirectCursorCommand(platform, env, home);
1324
1975
  try {
1325
- if (direct && existsSync10(direct))
1976
+ if (direct && existsSync12(direct))
1326
1977
  return { command: direct, args };
1327
1978
  } catch {}
1328
1979
  if (isOnPath(binary, env, platform))
@@ -1344,12 +1995,12 @@ function cursorRoamingAppData(env, home) {
1344
1995
  if (roaming)
1345
1996
  return roaming;
1346
1997
  const profile = pickEnv2(env, "USERPROFILE") || home;
1347
- return profile ? join11(profile, "AppData", "Roaming") : "";
1998
+ return profile ? join15(profile, "AppData", "Roaming") : "";
1348
1999
  }
1349
2000
  function resolveCursorAuthCandidates(overrides) {
1350
2001
  const platform = overrides?.platform ?? process.platform;
1351
2002
  const env = overrides?.env ?? process.env;
1352
- const home = overrides?.home ?? homedir8();
2003
+ const home = overrides?.home ?? homedir10();
1353
2004
  const seen = new Set;
1354
2005
  const out = [];
1355
2006
  const push = (p) => {
@@ -1360,16 +2011,16 @@ function resolveCursorAuthCandidates(overrides) {
1360
2011
  };
1361
2012
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
1362
2013
  if (xdg)
1363
- push(join11(xdg, "cursor", "auth.json"));
2014
+ push(join15(xdg, "cursor", "auth.json"));
1364
2015
  if (platform === "win32") {
1365
2016
  const profile = pickEnv2(env, "USERPROFILE") || home;
1366
2017
  if (profile)
1367
- push(join11(profile, ".config", "cursor", "auth.json"));
2018
+ push(join15(profile, ".config", "cursor", "auth.json"));
1368
2019
  const roaming = cursorRoamingAppData(env, home);
1369
2020
  if (roaming)
1370
- push(join11(roaming, "Cursor", "User", "globalStorage", "storage.json"));
2021
+ push(join15(roaming, "Cursor", "User", "globalStorage", "storage.json"));
1371
2022
  } else if (home) {
1372
- push(join11(home, ".config", "cursor", "auth.json"));
2023
+ push(join15(home, ".config", "cursor", "auth.json"));
1373
2024
  }
1374
2025
  return out;
1375
2026
  }
@@ -1380,9 +2031,9 @@ function isValidCursorAuthFile(authFile) {
1380
2031
  try {
1381
2032
  if (!authFile || isStorageHintPath(authFile))
1382
2033
  return false;
1383
- if (!existsSync10(authFile))
2034
+ if (!existsSync12(authFile))
1384
2035
  return false;
1385
- const raw = readFileSync6(authFile, "utf8").trim();
2036
+ const raw = readFileSync7(authFile, "utf8").trim();
1386
2037
  if (!raw)
1387
2038
  return false;
1388
2039
  const parsed = JSON.parse(raw);
@@ -1400,9 +2051,9 @@ function isHintCursorStorageFile(authFile) {
1400
2051
  try {
1401
2052
  if (!authFile || !isStorageHintPath(authFile))
1402
2053
  return false;
1403
- if (!existsSync10(authFile))
2054
+ if (!existsSync12(authFile))
1404
2055
  return false;
1405
- const raw = readFileSync6(authFile, "utf8").trim();
2056
+ const raw = readFileSync7(authFile, "utf8").trim();
1406
2057
  if (!raw)
1407
2058
  return false;
1408
2059
  const parsed = JSON.parse(raw);
@@ -1418,7 +2069,7 @@ function isValidCursorCandidate(authFile) {
1418
2069
  }
1419
2070
  function probeCursorAuth(overrides) {
1420
2071
  const env = overrides?.env ?? process.env;
1421
- const home = overrides?.home ?? homedir8();
2072
+ const home = overrides?.home ?? homedir10();
1422
2073
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
1423
2074
  const candidates = resolveCursorAuthCandidates(overrides);
1424
2075
  let firstExisting = null;
@@ -1426,7 +2077,7 @@ function probeCursorAuth(overrides) {
1426
2077
  for (const candidate of candidates) {
1427
2078
  let exists = false;
1428
2079
  try {
1429
- exists = existsSync10(candidate);
2080
+ exists = existsSync12(candidate);
1430
2081
  } catch {
1431
2082
  exists = false;
1432
2083
  }
@@ -1438,12 +2089,12 @@ function probeCursorAuth(overrides) {
1438
2089
  if (isValidCursorCandidate(candidate))
1439
2090
  validFile = candidate;
1440
2091
  }
1441
- const fallback = home ? join11(home, ".config", "cursor", "auth.json") : "";
2092
+ const fallback = home ? join15(home, ".config", "cursor", "auth.json") : "";
1442
2093
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
1443
- const authDir = authFile ? dirname2(authFile) : "";
2094
+ const authDir = authFile ? dirname3(authFile) : "";
1444
2095
  let hasCodexHome = false;
1445
2096
  try {
1446
- hasCodexHome = authDir ? existsSync10(authDir) : false;
2097
+ hasCodexHome = authDir ? existsSync12(authDir) : false;
1447
2098
  } catch {
1448
2099
  hasCodexHome = false;
1449
2100
  }
@@ -1457,6 +2108,7 @@ function probeCursorAuth(overrides) {
1457
2108
  }
1458
2109
  var cursorAdapter = {
1459
2110
  id: "cursor-cli",
2111
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-does-not-guarantee-rules"),
1460
2112
  probeAuth: () => probeCursorAuth(),
1461
2113
  probeQuota: async () => probeCursorQuota(),
1462
2114
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
@@ -1570,6 +2222,7 @@ function probeDeepseekAuth() {
1570
2222
  }
1571
2223
  var deepseekAdapter = {
1572
2224
  id: "deepseek",
2225
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
1573
2226
  probeAuth: () => probeDeepseekAuth(),
1574
2227
  resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
1575
2228
  resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
@@ -1578,23 +2231,242 @@ var deepseekAdapter = {
1578
2231
  };
1579
2232
 
1580
2233
  // src/runtimes/agy/quota.ts
1581
- import { existsSync as existsSync11 } from "node:fs";
1582
- import { join as join12 } from "node:path";
2234
+ import { existsSync as existsSync13, readFileSync as readFileSync8, readdirSync as readdirSync2, statSync as statSync2 } from "node:fs";
2235
+ import { join as join16 } from "node:path";
2236
+ import { execFileSync } from "node:child_process";
2237
+ import * as os2 from "node:os";
1583
2238
  function resolveGeminiHome2() {
1584
2239
  const home = process.env.USERPROFILE || process.env.HOME || "";
1585
- return join12(home, ".gemini");
2240
+ return join16(home, ".gemini");
2241
+ }
2242
+ function resolveAntigravityAccount() {
2243
+ if (process.env.GOOGLE_ACCOUNT?.trim()) {
2244
+ const email = process.env.GOOGLE_ACCOUNT.trim();
2245
+ return { email, name: email.split("@")[0] };
2246
+ }
2247
+ if (process.env.ANTIGRAVITY_ACCOUNT?.trim()) {
2248
+ const email = process.env.ANTIGRAVITY_ACCOUNT.trim();
2249
+ return { email, name: email.split("@")[0] };
2250
+ }
2251
+ const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
2252
+ const candidates = [
2253
+ process.env.APPDATA ? join16(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
2254
+ join16(home, ".config", "Antigravity", "app_storage.json"),
2255
+ join16(home, "Library", "Application Support", "Antigravity", "app_storage.json")
2256
+ ].filter(Boolean);
2257
+ for (const file of candidates) {
2258
+ try {
2259
+ if (existsSync13(file)) {
2260
+ const raw = readFileSync8(file, "utf8");
2261
+ const json = JSON.parse(raw);
2262
+ const username = json["jetski.onboarding.lastLoginUsername"];
2263
+ if (username && typeof username === "string" && username.trim()) {
2264
+ const u = username.trim();
2265
+ return {
2266
+ email: u,
2267
+ name: u.includes("@") ? u.split("@")[0] : u
2268
+ };
2269
+ }
2270
+ }
2271
+ } catch {}
2272
+ }
2273
+ const osUser = process.env.USERNAME || process.env.USER;
2274
+ if (osUser?.trim()) {
2275
+ return { name: osUser.trim() };
2276
+ }
2277
+ return {};
2278
+ }
2279
+ function resolveAntigravityLanguageServer() {
2280
+ const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
2281
+ const appData = process.env.APPDATA || (process.platform === "win32" ? join16(home, "AppData", "Roaming") : "");
2282
+ const baseDirs = [
2283
+ appData ? join16(appData, "Antigravity IDE", "logs") : null,
2284
+ appData ? join16(appData, "Antigravity", "logs") : null,
2285
+ join16(home, ".config", "Antigravity IDE", "logs"),
2286
+ join16(home, ".config", "Antigravity", "logs"),
2287
+ join16(home, "Library", "Application Support", "Antigravity IDE", "logs"),
2288
+ join16(home, "Library", "Application Support", "Antigravity", "logs")
2289
+ ].filter(Boolean);
2290
+ for (const base of baseDirs) {
2291
+ try {
2292
+ if (!existsSync13(base))
2293
+ continue;
2294
+ const sessionDirs = readdirSync2(base).map((d) => {
2295
+ try {
2296
+ return { name: d, time: statSync2(join16(base, d)).mtimeMs };
2297
+ } catch {
2298
+ return null;
2299
+ }
2300
+ }).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
2301
+ for (const s of sessionDirs) {
2302
+ const logFile = join16(base, s.name, "ls-main.log");
2303
+ if (existsSync13(logFile)) {
2304
+ const content = readFileSync8(logFile, "utf8");
2305
+ const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
2306
+ const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
2307
+ if (csrfMatch && portMatch) {
2308
+ return {
2309
+ port: parseInt(portMatch[1], 10),
2310
+ csrfToken: csrfMatch[1]
2311
+ };
2312
+ }
2313
+ }
2314
+ }
2315
+ } catch {}
2316
+ }
2317
+ try {
2318
+ let out = "";
2319
+ if (process.platform === "win32") {
2320
+ out = execFileSync("powershell", [
2321
+ "-NoProfile",
2322
+ "-Command",
2323
+ `Get-CimInstance Win32_Process -Filter "Name like '%language_server%'" | Select-Object -ExpandProperty CommandLine`
2324
+ ], { encoding: "utf8", timeout: 4000, windowsHide: true });
2325
+ } else {
2326
+ out = execFileSync("ps", ["aux"], { encoding: "utf8", timeout: 4000 });
2327
+ }
2328
+ const lines = out.split(/\r?\n/);
2329
+ for (const l of lines) {
2330
+ const portMatch = l.match(/--https_server_port\s+(\d+)/);
2331
+ const csrfMatch = l.match(/--csrf_token\s+([a-f0-9\-]+)/);
2332
+ if (portMatch && csrfMatch) {
2333
+ return { port: parseInt(portMatch[1], 10), csrfToken: csrfMatch[1] };
2334
+ }
2335
+ }
2336
+ } catch {}
2337
+ return null;
1586
2338
  }
1587
2339
  async function probeAgyQuota(options) {
2340
+ const acc = resolveAntigravityAccount();
2341
+ const lsInfo = resolveAntigravityLanguageServer();
2342
+ if (lsInfo) {
2343
+ try {
2344
+ let data = null;
2345
+ const prevReject = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
2346
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
2347
+ try {
2348
+ const res = await fetch(`https://127.0.0.1:${lsInfo.port}/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary`, {
2349
+ method: "POST",
2350
+ headers: {
2351
+ "Content-Type": "application/json",
2352
+ "x-codeium-csrf-token": lsInfo.csrfToken
2353
+ },
2354
+ body: JSON.stringify({}),
2355
+ signal: AbortSignal.timeout(4000),
2356
+ tls: { rejectUnauthorized: false }
2357
+ });
2358
+ if (res.ok) {
2359
+ data = await res.json();
2360
+ }
2361
+ } catch {
2362
+ try {
2363
+ const raw = execFileSync(process.platform === "win32" ? "curl.exe" : "curl", [
2364
+ "-k",
2365
+ "-s",
2366
+ "-X",
2367
+ "POST",
2368
+ "-H",
2369
+ "Content-Type: application/json",
2370
+ "-H",
2371
+ `x-codeium-csrf-token: ${lsInfo.csrfToken}`,
2372
+ "-d",
2373
+ "{}",
2374
+ `https://127.0.0.1:${lsInfo.port}/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary`
2375
+ ], { encoding: "utf8", timeout: 4000 });
2376
+ data = JSON.parse(raw);
2377
+ } catch {}
2378
+ } finally {
2379
+ if (prevReject !== undefined) {
2380
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = prevReject;
2381
+ } else {
2382
+ delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
2383
+ }
2384
+ }
2385
+ if (data?.response?.groups) {
2386
+ const groups = data.response.groups;
2387
+ const formatReset = (isoStr, fallbackDesc) => {
2388
+ if (fallbackDesc && fallbackDesc.includes("it will fully refresh in ")) {
2389
+ const m = fallbackDesc.match(/it will fully refresh in (.+?)\.?$/);
2390
+ if (m?.[1])
2391
+ return `Resets in ${m[1].trim()}`;
2392
+ }
2393
+ if (!isoStr)
2394
+ return;
2395
+ const diffMs = new Date(isoStr).getTime() - Date.now();
2396
+ if (diffMs <= 0)
2397
+ return "已重置";
2398
+ const totalMins = Math.floor(diffMs / 60000);
2399
+ const hours = Math.floor(totalMins / 60);
2400
+ const days = Math.floor(hours / 24);
2401
+ if (days > 0)
2402
+ return `Resets in ${days}d ${hours % 24}h`;
2403
+ return `Resets in ${hours}h ${totalMins % 60}m`;
2404
+ };
2405
+ const toWindow = (b, groupName, label, durMins) => {
2406
+ if (!b)
2407
+ return;
2408
+ const frac = typeof b.remainingFraction === "number" ? b.remainingFraction : 1;
2409
+ const percentLeft = Math.max(0, Math.min(100, Math.round(frac * 100)));
2410
+ const usedPercent = 100 - percentLeft;
2411
+ return {
2412
+ label,
2413
+ group: groupName,
2414
+ percentLeft,
2415
+ usedPercent,
2416
+ windowDurationMins: durMins,
2417
+ resetsAt: formatReset(b.resetTime, b.description)
2418
+ };
2419
+ };
2420
+ const geminiGroup = groups.find((g) => g.displayName?.toLowerCase().includes("gemini"));
2421
+ const thirdPartyGroup = groups.find((g) => g.displayName?.toLowerCase().includes("claude") || g.displayName?.toLowerCase().includes("gpt"));
2422
+ const gemini5h = geminiGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("five hour") || b.bucketId?.includes("5h") || b.window === "5h");
2423
+ const geminiWeekly = geminiGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("weekly") || b.bucketId?.includes("weekly") || b.window === "weekly");
2424
+ const tp5h = thirdPartyGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("five hour") || b.bucketId?.includes("5h") || b.window === "5h");
2425
+ const tpWeekly = thirdPartyGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("weekly") || b.bucketId?.includes("weekly") || b.window === "weekly");
2426
+ const primaryWindow = toWindow(gemini5h, "Gemini Models", "5-Hour limit", 300) || {
2427
+ label: "5-Hour limit",
2428
+ group: "Gemini Models",
2429
+ percentLeft: 100,
2430
+ usedPercent: 0,
2431
+ windowDurationMins: 300
2432
+ };
2433
+ const secondaryWindow = toWindow(geminiWeekly, "Gemini Models", "Weekly limit", 10080);
2434
+ const extraWindows = [
2435
+ toWindow(tp5h, "Claude and GPT models", "5-Hour limit", 300),
2436
+ toWindow(tpWeekly, "Claude and GPT models", "Weekly limit", 10080)
2437
+ ].filter(Boolean);
2438
+ return {
2439
+ runtimeId: "agy",
2440
+ provider: "Google Antigravity",
2441
+ account: {
2442
+ email: acc.email,
2443
+ name: acc.name || "Google Developer",
2444
+ plan: "Google AI Pro",
2445
+ type: "gemini"
2446
+ },
2447
+ primaryWindow,
2448
+ secondaryWindow,
2449
+ extraWindows: extraWindows.length > 0 ? extraWindows : undefined,
2450
+ credits: {
2451
+ unlimited: true,
2452
+ balance: "unlimited"
2453
+ },
2454
+ status: "ok",
2455
+ updatedAt: Date.now()
2456
+ };
2457
+ }
2458
+ } catch {}
2459
+ }
1588
2460
  const geminiHome = resolveGeminiHome2();
1589
- const hasAgyDir = existsSync11(join12(geminiHome, "antigravity")) || existsSync11(join12(geminiHome, "antigravity-cli"));
2461
+ const hasAgyDir = existsSync13(join16(geminiHome, "antigravity")) || existsSync13(join16(geminiHome, "antigravity-cli"));
1590
2462
  const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
1591
- const isAvailable = hasAgyDir || hasApiKey;
2463
+ const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
1592
2464
  if (!isAvailable) {
1593
2465
  return {
1594
2466
  runtimeId: "agy",
1595
2467
  provider: "Google Antigravity",
1596
2468
  status: "unauthorized",
1597
- message: "wenjianlingu antigravity cli",
2469
+ message: "未检测到 Antigravity 登录凭据",
1598
2470
  updatedAt: Date.now()
1599
2471
  };
1600
2472
  }
@@ -1602,21 +2474,41 @@ async function probeAgyQuota(options) {
1602
2474
  runtimeId: "agy",
1603
2475
  provider: "Google Antigravity",
1604
2476
  account: {
1605
- plan: "Antigravity / Gemini",
2477
+ email: acc.email,
2478
+ name: acc.name || "Google Developer",
2479
+ plan: "Google AI Pro",
1606
2480
  type: "gemini"
1607
2481
  },
1608
2482
  primaryWindow: {
1609
2483
  label: "5-Hour limit",
2484
+ group: "Gemini Models",
1610
2485
  percentLeft: 100,
1611
2486
  usedPercent: 0,
1612
2487
  windowDurationMins: 300
1613
2488
  },
1614
2489
  secondaryWindow: {
1615
2490
  label: "Weekly limit",
2491
+ group: "Gemini Models",
1616
2492
  percentLeft: 100,
1617
2493
  usedPercent: 0,
1618
2494
  windowDurationMins: 10080
1619
2495
  },
2496
+ extraWindows: [
2497
+ {
2498
+ label: "5-Hour limit",
2499
+ group: "Claude and GPT models",
2500
+ percentLeft: 100,
2501
+ usedPercent: 0,
2502
+ windowDurationMins: 300
2503
+ },
2504
+ {
2505
+ label: "Weekly limit",
2506
+ group: "Claude and GPT models",
2507
+ percentLeft: 100,
2508
+ usedPercent: 0,
2509
+ windowDurationMins: 10080
2510
+ }
2511
+ ],
1620
2512
  credits: {
1621
2513
  unlimited: true,
1622
2514
  balance: "unlimited"
@@ -1638,6 +2530,12 @@ function probeAgyAuth() {
1638
2530
  }
1639
2531
  var agyAdapter = {
1640
2532
  id: "agy",
2533
+ prepareAppResources: async ({ directory }) => {
2534
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
2535
+ return { ...prep, env: { AGY_ACP_RESOURCES_DIR: directory }, report: { ...prep.report, rulesPrepared: prep.report.rulesChars > 0 } };
2536
+ },
2537
+ appResourceSessionMeta: (directory) => ({ appResources: { directory } }),
2538
+ supportedBridgeVersions: ["0.1.24"],
1641
2539
  probeAuth: () => probeAgyAuth(),
1642
2540
  probeQuota: (options) => probeAgyQuota(options),
1643
2541
  orderAuthMethods: (methods) => methods,
@@ -1678,6 +2576,9 @@ function getAcpRuntimeAdapter(runtimeId) {
1678
2576
 
1679
2577
  // src/process/process-manager.ts
1680
2578
  import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
2579
+ function processKey(runtimeId, scopeKey) {
2580
+ return scopeKey ? `${scopeKey}:${runtimeId}` : runtimeId;
2581
+ }
1681
2582
  var active = new Map;
1682
2583
  var ACP_EARLY_EXIT_WINDOW_MS = 3000;
1683
2584
  var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
@@ -1709,7 +2610,8 @@ function spawnAcpProcess(options) {
1709
2610
  if (!options.runtime?.id || !options.runtime.command || !Array.isArray(options.runtime.args)) {
1710
2611
  throw new Error(`ACP 运行时模板缺失 command/args: ${options.runtime?.id ?? "(empty)"}`);
1711
2612
  }
1712
- const existing = active.get(options.runtime.id);
2613
+ const key = processKey(options.runtime.id, options.scopeKey);
2614
+ const existing = active.get(key);
1713
2615
  if (existing) {
1714
2616
  existing.kill();
1715
2617
  }
@@ -1770,6 +2672,9 @@ function spawnAcpProcess(options) {
1770
2672
  });
1771
2673
  const handle = {
1772
2674
  runtimeId: options.runtime.id,
2675
+ scopeKey: options.scopeKey,
2676
+ executionContext: options.executionContext,
2677
+ profileTag: options.profileTag ?? null,
1773
2678
  child,
1774
2679
  spawnedAt: Date.now(),
1775
2680
  stderrTail,
@@ -1787,7 +2692,7 @@ function spawnAcpProcess(options) {
1787
2692
  } catch {}
1788
2693
  }
1789
2694
  }
1790
- active.delete(options.runtime.id);
2695
+ active.delete(key);
1791
2696
  }
1792
2697
  };
1793
2698
  child.on("exit", (code, signal) => {
@@ -1795,10 +2700,11 @@ function spawnAcpProcess(options) {
1795
2700
  if (rest)
1796
2701
  pushStderrTailLine(rest);
1797
2702
  stderrBuffer = "";
1798
- active.delete(options.runtime.id);
2703
+ if (active.get(key) === handle)
2704
+ active.delete(key);
1799
2705
  options.onExit?.(code, signal);
1800
2706
  });
1801
- active.set(options.runtime.id, handle);
2707
+ active.set(key, handle);
1802
2708
  return handle;
1803
2709
  }
1804
2710
  function getAcpEarlyExitStderrDetail(handle, _now = Date.now()) {
@@ -1826,27 +2732,47 @@ function disposeAllAcpProcesses() {
1826
2732
  }
1827
2733
  active.clear();
1828
2734
  }
1829
- function getActiveAcpProcess(runtimeId) {
1830
- return active.get(runtimeId);
2735
+ function getActiveAcpProcess(runtimeId, scopeKey) {
2736
+ return active.get(processKey(runtimeId, scopeKey));
1831
2737
  }
1832
2738
  function listLiveAcpRuntimeIds() {
1833
- const ids = [];
1834
- for (const [runtimeId, handle] of active) {
2739
+ const ids = new Set;
2740
+ for (const handle of active.values()) {
1835
2741
  if (isSpawnedAcpProcessAlive(handle))
1836
- ids.push(runtimeId);
2742
+ ids.add(handle.runtimeId);
1837
2743
  }
1838
- return ids.sort();
2744
+ return [...ids].sort();
1839
2745
  }
1840
- function getLiveAcpProcess(runtimeId) {
1841
- const handle = active.get(runtimeId);
2746
+ function getLiveAcpProcess(runtimeId, query = {}) {
2747
+ const key = processKey(runtimeId, query.scopeKey);
2748
+ const handle = active.get(key);
1842
2749
  if (!handle)
1843
2750
  return;
1844
2751
  if (!isSpawnedAcpProcessAlive(handle)) {
1845
- active.delete(runtimeId);
2752
+ active.delete(key);
2753
+ return;
2754
+ }
2755
+ if (query.executionContext !== undefined && (handle.executionContext ?? null) !== query.executionContext) {
1846
2756
  return;
1847
2757
  }
2758
+ if (query.expectedTag !== undefined && (handle.profileTag ?? null) !== query.expectedTag)
2759
+ return;
1848
2760
  return handle;
1849
2761
  }
2762
+ function tryReuseLiveAcpProcess(runtimeId, query = {}) {
2763
+ const hit = getLiveAcpProcess(runtimeId, query);
2764
+ if (hit)
2765
+ return { status: "hit", handle: hit };
2766
+ if (query.expectedTag === undefined)
2767
+ return { status: "miss" };
2768
+ const stale = getLiveAcpProcess(runtimeId, { scopeKey: query.scopeKey, executionContext: query.executionContext });
2769
+ if (!stale)
2770
+ return { status: "miss" };
2771
+ if (query.isBusy?.(stale))
2772
+ return { status: "busy", handle: stale };
2773
+ stale.kill();
2774
+ return { status: "miss" };
2775
+ }
1850
2776
 
1851
2777
  // src/client/sdk-client.ts
1852
2778
  import { PassThrough, Readable, Writable } from "node:stream";
@@ -1920,18 +2846,18 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
1920
2846
  import { methods, RequestError } from "@agentclientprotocol/sdk";
1921
2847
 
1922
2848
  // src/client/acp-fs.ts
1923
- import { access, readFile as readFile2, writeFile as writeFile3 } from "node:fs/promises";
1924
- import { dirname as dirname3, extname, resolve, sep } from "node:path";
1925
- import { mkdir as mkdir3 } from "node:fs/promises";
2849
+ import { access, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
2850
+ import { dirname as dirname4, extname, resolve as resolve2, sep as sep2 } from "node:path";
2851
+ import { mkdir as mkdir4 } from "node:fs/promises";
1926
2852
  var MAX_READ_BYTES = 2 * 1024 * 1024;
1927
2853
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
1928
2854
  function isBinaryDocumentPath(filePath) {
1929
2855
  return BINARY_DOCUMENT_EXTENSIONS.has(extname(filePath).toLowerCase());
1930
2856
  }
1931
2857
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
1932
- const root = resolve(workspaceRoot);
1933
- const target = resolve(filePath);
1934
- const rootWithSep = root.endsWith(sep) ? root : root + sep;
2858
+ const root = resolve2(workspaceRoot);
2859
+ const target = resolve2(filePath);
2860
+ const rootWithSep = root.endsWith(sep2) ? root : root + sep2;
1935
2861
  if (target !== root && !target.startsWith(rootWithSep)) {
1936
2862
  throw new Error(`路径不在工作区内: ${filePath}`);
1937
2863
  }
@@ -1943,7 +2869,7 @@ async function acpReadTextFile(params) {
1943
2869
  }
1944
2870
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
1945
2871
  await access(abs);
1946
- let content = await readFile2(abs, "utf-8");
2872
+ let content = await readFile4(abs, "utf-8");
1947
2873
  if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
1948
2874
  content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
1949
2875
  content += `
@@ -1962,8 +2888,8 @@ async function acpReadTextFile(params) {
1962
2888
  }
1963
2889
  async function acpWriteTextFile(params) {
1964
2890
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
1965
- await mkdir3(dirname3(abs), { recursive: true });
1966
- await writeFile3(abs, params.content, "utf-8");
2891
+ await mkdir4(dirname4(abs), { recursive: true });
2892
+ await writeFile4(abs, params.content, "utf-8");
1967
2893
  return {};
1968
2894
  }
1969
2895
 
@@ -2323,6 +3249,25 @@ function isTransientAcpTransportError(error) {
2323
3249
  async function restoreOrCreateAcpSession(input) {
2324
3250
  const resumeId = input.resumeSessionId?.trim() || null;
2325
3251
  const restoreAttempts = [];
3252
+ let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
3253
+ let nativeSessionAccepted = false;
3254
+ const request = async (method, params) => {
3255
+ if (!input.sessionMeta)
3256
+ return input.request(method, params);
3257
+ try {
3258
+ const result = await input.request(method, { ...params, _meta: input.sessionMeta });
3259
+ nativeSessionAccepted = true;
3260
+ return result;
3261
+ } catch (error) {
3262
+ const rejected = error instanceof RequestError2 && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
3263
+ if (!rejected || isTransientAcpTransportError(error))
3264
+ throw error;
3265
+ log("warn", "native resource options failed; retry without extension");
3266
+ const result = await input.request(method, params);
3267
+ nativeSessionAccepted = false;
3268
+ return result;
3269
+ }
3270
+ };
2326
3271
  const delayMs = input.retryDelayMs ?? 250;
2327
3272
  const log = input.log ?? ((level, message, data) => {
2328
3273
  if (level === "info" && false)
@@ -2344,7 +3289,7 @@ async function restoreOrCreateAcpSession(input) {
2344
3289
  maxTries
2345
3290
  });
2346
3291
  try {
2347
- const result = await input.request(rpcMethod, {
3292
+ const result = await request(rpcMethod, {
2348
3293
  sessionId: resumeId,
2349
3294
  cwd: input.cwd,
2350
3295
  mcpServers: input.mcpServers ?? []
@@ -2383,7 +3328,7 @@ async function restoreOrCreateAcpSession(input) {
2383
3328
  mcpServers: input.mcpServers ?? []
2384
3329
  };
2385
3330
  try {
2386
- return await input.request("session/new", baseParams);
3331
+ return await request("session/new", baseParams);
2387
3332
  } catch (firstError) {
2388
3333
  if ((input.mcpServers ?? []).length === 0)
2389
3334
  throw firstError;
@@ -2391,10 +3336,12 @@ async function restoreOrCreateAcpSession(input) {
2391
3336
  error: errorMessage(firstError)
2392
3337
  });
2393
3338
  try {
2394
- return await input.request("session/new", {
3339
+ const result = await request("session/new", {
2395
3340
  cwd: input.cwd,
2396
3341
  mcpServers: []
2397
3342
  });
3343
+ mcpServersAccepted = false;
3344
+ return result;
2398
3345
  } catch {
2399
3346
  throw firstError;
2400
3347
  }
@@ -2410,6 +3357,8 @@ async function restoreOrCreateAcpSession(input) {
2410
3357
  configOptions: withModelsFallback(resumed),
2411
3358
  restoreMethod: "resume",
2412
3359
  sessionRestored: true,
3360
+ mcpServersAccepted,
3361
+ nativeSessionAccepted,
2413
3362
  requestedSessionId: resumeId,
2414
3363
  restoreAttempts
2415
3364
  };
@@ -2428,6 +3377,8 @@ async function restoreOrCreateAcpSession(input) {
2428
3377
  configOptions: withModelsFallback(loaded),
2429
3378
  restoreMethod: "load",
2430
3379
  sessionRestored: true,
3380
+ mcpServersAccepted,
3381
+ nativeSessionAccepted,
2431
3382
  requestedSessionId: resumeId,
2432
3383
  restoreAttempts
2433
3384
  };
@@ -2449,6 +3400,8 @@ async function restoreOrCreateAcpSession(input) {
2449
3400
  configOptions: withModelsFallback(sessionResult),
2450
3401
  restoreMethod: "new",
2451
3402
  sessionRestored: false,
3403
+ mcpServersAccepted,
3404
+ nativeSessionAccepted,
2452
3405
  requestedSessionId: resumeId ?? undefined,
2453
3406
  restoreAttempts
2454
3407
  };
@@ -2639,9 +3592,9 @@ class AcpTerminalManager {
2639
3592
  }
2640
3593
 
2641
3594
  // src/client/acp-proxy-service.ts
2642
- import { mkdir as mkdir4, readFile as readFile3, writeFile as writeFile4 } from "node:fs/promises";
2643
- import { existsSync as existsSync12 } from "node:fs";
2644
- import { join as join13 } from "node:path";
3595
+ import { mkdir as mkdir5, readFile as readFile5, writeFile as writeFile5 } from "node:fs/promises";
3596
+ import { existsSync as existsSync14 } from "node:fs";
3597
+ import { join as join17 } from "node:path";
2645
3598
  var DEFAULT_ACP_PROXY_SETTINGS = {
2646
3599
  enabled: false,
2647
3600
  host: "127.0.0.1",
@@ -2650,7 +3603,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
2650
3603
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
2651
3604
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
2652
3605
  function proxyFilePath(dir) {
2653
- return join13(dir, "agent", "proxy.json");
3606
+ return join17(dir, "agent", "proxy.json");
2654
3607
  }
2655
3608
  function validate2(settings) {
2656
3609
  if (!settings.host.trim())
@@ -2662,10 +3615,10 @@ function validate2(settings) {
2662
3615
  }
2663
3616
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
2664
3617
  const file = proxyFilePath(dir);
2665
- if (!existsSync12(file))
3618
+ if (!existsSync14(file))
2666
3619
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
2667
3620
  try {
2668
- const raw = JSON.parse(await readFile3(file, "utf8"));
3621
+ const raw = JSON.parse(await readFile5(file, "utf8"));
2669
3622
  return {
2670
3623
  enabled: raw.enabled === true,
2671
3624
  host: typeof raw.host === "string" && raw.host.trim() ? raw.host : DEFAULT_ACP_PROXY_SETTINGS.host,
@@ -2684,8 +3637,8 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
2684
3637
  host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
2685
3638
  port: payload.port
2686
3639
  };
2687
- await mkdir4(join13(dir, "agent"), { recursive: true });
2688
- await writeFile4(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
3640
+ await mkdir5(join17(dir, "agent"), { recursive: true });
3641
+ await writeFile5(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
2689
3642
  return ok(stored);
2690
3643
  }
2691
3644
  function buildAcpProxySpawnEnv(settings) {
@@ -2707,6 +3660,116 @@ function buildAcpProxySpawnEnv(settings) {
2707
3660
  };
2708
3661
  }
2709
3662
 
3663
+ // src/session/compat-guide.ts
3664
+ var COMPAT_CONTEXT_TAG = "acp-compat-context";
3665
+ function shortDigest(digest) {
3666
+ return digest ? digest.slice(0, 16) : "none";
3667
+ }
3668
+ function buildCompatGuideText(input) {
3669
+ const hasRules = (input.rulesText ?? "").trim() !== "";
3670
+ const hasSkills = input.skills.length > 0;
3671
+ if (!hasRules && !hasSkills)
3672
+ return null;
3673
+ const lines = [];
3674
+ lines.push(`<${COMPAT_CONTEXT_TAG} mode="compatibility" profile="${shortDigest(input.digest)}" session="${input.sessionId}" gen="${input.generation}">`, "NOTE FOR THE MODEL: the block below is host-provided context delivered over the user channel", "(compatibility mode). It is NOT a system or developer instruction and does not override them.", "");
3675
+ if (hasRules) {
3676
+ lines.push("--- host rules (same source as the host app, delivered once per session) ---", "");
3677
+ lines.push(input.rulesText.trim(), "");
3678
+ }
3679
+ if (hasSkills) {
3680
+ lines.push("--- host skills catalog (names and descriptions only; read full text on demand) ---", "");
3681
+ for (const skill of input.skills) {
3682
+ lines.push(`- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`);
3683
+ }
3684
+ lines.push("", input.skillsViaMcp ? "Read a skill body with the app_read_skill MCP tool before claiming its content." : "Skill bodies are available on request; ask the host if no skill tool is listed.");
3685
+ lines.push("");
3686
+ }
3687
+ lines.push(`</${COMPAT_CONTEXT_TAG}>`);
3688
+ return lines.join(`
3689
+ `);
3690
+ }
3691
+ function compatDeliveryKey(sessionId, generation, digest) {
3692
+ return `${generation}:${sessionId}:${digest ?? "none"}`;
3693
+ }
3694
+
3695
+ // src/mcp/app-skills-mcp.ts
3696
+ import { dirname as dirname5, join as join18 } from "node:path";
3697
+ import { fileURLToPath } from "node:url";
3698
+ import { existsSync as existsSync15, readFileSync as readFileSync9, statSync as statSync3 } from "node:fs";
3699
+ var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
3700
+ var APP_SKILLS_TOOLS = [
3701
+ {
3702
+ name: "app_list_skills",
3703
+ description: "List host skill catalog (names and one-line descriptions). " + "Call this first to discover available skills; then read a body with app_read_skill before claiming its content. " + "Skill bodies are never inlined here—always read on demand.",
3704
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
3705
+ },
3706
+ {
3707
+ name: "app_read_skill",
3708
+ description: "Read one registered skill body by exact name from app_list_skills. " + "Optional ref reads another Markdown file in the same skill directory " + "(same-directory relative .md only; anything else is rejected).",
3709
+ inputSchema: {
3710
+ type: "object",
3711
+ properties: {
3712
+ name: { type: "string", description: "Exact skill name from app_list_skills" },
3713
+ ref: {
3714
+ type: "string",
3715
+ description: "Optional same-directory relative Markdown file (default SKILL.md)"
3716
+ }
3717
+ },
3718
+ required: ["name"],
3719
+ additionalProperties: false
3720
+ }
3721
+ }
3722
+ ];
3723
+ function buildAppSkillsMcpServer(directory, opts) {
3724
+ return {
3725
+ name: opts?.name ?? APP_SKILLS_MCP_SERVER_NAME,
3726
+ command: process.execPath,
3727
+ env: process.versions.electron ? [{ name: "ELECTRON_RUN_AS_NODE", value: "1" }] : [],
3728
+ args: [opts?.runnerPath ?? resolveAppSkillsRunnerPath(), directory]
3729
+ };
3730
+ }
3731
+ function resolveAppSkillsRunnerPath(fromFile) {
3732
+ const base = fromFile ?? fileURLToPath(import.meta.url);
3733
+ const candidates = [
3734
+ join18(dirname5(base), "app-skills-mcp-serve.cjs"),
3735
+ join18(dirname5(base), "app-skills-mcp-serve.ts")
3736
+ ];
3737
+ for (const candidate of candidates) {
3738
+ if (existsSync15(candidate))
3739
+ return candidate;
3740
+ }
3741
+ throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
3742
+ }
3743
+
3744
+ // src/client/acp-client.ts
3745
+ import { randomUUID as randomUUID2 } from "node:crypto";
3746
+
3747
+ // src/resources/eligibility.ts
3748
+ var NATIVE_ELIGIBLE_BRIDGE_VERSIONS = {
3749
+ "codex-acp": ["2.2.2"],
3750
+ opencode: ["1.18.35"],
3751
+ claude: ["0.91.0"],
3752
+ agy: ["0.1.24"]
3753
+ };
3754
+ function resolveRuntimeEligibility(runtimeId) {
3755
+ const id = (runtimeId ?? "").trim();
3756
+ if (!id || !(id in NATIVE_ELIGIBLE_BRIDGE_VERSIONS)) {
3757
+ return { eligible: false, reason: "runtime-not-verified" };
3758
+ }
3759
+ return { eligible: true };
3760
+ }
3761
+ function isSupportedBridgeVersion(runtimeId, version) {
3762
+ const versions = NATIVE_ELIGIBLE_BRIDGE_VERSIONS[(runtimeId ?? "").trim()];
3763
+ if (!versions)
3764
+ return { eligible: false, reason: "runtime-not-verified" };
3765
+ const normalized = version?.trim().replace(/^v/, "");
3766
+ if (!normalized)
3767
+ return { eligible: false, reason: "unknown-bridge-version" };
3768
+ if (!versions.includes(normalized))
3769
+ return { eligible: false, reason: "unsupported-bridge-version" };
3770
+ return { eligible: true };
3771
+ }
3772
+
2710
3773
  // src/session/session-capabilities.ts
2711
3774
  function parseLoadSessionSupported(caps) {
2712
3775
  return caps.loadSession === true;
@@ -2743,11 +3806,13 @@ class AcpSessionHandle {
2743
3806
  client;
2744
3807
  restoreMethod;
2745
3808
  configOptions;
2746
- constructor(sessionId, client, restoreMethod, configOptions) {
3809
+ resourceReport;
3810
+ constructor(sessionId, client, restoreMethod, configOptions, resourceReport) {
2747
3811
  this.sessionId = sessionId;
2748
3812
  this.client = client;
2749
3813
  this.restoreMethod = restoreMethod;
2750
3814
  this.configOptions = configOptions;
3815
+ this.resourceReport = resourceReport;
2751
3816
  }
2752
3817
  async prompt(promptText, options) {
2753
3818
  return this.client.promptSession(this.sessionId, promptText, options);
@@ -2776,6 +3841,10 @@ class AcpClient {
2776
3841
  clientInfo;
2777
3842
  dataDir;
2778
3843
  extraEnv;
3844
+ configurationScope;
3845
+ sessionConfig = null;
3846
+ resourcesDir;
3847
+ processScopeKey = randomUUID2();
2779
3848
  callbacks;
2780
3849
  terminals = new AcpTerminalManager;
2781
3850
  processHandle = null;
@@ -2783,6 +3852,17 @@ class AcpClient {
2783
3852
  sdkConnection = null;
2784
3853
  streamHandle = null;
2785
3854
  initResponse = null;
3855
+ inflightPrompts = new Set;
3856
+ resourcePrep = null;
3857
+ connectionGen = 0;
3858
+ attachSkillsMcp;
3859
+ sessionLedger = new Map;
3860
+ compatSentKeys = new Set;
3861
+ compatSnapshots = new Map;
3862
+ get resourceReport() {
3863
+ const report = this.resourcePrep?.report;
3864
+ return report ? { ...report, skillsFound: [...report.skillsFound] } : null;
3865
+ }
2786
3866
  constructor(options) {
2787
3867
  this.workspaceRoot = options.workspaceRoot;
2788
3868
  this.clientInfo = {
@@ -2791,6 +3871,14 @@ class AcpClient {
2791
3871
  };
2792
3872
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
2793
3873
  this.extraEnv = options.env ?? {};
3874
+ if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
3875
+ throw new Error("resources.directory 必须是本机绝对路径");
3876
+ }
3877
+ this.configurationScope = options.resources?.configurationScope ?? "overlay";
3878
+ if (!["overlay", "session"].includes(this.configurationScope))
3879
+ throw new Error("Invalid resources.configurationScope");
3880
+ this.resourcesDir = options.resources?.directory ?? null;
3881
+ this.attachSkillsMcp = options.resources?.attachSkillsMcp !== false;
2794
3882
  this.callbacks = options.callbacks ?? {};
2795
3883
  const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
2796
3884
  this.adapter = getAcpRuntimeAdapter(runtimeId);
@@ -2817,6 +3905,14 @@ class AcpClient {
2817
3905
  return this.initResponse;
2818
3906
  }
2819
3907
  async connect() {
3908
+ if (this.inflightPrompts.size > 0)
3909
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
3910
+ if (this.isConnected && this.initResponse)
3911
+ return ok({ status: this.status, init: this.initResponse });
3912
+ if (this.currentStatus === "connecting")
3913
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在连接" });
3914
+ this.connectionGen += 1;
3915
+ const connectGen = this.connectionGen;
2820
3916
  try {
2821
3917
  this.setStatus("connecting");
2822
3918
  const blocker = this.adapter.resolveSpawnBlocker?.();
@@ -2842,16 +3938,105 @@ class AcpClient {
2842
3938
  ...baseEnv,
2843
3939
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
2844
3940
  };
3941
+ let resourceEnv = {};
3942
+ let profileTag = null;
3943
+ if (this.resourcesDir && this.configurationScope === "session") {
3944
+ const profile = await createSessionConfigHome(this.runtimeInfo.id, this.resourcesDir);
3945
+ if (connectGen !== this.connectionGen || this.status !== "connecting") {
3946
+ await profile.dispose();
3947
+ return err({ code: "CANCELLED", message: "连接已取消" });
3948
+ }
3949
+ this.sessionConfig = profile;
3950
+ resourceEnv = this.sessionConfig.env;
3951
+ const load = readAppResourcesDir(this.resourcesDir);
3952
+ this.resourcePrep = { profileTag: null, report: {
3953
+ rulesApplied: false,
3954
+ rulesPrepared: false,
3955
+ skillsApplied: false,
3956
+ rulesChars: load.rules?.chars ?? 0,
3957
+ profileDigest: digestAppResources(load),
3958
+ skillsFound: load.skills.map((s) => s.name),
3959
+ configurationScope: "session",
3960
+ configurationDirectory: this.sessionConfig.directory,
3961
+ configurationRulesFile: this.sessionConfig.rulesFile,
3962
+ reason: this.sessionConfig.nativeRules ? "isolated-config-not-runtime-verified" : "isolated-config-rule-discovery-not-verified"
3963
+ } };
3964
+ } else if (this.resourcesDir && this.adapter.prepareAppResources) {
3965
+ try {
3966
+ const prep = await this.adapter.prepareAppResources({
3967
+ directory: this.resourcesDir,
3968
+ command: effectiveRuntime.command,
3969
+ workspaceRoot: this.workspaceRoot,
3970
+ env: { ...process.env, ...spawnEnv.env }
3971
+ });
3972
+ if (prep.env)
3973
+ resourceEnv = prep.env;
3974
+ prep.report.rulesPrepared = prep.report.rulesPrepared ?? prep.report.rulesApplied;
3975
+ prep.report.rulesApplied = false;
3976
+ prep.report.skillsApplied = false;
3977
+ const digest = prep.report.profileDigest;
3978
+ profileTag = digest ? `${this.runtimeInfo.id}:resources@${digest.slice(0, 16)}` : null;
3979
+ this.resourcePrep = { profileTag, report: prep.report };
3980
+ } catch (error) {
3981
+ this.resourcePrep = {
3982
+ profileTag: null,
3983
+ report: {
3984
+ rulesApplied: false,
3985
+ rulesChars: 0,
3986
+ profileDigest: null,
3987
+ skillsFound: [],
3988
+ reason: "prepare-failed"
3989
+ }
3990
+ };
3991
+ this.callbacks.onLog?.("warn", "应用资源准备失败,已回退兼容", {
3992
+ error: error instanceof Error ? error.message : String(error)
3993
+ });
3994
+ }
3995
+ } else {
3996
+ const load = this.resourcesDir ? readAppResourcesDir(this.resourcesDir) : null;
3997
+ this.resourcePrep = load ? { profileTag: null, report: {
3998
+ rulesApplied: false,
3999
+ rulesPrepared: false,
4000
+ skillsApplied: false,
4001
+ rulesChars: load.rules?.chars ?? 0,
4002
+ profileDigest: digestAppResources(load),
4003
+ skillsFound: load.skills.map((s) => s.name),
4004
+ reason: "runtime-not-supported"
4005
+ } } : null;
4006
+ }
4007
+ const finalEnv = { ...spawnEnv.env, ...resourceEnv };
2845
4008
  await this.adapter.beforeSpawn?.();
2846
- const processHandle = spawnAcpProcess({
4009
+ if (connectGen !== this.connectionGen || this.status !== "connecting")
4010
+ return err({ code: "CANCELLED", message: "连接已取消" });
4011
+ let reuseDegraded = false;
4012
+ let reusedHandle = null;
4013
+ if (profileTag) {
4014
+ const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
4015
+ expectedTag: profileTag,
4016
+ scopeKey: this.processScopeKey,
4017
+ isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
4018
+ });
4019
+ if (reuse.status === "hit") {
4020
+ reusedHandle = reuse.handle;
4021
+ } else if (reuse.status === "busy") {
4022
+ reusedHandle = reuse.handle;
4023
+ reuseDegraded = true;
4024
+ this.callbacks.onLog?.("warn", "应用资源摘要已变更但旧进程正忙,沿用旧进程并降级,新摘要下次冷启动生效");
4025
+ }
4026
+ }
4027
+ const processHandle = reusedHandle ?? spawnAcpProcess({
2847
4028
  runtime: effectiveRuntime,
2848
4029
  cwd: this.workspaceRoot,
2849
- env: spawnEnv.env,
4030
+ scopeKey: this.processScopeKey,
4031
+ env: finalEnv,
2850
4032
  envRemove: spawnEnv.envRemove,
4033
+ profileTag,
2851
4034
  onStderrLine: (line) => {
2852
4035
  this.callbacks.onStderrLine?.(line);
2853
4036
  },
2854
4037
  onExit: (code, signal) => {
4038
+ if (this.connectionGen !== connectGen)
4039
+ return;
2855
4040
  this.callbacks.onLog?.("warn", `Agent 进程已退出 (code: ${code}, signal: ${signal})`);
2856
4041
  if (this.status === "connected" || this.status === "connecting") {
2857
4042
  this.disconnect("Agent 进程异常终止");
@@ -2902,9 +4087,28 @@ class AcpClient {
2902
4087
  }
2903
4088
  });
2904
4089
  this.initResponse = initResp;
4090
+ if (this.resourcePrep) {
4091
+ const agentInfo = initResp?.agentInfo;
4092
+ const bridgeVersion = typeof agentInfo?.version === "string" ? agentInfo.version : undefined;
4093
+ const supported = isSupportedBridgeVersion(this.runtimeInfo.id, bridgeVersion).eligible && (this.adapter.supportedBridgeVersions?.includes(bridgeVersion?.replace(/^v/, "") ?? "") ?? false);
4094
+ this.resourcePrep.report.bridgeVersion = bridgeVersion;
4095
+ this.resourcePrep.report.bridgeSupported = supported;
4096
+ if (this.processHandle)
4097
+ this.processHandle.bridgeVersion = bridgeVersion;
4098
+ if (supported && this.resourcePrep.report.reason === "native-session-version-not-verified")
4099
+ delete this.resourcePrep.report.reason;
4100
+ if (!supported) {
4101
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "unsupported-bridge-version";
4102
+ }
4103
+ if (reuseDegraded) {
4104
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "busy-deferred-stale-rules";
4105
+ }
4106
+ }
2905
4107
  this.setStatus("connected");
2906
4108
  return ok({ status: "connected", init: initResp });
2907
4109
  } catch (e) {
4110
+ if (connectGen !== this.connectionGen)
4111
+ return err({ code: "CANCELLED", message: "连接已被新请求取代" });
2908
4112
  const message = e instanceof Error ? e.message : String(e);
2909
4113
  this.setStatus("error", message);
2910
4114
  await this.disconnect(message);
@@ -2943,6 +4147,29 @@ class AcpClient {
2943
4147
  const resumeSupported = Boolean(init && parseResumeSessionSupported(init.agentCapabilities));
2944
4148
  const loadSupported = Boolean(init && parseLoadSessionSupported(init.agentCapabilities));
2945
4149
  try {
4150
+ let skillsExposed = "none";
4151
+ let mcpServers = options?.mcpServers ?? [];
4152
+ if (this.resourcesDir && this.attachSkillsMcp) {
4153
+ try {
4154
+ const descriptor = buildAppSkillsMcpServer(this.resourcesDir);
4155
+ const callerNames = new Set;
4156
+ for (const entry of mcpServers) {
4157
+ if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
4158
+ callerNames.add(entry.name);
4159
+ }
4160
+ }
4161
+ if (callerNames.has(descriptor.name)) {
4162
+ this.callbacks.onLog?.("warn", "调用方已有同名技能 MCP 服务,保留调用方版本", { name: descriptor.name });
4163
+ } else {
4164
+ mcpServers = [...mcpServers, descriptor];
4165
+ skillsExposed = "mcp-exposed";
4166
+ }
4167
+ } catch (error) {
4168
+ this.callbacks.onLog?.("warn", "技能 MCP 描述符构建失败,本次会话无技能 MCP", {
4169
+ error: error instanceof Error ? error.message : String(error)
4170
+ });
4171
+ }
4172
+ }
2946
4173
  const openResult = await restoreOrCreateAcpSession({
2947
4174
  request: async (method, params) => {
2948
4175
  return sdkRequest(agent, method, params);
@@ -2951,12 +4178,27 @@ class AcpClient {
2951
4178
  resumeSessionId: options?.resumeSessionId ?? null,
2952
4179
  resumeSupported,
2953
4180
  loadSupported,
2954
- mcpServers: options?.mcpServers ?? [],
4181
+ mcpServers,
4182
+ sessionMeta: (!this.sessionConfig || this.runtimeInfo.id === "agy") && this.resourcesDir && this.resourcePrep?.report.bridgeSupported ? this.adapter.appResourceSessionMeta?.(this.resourcesDir) : undefined,
2955
4183
  log: (level, msg, meta) => {
2956
4184
  this.callbacks.onLog?.(level, msg, meta);
2957
4185
  }
2958
4186
  });
2959
- const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions);
4187
+ if (!openResult.mcpServersAccepted)
4188
+ skillsExposed = "none";
4189
+ this.sessionLedger.set(openResult.sessionId, {
4190
+ restoreMethod: openResult.restoreMethod,
4191
+ gen: this.connectionGen,
4192
+ skillsExposed,
4193
+ nativeRules: openResult.nativeSessionAccepted
4194
+ });
4195
+ const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions, this.resourcePrep?.report ? {
4196
+ ...this.resourcePrep.report,
4197
+ skillsFound: [...this.resourcePrep.report.skillsFound],
4198
+ skillsExposed,
4199
+ rulesApplied: openResult.nativeSessionAccepted || !this.adapter.appResourceSessionMeta && openResult.restoreMethod === "new" && this.resourcePrep.report.bridgeSupported === true && this.resourcePrep.report.rulesPrepared === true,
4200
+ ...openResult.restoreMethod !== "new" && !openResult.nativeSessionAccepted ? { reason: "session-restored-not-verified" } : {}
4201
+ } : null);
2960
4202
  return ok(handle);
2961
4203
  } catch (e) {
2962
4204
  const message = e instanceof Error ? e.message : String(e);
@@ -2967,6 +4209,7 @@ class AcpClient {
2967
4209
  if (!this.sdkConnection?.agent) {
2968
4210
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
2969
4211
  }
4212
+ this.inflightPrompts.add(sessionId);
2970
4213
  try {
2971
4214
  const prompt = [{ type: "text", text: promptText }];
2972
4215
  for (const image of options?.images ?? []) {
@@ -2974,16 +4217,52 @@ class AcpClient {
2974
4217
  continue;
2975
4218
  prompt.push({ type: "image", mimeType: image.mimeType, data: image.data });
2976
4219
  }
4220
+ const compat = this.buildCompatPrepend(sessionId);
4221
+ const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
2977
4222
  const response = await sdkRequest(this.sdkConnection.agent, methods2.agent.session.prompt, {
2978
4223
  sessionId,
2979
- prompt
4224
+ prompt: blocks
2980
4225
  }, options?.timeoutMs);
2981
4226
  return ok(response);
2982
4227
  } catch (e) {
2983
4228
  const message = e instanceof Error ? e.message : String(e);
2984
4229
  return err({ code: "ACP_PROTOCOL_ERROR", message });
4230
+ } finally {
4231
+ this.inflightPrompts.delete(sessionId);
2985
4232
  }
2986
4233
  }
4234
+ buildCompatPrepend(sessionId) {
4235
+ if (!this.resourcesDir)
4236
+ return null;
4237
+ if (this.sessionConfig?.nativeRules)
4238
+ return null;
4239
+ const entry = this.sessionLedger.get(sessionId);
4240
+ if (!entry)
4241
+ return null;
4242
+ const connReport = this.resourcePrep?.report;
4243
+ const nativelyDelivered = entry.nativeRules || !this.adapter.appResourceSessionMeta && entry.restoreMethod === "new" && entry.gen === this.connectionGen && connReport?.rulesPrepared === true && connReport?.bridgeSupported === true;
4244
+ if (nativelyDelivered)
4245
+ return null;
4246
+ const load = readAppResourcesDir(this.resourcesDir);
4247
+ const rulesText = readAppRulesText(this.resourcesDir);
4248
+ const digest = digestAppResources(load);
4249
+ const key = compatDeliveryKey(sessionId, this.connectionGen, digest);
4250
+ if (this.compatSentKeys.has(key))
4251
+ return null;
4252
+ const text = buildCompatGuideText({
4253
+ rulesText,
4254
+ skills: load.skills.map((s) => ({ name: s.name, description: s.description })),
4255
+ skillsViaMcp: entry.skillsExposed === "mcp-exposed",
4256
+ digest,
4257
+ sessionId,
4258
+ generation: this.connectionGen
4259
+ });
4260
+ if (!text)
4261
+ return null;
4262
+ this.compatSnapshots.set(key, { text, digest });
4263
+ this.compatSentKeys.add(key);
4264
+ return text;
4265
+ }
2987
4266
  async setSessionConfigOption(sessionId, configId, value) {
2988
4267
  if (!this.sdkConnection?.agent) {
2989
4268
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
@@ -3002,6 +4281,10 @@ class AcpClient {
3002
4281
  }
3003
4282
  async disconnect(reason) {
3004
4283
  this.setStatus("disconnected", reason);
4284
+ this.resourcePrep = null;
4285
+ this.sessionLedger.clear();
4286
+ this.compatSentKeys.clear();
4287
+ this.compatSnapshots.clear();
3005
4288
  try {
3006
4289
  this.streamHandle?.dispose();
3007
4290
  this.sdkConnection?.close();
@@ -3017,6 +4300,15 @@ class AcpClient {
3017
4300
  } catch {}
3018
4301
  this.processHandle = null;
3019
4302
  }
4303
+ const config = this.sessionConfig;
4304
+ this.sessionConfig = null;
4305
+ if (config) {
4306
+ try {
4307
+ await config.dispose();
4308
+ } catch {
4309
+ this.callbacks.onLog?.("warn", "Session configuration cleanup failed; directory retained", { directory: config.directory });
4310
+ }
4311
+ }
3020
4312
  }
3021
4313
  setStatus(status, detail) {
3022
4314
  this.status = status;
@@ -3942,6 +5234,10 @@ export {
3942
5234
  ACP_EARLY_EXIT_WINDOW_MS,
3943
5235
  ACP_SDK_REQUEST_TIMEOUT_MS,
3944
5236
  AGY_ACP_NPM_PACKAGE,
5237
+ APP_RESOURCE_CAPABILITIES,
5238
+ APP_RULES_FILE,
5239
+ APP_SKILLS_DIR,
5240
+ APP_SKILL_FILE,
3945
5241
  AcpClient,
3946
5242
  AcpSessionHandle,
3947
5243
  AcpTerminalManager,
@@ -3960,6 +5256,7 @@ export {
3960
5256
  INKDOWN_VIRTUAL_DIR,
3961
5257
  INKDOWN_VIRTUAL_RESOURCES,
3962
5258
  LEGACY_ZED_CODEX_ACP_NPM_PACKAGE,
5259
+ NATIVE_ELIGIBLE_BRIDGE_VERSIONS,
3963
5260
  OPENCODE_CLI_NPM_PACKAGE,
3964
5261
  QuotaCache,
3965
5262
  acpReadTextFile,
@@ -3975,15 +5272,18 @@ export {
3975
5272
  callInkdownMcpTool,
3976
5273
  callInkdownTocTool,
3977
5274
  claudeAdapter,
5275
+ claudeResourceSessionMeta,
3978
5276
  clearAcpProvider,
3979
5277
  clearCursorCatalogCache,
3980
5278
  codexAdapter,
3981
5279
  connectSdkClient,
3982
5280
  copilotAdapter,
3983
5281
  createSdkStreamHandle,
5282
+ createSessionConfigHome,
3984
5283
  cursorAdapter,
3985
5284
  decideConnectAuth,
3986
5285
  deepseekAdapter,
5286
+ digestAppResources,
3987
5287
  disposeAllAcpProcesses,
3988
5288
  emptyAcpAuthPreflight,
3989
5289
  err,
@@ -4003,6 +5303,7 @@ export {
4003
5303
  getDefaultAgentDataDir,
4004
5304
  getLiveAcpProcess,
4005
5305
  handleInkdownMcpRpc,
5306
+ isAbsolutePathLike,
4006
5307
  isAppError,
4007
5308
  isBinaryDocumentPath,
4008
5309
  isCancelled,
@@ -4012,11 +5313,15 @@ export {
4012
5313
  isInkdownVirtualDirPath,
4013
5314
  isOk,
4014
5315
  isSpawnedAcpProcessAlive,
5316
+ isSupportedBridgeVersion,
4015
5317
  isTransientAcpTransportError,
4016
5318
  isValidCursorAuthFile,
4017
5319
  isValidOpencodeAuthFile,
4018
5320
  listAcpRuntimes,
4019
5321
  listLiveAcpRuntimeIds,
5322
+ mergeCodexConfigJson,
5323
+ mergeConfigTomlPreserving,
5324
+ mergeOpenCodeAppConfig,
4020
5325
  mergeTopLevelModelsIntoConfigOptions,
4021
5326
  ok,
4022
5327
  opencodeAdapter,
@@ -4030,7 +5335,11 @@ export {
4030
5335
  parsePromptCapabilities,
4031
5336
  parseRateLimitsFromStatusText,
4032
5337
  parseResumeSessionSupported,
5338
+ parseSkillFrontmatter,
4033
5339
  pickAllowOptionId,
5340
+ prepareClaudeResources,
5341
+ prepareCompatibilityResources,
5342
+ prepareOpenCodeResources,
4034
5343
  probeAgyAuth,
4035
5344
  probeClaudeAuth,
4036
5345
  probeClaudeQuota,
@@ -4045,6 +5354,8 @@ export {
4045
5354
  probeOpencodeQuota,
4046
5355
  provisionCustomProviderCodexHome,
4047
5356
  readAcpProxySettings,
5357
+ readAppResourcesDir,
5358
+ readAppRulesText,
4048
5359
  readStoredAcpProvider,
4049
5360
  registerAcpClientHandlers,
4050
5361
  resolveClaudeHome,
@@ -4060,6 +5371,7 @@ export {
4060
5371
  resolveOpencodeAuthCandidates,
4061
5372
  resolveOpencodeAuthFile,
4062
5373
  resolveOpencodeAuthPath,
5374
+ resolveRuntimeEligibility,
4063
5375
  restoreOrCreateAcpSession,
4064
5376
  runConnectAuthGate,
4065
5377
  saveAcpProvider,
@@ -4070,5 +5382,6 @@ export {
4070
5382
  synthesizeModelOptionFromTopLevelModels,
4071
5383
  toAppError,
4072
5384
  truncateOutputFromStart,
5385
+ tryReuseLiveAcpProcess,
4073
5386
  withAcpEarlyExitDetail
4074
5387
  };