@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/sidecar.cjs CHANGED
@@ -36,7 +36,7 @@ var __toESM = (mod, isNodeMode, target) => {
36
36
  var readline2 = __toESM(require("node:readline"), 1);
37
37
 
38
38
  // src/version.ts
39
- var ACP_CLIENT_VERSION = "0.1.6";
39
+ var ACP_CLIENT_VERSION = "0.1.8";
40
40
  // src/contracts/index.ts
41
41
  function ok(value) {
42
42
  return { ok: true, value };
@@ -175,6 +175,243 @@ var BUILTIN_ACP_RUNTIMES = [
175
175
  function findBuiltinAcpRuntime(id) {
176
176
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
177
177
  }
178
+ // src/resources/session-config.ts
179
+ var import_node_fs2 = require("node:fs");
180
+ var import_promises = require("node:fs/promises");
181
+ var import_node_os = require("node:os");
182
+ var import_node_path2 = require("node:path");
183
+
184
+ // src/resources/app-resources.ts
185
+ var import_node_crypto = require("node:crypto");
186
+ var import_node_fs = require("node:fs");
187
+ var import_node_path = require("node:path");
188
+ var APP_RULES_FILE = "AGENTS.md";
189
+ var APP_SKILLS_DIR = "skills";
190
+ var APP_SKILL_FILE = "SKILL.md";
191
+ function parseSkillFrontmatter(text) {
192
+ const lines = text.split(`
193
+ `);
194
+ if (lines[0]?.trim() !== "---")
195
+ return {};
196
+ const out = {};
197
+ for (let i = 1;i < lines.length; i += 1) {
198
+ const line = lines[i] ?? "";
199
+ if (line.trim() === "---")
200
+ break;
201
+ const cut = line.indexOf(":");
202
+ if (cut <= 0)
203
+ continue;
204
+ const key = line.slice(0, cut).trim().toLowerCase();
205
+ if (key !== "name" && key !== "description")
206
+ continue;
207
+ const value = line.slice(cut + 1).trim().replace(/^['"]|['"]$/g, "");
208
+ if (value)
209
+ out[key] = value;
210
+ }
211
+ return out;
212
+ }
213
+ function sha256Hex(text) {
214
+ return import_node_crypto.createHash("sha256").update(text, "utf8").digest("hex");
215
+ }
216
+ function readTextFile(path) {
217
+ try {
218
+ if (!import_node_fs.statSync(path).isFile())
219
+ return null;
220
+ const text = import_node_fs.readFileSync(path, "utf8");
221
+ return text.trim() ? text : null;
222
+ } catch {
223
+ return null;
224
+ }
225
+ }
226
+ function readAppResourcesDir(directory) {
227
+ const warnings = [];
228
+ if (!import_node_path.isAbsolute(directory))
229
+ return { directoryReadable: false, rules: null, skills: [], warnings: ["资源目录必须是本机绝对路径"] };
230
+ let directoryReadable = false;
231
+ try {
232
+ directoryReadable = import_node_fs.statSync(directory).isDirectory();
233
+ } catch {
234
+ directoryReadable = false;
235
+ }
236
+ if (!directoryReadable) {
237
+ return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
238
+ }
239
+ let rules = null;
240
+ const rulesText = readTextFile(import_node_path.join(directory, APP_RULES_FILE));
241
+ if (rulesText === null) {
242
+ warnings.push(`缺常驻规则: ${APP_RULES_FILE}`);
243
+ } else {
244
+ rules = { chars: rulesText.length, digest: sha256Hex(`app-rules-v1
245
+ ${rulesText}`) };
246
+ }
247
+ const skills = [];
248
+ const skillsRoot = import_node_path.join(directory, APP_SKILLS_DIR);
249
+ let skillNames = [];
250
+ try {
251
+ if (import_node_fs.statSync(skillsRoot).isDirectory()) {
252
+ skillNames = import_node_fs.readdirSync(skillsRoot).filter((name) => {
253
+ try {
254
+ return import_node_fs.statSync(import_node_path.join(skillsRoot, name)).isDirectory();
255
+ } catch {
256
+ return false;
257
+ }
258
+ });
259
+ }
260
+ } catch {
261
+ skillNames = [];
262
+ }
263
+ for (const name of skillNames.sort()) {
264
+ const rel = `${APP_SKILLS_DIR}/${name}/${APP_SKILL_FILE}`;
265
+ const text = readTextFile(import_node_path.join(directory, rel));
266
+ if (text === null) {
267
+ warnings.push(`技能缺正文已跳过: ${rel}`);
268
+ continue;
269
+ }
270
+ const front = parseSkillFrontmatter(text);
271
+ const skillName = front.name || name;
272
+ if (skills.some((s) => s.name === skillName)) {
273
+ warnings.push(`技能重名已跳过(保留首个): ${skillName}`);
274
+ continue;
275
+ }
276
+ const description = front.description || "";
277
+ skills.push({
278
+ name: skillName,
279
+ description,
280
+ path: rel,
281
+ chars: text.length,
282
+ digest: sha256Hex(`app-skill-v1
283
+ ${skillName}
284
+ ${description}
285
+ ${text}`)
286
+ });
287
+ }
288
+ return { directoryReadable: true, rules, skills, warnings };
289
+ }
290
+ function digestAppResources(load) {
291
+ if (!load.rules)
292
+ return null;
293
+ const skillPart = load.skills.map((s) => `${s.name}:${s.digest}`).join(`
294
+ `);
295
+ return sha256Hex(`app-resources-v1
296
+ ${load.rules.digest}
297
+ ${skillPart}`);
298
+ }
299
+ function readAppRulesText(directory) {
300
+ return readTextFile(import_node_path.join(directory, APP_RULES_FILE));
301
+ }
302
+ function isAbsolutePathLike(path) {
303
+ return import_node_path.isAbsolute(path);
304
+ }
305
+
306
+ // src/resources/session-config.ts
307
+ async function createSessionConfigHome(runtime, resources) {
308
+ if (!import_node_path2.isAbsolute(resources))
309
+ throw new Error("Resources must be an absolute path");
310
+ const id = runtime === "cursor" ? "cursor-cli" : runtime;
311
+ const supported = ["agy", "codex-acp", "claude", "gemini", "copilot", "cursor-cli", "opencode", "opencode-v2"];
312
+ if (!supported.includes(id))
313
+ throw new Error("Session configuration home is not verified for runtime: " + runtime);
314
+ const text = readAppRulesText(resources);
315
+ if (!text)
316
+ throw new Error("Session configuration requires nonempty AGENTS.md");
317
+ const parent = import_node_path2.resolve(import_node_os.tmpdir());
318
+ const directory = await import_promises.mkdtemp(import_node_path2.join(parent, "acp-session-config-"));
319
+ const checkRoot = () => {
320
+ if (import_node_path2.resolve(directory) === parent || !import_node_path2.resolve(directory).startsWith(parent + import_node_path2.sep) || !import_node_path2.relative(parent, directory).startsWith("acp-session-config-"))
321
+ throw new Error("Unsafe configuration cleanup target");
322
+ };
323
+ const dispose = async () => {
324
+ checkRoot();
325
+ let failure;
326
+ for (let i = 0;i < 30; i++) {
327
+ try {
328
+ await import_promises.rm(directory, { recursive: true, force: true });
329
+ return;
330
+ } catch (error) {
331
+ failure = error;
332
+ await new Promise((r) => setTimeout(r, 100));
333
+ }
334
+ }
335
+ throw failure;
336
+ };
337
+ try {
338
+ const config = import_node_path2.join(directory, "config");
339
+ await import_promises.mkdir(config, { recursive: true, mode: 448 });
340
+ let env;
341
+ let rulesFile;
342
+ let skillsRoot = import_node_path2.join(config, "skills");
343
+ let nativeRules = true;
344
+ if (id === "agy") {
345
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
346
+ env = { AGY_ACP_RESOURCES_DIR: config };
347
+ nativeRules = false;
348
+ } else if (id === "gemini") {
349
+ const root = import_node_path2.join(directory, "home", ".gemini");
350
+ await import_promises.mkdir(root, { recursive: true, mode: 448 });
351
+ rulesFile = import_node_path2.join(root, "GEMINI.md");
352
+ skillsRoot = import_node_path2.join(root, "skills");
353
+ env = { GEMINI_CLI_HOME: import_node_path2.join(directory, "home") };
354
+ } else if (id === "claude") {
355
+ rulesFile = import_node_path2.join(config, "CLAUDE.md");
356
+ env = { CLAUDE_CONFIG_DIR: config };
357
+ } else if (id === "codex-acp") {
358
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
359
+ env = { CODEX_HOME: config };
360
+ } else if (id === "copilot") {
361
+ rulesFile = import_node_path2.join(config, "copilot-instructions.md");
362
+ env = { COPILOT_HOME: config, COPILOT_CUSTOM_INSTRUCTIONS_DIRS: config, COPILOT_SKILLS_DIRS: skillsRoot };
363
+ await import_promises.writeFile(import_node_path2.join(config, "AGENTS.md"), text, { mode: 384 });
364
+ } else if (id === "cursor-cli") {
365
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
366
+ env = { CURSOR_CONFIG_DIR: config };
367
+ nativeRules = false;
368
+ } else {
369
+ const root = import_node_path2.join(directory, "xdg-config", "opencode");
370
+ await import_promises.mkdir(root, { recursive: true, mode: 448 });
371
+ rulesFile = import_node_path2.join(root, "AGENTS.md");
372
+ skillsRoot = import_node_path2.join(root, "skills");
373
+ env = { XDG_CONFIG_HOME: import_node_path2.join(directory, "xdg-config"), XDG_DATA_HOME: import_node_path2.join(directory, "xdg-data"), XDG_CACHE_HOME: import_node_path2.join(directory, "xdg-cache"), XDG_STATE_HOME: import_node_path2.join(directory, "xdg-state") };
374
+ if (id === "opencode")
375
+ env.OPENCODE_CONFIG_DIR = root;
376
+ const skills = id === "opencode" ? { paths: [skillsRoot] } : [skillsRoot];
377
+ await import_promises.writeFile(import_node_path2.join(root, "opencode.json"), JSON.stringify({ instructions: [rulesFile], skills }), { mode: 384 });
378
+ }
379
+ await import_promises.writeFile(rulesFile, text, { mode: 384 });
380
+ const input = import_node_path2.join(resources, "skills");
381
+ try {
382
+ const info = await import_promises.lstat(input);
383
+ if (info.isSymbolicLink() || !info.isDirectory())
384
+ throw new Error("Skill root must be a regular directory");
385
+ const physical = await import_promises.realpath(input);
386
+ const copy = async (from, to) => {
387
+ await import_promises.mkdir(to, { recursive: true, mode: 448 });
388
+ for (const entry of await import_promises.readdir(from, { withFileTypes: true })) {
389
+ const src = import_node_path2.join(from, entry.name);
390
+ const info = await import_promises.lstat(src);
391
+ if (info.isSymbolicLink())
392
+ throw new Error("Skill symlink is not allowed");
393
+ const actual = await import_promises.realpath(src);
394
+ const rel = import_node_path2.relative(physical, actual);
395
+ if (rel.startsWith(".." + import_node_path2.sep) || rel === ".." || import_node_path2.isAbsolute(rel))
396
+ throw new Error("Skill path escapes resources");
397
+ if (info.isDirectory())
398
+ await copy(src, import_node_path2.join(to, entry.name));
399
+ else if (info.isFile() && entry.name.toLowerCase().endsWith(".md"))
400
+ await import_promises.writeFile(import_node_path2.join(to, entry.name), await import_promises.readFile(src), { mode: 384 });
401
+ }
402
+ };
403
+ await copy(input, skillsRoot);
404
+ } catch (error) {
405
+ if (error.code !== "ENOENT" || import_node_fs2.existsSync(input))
406
+ throw error;
407
+ }
408
+ return { directory, env, rulesFile, nativeRules, dispose };
409
+ } catch (error) {
410
+ await dispose();
411
+ throw error;
412
+ }
413
+ }
414
+
178
415
  // src/session/available-commands.ts
179
416
  function normalizeCommand(raw) {
180
417
  if (!raw || typeof raw !== "object")
@@ -10298,15 +10535,15 @@ var legacyClientNotificationMethods = new Set([
10298
10535
  ]);
10299
10536
 
10300
10537
  // src/runtimes/codex/quota.ts
10301
- var import_node_fs2 = require("node:fs");
10302
- var import_node_path2 = require("node:path");
10538
+ var import_node_fs4 = require("node:fs");
10539
+ var import_node_path4 = require("node:path");
10303
10540
  var import_node_child_process = require("node:child_process");
10304
10541
  var import_node_readline = __toESM(require("node:readline"), 1);
10305
10542
 
10306
10543
  // src/runtimes/codex/codex-auth-preflight.ts
10307
- var import_node_fs = require("node:fs");
10308
- var import_node_os = require("node:os");
10309
- var import_node_path = require("node:path");
10544
+ var import_node_fs3 = require("node:fs");
10545
+ var import_node_os2 = require("node:os");
10546
+ var import_node_path3 = require("node:path");
10310
10547
  function emptyAcpAuthPreflight() {
10311
10548
  return {
10312
10549
  codexHome: "",
@@ -10320,12 +10557,12 @@ function resolveCodexHome() {
10320
10557
  const fromEnv = process.env.CODEX_HOME?.trim();
10321
10558
  if (fromEnv)
10322
10559
  return fromEnv;
10323
- return import_node_path.join(import_node_os.homedir(), ".codex");
10560
+ return import_node_path3.join(import_node_os2.homedir(), ".codex");
10324
10561
  }
10325
10562
  function probeCodexAuth() {
10326
10563
  const codexHome = resolveCodexHome();
10327
- const hasCodexHome = import_node_fs.existsSync(codexHome);
10328
- const hasAuthFile = import_node_fs.existsSync(import_node_path.join(codexHome, "auth.json"));
10564
+ const hasCodexHome = import_node_fs3.existsSync(codexHome);
10565
+ const hasAuthFile = import_node_fs3.existsSync(import_node_path3.join(codexHome, "auth.json"));
10329
10566
  const hasApiKeyEnv = Boolean(process.env.CODEX_API_KEY?.trim() || process.env.OPENAI_API_KEY?.trim());
10330
10567
  return {
10331
10568
  codexHome,
@@ -10349,8 +10586,8 @@ function decodeJwtPayload(token) {
10349
10586
  }
10350
10587
  }
10351
10588
  var cachedDynamicResult = null;
10352
- async function queryCodexAppServer(timeoutMs = 4000) {
10353
- if (cachedDynamicResult && Date.now() - cachedDynamicResult.time < 15000) {
10589
+ async function queryCodexAppServer(timeoutMs = 1e4) {
10590
+ if (cachedDynamicResult && Date.now() - cachedDynamicResult.time < 120000) {
10354
10591
  return cachedDynamicResult.res;
10355
10592
  }
10356
10593
  return new Promise((resolve) => {
@@ -10375,7 +10612,8 @@ async function queryCodexAppServer(timeoutMs = 4000) {
10375
10612
  };
10376
10613
  timer = setTimeout(() => cleanup(null), timeoutMs);
10377
10614
  try {
10378
- proc = import_node_child_process.spawn("codex", ["app-server"], {
10615
+ const cmd = process.platform === "win32" ? "codex" : import_node_fs4.existsSync("/mnt/c/Users") ? "codex.exe" : "codex";
10616
+ proc = import_node_child_process.spawn(cmd, ["app-server"], {
10379
10617
  stdio: ["pipe", "pipe", "pipe"],
10380
10618
  shell: process.platform === "win32",
10381
10619
  windowsHide: true
@@ -10445,13 +10683,13 @@ function formatEpochTime(epochSeconds) {
10445
10683
  }
10446
10684
  async function probeCodexQuota(options) {
10447
10685
  const codexHome = resolveCodexHome();
10448
- const authPath = import_node_path2.join(codexHome, "auth.json");
10686
+ const authPath = import_node_path4.join(codexHome, "auth.json");
10449
10687
  let accountEmail;
10450
10688
  let accountPlan = "Codex Free / Local";
10451
10689
  let isLoggedIn = false;
10452
- if (import_node_fs2.existsSync(authPath)) {
10690
+ if (import_node_fs4.existsSync(authPath)) {
10453
10691
  try {
10454
- const authData = JSON.parse(import_node_fs2.readFileSync(authPath, "utf8"));
10692
+ const authData = JSON.parse(import_node_fs4.readFileSync(authPath, "utf8"));
10455
10693
  if (authData.OPENAI_API_KEY) {
10456
10694
  isLoggedIn = true;
10457
10695
  accountPlan = "OpenAI API Key";
@@ -10476,7 +10714,7 @@ async function probeCodexQuota(options) {
10476
10714
  isLoggedIn = true;
10477
10715
  accountPlan = "API Key (Env)";
10478
10716
  }
10479
- const dynamic = await queryCodexAppServer(4000);
10717
+ const dynamic = await queryCodexAppServer(1e4);
10480
10718
  if (dynamic) {
10481
10719
  isLoggedIn = true;
10482
10720
  if (dynamic.account?.email)
@@ -10542,8 +10780,92 @@ async function probeCodexQuota(options) {
10542
10780
  }
10543
10781
 
10544
10782
  // src/runtimes/codex/index.ts
10545
- var import_promises2 = require("node:fs/promises");
10546
- var import_node_path5 = require("node:path");
10783
+ var import_promises3 = require("node:fs/promises");
10784
+ var import_node_path7 = require("node:path");
10785
+ var import_node_os4 = require("node:os");
10786
+ var import_node_fs6 = require("node:fs");
10787
+ var import_node_crypto2 = require("node:crypto");
10788
+
10789
+ // src/resources/config-text.ts
10790
+ function mergeCodexConfigJson(input) {
10791
+ const block = (input.hostBlock ?? "").trim();
10792
+ if (!block)
10793
+ return { ok: false, reason: "empty-block" };
10794
+ const raw = (input.existingRaw ?? "").trim();
10795
+ if (!raw) {
10796
+ return { ok: true, json: JSON.stringify({ developer_instructions: block }), preservedUserInstructions: false };
10797
+ }
10798
+ let parsed;
10799
+ try {
10800
+ parsed = JSON.parse(raw);
10801
+ } catch {
10802
+ return { ok: false, reason: "invalid-json" };
10803
+ }
10804
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
10805
+ return { ok: false, reason: "invalid-json" };
10806
+ }
10807
+ const merged = { ...parsed };
10808
+ const existing = merged["developer_instructions"];
10809
+ if (existing === undefined) {
10810
+ merged["developer_instructions"] = block;
10811
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: false };
10812
+ }
10813
+ if (typeof existing !== "string") {
10814
+ return { ok: false, reason: "conflicting-value" };
10815
+ }
10816
+ const kept = existing.trim();
10817
+ merged["developer_instructions"] = kept ? `${block}
10818
+
10819
+ ${kept}` : block;
10820
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: kept !== "" };
10821
+ }
10822
+ function mergeConfigTomlPreserving(input) {
10823
+ const block = (input.replacementBlock ?? "").trim() ? `${input.replacementBlock.trim()}
10824
+ ` : "";
10825
+ if (!input.existingText || !input.existingText.trim())
10826
+ return block;
10827
+ if (/"""|'''/.test(input.existingText) || /^\s*\[.*["'].*\]|^\s*\[\[|^\s*["'](?:model|model_provider)["']\s*=/m.test(input.existingText)) {
10828
+ throw new Error("复杂 TOML 配置需要结构化合并,已保留原文件");
10829
+ }
10830
+ const topKeys = new Set(input.managedTopKeys);
10831
+ const tables = new Set(input.managedTables);
10832
+ const out = [];
10833
+ let inManagedTable = false;
10834
+ let inAnyTable = false;
10835
+ for (const line of input.existingText.split(`
10836
+ `)) {
10837
+ const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(line)?.[1]?.trim() ?? null;
10838
+ if (header !== null) {
10839
+ inAnyTable = true;
10840
+ inManagedTable = tables.has(header);
10841
+ if (!inManagedTable)
10842
+ out.push(line);
10843
+ continue;
10844
+ }
10845
+ if (inManagedTable)
10846
+ continue;
10847
+ if (!inAnyTable) {
10848
+ const key = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1];
10849
+ if (key && topKeys.has(key))
10850
+ continue;
10851
+ }
10852
+ out.push(line);
10853
+ }
10854
+ const kept = out.join(`
10855
+ `).trim();
10856
+ if (!kept)
10857
+ return block;
10858
+ const tableAt = block.search(/^\s*\[/m);
10859
+ if (tableAt < 0)
10860
+ return block + `
10861
+ ` + kept + `
10862
+ `;
10863
+ return block.slice(0, tableAt).trimEnd() + `
10864
+
10865
+ ` + kept + `
10866
+
10867
+ ` + block.slice(tableAt);
10868
+ }
10547
10869
 
10548
10870
  // src/runtimes/codex/codex-provider-home.ts
10549
10871
  var INKDOWN_PROVIDER_ID = "inkdown-custom";
@@ -10575,13 +10897,13 @@ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
10575
10897
  }
10576
10898
 
10577
10899
  // src/runtimes/codex/codex-provider.ts
10578
- var import_promises = require("node:fs/promises");
10579
- var import_node_fs3 = require("node:fs");
10580
- var import_node_path4 = require("node:path");
10900
+ var import_promises2 = require("node:fs/promises");
10901
+ var import_node_fs5 = require("node:fs");
10902
+ var import_node_path6 = require("node:path");
10581
10903
 
10582
10904
  // src/client/acp-paths.ts
10583
- var import_node_os2 = require("node:os");
10584
- var import_node_path3 = require("node:path");
10905
+ var import_node_os3 = require("node:os");
10906
+ var import_node_path5 = require("node:path");
10585
10907
  function getDefaultAgentDataDir() {
10586
10908
  if (process.env.INKDOWN_DATA_DIR) {
10587
10909
  return process.env.INKDOWN_DATA_DIR;
@@ -10590,27 +10912,27 @@ function getDefaultAgentDataDir() {
10590
10912
  return process.env.ACP_DATA_DIR;
10591
10913
  }
10592
10914
  if (process.platform === "win32") {
10593
- return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path3.join(import_node_os2.homedir(), "AppData", "Local", "inkdown");
10915
+ return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path5.join(import_node_os3.homedir(), "AppData", "Local", "inkdown");
10594
10916
  }
10595
10917
  if (process.platform === "darwin") {
10596
- return import_node_path3.join(import_node_os2.homedir(), "Library", "Application Support", "inkdown");
10918
+ return import_node_path5.join(import_node_os3.homedir(), "Library", "Application Support", "inkdown");
10597
10919
  }
10598
- return process.env.XDG_DATA_HOME || import_node_path3.join(import_node_os2.homedir(), ".local", "share", "inkdown");
10920
+ return process.env.XDG_DATA_HOME || import_node_path5.join(import_node_os3.homedir(), ".local", "share", "inkdown");
10599
10921
  }
10600
10922
 
10601
10923
  // src/runtimes/codex/codex-provider.ts
10602
10924
  function providerFilePath(dir) {
10603
- return import_node_path4.join(dir, "agent", "provider.json");
10925
+ return import_node_path6.join(dir, "agent", "provider.json");
10604
10926
  }
10605
10927
  function providerHomePath(dir) {
10606
- return import_node_path4.join(dir, "agent", "codex-home");
10928
+ return import_node_path6.join(dir, "agent", "codex-home");
10607
10929
  }
10608
10930
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
10609
10931
  const file = providerFilePath(dir);
10610
- if (!import_node_fs3.existsSync(file))
10932
+ if (!import_node_fs5.existsSync(file))
10611
10933
  return null;
10612
10934
  try {
10613
- const raw = JSON.parse(await import_promises.readFile(file, "utf8"));
10935
+ const raw = JSON.parse(await import_promises2.readFile(file, "utf8"));
10614
10936
  if (typeof raw.baseUrl !== "string" || typeof raw.model !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
10615
10937
  return null;
10616
10938
  }
@@ -10632,8 +10954,20 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
10632
10954
  // src/runtimes/codex/index.ts
10633
10955
  async function provisionCustomProviderCodexHome(provider, codexHome) {
10634
10956
  try {
10635
- await import_promises2.mkdir(codexHome, { recursive: true });
10636
- await import_promises2.writeFile(import_node_path5.join(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
10957
+ await import_promises3.mkdir(codexHome, { recursive: true });
10958
+ let existing = null;
10959
+ try {
10960
+ existing = await import_promises3.readFile(import_node_path7.join(codexHome, "config.toml"), "utf8");
10961
+ } catch (error) {
10962
+ if (error.code !== "ENOENT")
10963
+ throw error;
10964
+ }
10965
+ await import_promises3.writeFile(import_node_path7.join(codexHome, "config.toml"), mergeConfigTomlPreserving({
10966
+ existingText: existing,
10967
+ managedTopKeys: ["model", "model_provider"],
10968
+ managedTables: [`model_providers.${INKDOWN_PROVIDER_ID}`],
10969
+ replacementBlock: buildCustomProviderConfigToml(provider)
10970
+ }), "utf8");
10637
10971
  return true;
10638
10972
  } catch (error) {
10639
10973
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -10643,6 +10977,78 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
10643
10977
  var codexAdapter = {
10644
10978
  id: "codex-acp",
10645
10979
  probeQuota: async (options) => probeCodexQuota(options),
10980
+ supportedBridgeVersions: ["2.2.2"],
10981
+ prepareAppResources: async ({ directory, workspaceRoot, env: overrideEnv }) => {
10982
+ const load = readAppResourcesDir(directory);
10983
+ const skillsFound = load.skills.map((s) => s.name);
10984
+ const rulesText = readAppRulesText(directory);
10985
+ if (!rulesText) {
10986
+ return {
10987
+ report: {
10988
+ rulesApplied: false,
10989
+ rulesChars: 0,
10990
+ profileDigest: null,
10991
+ skillsFound,
10992
+ reason: "rules-missing"
10993
+ }
10994
+ };
10995
+ }
10996
+ const env = { ...process.env, ...overrideEnv };
10997
+ const notApplied = (reason) => ({ report: {
10998
+ rulesApplied: false,
10999
+ rulesPrepared: false,
11000
+ skillsApplied: false,
11001
+ rulesChars: rulesText.length,
11002
+ profileDigest: digestAppResources(load),
11003
+ skillsFound,
11004
+ reason
11005
+ } });
11006
+ if (!load.directoryReadable)
11007
+ return notApplied("invalid-resource-directory");
11008
+ if (env.CODEX_PATH)
11009
+ return notApplied("execution-not-verified");
11010
+ const codexHome = env.CODEX_HOME || import_node_path7.join(import_node_os4.homedir(), ".codex");
11011
+ try {
11012
+ await import_promises3.readFile(import_node_path7.join(codexHome, "config.toml"));
11013
+ return notApplied("effective-config-not-verified");
11014
+ } catch (error) {
11015
+ if (error.code !== "ENOENT")
11016
+ return notApplied("effective-config-not-verified");
11017
+ }
11018
+ for (let dir = workspaceRoot;dir; ) {
11019
+ if (import_node_fs6.existsSync(import_node_path7.join(dir, ".codex", "config.toml")))
11020
+ return notApplied("effective-config-not-verified");
11021
+ if (import_node_fs6.existsSync(import_node_path7.join(dir, ".git")))
11022
+ break;
11023
+ const parent = import_node_path7.dirname(dir);
11024
+ if (parent === dir)
11025
+ break;
11026
+ dir = parent;
11027
+ }
11028
+ const merged = mergeCodexConfigJson({ existingRaw: env["CODEX_CONFIG"], hostBlock: rulesText });
11029
+ if (!merged.ok) {
11030
+ return {
11031
+ report: {
11032
+ rulesApplied: false,
11033
+ rulesChars: rulesText.length,
11034
+ profileDigest: digestAppResources(load),
11035
+ skillsFound,
11036
+ reason: merged.reason === "invalid-json" ? "invalid-codex-config" : "conflicting-codex-config"
11037
+ }
11038
+ };
11039
+ }
11040
+ return {
11041
+ env: { CODEX_CONFIG: merged.json },
11042
+ report: {
11043
+ rulesApplied: false,
11044
+ rulesPrepared: true,
11045
+ skillsApplied: false,
11046
+ rulesChars: rulesText.length,
11047
+ profileDigest: import_node_crypto2.createHash("sha256").update(JSON.stringify([digestAppResources(load), codexHome, workspaceRoot, merged.json])).digest("hex"),
11048
+ skillsFound
11049
+ }
11050
+ };
11051
+ },
10646
11052
  probeAuth: () => {
10647
11053
  return probeCodexAuth();
10648
11054
  },
@@ -10659,11 +11065,73 @@ var codexAdapter = {
10659
11065
  }
10660
11066
  };
10661
11067
 
10662
- // src/runtimes/claude/quota.ts
10663
- var import_node_fs4 = require("node:fs");
10664
- var import_node_os3 = require("node:os");
10665
- var import_node_path6 = require("node:path");
11068
+ // src/resources/runtime-bindings.ts
11069
+ var import_node_path8 = require("node:path");
10666
11070
  var import_node_child_process2 = require("node:child_process");
11071
+ var import_node_util = require("node:util");
11072
+ function prepareCompatibilityResources(directory, reason) {
11073
+ const load = readAppResourcesDir(directory);
11074
+ return { report: {
11075
+ rulesApplied: false,
11076
+ rulesPrepared: false,
11077
+ skillsApplied: false,
11078
+ rulesChars: load.rules?.chars ?? 0,
11079
+ profileDigest: digestAppResources(load),
11080
+ skillsFound: load.skills.map((s) => s.name),
11081
+ reason
11082
+ } };
11083
+ }
11084
+ function mergeOpenCodeAppConfig(raw, directory) {
11085
+ const value = raw?.trim() ? JSON.parse(raw) : {};
11086
+ if (!value || typeof value !== "object" || Array.isArray(value))
11087
+ throw new Error("invalid-opencode-config");
11088
+ const config = value;
11089
+ if (config.instructions !== undefined && (!Array.isArray(config.instructions) || config.instructions.some((v) => typeof v !== "string")))
11090
+ throw new Error("invalid-opencode-instructions");
11091
+ if (config.skills !== undefined && (!config.skills || typeof config.skills !== "object" || Array.isArray(config.skills)))
11092
+ throw new Error("invalid-opencode-skills");
11093
+ const skills = config.skills ?? {};
11094
+ if (skills.paths !== undefined && (!Array.isArray(skills.paths) || skills.paths.some((v) => typeof v !== "string")))
11095
+ throw new Error("invalid-opencode-skill-paths");
11096
+ return JSON.stringify({
11097
+ ...config,
11098
+ instructions: [...new Set([...config.instructions ?? [], import_node_path8.join(directory, "AGENTS.md")])],
11099
+ skills: { ...skills, paths: [...new Set([...skills.paths ?? [], import_node_path8.join(directory, "skills")])] }
11100
+ });
11101
+ }
11102
+ async function prepareOpenCodeResources(input) {
11103
+ const prep = prepareCompatibilityResources(input.directory, "native-entry-not-verified");
11104
+ if (!input.command || !readAppRulesText(input.directory))
11105
+ return prep;
11106
+ try {
11107
+ const { stdout } = await import_node_util.promisify(import_node_child_process2.execFile)(input.command, ["--version"], { env: input.env, timeout: 8000, windowsHide: true });
11108
+ if (stdout.trim() !== "1.18.35")
11109
+ return prep;
11110
+ const json = mergeOpenCodeAppConfig(input.env?.OPENCODE_CONFIG_CONTENT, input.directory);
11111
+ return { env: { OPENCODE_CONFIG_CONTENT: json }, report: { ...prep.report, rulesPrepared: true, reason: undefined } };
11112
+ } catch {
11113
+ return { ...prep, report: { ...prep.report, reason: "native-config-prepare-failed" } };
11114
+ }
11115
+ }
11116
+ function prepareClaudeResources(directory) {
11117
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
11118
+ return { ...prep, report: { ...prep.report, rulesPrepared: !!readAppRulesText(directory) } };
11119
+ }
11120
+ function claudeResourceSessionMeta(directory) {
11121
+ const text = readAppRulesText(directory);
11122
+ if (!text)
11123
+ return;
11124
+ return {
11125
+ systemPrompt: { type: "preset", preset: "claude_code", append: text },
11126
+ claudeCode: { options: { plugins: [{ type: "local", path: directory }] } }
11127
+ };
11128
+ }
11129
+
11130
+ // src/runtimes/claude/quota.ts
11131
+ var import_node_fs7 = require("node:fs");
11132
+ var import_node_os5 = require("node:os");
11133
+ var import_node_path9 = require("node:path");
11134
+ var import_node_child_process3 = require("node:child_process");
10667
11135
  var cachedClaudeAuth = null;
10668
11136
  async function queryClaudeAuthStatus(timeoutMs = 1200) {
10669
11137
  if (cachedClaudeAuth && Date.now() - cachedClaudeAuth.time < 30000) {
@@ -10671,7 +11139,7 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
10671
11139
  }
10672
11140
  return new Promise((resolve) => {
10673
11141
  try {
10674
- import_node_child_process2.execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
11142
+ import_node_child_process3.execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
10675
11143
  if (!stdout)
10676
11144
  return resolve(null);
10677
11145
  try {
@@ -10689,15 +11157,15 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
10689
11157
  }
10690
11158
  async function probeClaudeQuota(options) {
10691
11159
  const claudeHome = resolveClaudeHome();
10692
- const claudeJsonPath = import_node_path6.join(import_node_os3.homedir(), ".claude.json");
10693
- const credsPath = import_node_path6.join(claudeHome, ".credentials.json");
11160
+ const claudeJsonPath = import_node_path9.join(import_node_os5.homedir(), ".claude.json");
11161
+ const credsPath = import_node_path9.join(claudeHome, ".credentials.json");
10694
11162
  let isLoggedIn = false;
10695
11163
  let isBanned = false;
10696
11164
  let accountEmail;
10697
11165
  let plan = "Claude Free / Default";
10698
- if (import_node_fs4.existsSync(claudeJsonPath)) {
11166
+ if (import_node_fs7.existsSync(claudeJsonPath)) {
10699
11167
  try {
10700
- const data = JSON.parse(import_node_fs4.readFileSync(claudeJsonPath, "utf8"));
11168
+ const data = JSON.parse(import_node_fs7.readFileSync(claudeJsonPath, "utf8"));
10701
11169
  if (data.oauthAccount) {
10702
11170
  isLoggedIn = true;
10703
11171
  accountEmail = data.oauthAccount.emailAddress;
@@ -10708,9 +11176,9 @@ async function probeClaudeQuota(options) {
10708
11176
  }
10709
11177
  } catch {}
10710
11178
  }
10711
- if (import_node_fs4.existsSync(credsPath)) {
11179
+ if (import_node_fs7.existsSync(credsPath)) {
10712
11180
  try {
10713
- const creds = JSON.parse(import_node_fs4.readFileSync(credsPath, "utf8"));
11181
+ const creds = JSON.parse(import_node_fs7.readFileSync(credsPath, "utf8"));
10714
11182
  if (creds.accessToken || creds.sessionKey)
10715
11183
  isLoggedIn = true;
10716
11184
  } catch {}
@@ -10762,19 +11230,19 @@ async function probeClaudeQuota(options) {
10762
11230
  }
10763
11231
 
10764
11232
  // src/runtimes/claude/index.ts
10765
- var import_node_fs5 = require("node:fs");
10766
- var import_node_os4 = require("node:os");
10767
- var import_node_path7 = require("node:path");
11233
+ var import_node_fs8 = require("node:fs");
11234
+ var import_node_os6 = require("node:os");
11235
+ var import_node_path10 = require("node:path");
10768
11236
  function resolveClaudeHome() {
10769
11237
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
10770
11238
  if (fromEnv)
10771
11239
  return fromEnv;
10772
- return import_node_path7.join(import_node_os4.homedir(), ".claude");
11240
+ return import_node_path10.join(import_node_os6.homedir(), ".claude");
10773
11241
  }
10774
11242
  function probeClaudeAuth() {
10775
11243
  const claudeHome = resolveClaudeHome();
10776
- const hasCodexHome = import_node_fs5.existsSync(claudeHome);
10777
- const hasAuthFile = import_node_fs5.existsSync(import_node_path7.join(import_node_os4.homedir(), ".claude.json")) || import_node_fs5.existsSync(import_node_path7.join(claudeHome, ".credentials.json"));
11244
+ const hasCodexHome = import_node_fs8.existsSync(claudeHome);
11245
+ const hasAuthFile = import_node_fs8.existsSync(import_node_path10.join(import_node_os6.homedir(), ".claude.json")) || import_node_fs8.existsSync(import_node_path10.join(claudeHome, ".credentials.json"));
10778
11246
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
10779
11247
  return {
10780
11248
  codexHome: claudeHome,
@@ -10786,6 +11254,9 @@ function probeClaudeAuth() {
10786
11254
  }
10787
11255
  var claudeAdapter = {
10788
11256
  id: "claude",
11257
+ supportedBridgeVersions: ["0.91.0"],
11258
+ prepareAppResources: async ({ directory }) => prepareClaudeResources(directory),
11259
+ appResourceSessionMeta: claudeResourceSessionMeta,
10789
11260
  probeAuth: () => probeClaudeAuth(),
10790
11261
  probeQuota: async (options) => probeClaudeQuota(options),
10791
11262
  orderAuthMethods: (methods) => methods,
@@ -10793,16 +11264,16 @@ var claudeAdapter = {
10793
11264
  };
10794
11265
 
10795
11266
  // src/runtimes/gemini/index.ts
10796
- var import_node_fs6 = require("node:fs");
10797
- var import_node_os5 = require("node:os");
10798
- var import_node_path8 = require("node:path");
11267
+ var import_node_fs9 = require("node:fs");
11268
+ var import_node_os7 = require("node:os");
11269
+ var import_node_path11 = require("node:path");
10799
11270
  function resolveGeminiHome() {
10800
- return import_node_path8.join(import_node_os5.homedir(), ".gemini");
11271
+ return import_node_path11.join(import_node_os7.homedir(), ".gemini");
10801
11272
  }
10802
11273
  function probeGeminiAuth() {
10803
11274
  const geminiHome = resolveGeminiHome();
10804
- const hasCodexHome = import_node_fs6.existsSync(geminiHome);
10805
- const hasAuthFile = import_node_fs6.existsSync(import_node_path8.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
11275
+ const hasCodexHome = import_node_fs9.existsSync(geminiHome);
11276
+ const hasAuthFile = import_node_fs9.existsSync(import_node_path11.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
10806
11277
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
10807
11278
  return {
10808
11279
  codexHome: geminiHome,
@@ -10814,24 +11285,25 @@ function probeGeminiAuth() {
10814
11285
  }
10815
11286
  var geminiAdapter = {
10816
11287
  id: "gemini",
11288
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-would-isolate-auth"),
10817
11289
  probeAuth: () => probeGeminiAuth(),
10818
11290
  orderAuthMethods: (methods) => methods,
10819
11291
  canSkipInteractiveAuth: () => false
10820
11292
  };
10821
11293
 
10822
11294
  // src/runtimes/copilot/index.ts
10823
- var import_node_fs7 = require("node:fs");
10824
- var import_node_os6 = require("node:os");
10825
- var import_node_path9 = require("node:path");
11295
+ var import_node_fs10 = require("node:fs");
11296
+ var import_node_os8 = require("node:os");
11297
+ var import_node_path12 = require("node:path");
10826
11298
  function resolveCopilotHome() {
10827
11299
  const fromEnv = process.env.COPILOT_HOME?.trim();
10828
11300
  if (fromEnv)
10829
11301
  return fromEnv;
10830
- return import_node_path9.join(import_node_os6.homedir(), ".copilot");
11302
+ return import_node_path12.join(import_node_os8.homedir(), ".copilot");
10831
11303
  }
10832
11304
  function hasCopilotLogin(home) {
10833
11305
  try {
10834
- const raw = import_node_fs7.readFileSync(import_node_path9.join(home, "config.json"), "utf8");
11306
+ const raw = import_node_fs10.readFileSync(import_node_path12.join(home, "config.json"), "utf8");
10835
11307
  const parsed = JSON.parse(raw);
10836
11308
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
10837
11309
  } catch {
@@ -10840,7 +11312,7 @@ function hasCopilotLogin(home) {
10840
11312
  }
10841
11313
  function probeCopilotAuth() {
10842
11314
  const copilotHome = resolveCopilotHome();
10843
- const hasCodexHome = import_node_fs7.existsSync(copilotHome);
11315
+ const hasCodexHome = import_node_fs10.existsSync(copilotHome);
10844
11316
  const hasAuthFile = hasCopilotLogin(copilotHome);
10845
11317
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
10846
11318
  return {
@@ -10853,18 +11325,21 @@ function probeCopilotAuth() {
10853
11325
  }
10854
11326
  var copilotAdapter = {
10855
11327
  id: "copilot",
11328
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-entry-not-verified"),
10856
11329
  probeAuth: () => probeCopilotAuth(),
10857
11330
  orderAuthMethods: (methods) => methods,
10858
11331
  canSkipInteractiveAuth: () => false
10859
11332
  };
10860
11333
 
10861
11334
  // src/runtimes/opencode/quota.ts
10862
- var import_node_fs8 = require("node:fs");
10863
- var import_node_child_process3 = require("node:child_process");
11335
+ var import_node_fs11 = require("node:fs");
11336
+ var import_node_child_process4 = require("node:child_process");
11337
+ var os = __toESM(require("node:os"), 1);
11338
+ var path = __toESM(require("node:path"), 1);
10864
11339
  function resolveOpencodeAuthPath() {
10865
11340
  const candidates = resolveOpencodeAuthCandidates();
10866
11341
  for (const c of candidates) {
10867
- if (import_node_fs8.existsSync(c))
11342
+ if (import_node_fs11.existsSync(c))
10868
11343
  return c;
10869
11344
  }
10870
11345
  return candidates[0] ?? null;
@@ -10876,7 +11351,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
10876
11351
  }
10877
11352
  return new Promise((resolve) => {
10878
11353
  try {
10879
- import_node_child_process3.execFile("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
11354
+ import_node_child_process4.execFile("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
10880
11355
  if (!stdout)
10881
11356
  return resolve(null);
10882
11357
  try {
@@ -10895,7 +11370,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
10895
11370
  async function queryOpencodeAuthList(timeoutMs = 1200) {
10896
11371
  return new Promise((resolve) => {
10897
11372
  try {
10898
- import_node_child_process3.execFile("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
11373
+ import_node_child_process4.execFile("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
10899
11374
  if (!stdout)
10900
11375
  return resolve([]);
10901
11376
  const lines = stdout.split(`
@@ -10907,14 +11382,170 @@ async function queryOpencodeAuthList(timeoutMs = 1200) {
10907
11382
  }
10908
11383
  });
10909
11384
  }
11385
+ function readLocalOpencodeCredentials() {
11386
+ const home = os.homedir();
11387
+ const dbPaths = [
11388
+ path.join(home, ".local", "share", "opencode", "opencode.db"),
11389
+ process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "opencode", "opencode.db") : null,
11390
+ path.join(home, ".config", "opencode", "opencode.db")
11391
+ ].filter(Boolean);
11392
+ for (const dbPath of dbPaths) {
11393
+ if (!import_node_fs11.existsSync(dbPath))
11394
+ continue;
11395
+ try {
11396
+ let rows = [];
11397
+ if (typeof process.versions?.bun !== "undefined") {
11398
+ const { Database } = require("bun:sqlite");
11399
+ const db = new Database(dbPath, { readonly: true });
11400
+ rows = db.query("SELECT integration_id, value FROM credential").all();
11401
+ db.close();
11402
+ } else {
11403
+ const { DatabaseSync } = require("node:sqlite");
11404
+ const db = new DatabaseSync(dbPath, { readOnly: true });
11405
+ rows = db.prepare("SELECT integration_id, value FROM credential").all();
11406
+ db.close();
11407
+ }
11408
+ const opencodeCred = rows.find((r) => r.integration_id === "opencode");
11409
+ if (opencodeCred?.value) {
11410
+ const parsed = JSON.parse(opencodeCred.value);
11411
+ const meta = parsed.metadata || {};
11412
+ return {
11413
+ email: meta.email || undefined,
11414
+ name: meta.email ? meta.email.split("@")[0] : meta.orgName || undefined,
11415
+ token: parsed.access || undefined,
11416
+ orgId: meta.orgID || undefined,
11417
+ accountId: meta.accountID || undefined
11418
+ };
11419
+ }
11420
+ } catch {
11421
+ try {
11422
+ const buf = import_node_fs11.readFileSync(dbPath, "utf8");
11423
+ const emailMatch = buf.match(/"email"\s*:\s*"([^"]+)"/);
11424
+ const tokenMatch = buf.match(/"access"\s*:\s*"(st_[a-zA-Z0-9_\\-]+)"/);
11425
+ const orgMatch = buf.match(/"orgID"\s*:\s*"(wrk_[a-zA-Z0-9_\\-]+)"/);
11426
+ const accMatch = buf.match(/"accountID"\s*:\s*"(acc_[a-zA-Z0-9_\\-]+)"/);
11427
+ if (emailMatch || tokenMatch) {
11428
+ return {
11429
+ email: emailMatch?.[1],
11430
+ name: emailMatch?.[1]?.split("@")[0],
11431
+ token: tokenMatch?.[1],
11432
+ orgId: orgMatch?.[1],
11433
+ accountId: accMatch?.[1]
11434
+ };
11435
+ }
11436
+ } catch {}
11437
+ }
11438
+ }
11439
+ return {};
11440
+ }
11441
+ async function probeOpencodeGoOnlineQuota(creds, runtimeId = "opencode") {
11442
+ if (!creds.token || !creds.orgId)
11443
+ return null;
11444
+ try {
11445
+ const res = await fetch("https://opencode.ai/console/api/go/status", {
11446
+ headers: {
11447
+ Authorization: `Bearer ${creds.token}`,
11448
+ "x-opencode-org-id": creds.orgId,
11449
+ "x-opencode-account-id": creds.accountId || ""
11450
+ },
11451
+ signal: AbortSignal.timeout(3500)
11452
+ });
11453
+ if (!res.ok)
11454
+ return null;
11455
+ const data = await res.json();
11456
+ const meters = data?.access?.meters;
11457
+ if (!meters)
11458
+ return null;
11459
+ const formatReset = (isoStr) => {
11460
+ if (!isoStr)
11461
+ return;
11462
+ const diffMs = new Date(isoStr).getTime() - Date.now();
11463
+ if (diffMs <= 0)
11464
+ return "已重置";
11465
+ const totalMins = Math.floor(diffMs / 60000);
11466
+ const hours = Math.floor(totalMins / 60);
11467
+ const days = Math.floor(hours / 24);
11468
+ if (days > 0) {
11469
+ const remH = hours % 24;
11470
+ return `Resets in ${days}d ${remH}h`;
11471
+ }
11472
+ const remM = totalMins % 60;
11473
+ return `Resets in ${hours}h ${remM}m`;
11474
+ };
11475
+ const calcWindow = (m, label, durMins) => {
11476
+ if (!m || !m.limitMicroCents)
11477
+ return;
11478
+ const limit = Number(m.limitMicroCents);
11479
+ const used = Number(m.usedMicroCents || 0);
11480
+ const usedPercent = limit > 0 ? Math.round(used / limit * 100) : 0;
11481
+ const percentLeft = Math.max(0, 100 - usedPercent);
11482
+ return {
11483
+ label,
11484
+ usedPercent,
11485
+ percentLeft,
11486
+ windowDurationMins: durMins,
11487
+ resetsAt: formatReset(m.resetsAt)
11488
+ };
11489
+ };
11490
+ const rolling = calcWindow(meters.fiveHour, "Rolling", 300);
11491
+ const weekly = calcWindow(meters.week, "Weekly", 10080);
11492
+ const monthly = calcWindow(meters.month, "Monthly", 43200);
11493
+ let creditBalance = "$0.00";
11494
+ try {
11495
+ const bRes = await fetch("https://opencode.ai/console/api/billing/status", {
11496
+ headers: {
11497
+ Authorization: `Bearer ${creds.token}`,
11498
+ "x-opencode-org-id": creds.orgId,
11499
+ "x-opencode-account-id": creds.accountId || ""
11500
+ },
11501
+ signal: AbortSignal.timeout(2000)
11502
+ });
11503
+ if (bRes.ok) {
11504
+ const bData = await bRes.json();
11505
+ const availMicro = Number(bData.availableMicroCents || 0);
11506
+ creditBalance = `$${(availMicro / 1e8).toFixed(2)}`;
11507
+ }
11508
+ } catch {}
11509
+ const quota = {
11510
+ runtimeId,
11511
+ provider: "OpenCode",
11512
+ account: {
11513
+ email: creds.email,
11514
+ name: creds.name || "OpenCode User",
11515
+ plan: "OpenCode Go",
11516
+ type: "opencode"
11517
+ },
11518
+ primaryWindow: rolling,
11519
+ secondaryWindow: weekly,
11520
+ extraWindows: monthly ? [monthly] : undefined,
11521
+ credits: {
11522
+ balance: creditBalance,
11523
+ currency: "USD",
11524
+ unlimited: false
11525
+ },
11526
+ status: "ok",
11527
+ updatedAt: Date.now()
11528
+ };
11529
+ return quota;
11530
+ } catch {
11531
+ return null;
11532
+ }
11533
+ }
10910
11534
  async function probeOpencodeQuota(runtimeId = "opencode") {
11535
+ const dbCreds = readLocalOpencodeCredentials();
11536
+ if (dbCreds.token) {
11537
+ const goQuota = await probeOpencodeGoOnlineQuota(dbCreds, runtimeId);
11538
+ if (goQuota)
11539
+ return goQuota;
11540
+ }
10911
11541
  const authPath = resolveOpencodeAuthPath();
10912
- let isLoggedIn = false;
10913
- let accountEmail;
11542
+ let isLoggedIn = Boolean(dbCreds.token || dbCreds.email);
11543
+ let accountEmail = dbCreds.email;
11544
+ let accountName = dbCreds.name;
10914
11545
  let plan = "OpenCode Community";
10915
- if (authPath && import_node_fs8.existsSync(authPath)) {
11546
+ if (authPath && import_node_fs11.existsSync(authPath)) {
10916
11547
  try {
10917
- const data = JSON.parse(import_node_fs8.readFileSync(authPath, "utf8"));
11548
+ const data = JSON.parse(import_node_fs11.readFileSync(authPath, "utf8"));
10918
11549
  if (data && typeof data === "object") {
10919
11550
  const keys = Object.keys(data);
10920
11551
  if (keys.length > 0) {
@@ -10934,7 +11565,9 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
10934
11565
  if (authList.length > 0) {
10935
11566
  isLoggedIn = true;
10936
11567
  const providers = authList.map((l) => l.split(/\s{2,}/)[0]).filter(Boolean);
10937
- if (providers.length > 0) {
11568
+ if (providers.some((p) => p.toLowerCase().includes("go"))) {
11569
+ plan = "OpenCode Go";
11570
+ } else if (providers.length > 0) {
10938
11571
  plan = `OpenCode (${providers.join(", ")})`;
10939
11572
  }
10940
11573
  }
@@ -10953,7 +11586,7 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
10953
11586
  let credits;
10954
11587
  if (stats && typeof stats.cost === "number") {
10955
11588
  credits = {
10956
- balance: stats.cost > 0 ? `$${stats.cost.toFixed(2)} spent` : "0.00"
11589
+ balance: stats.cost > 0 ? `$${stats.cost.toFixed(2)} spent` : "$0.00"
10957
11590
  };
10958
11591
  }
10959
11592
  return {
@@ -10961,6 +11594,7 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
10961
11594
  provider: "OpenCode",
10962
11595
  account: {
10963
11596
  email: accountEmail,
11597
+ name: accountName,
10964
11598
  plan,
10965
11599
  type: "provider_oauth"
10966
11600
  },
@@ -10971,16 +11605,16 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
10971
11605
  }
10972
11606
 
10973
11607
  // src/runtimes/opencode/index.ts
10974
- var import_node_fs9 = require("node:fs");
10975
- var import_node_os7 = require("node:os");
10976
- var import_node_path10 = require("node:path");
11608
+ var import_node_fs12 = require("node:fs");
11609
+ var import_node_os9 = require("node:os");
11610
+ var import_node_path13 = require("node:path");
10977
11611
  function pickEnv(env, key) {
10978
11612
  return env?.[key]?.trim() ?? "";
10979
11613
  }
10980
11614
  function resolveOpencodeAuthCandidates(overrides) {
10981
11615
  const platform = overrides?.platform ?? process.platform;
10982
11616
  const env = overrides?.env ?? process.env;
10983
- const home = overrides?.home ?? import_node_os7.homedir();
11617
+ const home = overrides?.home ?? import_node_os9.homedir();
10984
11618
  const seen = new Set;
10985
11619
  const out = [];
10986
11620
  const push = (p) => {
@@ -10991,27 +11625,27 @@ function resolveOpencodeAuthCandidates(overrides) {
10991
11625
  };
10992
11626
  const xdg = pickEnv(env, "XDG_DATA_HOME");
10993
11627
  if (xdg)
10994
- push(import_node_path10.join(xdg, "opencode", "auth.json"));
11628
+ push(import_node_path13.join(xdg, "opencode", "auth.json"));
10995
11629
  if (platform === "win32") {
10996
- const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path10.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
11630
+ const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path13.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
10997
11631
  if (localAppData)
10998
- push(import_node_path10.join(localAppData, "opencode", "auth.json"));
11632
+ push(import_node_path13.join(localAppData, "opencode", "auth.json"));
10999
11633
  const userProfile = pickEnv(env, "USERPROFILE") || home;
11000
11634
  if (userProfile)
11001
- push(import_node_path10.join(userProfile, ".local", "share", "opencode", "auth.json"));
11635
+ push(import_node_path13.join(userProfile, ".local", "share", "opencode", "auth.json"));
11002
11636
  } else if (home) {
11003
- push(import_node_path10.join(home, ".local", "share", "opencode", "auth.json"));
11637
+ push(import_node_path13.join(home, ".local", "share", "opencode", "auth.json"));
11004
11638
  }
11005
11639
  return out;
11006
11640
  }
11007
11641
  function resolveOpencodeAuthFile() {
11008
- return resolveOpencodeAuthCandidates()[0] ?? import_node_path10.join(import_node_os7.homedir(), ".local", "share", "opencode", "auth.json");
11642
+ return resolveOpencodeAuthCandidates()[0] ?? import_node_path13.join(import_node_os9.homedir(), ".local", "share", "opencode", "auth.json");
11009
11643
  }
11010
11644
  function isValidOpencodeAuthFile(authFile) {
11011
11645
  try {
11012
- if (!authFile || !import_node_fs9.existsSync(authFile))
11646
+ if (!authFile || !import_node_fs12.existsSync(authFile))
11013
11647
  return false;
11014
- const raw = import_node_fs9.readFileSync(authFile, "utf8").trim();
11648
+ const raw = import_node_fs12.readFileSync(authFile, "utf8").trim();
11015
11649
  if (!raw)
11016
11650
  return false;
11017
11651
  const parsed = JSON.parse(raw);
@@ -11029,7 +11663,7 @@ function probeOpencodeAuth(overrides) {
11029
11663
  for (const candidate of candidates) {
11030
11664
  let exists = false;
11031
11665
  try {
11032
- exists = import_node_fs9.existsSync(candidate);
11666
+ exists = import_node_fs12.existsSync(candidate);
11033
11667
  } catch {
11034
11668
  exists = false;
11035
11669
  }
@@ -11042,10 +11676,10 @@ function probeOpencodeAuth(overrides) {
11042
11676
  validFile = candidate;
11043
11677
  }
11044
11678
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
11045
- const authDir = import_node_path10.dirname(authFile);
11679
+ const authDir = import_node_path13.dirname(authFile);
11046
11680
  let hasCodexHome = false;
11047
11681
  try {
11048
- hasCodexHome = import_node_fs9.existsSync(authDir);
11682
+ hasCodexHome = import_node_fs12.existsSync(authDir);
11049
11683
  } catch {
11050
11684
  hasCodexHome = false;
11051
11685
  }
@@ -11060,6 +11694,8 @@ function probeOpencodeAuth(overrides) {
11060
11694
  }
11061
11695
  var opencodeAdapter = {
11062
11696
  id: "opencode",
11697
+ supportedBridgeVersions: ["1.18.35"],
11698
+ prepareAppResources: prepareOpenCodeResources,
11063
11699
  probeAuth: () => probeOpencodeAuth(),
11064
11700
  probeQuota: async () => probeOpencodeQuota(),
11065
11701
  orderAuthMethods: (methods) => methods,
@@ -11070,6 +11706,7 @@ var opencodeAdapter = {
11070
11706
  // src/runtimes/opencode-v2/index.ts
11071
11707
  var opencodeV2Adapter = {
11072
11708
  id: "opencode-v2",
11709
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
11073
11710
  probeAuth: () => probeOpencodeAuth(),
11074
11711
  orderAuthMethods: (methods) => methods,
11075
11712
  canSkipInteractiveAuth: () => false,
@@ -11099,27 +11736,27 @@ async function probeCursorQuota() {
11099
11736
  };
11100
11737
  }
11101
11738
  // src/runtimes/cursor/index.ts
11102
- var import_node_fs10 = require("node:fs");
11103
- var import_node_os8 = require("node:os");
11104
- var import_node_path11 = require("node:path");
11739
+ var import_node_fs13 = require("node:fs");
11740
+ var import_node_os10 = require("node:os");
11741
+ var import_node_path14 = require("node:path");
11105
11742
  function cursorLocalAppData(env) {
11106
11743
  const local = env.LOCALAPPDATA?.trim();
11107
11744
  if (local)
11108
11745
  return local;
11109
11746
  const profile = env.USERPROFILE?.trim();
11110
- return profile ? import_node_path11.join(profile, "AppData", "Local") : "";
11747
+ return profile ? import_node_path14.join(profile, "AppData", "Local") : "";
11111
11748
  }
11112
11749
  function isOnPath(command, env, platform) {
11113
11750
  const pathValue = env.PATH ?? env.Path ?? "";
11114
11751
  if (!pathValue.trim())
11115
11752
  return false;
11116
- const sep = platform === "win32" ? ";" : import_node_path11.delimiter;
11753
+ const sep = platform === "win32" ? ";" : import_node_path14.delimiter;
11117
11754
  for (const dir of pathValue.split(sep)) {
11118
11755
  const trimmed = dir.trim().replace(/^"|"$/g, "");
11119
11756
  if (!trimmed)
11120
11757
  continue;
11121
11758
  try {
11122
- if (import_node_fs10.existsSync(import_node_path11.join(trimmed, command)))
11759
+ if (import_node_fs13.existsSync(import_node_path14.join(trimmed, command)))
11123
11760
  return true;
11124
11761
  } catch {}
11125
11762
  }
@@ -11128,19 +11765,19 @@ function isOnPath(command, env, platform) {
11128
11765
  function resolveDirectCursorCommand(platform, env, home) {
11129
11766
  if (platform === "win32") {
11130
11767
  const localAppData = cursorLocalAppData(env);
11131
- return localAppData ? import_node_path11.join(localAppData, "cursor-agent", "agent.cmd") : "";
11768
+ return localAppData ? import_node_path14.join(localAppData, "cursor-agent", "agent.cmd") : "";
11132
11769
  }
11133
- return home ? import_node_path11.join(home, ".local", "bin", "agent") : "";
11770
+ return home ? import_node_path14.join(home, ".local", "bin", "agent") : "";
11134
11771
  }
11135
11772
  function resolveCursorSpawnCommand(overrides) {
11136
11773
  const args = ["acp"];
11137
11774
  const platform = overrides?.platform ?? process.platform;
11138
11775
  const env = overrides?.env ?? process.env;
11139
- const home = overrides?.home ?? import_node_os8.homedir();
11776
+ const home = overrides?.home ?? import_node_os10.homedir();
11140
11777
  const binary = platform === "win32" ? "agent.cmd" : "agent";
11141
11778
  const direct = resolveDirectCursorCommand(platform, env, home);
11142
11779
  try {
11143
- if (direct && import_node_fs10.existsSync(direct))
11780
+ if (direct && import_node_fs13.existsSync(direct))
11144
11781
  return { command: direct, args };
11145
11782
  } catch {}
11146
11783
  if (isOnPath(binary, env, platform))
@@ -11155,12 +11792,12 @@ function cursorRoamingAppData(env, home) {
11155
11792
  if (roaming)
11156
11793
  return roaming;
11157
11794
  const profile = pickEnv2(env, "USERPROFILE") || home;
11158
- return profile ? import_node_path11.join(profile, "AppData", "Roaming") : "";
11795
+ return profile ? import_node_path14.join(profile, "AppData", "Roaming") : "";
11159
11796
  }
11160
11797
  function resolveCursorAuthCandidates(overrides) {
11161
11798
  const platform = overrides?.platform ?? process.platform;
11162
11799
  const env = overrides?.env ?? process.env;
11163
- const home = overrides?.home ?? import_node_os8.homedir();
11800
+ const home = overrides?.home ?? import_node_os10.homedir();
11164
11801
  const seen = new Set;
11165
11802
  const out = [];
11166
11803
  const push = (p) => {
@@ -11171,16 +11808,16 @@ function resolveCursorAuthCandidates(overrides) {
11171
11808
  };
11172
11809
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
11173
11810
  if (xdg)
11174
- push(import_node_path11.join(xdg, "cursor", "auth.json"));
11811
+ push(import_node_path14.join(xdg, "cursor", "auth.json"));
11175
11812
  if (platform === "win32") {
11176
11813
  const profile = pickEnv2(env, "USERPROFILE") || home;
11177
11814
  if (profile)
11178
- push(import_node_path11.join(profile, ".config", "cursor", "auth.json"));
11815
+ push(import_node_path14.join(profile, ".config", "cursor", "auth.json"));
11179
11816
  const roaming = cursorRoamingAppData(env, home);
11180
11817
  if (roaming)
11181
- push(import_node_path11.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
11818
+ push(import_node_path14.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
11182
11819
  } else if (home) {
11183
- push(import_node_path11.join(home, ".config", "cursor", "auth.json"));
11820
+ push(import_node_path14.join(home, ".config", "cursor", "auth.json"));
11184
11821
  }
11185
11822
  return out;
11186
11823
  }
@@ -11191,9 +11828,9 @@ function isValidCursorAuthFile(authFile) {
11191
11828
  try {
11192
11829
  if (!authFile || isStorageHintPath(authFile))
11193
11830
  return false;
11194
- if (!import_node_fs10.existsSync(authFile))
11831
+ if (!import_node_fs13.existsSync(authFile))
11195
11832
  return false;
11196
- const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
11833
+ const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
11197
11834
  if (!raw)
11198
11835
  return false;
11199
11836
  const parsed = JSON.parse(raw);
@@ -11211,9 +11848,9 @@ function isHintCursorStorageFile(authFile) {
11211
11848
  try {
11212
11849
  if (!authFile || !isStorageHintPath(authFile))
11213
11850
  return false;
11214
- if (!import_node_fs10.existsSync(authFile))
11851
+ if (!import_node_fs13.existsSync(authFile))
11215
11852
  return false;
11216
- const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
11853
+ const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
11217
11854
  if (!raw)
11218
11855
  return false;
11219
11856
  const parsed = JSON.parse(raw);
@@ -11229,7 +11866,7 @@ function isValidCursorCandidate(authFile) {
11229
11866
  }
11230
11867
  function probeCursorAuth(overrides) {
11231
11868
  const env = overrides?.env ?? process.env;
11232
- const home = overrides?.home ?? import_node_os8.homedir();
11869
+ const home = overrides?.home ?? import_node_os10.homedir();
11233
11870
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
11234
11871
  const candidates = resolveCursorAuthCandidates(overrides);
11235
11872
  let firstExisting = null;
@@ -11237,7 +11874,7 @@ function probeCursorAuth(overrides) {
11237
11874
  for (const candidate of candidates) {
11238
11875
  let exists = false;
11239
11876
  try {
11240
- exists = import_node_fs10.existsSync(candidate);
11877
+ exists = import_node_fs13.existsSync(candidate);
11241
11878
  } catch {
11242
11879
  exists = false;
11243
11880
  }
@@ -11249,12 +11886,12 @@ function probeCursorAuth(overrides) {
11249
11886
  if (isValidCursorCandidate(candidate))
11250
11887
  validFile = candidate;
11251
11888
  }
11252
- const fallback = home ? import_node_path11.join(home, ".config", "cursor", "auth.json") : "";
11889
+ const fallback = home ? import_node_path14.join(home, ".config", "cursor", "auth.json") : "";
11253
11890
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
11254
- const authDir = authFile ? import_node_path11.dirname(authFile) : "";
11891
+ const authDir = authFile ? import_node_path14.dirname(authFile) : "";
11255
11892
  let hasCodexHome = false;
11256
11893
  try {
11257
- hasCodexHome = authDir ? import_node_fs10.existsSync(authDir) : false;
11894
+ hasCodexHome = authDir ? import_node_fs13.existsSync(authDir) : false;
11258
11895
  } catch {
11259
11896
  hasCodexHome = false;
11260
11897
  }
@@ -11268,6 +11905,7 @@ function probeCursorAuth(overrides) {
11268
11905
  }
11269
11906
  var cursorAdapter = {
11270
11907
  id: "cursor-cli",
11908
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-does-not-guarantee-rules"),
11271
11909
  probeAuth: () => probeCursorAuth(),
11272
11910
  probeQuota: async () => probeCursorQuota(),
11273
11911
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
@@ -11316,6 +11954,7 @@ function probeDeepseekAuth() {
11316
11954
  }
11317
11955
  var deepseekAdapter = {
11318
11956
  id: "deepseek",
11957
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
11319
11958
  probeAuth: () => probeDeepseekAuth(),
11320
11959
  resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
11321
11960
  resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
@@ -11324,23 +11963,242 @@ var deepseekAdapter = {
11324
11963
  };
11325
11964
 
11326
11965
  // src/runtimes/agy/quota.ts
11327
- var import_node_fs11 = require("node:fs");
11328
- var import_node_path12 = require("node:path");
11966
+ var import_node_fs14 = require("node:fs");
11967
+ var import_node_path15 = require("node:path");
11968
+ var import_node_child_process5 = require("node:child_process");
11969
+ var os2 = __toESM(require("node:os"), 1);
11329
11970
  function resolveGeminiHome2() {
11330
11971
  const home = process.env.USERPROFILE || process.env.HOME || "";
11331
- return import_node_path12.join(home, ".gemini");
11972
+ return import_node_path15.join(home, ".gemini");
11973
+ }
11974
+ function resolveAntigravityAccount() {
11975
+ if (process.env.GOOGLE_ACCOUNT?.trim()) {
11976
+ const email = process.env.GOOGLE_ACCOUNT.trim();
11977
+ return { email, name: email.split("@")[0] };
11978
+ }
11979
+ if (process.env.ANTIGRAVITY_ACCOUNT?.trim()) {
11980
+ const email = process.env.ANTIGRAVITY_ACCOUNT.trim();
11981
+ return { email, name: email.split("@")[0] };
11982
+ }
11983
+ const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
11984
+ const candidates = [
11985
+ process.env.APPDATA ? import_node_path15.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
11986
+ import_node_path15.join(home, ".config", "Antigravity", "app_storage.json"),
11987
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
11988
+ ].filter(Boolean);
11989
+ for (const file of candidates) {
11990
+ try {
11991
+ if (import_node_fs14.existsSync(file)) {
11992
+ const raw = import_node_fs14.readFileSync(file, "utf8");
11993
+ const json = JSON.parse(raw);
11994
+ const username = json["jetski.onboarding.lastLoginUsername"];
11995
+ if (username && typeof username === "string" && username.trim()) {
11996
+ const u = username.trim();
11997
+ return {
11998
+ email: u,
11999
+ name: u.includes("@") ? u.split("@")[0] : u
12000
+ };
12001
+ }
12002
+ }
12003
+ } catch {}
12004
+ }
12005
+ const osUser = process.env.USERNAME || process.env.USER;
12006
+ if (osUser?.trim()) {
12007
+ return { name: osUser.trim() };
12008
+ }
12009
+ return {};
12010
+ }
12011
+ function resolveAntigravityLanguageServer() {
12012
+ const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
12013
+ const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path15.join(home, "AppData", "Roaming") : "");
12014
+ const baseDirs = [
12015
+ appData ? import_node_path15.join(appData, "Antigravity IDE", "logs") : null,
12016
+ appData ? import_node_path15.join(appData, "Antigravity", "logs") : null,
12017
+ import_node_path15.join(home, ".config", "Antigravity IDE", "logs"),
12018
+ import_node_path15.join(home, ".config", "Antigravity", "logs"),
12019
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
12020
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity", "logs")
12021
+ ].filter(Boolean);
12022
+ for (const base of baseDirs) {
12023
+ try {
12024
+ if (!import_node_fs14.existsSync(base))
12025
+ continue;
12026
+ const sessionDirs = import_node_fs14.readdirSync(base).map((d) => {
12027
+ try {
12028
+ return { name: d, time: import_node_fs14.statSync(import_node_path15.join(base, d)).mtimeMs };
12029
+ } catch {
12030
+ return null;
12031
+ }
12032
+ }).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
12033
+ for (const s of sessionDirs) {
12034
+ const logFile = import_node_path15.join(base, s.name, "ls-main.log");
12035
+ if (import_node_fs14.existsSync(logFile)) {
12036
+ const content = import_node_fs14.readFileSync(logFile, "utf8");
12037
+ const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
12038
+ const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
12039
+ if (csrfMatch && portMatch) {
12040
+ return {
12041
+ port: parseInt(portMatch[1], 10),
12042
+ csrfToken: csrfMatch[1]
12043
+ };
12044
+ }
12045
+ }
12046
+ }
12047
+ } catch {}
12048
+ }
12049
+ try {
12050
+ let out = "";
12051
+ if (process.platform === "win32") {
12052
+ out = import_node_child_process5.execFileSync("powershell", [
12053
+ "-NoProfile",
12054
+ "-Command",
12055
+ `Get-CimInstance Win32_Process -Filter "Name like '%language_server%'" | Select-Object -ExpandProperty CommandLine`
12056
+ ], { encoding: "utf8", timeout: 4000, windowsHide: true });
12057
+ } else {
12058
+ out = import_node_child_process5.execFileSync("ps", ["aux"], { encoding: "utf8", timeout: 4000 });
12059
+ }
12060
+ const lines = out.split(/\r?\n/);
12061
+ for (const l of lines) {
12062
+ const portMatch = l.match(/--https_server_port\s+(\d+)/);
12063
+ const csrfMatch = l.match(/--csrf_token\s+([a-f0-9\-]+)/);
12064
+ if (portMatch && csrfMatch) {
12065
+ return { port: parseInt(portMatch[1], 10), csrfToken: csrfMatch[1] };
12066
+ }
12067
+ }
12068
+ } catch {}
12069
+ return null;
11332
12070
  }
11333
12071
  async function probeAgyQuota(options) {
12072
+ const acc = resolveAntigravityAccount();
12073
+ const lsInfo = resolveAntigravityLanguageServer();
12074
+ if (lsInfo) {
12075
+ try {
12076
+ let data = null;
12077
+ const prevReject = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
12078
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
12079
+ try {
12080
+ const res = await fetch(`https://127.0.0.1:${lsInfo.port}/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary`, {
12081
+ method: "POST",
12082
+ headers: {
12083
+ "Content-Type": "application/json",
12084
+ "x-codeium-csrf-token": lsInfo.csrfToken
12085
+ },
12086
+ body: JSON.stringify({}),
12087
+ signal: AbortSignal.timeout(4000),
12088
+ tls: { rejectUnauthorized: false }
12089
+ });
12090
+ if (res.ok) {
12091
+ data = await res.json();
12092
+ }
12093
+ } catch {
12094
+ try {
12095
+ const raw = import_node_child_process5.execFileSync(process.platform === "win32" ? "curl.exe" : "curl", [
12096
+ "-k",
12097
+ "-s",
12098
+ "-X",
12099
+ "POST",
12100
+ "-H",
12101
+ "Content-Type: application/json",
12102
+ "-H",
12103
+ `x-codeium-csrf-token: ${lsInfo.csrfToken}`,
12104
+ "-d",
12105
+ "{}",
12106
+ `https://127.0.0.1:${lsInfo.port}/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary`
12107
+ ], { encoding: "utf8", timeout: 4000 });
12108
+ data = JSON.parse(raw);
12109
+ } catch {}
12110
+ } finally {
12111
+ if (prevReject !== undefined) {
12112
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = prevReject;
12113
+ } else {
12114
+ delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
12115
+ }
12116
+ }
12117
+ if (data?.response?.groups) {
12118
+ const groups = data.response.groups;
12119
+ const formatReset = (isoStr, fallbackDesc) => {
12120
+ if (fallbackDesc && fallbackDesc.includes("it will fully refresh in ")) {
12121
+ const m = fallbackDesc.match(/it will fully refresh in (.+?)\.?$/);
12122
+ if (m?.[1])
12123
+ return `Resets in ${m[1].trim()}`;
12124
+ }
12125
+ if (!isoStr)
12126
+ return;
12127
+ const diffMs = new Date(isoStr).getTime() - Date.now();
12128
+ if (diffMs <= 0)
12129
+ return "已重置";
12130
+ const totalMins = Math.floor(diffMs / 60000);
12131
+ const hours = Math.floor(totalMins / 60);
12132
+ const days = Math.floor(hours / 24);
12133
+ if (days > 0)
12134
+ return `Resets in ${days}d ${hours % 24}h`;
12135
+ return `Resets in ${hours}h ${totalMins % 60}m`;
12136
+ };
12137
+ const toWindow = (b, groupName, label, durMins) => {
12138
+ if (!b)
12139
+ return;
12140
+ const frac = typeof b.remainingFraction === "number" ? b.remainingFraction : 1;
12141
+ const percentLeft = Math.max(0, Math.min(100, Math.round(frac * 100)));
12142
+ const usedPercent = 100 - percentLeft;
12143
+ return {
12144
+ label,
12145
+ group: groupName,
12146
+ percentLeft,
12147
+ usedPercent,
12148
+ windowDurationMins: durMins,
12149
+ resetsAt: formatReset(b.resetTime, b.description)
12150
+ };
12151
+ };
12152
+ const geminiGroup = groups.find((g) => g.displayName?.toLowerCase().includes("gemini"));
12153
+ const thirdPartyGroup = groups.find((g) => g.displayName?.toLowerCase().includes("claude") || g.displayName?.toLowerCase().includes("gpt"));
12154
+ const gemini5h = geminiGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("five hour") || b.bucketId?.includes("5h") || b.window === "5h");
12155
+ const geminiWeekly = geminiGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("weekly") || b.bucketId?.includes("weekly") || b.window === "weekly");
12156
+ const tp5h = thirdPartyGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("five hour") || b.bucketId?.includes("5h") || b.window === "5h");
12157
+ const tpWeekly = thirdPartyGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("weekly") || b.bucketId?.includes("weekly") || b.window === "weekly");
12158
+ const primaryWindow = toWindow(gemini5h, "Gemini Models", "5-Hour limit", 300) || {
12159
+ label: "5-Hour limit",
12160
+ group: "Gemini Models",
12161
+ percentLeft: 100,
12162
+ usedPercent: 0,
12163
+ windowDurationMins: 300
12164
+ };
12165
+ const secondaryWindow = toWindow(geminiWeekly, "Gemini Models", "Weekly limit", 10080);
12166
+ const extraWindows = [
12167
+ toWindow(tp5h, "Claude and GPT models", "5-Hour limit", 300),
12168
+ toWindow(tpWeekly, "Claude and GPT models", "Weekly limit", 10080)
12169
+ ].filter(Boolean);
12170
+ return {
12171
+ runtimeId: "agy",
12172
+ provider: "Google Antigravity",
12173
+ account: {
12174
+ email: acc.email,
12175
+ name: acc.name || "Google Developer",
12176
+ plan: "Google AI Pro",
12177
+ type: "gemini"
12178
+ },
12179
+ primaryWindow,
12180
+ secondaryWindow,
12181
+ extraWindows: extraWindows.length > 0 ? extraWindows : undefined,
12182
+ credits: {
12183
+ unlimited: true,
12184
+ balance: "unlimited"
12185
+ },
12186
+ status: "ok",
12187
+ updatedAt: Date.now()
12188
+ };
12189
+ }
12190
+ } catch {}
12191
+ }
11334
12192
  const geminiHome = resolveGeminiHome2();
11335
- const hasAgyDir = import_node_fs11.existsSync(import_node_path12.join(geminiHome, "antigravity")) || import_node_fs11.existsSync(import_node_path12.join(geminiHome, "antigravity-cli"));
12193
+ const hasAgyDir = import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity")) || import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity-cli"));
11336
12194
  const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
11337
- const isAvailable = hasAgyDir || hasApiKey;
12195
+ const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
11338
12196
  if (!isAvailable) {
11339
12197
  return {
11340
12198
  runtimeId: "agy",
11341
12199
  provider: "Google Antigravity",
11342
12200
  status: "unauthorized",
11343
- message: "wenjianlingu antigravity cli",
12201
+ message: "未检测到 Antigravity 登录凭据",
11344
12202
  updatedAt: Date.now()
11345
12203
  };
11346
12204
  }
@@ -11348,21 +12206,41 @@ async function probeAgyQuota(options) {
11348
12206
  runtimeId: "agy",
11349
12207
  provider: "Google Antigravity",
11350
12208
  account: {
11351
- plan: "Antigravity / Gemini",
12209
+ email: acc.email,
12210
+ name: acc.name || "Google Developer",
12211
+ plan: "Google AI Pro",
11352
12212
  type: "gemini"
11353
12213
  },
11354
12214
  primaryWindow: {
11355
12215
  label: "5-Hour limit",
12216
+ group: "Gemini Models",
11356
12217
  percentLeft: 100,
11357
12218
  usedPercent: 0,
11358
12219
  windowDurationMins: 300
11359
12220
  },
11360
12221
  secondaryWindow: {
11361
12222
  label: "Weekly limit",
12223
+ group: "Gemini Models",
11362
12224
  percentLeft: 100,
11363
12225
  usedPercent: 0,
11364
12226
  windowDurationMins: 10080
11365
12227
  },
12228
+ extraWindows: [
12229
+ {
12230
+ label: "5-Hour limit",
12231
+ group: "Claude and GPT models",
12232
+ percentLeft: 100,
12233
+ usedPercent: 0,
12234
+ windowDurationMins: 300
12235
+ },
12236
+ {
12237
+ label: "Weekly limit",
12238
+ group: "Claude and GPT models",
12239
+ percentLeft: 100,
12240
+ usedPercent: 0,
12241
+ windowDurationMins: 10080
12242
+ }
12243
+ ],
11366
12244
  credits: {
11367
12245
  unlimited: true,
11368
12246
  balance: "unlimited"
@@ -11384,6 +12262,12 @@ function probeAgyAuth() {
11384
12262
  }
11385
12263
  var agyAdapter = {
11386
12264
  id: "agy",
12265
+ prepareAppResources: async ({ directory }) => {
12266
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
12267
+ return { ...prep, env: { AGY_ACP_RESOURCES_DIR: directory }, report: { ...prep.report, rulesPrepared: prep.report.rulesChars > 0 } };
12268
+ },
12269
+ appResourceSessionMeta: (directory) => ({ appResources: { directory } }),
12270
+ supportedBridgeVersions: ["0.1.24"],
11387
12271
  probeAuth: () => probeAgyAuth(),
11388
12272
  probeQuota: (options) => probeAgyQuota(options),
11389
12273
  orderAuthMethods: (methods) => methods,
@@ -11423,7 +12307,10 @@ function getAcpRuntimeAdapter(runtimeId) {
11423
12307
  }
11424
12308
 
11425
12309
  // src/process/process-manager.ts
11426
- var import_node_child_process4 = require("node:child_process");
12310
+ var import_node_child_process6 = require("node:child_process");
12311
+ function processKey(runtimeId, scopeKey) {
12312
+ return scopeKey ? `${scopeKey}:${runtimeId}` : runtimeId;
12313
+ }
11427
12314
  var active = new Map;
11428
12315
  var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
11429
12316
  function isSpawnedAcpProcessAlive(handle) {
@@ -11434,7 +12321,7 @@ function killProcessTree(pid) {
11434
12321
  if (process.platform !== "win32")
11435
12322
  return;
11436
12323
  try {
11437
- import_node_child_process4.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
12324
+ import_node_child_process6.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
11438
12325
  windowsHide: true,
11439
12326
  timeout: 8000
11440
12327
  });
@@ -11454,7 +12341,8 @@ function spawnAcpProcess(options) {
11454
12341
  if (!options.runtime?.id || !options.runtime.command || !Array.isArray(options.runtime.args)) {
11455
12342
  throw new Error(`ACP 运行时模板缺失 command/args: ${options.runtime?.id ?? "(empty)"}`);
11456
12343
  }
11457
- const existing = active.get(options.runtime.id);
12344
+ const key = processKey(options.runtime.id, options.scopeKey);
12345
+ const existing = active.get(key);
11458
12346
  if (existing) {
11459
12347
  existing.kill();
11460
12348
  }
@@ -11477,7 +12365,7 @@ function spawnAcpProcess(options) {
11477
12365
  } else {
11478
12366
  delete env.NO_BROWSER;
11479
12367
  }
11480
- const child = import_node_child_process4.spawn(file, options.runtime.args, {
12368
+ const child = import_node_child_process6.spawn(file, options.runtime.args, {
11481
12369
  cwd: options.cwd,
11482
12370
  env,
11483
12371
  stdio: ["pipe", "pipe", "pipe"],
@@ -11515,6 +12403,9 @@ function spawnAcpProcess(options) {
11515
12403
  });
11516
12404
  const handle = {
11517
12405
  runtimeId: options.runtime.id,
12406
+ scopeKey: options.scopeKey,
12407
+ executionContext: options.executionContext,
12408
+ profileTag: options.profileTag ?? null,
11518
12409
  child,
11519
12410
  spawnedAt: Date.now(),
11520
12411
  stderrTail,
@@ -11532,7 +12423,7 @@ function spawnAcpProcess(options) {
11532
12423
  } catch {}
11533
12424
  }
11534
12425
  }
11535
- active.delete(options.runtime.id);
12426
+ active.delete(key);
11536
12427
  }
11537
12428
  };
11538
12429
  child.on("exit", (code, signal) => {
@@ -11540,12 +12431,43 @@ function spawnAcpProcess(options) {
11540
12431
  if (rest)
11541
12432
  pushStderrTailLine(rest);
11542
12433
  stderrBuffer = "";
11543
- active.delete(options.runtime.id);
12434
+ if (active.get(key) === handle)
12435
+ active.delete(key);
11544
12436
  options.onExit?.(code, signal);
11545
12437
  });
11546
- active.set(options.runtime.id, handle);
12438
+ active.set(key, handle);
12439
+ return handle;
12440
+ }
12441
+ function getLiveAcpProcess(runtimeId, query = {}) {
12442
+ const key = processKey(runtimeId, query.scopeKey);
12443
+ const handle = active.get(key);
12444
+ if (!handle)
12445
+ return;
12446
+ if (!isSpawnedAcpProcessAlive(handle)) {
12447
+ active.delete(key);
12448
+ return;
12449
+ }
12450
+ if (query.executionContext !== undefined && (handle.executionContext ?? null) !== query.executionContext) {
12451
+ return;
12452
+ }
12453
+ if (query.expectedTag !== undefined && (handle.profileTag ?? null) !== query.expectedTag)
12454
+ return;
11547
12455
  return handle;
11548
12456
  }
12457
+ function tryReuseLiveAcpProcess(runtimeId, query = {}) {
12458
+ const hit = getLiveAcpProcess(runtimeId, query);
12459
+ if (hit)
12460
+ return { status: "hit", handle: hit };
12461
+ if (query.expectedTag === undefined)
12462
+ return { status: "miss" };
12463
+ const stale = getLiveAcpProcess(runtimeId, { scopeKey: query.scopeKey, executionContext: query.executionContext });
12464
+ if (!stale)
12465
+ return { status: "miss" };
12466
+ if (query.isBusy?.(stale))
12467
+ return { status: "busy", handle: stale };
12468
+ stale.kill();
12469
+ return { status: "miss" };
12470
+ }
11549
12471
 
11550
12472
  // src/client/sdk-client.ts
11551
12473
  var import_node_stream = require("node:stream");
@@ -11612,18 +12534,18 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
11612
12534
  }
11613
12535
 
11614
12536
  // src/client/acp-fs.ts
11615
- var import_promises3 = require("node:fs/promises");
11616
- var import_node_path13 = require("node:path");
11617
12537
  var import_promises4 = require("node:fs/promises");
12538
+ var import_node_path16 = require("node:path");
12539
+ var import_promises5 = require("node:fs/promises");
11618
12540
  var MAX_READ_BYTES = 2 * 1024 * 1024;
11619
12541
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
11620
12542
  function isBinaryDocumentPath(filePath) {
11621
- return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path13.extname(filePath).toLowerCase());
12543
+ return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path16.extname(filePath).toLowerCase());
11622
12544
  }
11623
12545
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
11624
- const root = import_node_path13.resolve(workspaceRoot);
11625
- const target = import_node_path13.resolve(filePath);
11626
- const rootWithSep = root.endsWith(import_node_path13.sep) ? root : root + import_node_path13.sep;
12546
+ const root = import_node_path16.resolve(workspaceRoot);
12547
+ const target = import_node_path16.resolve(filePath);
12548
+ const rootWithSep = root.endsWith(import_node_path16.sep) ? root : root + import_node_path16.sep;
11627
12549
  if (target !== root && !target.startsWith(rootWithSep)) {
11628
12550
  throw new Error(`路径不在工作区内: ${filePath}`);
11629
12551
  }
@@ -11634,8 +12556,8 @@ async function acpReadTextFile(params) {
11634
12556
  throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
11635
12557
  }
11636
12558
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
11637
- await import_promises3.access(abs);
11638
- let content = await import_promises3.readFile(abs, "utf-8");
12559
+ await import_promises4.access(abs);
12560
+ let content = await import_promises4.readFile(abs, "utf-8");
11639
12561
  if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
11640
12562
  content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
11641
12563
  content += `
@@ -11654,8 +12576,8 @@ async function acpReadTextFile(params) {
11654
12576
  }
11655
12577
  async function acpWriteTextFile(params) {
11656
12578
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
11657
- await import_promises4.mkdir(import_node_path13.dirname(abs), { recursive: true });
11658
- await import_promises3.writeFile(abs, params.content, "utf-8");
12579
+ await import_promises5.mkdir(import_node_path16.dirname(abs), { recursive: true });
12580
+ await import_promises4.writeFile(abs, params.content, "utf-8");
11659
12581
  return {};
11660
12582
  }
11661
12583
 
@@ -11982,6 +12904,25 @@ function isTransientAcpTransportError(error) {
11982
12904
  async function restoreOrCreateAcpSession(input) {
11983
12905
  const resumeId = input.resumeSessionId?.trim() || null;
11984
12906
  const restoreAttempts = [];
12907
+ let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
12908
+ let nativeSessionAccepted = false;
12909
+ const request = async (method, params) => {
12910
+ if (!input.sessionMeta)
12911
+ return input.request(method, params);
12912
+ try {
12913
+ const result = await input.request(method, { ...params, _meta: input.sessionMeta });
12914
+ nativeSessionAccepted = true;
12915
+ return result;
12916
+ } catch (error) {
12917
+ const rejected = error instanceof RequestError && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
12918
+ if (!rejected || isTransientAcpTransportError(error))
12919
+ throw error;
12920
+ log("warn", "native resource options failed; retry without extension");
12921
+ const result = await input.request(method, params);
12922
+ nativeSessionAccepted = false;
12923
+ return result;
12924
+ }
12925
+ };
11985
12926
  const delayMs = input.retryDelayMs ?? 250;
11986
12927
  const log = input.log ?? ((level, message, data) => {
11987
12928
  if (level === "info" && false)
@@ -12003,7 +12944,7 @@ async function restoreOrCreateAcpSession(input) {
12003
12944
  maxTries
12004
12945
  });
12005
12946
  try {
12006
- const result = await input.request(rpcMethod, {
12947
+ const result = await request(rpcMethod, {
12007
12948
  sessionId: resumeId,
12008
12949
  cwd: input.cwd,
12009
12950
  mcpServers: input.mcpServers ?? []
@@ -12042,7 +12983,7 @@ async function restoreOrCreateAcpSession(input) {
12042
12983
  mcpServers: input.mcpServers ?? []
12043
12984
  };
12044
12985
  try {
12045
- return await input.request("session/new", baseParams);
12986
+ return await request("session/new", baseParams);
12046
12987
  } catch (firstError) {
12047
12988
  if ((input.mcpServers ?? []).length === 0)
12048
12989
  throw firstError;
@@ -12050,10 +12991,12 @@ async function restoreOrCreateAcpSession(input) {
12050
12991
  error: errorMessage(firstError)
12051
12992
  });
12052
12993
  try {
12053
- return await input.request("session/new", {
12994
+ const result = await request("session/new", {
12054
12995
  cwd: input.cwd,
12055
12996
  mcpServers: []
12056
12997
  });
12998
+ mcpServersAccepted = false;
12999
+ return result;
12057
13000
  } catch {
12058
13001
  throw firstError;
12059
13002
  }
@@ -12069,6 +13012,8 @@ async function restoreOrCreateAcpSession(input) {
12069
13012
  configOptions: withModelsFallback(resumed),
12070
13013
  restoreMethod: "resume",
12071
13014
  sessionRestored: true,
13015
+ mcpServersAccepted,
13016
+ nativeSessionAccepted,
12072
13017
  requestedSessionId: resumeId,
12073
13018
  restoreAttempts
12074
13019
  };
@@ -12087,6 +13032,8 @@ async function restoreOrCreateAcpSession(input) {
12087
13032
  configOptions: withModelsFallback(loaded),
12088
13033
  restoreMethod: "load",
12089
13034
  sessionRestored: true,
13035
+ mcpServersAccepted,
13036
+ nativeSessionAccepted,
12090
13037
  requestedSessionId: resumeId,
12091
13038
  restoreAttempts
12092
13039
  };
@@ -12108,14 +13055,16 @@ async function restoreOrCreateAcpSession(input) {
12108
13055
  configOptions: withModelsFallback(sessionResult),
12109
13056
  restoreMethod: "new",
12110
13057
  sessionRestored: false,
13058
+ mcpServersAccepted,
13059
+ nativeSessionAccepted,
12111
13060
  requestedSessionId: resumeId ?? undefined,
12112
13061
  restoreAttempts
12113
13062
  };
12114
13063
  }
12115
13064
 
12116
13065
  // src/client/acp-terminal.ts
12117
- var import_node_child_process5 = require("node:child_process");
12118
- var import_node_crypto = require("node:crypto");
13066
+ var import_node_child_process7 = require("node:child_process");
13067
+ var import_node_crypto3 = require("node:crypto");
12119
13068
 
12120
13069
  // src/transport/terminal-output-buffer.ts
12121
13070
  function truncateOutputFromStart(text, byteLimit) {
@@ -12167,14 +13116,14 @@ class AcpTerminalManager {
12167
13116
  throw new Error("terminal/create 需要 command");
12168
13117
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
12169
13118
  const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : DEFAULT_OUTPUT_BYTE_LIMIT;
12170
- const child = import_node_child_process5.spawn(command, params.args ?? [], {
13119
+ const child = import_node_child_process7.spawn(command, params.args ?? [], {
12171
13120
  cwd,
12172
13121
  env: buildEnv(params.env),
12173
13122
  windowsHide: true,
12174
13123
  shell: false,
12175
13124
  stdio: ["ignore", "pipe", "pipe"]
12176
13125
  });
12177
- const id = `term_${import_node_crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;
13126
+ const id = `term_${import_node_crypto3.randomUUID().replace(/-/g, "").slice(0, 12)}`;
12178
13127
  const record = {
12179
13128
  id,
12180
13129
  sessionId: params.sessionId,
@@ -12263,7 +13212,7 @@ class AcpTerminalManager {
12263
13212
  return;
12264
13213
  if (process.platform === "win32") {
12265
13214
  try {
12266
- import_node_child_process5.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
13215
+ import_node_child_process7.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
12267
13216
  windowsHide: true,
12268
13217
  stdio: "ignore"
12269
13218
  });
@@ -12298,9 +13247,9 @@ class AcpTerminalManager {
12298
13247
  }
12299
13248
 
12300
13249
  // src/client/acp-proxy-service.ts
12301
- var import_promises5 = require("node:fs/promises");
12302
- var import_node_fs12 = require("node:fs");
12303
- var import_node_path14 = require("node:path");
13250
+ var import_promises6 = require("node:fs/promises");
13251
+ var import_node_fs15 = require("node:fs");
13252
+ var import_node_path17 = require("node:path");
12304
13253
  var DEFAULT_ACP_PROXY_SETTINGS = {
12305
13254
  enabled: false,
12306
13255
  host: "127.0.0.1",
@@ -12309,14 +13258,14 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
12309
13258
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
12310
13259
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
12311
13260
  function proxyFilePath(dir) {
12312
- return import_node_path14.join(dir, "agent", "proxy.json");
13261
+ return import_node_path17.join(dir, "agent", "proxy.json");
12313
13262
  }
12314
13263
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
12315
13264
  const file = proxyFilePath(dir);
12316
- if (!import_node_fs12.existsSync(file))
13265
+ if (!import_node_fs15.existsSync(file))
12317
13266
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
12318
13267
  try {
12319
- const raw = JSON.parse(await import_promises5.readFile(file, "utf8"));
13268
+ const raw = JSON.parse(await import_promises6.readFile(file, "utf8"));
12320
13269
  return {
12321
13270
  enabled: raw.enabled === true,
12322
13271
  host: typeof raw.host === "string" && raw.host.trim() ? raw.host : DEFAULT_ACP_PROXY_SETTINGS.host,
@@ -12345,6 +13294,109 @@ function buildAcpProxySpawnEnv(settings) {
12345
13294
  };
12346
13295
  }
12347
13296
 
13297
+ // src/session/compat-guide.ts
13298
+ var COMPAT_CONTEXT_TAG = "acp-compat-context";
13299
+ function shortDigest(digest) {
13300
+ return digest ? digest.slice(0, 16) : "none";
13301
+ }
13302
+ function buildCompatGuideText(input) {
13303
+ const hasRules = (input.rulesText ?? "").trim() !== "";
13304
+ const hasSkills = input.skills.length > 0;
13305
+ if (!hasRules && !hasSkills)
13306
+ return null;
13307
+ const lines = [];
13308
+ 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.", "");
13309
+ if (hasRules) {
13310
+ lines.push("--- host rules (same source as the host app, delivered once per session) ---", "");
13311
+ lines.push(input.rulesText.trim(), "");
13312
+ }
13313
+ if (hasSkills) {
13314
+ lines.push("--- host skills catalog (names and descriptions only; read full text on demand) ---", "");
13315
+ for (const skill of input.skills) {
13316
+ lines.push(`- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`);
13317
+ }
13318
+ 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.");
13319
+ lines.push("");
13320
+ }
13321
+ lines.push(`</${COMPAT_CONTEXT_TAG}>`);
13322
+ return lines.join(`
13323
+ `);
13324
+ }
13325
+ function compatDeliveryKey(sessionId, generation, digest) {
13326
+ return `${generation}:${sessionId}:${digest ?? "none"}`;
13327
+ }
13328
+
13329
+ // src/mcp/app-skills-mcp.ts
13330
+ var import_node_path18 = require("node:path");
13331
+ var import_node_url = require("node:url");
13332
+ var import_node_fs16 = require("node:fs");
13333
+ var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
13334
+ var APP_SKILLS_TOOLS = [
13335
+ {
13336
+ name: "app_list_skills",
13337
+ 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.",
13338
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
13339
+ },
13340
+ {
13341
+ name: "app_read_skill",
13342
+ 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).",
13343
+ inputSchema: {
13344
+ type: "object",
13345
+ properties: {
13346
+ name: { type: "string", description: "Exact skill name from app_list_skills" },
13347
+ ref: {
13348
+ type: "string",
13349
+ description: "Optional same-directory relative Markdown file (default SKILL.md)"
13350
+ }
13351
+ },
13352
+ required: ["name"],
13353
+ additionalProperties: false
13354
+ }
13355
+ }
13356
+ ];
13357
+ function buildAppSkillsMcpServer(directory, opts) {
13358
+ return {
13359
+ name: opts?.name ?? APP_SKILLS_MCP_SERVER_NAME,
13360
+ command: process.execPath,
13361
+ env: process.versions.electron ? [{ name: "ELECTRON_RUN_AS_NODE", value: "1" }] : [],
13362
+ args: [opts?.runnerPath ?? resolveAppSkillsRunnerPath(), directory]
13363
+ };
13364
+ }
13365
+ function resolveAppSkillsRunnerPath(fromFile) {
13366
+ const base = fromFile ?? import_node_url.fileURLToPath("file:///home/runner/work/acp-client/acp-client/src/mcp/app-skills-mcp.ts");
13367
+ const candidates = [
13368
+ import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.cjs"),
13369
+ import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.ts")
13370
+ ];
13371
+ for (const candidate of candidates) {
13372
+ if (import_node_fs16.existsSync(candidate))
13373
+ return candidate;
13374
+ }
13375
+ throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
13376
+ }
13377
+
13378
+ // src/client/acp-client.ts
13379
+ var import_node_crypto4 = require("node:crypto");
13380
+
13381
+ // src/resources/eligibility.ts
13382
+ var NATIVE_ELIGIBLE_BRIDGE_VERSIONS = {
13383
+ "codex-acp": ["2.2.2"],
13384
+ opencode: ["1.18.35"],
13385
+ claude: ["0.91.0"],
13386
+ agy: ["0.1.24"]
13387
+ };
13388
+ function isSupportedBridgeVersion(runtimeId, version) {
13389
+ const versions = NATIVE_ELIGIBLE_BRIDGE_VERSIONS[(runtimeId ?? "").trim()];
13390
+ if (!versions)
13391
+ return { eligible: false, reason: "runtime-not-verified" };
13392
+ const normalized = version?.trim().replace(/^v/, "");
13393
+ if (!normalized)
13394
+ return { eligible: false, reason: "unknown-bridge-version" };
13395
+ if (!versions.includes(normalized))
13396
+ return { eligible: false, reason: "unsupported-bridge-version" };
13397
+ return { eligible: true };
13398
+ }
13399
+
12348
13400
  // src/session/session-capabilities.ts
12349
13401
  function parseLoadSessionSupported(caps) {
12350
13402
  return caps.loadSession === true;
@@ -12367,11 +13419,13 @@ class AcpSessionHandle {
12367
13419
  client;
12368
13420
  restoreMethod;
12369
13421
  configOptions;
12370
- constructor(sessionId, client, restoreMethod, configOptions) {
13422
+ resourceReport;
13423
+ constructor(sessionId, client, restoreMethod, configOptions, resourceReport) {
12371
13424
  this.sessionId = sessionId;
12372
13425
  this.client = client;
12373
13426
  this.restoreMethod = restoreMethod;
12374
13427
  this.configOptions = configOptions;
13428
+ this.resourceReport = resourceReport;
12375
13429
  }
12376
13430
  async prompt(promptText, options) {
12377
13431
  return this.client.promptSession(this.sessionId, promptText, options);
@@ -12400,6 +13454,10 @@ class AcpClient {
12400
13454
  clientInfo;
12401
13455
  dataDir;
12402
13456
  extraEnv;
13457
+ configurationScope;
13458
+ sessionConfig = null;
13459
+ resourcesDir;
13460
+ processScopeKey = import_node_crypto4.randomUUID();
12403
13461
  callbacks;
12404
13462
  terminals = new AcpTerminalManager;
12405
13463
  processHandle = null;
@@ -12407,6 +13465,17 @@ class AcpClient {
12407
13465
  sdkConnection = null;
12408
13466
  streamHandle = null;
12409
13467
  initResponse = null;
13468
+ inflightPrompts = new Set;
13469
+ resourcePrep = null;
13470
+ connectionGen = 0;
13471
+ attachSkillsMcp;
13472
+ sessionLedger = new Map;
13473
+ compatSentKeys = new Set;
13474
+ compatSnapshots = new Map;
13475
+ get resourceReport() {
13476
+ const report = this.resourcePrep?.report;
13477
+ return report ? { ...report, skillsFound: [...report.skillsFound] } : null;
13478
+ }
12410
13479
  constructor(options) {
12411
13480
  this.workspaceRoot = options.workspaceRoot;
12412
13481
  this.clientInfo = {
@@ -12415,6 +13484,14 @@ class AcpClient {
12415
13484
  };
12416
13485
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
12417
13486
  this.extraEnv = options.env ?? {};
13487
+ if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
13488
+ throw new Error("resources.directory 必须是本机绝对路径");
13489
+ }
13490
+ this.configurationScope = options.resources?.configurationScope ?? "overlay";
13491
+ if (!["overlay", "session"].includes(this.configurationScope))
13492
+ throw new Error("Invalid resources.configurationScope");
13493
+ this.resourcesDir = options.resources?.directory ?? null;
13494
+ this.attachSkillsMcp = options.resources?.attachSkillsMcp !== false;
12418
13495
  this.callbacks = options.callbacks ?? {};
12419
13496
  const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
12420
13497
  this.adapter = getAcpRuntimeAdapter(runtimeId);
@@ -12441,6 +13518,14 @@ class AcpClient {
12441
13518
  return this.initResponse;
12442
13519
  }
12443
13520
  async connect() {
13521
+ if (this.inflightPrompts.size > 0)
13522
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
13523
+ if (this.isConnected && this.initResponse)
13524
+ return ok({ status: this.status, init: this.initResponse });
13525
+ if (this.currentStatus === "connecting")
13526
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在连接" });
13527
+ this.connectionGen += 1;
13528
+ const connectGen = this.connectionGen;
12444
13529
  try {
12445
13530
  this.setStatus("connecting");
12446
13531
  const blocker = this.adapter.resolveSpawnBlocker?.();
@@ -12466,16 +13551,105 @@ class AcpClient {
12466
13551
  ...baseEnv,
12467
13552
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
12468
13553
  };
13554
+ let resourceEnv = {};
13555
+ let profileTag = null;
13556
+ if (this.resourcesDir && this.configurationScope === "session") {
13557
+ const profile = await createSessionConfigHome(this.runtimeInfo.id, this.resourcesDir);
13558
+ if (connectGen !== this.connectionGen || this.status !== "connecting") {
13559
+ await profile.dispose();
13560
+ return err({ code: "CANCELLED", message: "连接已取消" });
13561
+ }
13562
+ this.sessionConfig = profile;
13563
+ resourceEnv = this.sessionConfig.env;
13564
+ const load = readAppResourcesDir(this.resourcesDir);
13565
+ this.resourcePrep = { profileTag: null, report: {
13566
+ rulesApplied: false,
13567
+ rulesPrepared: false,
13568
+ skillsApplied: false,
13569
+ rulesChars: load.rules?.chars ?? 0,
13570
+ profileDigest: digestAppResources(load),
13571
+ skillsFound: load.skills.map((s) => s.name),
13572
+ configurationScope: "session",
13573
+ configurationDirectory: this.sessionConfig.directory,
13574
+ configurationRulesFile: this.sessionConfig.rulesFile,
13575
+ reason: this.sessionConfig.nativeRules ? "isolated-config-not-runtime-verified" : "isolated-config-rule-discovery-not-verified"
13576
+ } };
13577
+ } else if (this.resourcesDir && this.adapter.prepareAppResources) {
13578
+ try {
13579
+ const prep = await this.adapter.prepareAppResources({
13580
+ directory: this.resourcesDir,
13581
+ command: effectiveRuntime.command,
13582
+ workspaceRoot: this.workspaceRoot,
13583
+ env: { ...process.env, ...spawnEnv.env }
13584
+ });
13585
+ if (prep.env)
13586
+ resourceEnv = prep.env;
13587
+ prep.report.rulesPrepared = prep.report.rulesPrepared ?? prep.report.rulesApplied;
13588
+ prep.report.rulesApplied = false;
13589
+ prep.report.skillsApplied = false;
13590
+ const digest = prep.report.profileDigest;
13591
+ profileTag = digest ? `${this.runtimeInfo.id}:resources@${digest.slice(0, 16)}` : null;
13592
+ this.resourcePrep = { profileTag, report: prep.report };
13593
+ } catch (error) {
13594
+ this.resourcePrep = {
13595
+ profileTag: null,
13596
+ report: {
13597
+ rulesApplied: false,
13598
+ rulesChars: 0,
13599
+ profileDigest: null,
13600
+ skillsFound: [],
13601
+ reason: "prepare-failed"
13602
+ }
13603
+ };
13604
+ this.callbacks.onLog?.("warn", "应用资源准备失败,已回退兼容", {
13605
+ error: error instanceof Error ? error.message : String(error)
13606
+ });
13607
+ }
13608
+ } else {
13609
+ const load = this.resourcesDir ? readAppResourcesDir(this.resourcesDir) : null;
13610
+ this.resourcePrep = load ? { profileTag: null, report: {
13611
+ rulesApplied: false,
13612
+ rulesPrepared: false,
13613
+ skillsApplied: false,
13614
+ rulesChars: load.rules?.chars ?? 0,
13615
+ profileDigest: digestAppResources(load),
13616
+ skillsFound: load.skills.map((s) => s.name),
13617
+ reason: "runtime-not-supported"
13618
+ } } : null;
13619
+ }
13620
+ const finalEnv = { ...spawnEnv.env, ...resourceEnv };
12469
13621
  await this.adapter.beforeSpawn?.();
12470
- const processHandle = spawnAcpProcess({
13622
+ if (connectGen !== this.connectionGen || this.status !== "connecting")
13623
+ return err({ code: "CANCELLED", message: "连接已取消" });
13624
+ let reuseDegraded = false;
13625
+ let reusedHandle = null;
13626
+ if (profileTag) {
13627
+ const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
13628
+ expectedTag: profileTag,
13629
+ scopeKey: this.processScopeKey,
13630
+ isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
13631
+ });
13632
+ if (reuse.status === "hit") {
13633
+ reusedHandle = reuse.handle;
13634
+ } else if (reuse.status === "busy") {
13635
+ reusedHandle = reuse.handle;
13636
+ reuseDegraded = true;
13637
+ this.callbacks.onLog?.("warn", "应用资源摘要已变更但旧进程正忙,沿用旧进程并降级,新摘要下次冷启动生效");
13638
+ }
13639
+ }
13640
+ const processHandle = reusedHandle ?? spawnAcpProcess({
12471
13641
  runtime: effectiveRuntime,
12472
13642
  cwd: this.workspaceRoot,
12473
- env: spawnEnv.env,
13643
+ scopeKey: this.processScopeKey,
13644
+ env: finalEnv,
12474
13645
  envRemove: spawnEnv.envRemove,
13646
+ profileTag,
12475
13647
  onStderrLine: (line) => {
12476
13648
  this.callbacks.onStderrLine?.(line);
12477
13649
  },
12478
13650
  onExit: (code, signal) => {
13651
+ if (this.connectionGen !== connectGen)
13652
+ return;
12479
13653
  this.callbacks.onLog?.("warn", `Agent 进程已退出 (code: ${code}, signal: ${signal})`);
12480
13654
  if (this.status === "connected" || this.status === "connecting") {
12481
13655
  this.disconnect("Agent 进程异常终止");
@@ -12526,9 +13700,28 @@ class AcpClient {
12526
13700
  }
12527
13701
  });
12528
13702
  this.initResponse = initResp;
13703
+ if (this.resourcePrep) {
13704
+ const agentInfo = initResp?.agentInfo;
13705
+ const bridgeVersion = typeof agentInfo?.version === "string" ? agentInfo.version : undefined;
13706
+ const supported = isSupportedBridgeVersion(this.runtimeInfo.id, bridgeVersion).eligible && (this.adapter.supportedBridgeVersions?.includes(bridgeVersion?.replace(/^v/, "") ?? "") ?? false);
13707
+ this.resourcePrep.report.bridgeVersion = bridgeVersion;
13708
+ this.resourcePrep.report.bridgeSupported = supported;
13709
+ if (this.processHandle)
13710
+ this.processHandle.bridgeVersion = bridgeVersion;
13711
+ if (supported && this.resourcePrep.report.reason === "native-session-version-not-verified")
13712
+ delete this.resourcePrep.report.reason;
13713
+ if (!supported) {
13714
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "unsupported-bridge-version";
13715
+ }
13716
+ if (reuseDegraded) {
13717
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "busy-deferred-stale-rules";
13718
+ }
13719
+ }
12529
13720
  this.setStatus("connected");
12530
13721
  return ok({ status: "connected", init: initResp });
12531
13722
  } catch (e) {
13723
+ if (connectGen !== this.connectionGen)
13724
+ return err({ code: "CANCELLED", message: "连接已被新请求取代" });
12532
13725
  const message = e instanceof Error ? e.message : String(e);
12533
13726
  this.setStatus("error", message);
12534
13727
  await this.disconnect(message);
@@ -12567,6 +13760,29 @@ class AcpClient {
12567
13760
  const resumeSupported = Boolean(init && parseResumeSessionSupported(init.agentCapabilities));
12568
13761
  const loadSupported = Boolean(init && parseLoadSessionSupported(init.agentCapabilities));
12569
13762
  try {
13763
+ let skillsExposed = "none";
13764
+ let mcpServers = options?.mcpServers ?? [];
13765
+ if (this.resourcesDir && this.attachSkillsMcp) {
13766
+ try {
13767
+ const descriptor = buildAppSkillsMcpServer(this.resourcesDir);
13768
+ const callerNames = new Set;
13769
+ for (const entry of mcpServers) {
13770
+ if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
13771
+ callerNames.add(entry.name);
13772
+ }
13773
+ }
13774
+ if (callerNames.has(descriptor.name)) {
13775
+ this.callbacks.onLog?.("warn", "调用方已有同名技能 MCP 服务,保留调用方版本", { name: descriptor.name });
13776
+ } else {
13777
+ mcpServers = [...mcpServers, descriptor];
13778
+ skillsExposed = "mcp-exposed";
13779
+ }
13780
+ } catch (error) {
13781
+ this.callbacks.onLog?.("warn", "技能 MCP 描述符构建失败,本次会话无技能 MCP", {
13782
+ error: error instanceof Error ? error.message : String(error)
13783
+ });
13784
+ }
13785
+ }
12570
13786
  const openResult = await restoreOrCreateAcpSession({
12571
13787
  request: async (method, params) => {
12572
13788
  return sdkRequest(agent, method, params);
@@ -12575,12 +13791,27 @@ class AcpClient {
12575
13791
  resumeSessionId: options?.resumeSessionId ?? null,
12576
13792
  resumeSupported,
12577
13793
  loadSupported,
12578
- mcpServers: options?.mcpServers ?? [],
13794
+ mcpServers,
13795
+ sessionMeta: (!this.sessionConfig || this.runtimeInfo.id === "agy") && this.resourcesDir && this.resourcePrep?.report.bridgeSupported ? this.adapter.appResourceSessionMeta?.(this.resourcesDir) : undefined,
12579
13796
  log: (level, msg, meta) => {
12580
13797
  this.callbacks.onLog?.(level, msg, meta);
12581
13798
  }
12582
13799
  });
12583
- const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions);
13800
+ if (!openResult.mcpServersAccepted)
13801
+ skillsExposed = "none";
13802
+ this.sessionLedger.set(openResult.sessionId, {
13803
+ restoreMethod: openResult.restoreMethod,
13804
+ gen: this.connectionGen,
13805
+ skillsExposed,
13806
+ nativeRules: openResult.nativeSessionAccepted
13807
+ });
13808
+ const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions, this.resourcePrep?.report ? {
13809
+ ...this.resourcePrep.report,
13810
+ skillsFound: [...this.resourcePrep.report.skillsFound],
13811
+ skillsExposed,
13812
+ rulesApplied: openResult.nativeSessionAccepted || !this.adapter.appResourceSessionMeta && openResult.restoreMethod === "new" && this.resourcePrep.report.bridgeSupported === true && this.resourcePrep.report.rulesPrepared === true,
13813
+ ...openResult.restoreMethod !== "new" && !openResult.nativeSessionAccepted ? { reason: "session-restored-not-verified" } : {}
13814
+ } : null);
12584
13815
  return ok(handle);
12585
13816
  } catch (e) {
12586
13817
  const message = e instanceof Error ? e.message : String(e);
@@ -12591,6 +13822,7 @@ class AcpClient {
12591
13822
  if (!this.sdkConnection?.agent) {
12592
13823
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
12593
13824
  }
13825
+ this.inflightPrompts.add(sessionId);
12594
13826
  try {
12595
13827
  const prompt = [{ type: "text", text: promptText }];
12596
13828
  for (const image of options?.images ?? []) {
@@ -12598,16 +13830,52 @@ class AcpClient {
12598
13830
  continue;
12599
13831
  prompt.push({ type: "image", mimeType: image.mimeType, data: image.data });
12600
13832
  }
13833
+ const compat = this.buildCompatPrepend(sessionId);
13834
+ const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
12601
13835
  const response = await sdkRequest(this.sdkConnection.agent, methods.agent.session.prompt, {
12602
13836
  sessionId,
12603
- prompt
13837
+ prompt: blocks
12604
13838
  }, options?.timeoutMs);
12605
13839
  return ok(response);
12606
13840
  } catch (e) {
12607
13841
  const message = e instanceof Error ? e.message : String(e);
12608
13842
  return err({ code: "ACP_PROTOCOL_ERROR", message });
13843
+ } finally {
13844
+ this.inflightPrompts.delete(sessionId);
12609
13845
  }
12610
13846
  }
13847
+ buildCompatPrepend(sessionId) {
13848
+ if (!this.resourcesDir)
13849
+ return null;
13850
+ if (this.sessionConfig?.nativeRules)
13851
+ return null;
13852
+ const entry = this.sessionLedger.get(sessionId);
13853
+ if (!entry)
13854
+ return null;
13855
+ const connReport = this.resourcePrep?.report;
13856
+ const nativelyDelivered = entry.nativeRules || !this.adapter.appResourceSessionMeta && entry.restoreMethod === "new" && entry.gen === this.connectionGen && connReport?.rulesPrepared === true && connReport?.bridgeSupported === true;
13857
+ if (nativelyDelivered)
13858
+ return null;
13859
+ const load = readAppResourcesDir(this.resourcesDir);
13860
+ const rulesText = readAppRulesText(this.resourcesDir);
13861
+ const digest = digestAppResources(load);
13862
+ const key = compatDeliveryKey(sessionId, this.connectionGen, digest);
13863
+ if (this.compatSentKeys.has(key))
13864
+ return null;
13865
+ const text = buildCompatGuideText({
13866
+ rulesText,
13867
+ skills: load.skills.map((s) => ({ name: s.name, description: s.description })),
13868
+ skillsViaMcp: entry.skillsExposed === "mcp-exposed",
13869
+ digest,
13870
+ sessionId,
13871
+ generation: this.connectionGen
13872
+ });
13873
+ if (!text)
13874
+ return null;
13875
+ this.compatSnapshots.set(key, { text, digest });
13876
+ this.compatSentKeys.add(key);
13877
+ return text;
13878
+ }
12611
13879
  async setSessionConfigOption(sessionId, configId, value) {
12612
13880
  if (!this.sdkConnection?.agent) {
12613
13881
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
@@ -12626,6 +13894,10 @@ class AcpClient {
12626
13894
  }
12627
13895
  async disconnect(reason) {
12628
13896
  this.setStatus("disconnected", reason);
13897
+ this.resourcePrep = null;
13898
+ this.sessionLedger.clear();
13899
+ this.compatSentKeys.clear();
13900
+ this.compatSnapshots.clear();
12629
13901
  try {
12630
13902
  this.streamHandle?.dispose();
12631
13903
  this.sdkConnection?.close();
@@ -12641,6 +13913,15 @@ class AcpClient {
12641
13913
  } catch {}
12642
13914
  this.processHandle = null;
12643
13915
  }
13916
+ const config = this.sessionConfig;
13917
+ this.sessionConfig = null;
13918
+ if (config) {
13919
+ try {
13920
+ await config.dispose();
13921
+ } catch {
13922
+ this.callbacks.onLog?.("warn", "Session configuration cleanup failed; directory retained", { directory: config.directory });
13923
+ }
13924
+ }
12644
13925
  }
12645
13926
  setStatus(status, detail) {
12646
13927
  this.status = status;