@yitom/acp-client 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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.7";
39
+ var ACP_CLIENT_VERSION = "0.1.9";
40
40
  // src/contracts/index.ts
41
41
  function ok(value) {
42
42
  return { ok: true, value };
@@ -175,242 +175,8 @@ var BUILTIN_ACP_RUNTIMES = [
175
175
  function findBuiltinAcpRuntime(id) {
176
176
  return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
177
177
  }
178
- // src/session/available-commands.ts
179
- function normalizeCommand(raw) {
180
- if (!raw || typeof raw !== "object")
181
- return null;
182
- const r = raw;
183
- if (typeof r.name !== "string" || !r.name.trim())
184
- return null;
185
- const out = {
186
- name: r.name.trim(),
187
- description: typeof r.description === "string" ? r.description : ""
188
- };
189
- const input = r.input;
190
- if (input && typeof input === "object" && typeof input.hint === "string") {
191
- out.input = { hint: input.hint };
192
- }
193
- if (r._meta && typeof r._meta === "object")
194
- out._meta = r._meta;
195
- return out;
196
- }
197
- function extractAvailableCommands(params) {
198
- if (!params || typeof params !== "object")
199
- return null;
200
- const p = params;
201
- if (typeof p.sessionId !== "string" || !p.update)
202
- return null;
203
- if (p.update.sessionUpdate !== "available_commands_update")
204
- return null;
205
- const list = Array.isArray(p.update.availableCommands) ? p.update.availableCommands : [];
206
- const commands = list.map(normalizeCommand).filter((c) => c !== null);
207
- return { sessionId: p.sessionId, commands };
208
- }
209
- class AvailableCommandsCache {
210
- bySession = new Map;
211
- waiters = new Map;
212
- observe(params) {
213
- const hit = extractAvailableCommands(params);
214
- if (!hit)
215
- return false;
216
- this.bySession.set(hit.sessionId, hit.commands);
217
- const ws = this.waiters.get(hit.sessionId);
218
- if (ws) {
219
- this.waiters.delete(hit.sessionId);
220
- for (const w of ws)
221
- w(hit.commands);
222
- }
223
- return true;
224
- }
225
- get(sessionId) {
226
- return this.bySession.get(sessionId);
227
- }
228
- wait(sessionId, timeoutMs = 150) {
229
- const cur = this.bySession.get(sessionId);
230
- if (cur || timeoutMs <= 0)
231
- return Promise.resolve(cur);
232
- return new Promise((resolve) => {
233
- const done = (c) => {
234
- clearTimeout(timer);
235
- const list = this.waiters.get(sessionId);
236
- if (list) {
237
- const i = list.indexOf(fn);
238
- if (i >= 0)
239
- list.splice(i, 1);
240
- if (list.length === 0)
241
- this.waiters.delete(sessionId);
242
- }
243
- resolve(c);
244
- };
245
- const fn = (c) => done(c);
246
- const timer = setTimeout(() => done(undefined), timeoutMs);
247
- const list = this.waiters.get(sessionId) ?? [];
248
- list.push(fn);
249
- this.waiters.set(sessionId, list);
250
- });
251
- }
252
- delete(sessionId) {
253
- this.bySession.delete(sessionId);
254
- }
255
- clear() {
256
- this.bySession.clear();
257
- }
258
- }
259
-
260
- // src/session/quota.ts
261
- function parseRateLimitsFromStatusText(text, runtimeId = "unknown") {
262
- if (!text || typeof text !== "string")
263
- return null;
264
- const lines = text.split(/\r?\n/);
265
- let account;
266
- const windows = [];
267
- let credits;
268
- let status = "ok";
269
- let message;
270
- if (/account (?:disabled|banned|suspended)|suspended|banned/i.test(text)) {
271
- status = "banned";
272
- message = "账号已封禁或暂停使用 (Account banned / suspended)";
273
- } else if (/RESOURCE_EXHAUSTED|quota reached|rate limit exceeded|429/i.test(text)) {
274
- status = "exhausted";
275
- message = "额度已用尽 (Quota / Rate limit reached)";
276
- } else if (/unauthorized|authentication failed|invalid api key/i.test(text)) {
277
- status = "unauthorized";
278
- message = "认证失效 (Unauthorized / Invalid credentials)";
279
- }
280
- for (const rawLine of lines) {
281
- const line = rawLine.replace(/\*\*/g, "").trim();
282
- if (!line)
283
- continue;
284
- const accMatch = line.match(/^Account\s*[::]\s*([^()]+?)(?:\s*\(([^)]+)\))?$/i);
285
- if (accMatch) {
286
- account = {
287
- plan: accMatch[1].trim(),
288
- email: accMatch[2]?.trim()
289
- };
290
- continue;
291
- }
292
- const credMatch = line.match(/(?:\b|^)(?:[\w\s-]*?credits?)\s*[::]\s*(unlimited|[\d.]+)/i);
293
- if (credMatch) {
294
- const val = credMatch[1].trim();
295
- credits = val.toLowerCase() === "unlimited" ? { unlimited: true, balance: "unlimited" } : { balance: Number(val) || val, unlimited: false };
296
- continue;
297
- }
298
- const winMatch = line.match(/(?:(?:[\w-]+\s+)?([\w\s-]+?(?:limit|spend limit|window)))\s*[::]\s*(\d+(?:\.\d+)?)%\s*(?:left|remaining)(?:\s*\((?:resets\s*(?:at\s*)?([^)]+)|([^)]+))\))?/i);
299
- if (winMatch) {
300
- const label = winMatch[1].trim();
301
- const pct = parseFloat(winMatch[2]);
302
- const resetsAt = (winMatch[3] || winMatch[4] || "").trim() || undefined;
303
- let windowDurationMins;
304
- const lower = label.toLowerCase();
305
- if (/5h|5-hour/i.test(lower))
306
- windowDurationMins = 300;
307
- else if (/week/i.test(lower))
308
- windowDurationMins = 10080;
309
- else if (/month/i.test(lower))
310
- windowDurationMins = 43200;
311
- else if (/day|24h/i.test(lower))
312
- windowDurationMins = 1440;
313
- else if (/(\d+)\s*h/i.test(lower)) {
314
- const m = lower.match(/(\d+)\s*h/);
315
- if (m)
316
- windowDurationMins = parseInt(m[1], 10) * 60;
317
- }
318
- windows.push({
319
- label,
320
- percentLeft: pct,
321
- usedPercent: Math.max(0, 100 - pct),
322
- resetsAt,
323
- windowDurationMins
324
- });
325
- continue;
326
- }
327
- const fastMatch = line.match(/(?:fast requests?|requests?)\s*[::]\s*(\d+)\s*\/\s*(\d+)/i);
328
- if (fastMatch) {
329
- const used = parseInt(fastMatch[1], 10);
330
- const total = parseInt(fastMatch[2], 10);
331
- const left = Math.max(0, total - used);
332
- const pct = total > 0 ? Math.round(left / total * 100) : 0;
333
- windows.push({
334
- label: "Fast requests",
335
- percentLeft: pct,
336
- usedPercent: total > 0 ? Math.round(used / total * 100) : 0,
337
- used,
338
- total
339
- });
340
- continue;
341
- }
342
- }
343
- if (!windows.length && !credits && !account && status === "ok") {
344
- return null;
345
- }
346
- const primary = windows.find((w) => /5h|5-hour|hour|primary|fast/i.test(w.label)) || windows[0];
347
- const secondary = windows.find((w) => w !== primary && /week|month|secondary/i.test(w.label)) || windows.find((w) => w !== primary);
348
- const extraWindows = windows.filter((w) => w !== primary && w !== secondary);
349
- if (primary && primary.percentLeft <= 10 && status === "ok") {
350
- status = "warning";
351
- }
352
- return {
353
- runtimeId,
354
- account,
355
- primaryWindow: primary,
356
- secondaryWindow: secondary,
357
- extraWindows: extraWindows.length ? extraWindows : undefined,
358
- credits,
359
- status,
360
- message,
361
- rawText: text,
362
- updatedAt: Date.now()
363
- };
364
- }
365
-
366
- class QuotaCache {
367
- bySession = new Map;
368
- byRuntime = new Map;
369
- observe(params, defaultRuntimeId = "unknown") {
370
- if (!params || typeof params !== "object")
371
- return null;
372
- const p = params;
373
- const sessionId = typeof p.sessionId === "string" ? p.sessionId : undefined;
374
- let textToParse = "";
375
- if (p.update?.content && p.update.content.type === "text" && typeof p.update.content.text === "string") {
376
- textToParse = p.update.content.text;
377
- } else if (p.update?.message?.content && Array.isArray(p.update.message.content)) {
378
- textToParse = p.update.message.content.filter((c) => c && c.type === "text" && typeof c.text === "string").map((c) => c.text).join(`
379
- `);
380
- }
381
- if (!textToParse)
382
- return null;
383
- if (!/(?:limit|credits?|Account:|5h|resets|banned|suspended|quota)/i.test(textToParse)) {
384
- return null;
385
- }
386
- const quota = parseRateLimitsFromStatusText(textToParse, defaultRuntimeId);
387
- if (quota) {
388
- if (sessionId)
389
- this.bySession.set(sessionId, quota);
390
- this.byRuntime.set(defaultRuntimeId, quota);
391
- return quota;
392
- }
393
- return null;
394
- }
395
- set(quota, sessionId) {
396
- if (sessionId)
397
- this.bySession.set(sessionId, quota);
398
- this.byRuntime.set(quota.runtimeId, quota);
399
- }
400
- get(sessionId, runtimeId) {
401
- if (sessionId && this.bySession.has(sessionId)) {
402
- return this.bySession.get(sessionId);
403
- }
404
- if (runtimeId && this.byRuntime.has(runtimeId)) {
405
- return this.byRuntime.get(runtimeId);
406
- }
407
- return;
408
- }
409
- clear() {
410
- this.bySession.clear();
411
- this.byRuntime.clear();
412
- }
413
- }
178
+ // src/client/sdk-client.ts
179
+ var import_node_stream = require("node:stream");
414
180
 
415
181
  // node_modules/@agentclientprotocol/sdk/dist/schema/index.js
416
182
  var AGENT_METHODS = {
@@ -10297,35 +10063,583 @@ var legacyClientNotificationMethods = new Set([
10297
10063
  CLIENT_METHODS.elicitation_complete
10298
10064
  ]);
10299
10065
 
10300
- // src/runtimes/codex/quota.ts
10301
- var import_node_fs2 = require("node:fs");
10302
- var import_node_path2 = require("node:path");
10303
- var import_node_child_process = require("node:child_process");
10304
- var import_node_readline = __toESM(require("node:readline"), 1);
10305
-
10306
- // 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");
10310
- function emptyAcpAuthPreflight() {
10311
- return {
10312
- codexHome: "",
10313
- hasCodexHome: false,
10314
- hasAuthFile: false,
10315
- hasApiKeyEnv: false,
10316
- looksLoggedIn: false
10317
- };
10066
+ // src/client/sdk-client.ts
10067
+ var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
10068
+ function createSdkStreamHandle(child) {
10069
+ const stdoutBridge = new import_node_stream.PassThrough;
10070
+ const stdinBridge = new import_node_stream.PassThrough;
10071
+ child.stdout.pipe(stdoutBridge);
10072
+ stdinBridge.pipe(child.stdin, { end: false });
10073
+ const output = import_node_stream.Writable.toWeb(stdinBridge);
10074
+ const input = import_node_stream.Readable.toWeb(stdoutBridge);
10075
+ const stream = ndJsonStream2(output, input);
10076
+ let disposed = false;
10077
+ return {
10078
+ stream,
10079
+ dispose: () => {
10080
+ if (disposed)
10081
+ return;
10082
+ disposed = true;
10083
+ try {
10084
+ child.stdout.unpipe(stdoutBridge);
10085
+ } catch {}
10086
+ try {
10087
+ stdinBridge.unpipe(child.stdin);
10088
+ } catch {}
10089
+ try {
10090
+ stdoutBridge.destroy();
10091
+ } catch {}
10092
+ try {
10093
+ stdinBridge.destroy();
10094
+ } catch {}
10095
+ }
10096
+ };
10097
+ }
10098
+ function connectSdkClient(child, configure, runtimeId) {
10099
+ if (runtimeId && true) {
10100
+ console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
10101
+ }
10102
+ const app = client({ name: "inkdown" });
10103
+ configure(app);
10104
+ const streamHandle = createSdkStreamHandle(child);
10105
+ const connection = app.connect(streamHandle.stream);
10106
+ return { app, connection, streamHandle };
10107
+ }
10108
+ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
10109
+ const controller = new AbortController;
10110
+ let timer;
10111
+ try {
10112
+ const pending = agent.request(method, params, {
10113
+ cancellationSignal: controller.signal
10114
+ });
10115
+ const timeout = new Promise((_, reject) => {
10116
+ timer = setTimeout(() => {
10117
+ controller.abort();
10118
+ reject(new Error(`请求超时: ${method}`));
10119
+ }, timeoutMs);
10120
+ timer.unref?.();
10121
+ });
10122
+ return await Promise.race([pending, timeout]);
10123
+ } finally {
10124
+ if (timer !== undefined)
10125
+ clearTimeout(timer);
10126
+ }
10127
+ }
10128
+ async function closeAcpSessions(agent, sessionIds, timeoutMs = 2000) {
10129
+ const failed = [];
10130
+ await Promise.all([...new Set(sessionIds)].map(async (sessionId) => {
10131
+ try {
10132
+ await sdkRequest(agent, "session/close", { sessionId }, timeoutMs);
10133
+ } catch {
10134
+ failed.push(sessionId);
10135
+ }
10136
+ }));
10137
+ return failed;
10138
+ }
10139
+
10140
+ // src/resources/session-config.ts
10141
+ var import_node_fs2 = require("node:fs");
10142
+ var import_promises = require("node:fs/promises");
10143
+ var import_node_os = require("node:os");
10144
+ var import_node_path2 = require("node:path");
10145
+
10146
+ // src/resources/app-resources.ts
10147
+ var import_node_crypto = require("node:crypto");
10148
+ var import_node_fs = require("node:fs");
10149
+ var import_node_path = require("node:path");
10150
+ var APP_RULES_FILE = "AGENTS.md";
10151
+ var APP_SKILLS_DIR = "skills";
10152
+ var APP_SKILL_FILE = "SKILL.md";
10153
+ function parseSkillFrontmatter(text) {
10154
+ const lines = text.split(`
10155
+ `);
10156
+ if (lines[0]?.trim() !== "---")
10157
+ return {};
10158
+ const out = {};
10159
+ for (let i = 1;i < lines.length; i += 1) {
10160
+ const line = lines[i] ?? "";
10161
+ if (line.trim() === "---")
10162
+ break;
10163
+ const cut = line.indexOf(":");
10164
+ if (cut <= 0)
10165
+ continue;
10166
+ const key = line.slice(0, cut).trim().toLowerCase();
10167
+ if (key !== "name" && key !== "description")
10168
+ continue;
10169
+ const value = line.slice(cut + 1).trim().replace(/^['"]|['"]$/g, "");
10170
+ if (value)
10171
+ out[key] = value;
10172
+ }
10173
+ return out;
10174
+ }
10175
+ function sha256Hex(text) {
10176
+ return import_node_crypto.createHash("sha256").update(text, "utf8").digest("hex");
10177
+ }
10178
+ function readTextFile(path) {
10179
+ try {
10180
+ if (!import_node_fs.statSync(path).isFile())
10181
+ return null;
10182
+ const text = import_node_fs.readFileSync(path, "utf8");
10183
+ return text.trim() ? text : null;
10184
+ } catch {
10185
+ return null;
10186
+ }
10187
+ }
10188
+ function readAppResourcesDir(directory) {
10189
+ const warnings = [];
10190
+ if (!import_node_path.isAbsolute(directory))
10191
+ return { directoryReadable: false, rules: null, skills: [], warnings: ["资源目录必须是本机绝对路径"] };
10192
+ let directoryReadable = false;
10193
+ try {
10194
+ directoryReadable = import_node_fs.statSync(directory).isDirectory();
10195
+ } catch {
10196
+ directoryReadable = false;
10197
+ }
10198
+ if (!directoryReadable) {
10199
+ return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
10200
+ }
10201
+ let rules = null;
10202
+ const rulesText = readTextFile(import_node_path.join(directory, APP_RULES_FILE));
10203
+ if (rulesText === null) {
10204
+ warnings.push(`缺常驻规则: ${APP_RULES_FILE}`);
10205
+ } else {
10206
+ rules = { chars: rulesText.length, digest: sha256Hex(`app-rules-v1
10207
+ ${rulesText}`) };
10208
+ }
10209
+ const skills = [];
10210
+ const skillsRoot = import_node_path.join(directory, APP_SKILLS_DIR);
10211
+ let skillNames = [];
10212
+ try {
10213
+ if (import_node_fs.statSync(skillsRoot).isDirectory()) {
10214
+ skillNames = import_node_fs.readdirSync(skillsRoot).filter((name) => {
10215
+ try {
10216
+ return import_node_fs.statSync(import_node_path.join(skillsRoot, name)).isDirectory();
10217
+ } catch {
10218
+ return false;
10219
+ }
10220
+ });
10221
+ }
10222
+ } catch {
10223
+ skillNames = [];
10224
+ }
10225
+ for (const name of skillNames.sort()) {
10226
+ const rel = `${APP_SKILLS_DIR}/${name}/${APP_SKILL_FILE}`;
10227
+ const text = readTextFile(import_node_path.join(directory, rel));
10228
+ if (text === null) {
10229
+ warnings.push(`技能缺正文已跳过: ${rel}`);
10230
+ continue;
10231
+ }
10232
+ const front = parseSkillFrontmatter(text);
10233
+ const skillName = front.name || name;
10234
+ if (skills.some((s) => s.name === skillName)) {
10235
+ warnings.push(`技能重名已跳过(保留首个): ${skillName}`);
10236
+ continue;
10237
+ }
10238
+ const description = front.description || "";
10239
+ skills.push({
10240
+ name: skillName,
10241
+ description,
10242
+ path: rel,
10243
+ chars: text.length,
10244
+ digest: sha256Hex(`app-skill-v1
10245
+ ${skillName}
10246
+ ${description}
10247
+ ${text}`)
10248
+ });
10249
+ }
10250
+ return { directoryReadable: true, rules, skills, warnings };
10251
+ }
10252
+ function digestAppResources(load) {
10253
+ if (!load.rules)
10254
+ return null;
10255
+ const skillPart = load.skills.map((s) => `${s.name}:${s.digest}`).join(`
10256
+ `);
10257
+ return sha256Hex(`app-resources-v1
10258
+ ${load.rules.digest}
10259
+ ${skillPart}`);
10260
+ }
10261
+ function readAppRulesText(directory) {
10262
+ return readTextFile(import_node_path.join(directory, APP_RULES_FILE));
10263
+ }
10264
+ function isAbsolutePathLike(path) {
10265
+ return import_node_path.isAbsolute(path);
10266
+ }
10267
+
10268
+ // src/resources/session-config.ts
10269
+ async function createSessionConfigHome(runtime, resources) {
10270
+ if (!import_node_path2.isAbsolute(resources))
10271
+ throw new Error("Resources must be an absolute path");
10272
+ const id = runtime === "cursor" ? "cursor-cli" : runtime;
10273
+ const supported = ["agy", "codex-acp", "claude", "gemini", "copilot", "cursor-cli", "opencode", "opencode-v2"];
10274
+ if (!supported.includes(id))
10275
+ throw new Error("Session configuration home is not verified for runtime: " + runtime);
10276
+ const text = readAppRulesText(resources);
10277
+ if (!text)
10278
+ throw new Error("Session configuration requires nonempty AGENTS.md");
10279
+ const parent = import_node_path2.resolve(import_node_os.tmpdir());
10280
+ const directory = await import_promises.mkdtemp(import_node_path2.join(parent, "acp-session-config-"));
10281
+ const checkRoot = () => {
10282
+ 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-"))
10283
+ throw new Error("Unsafe configuration cleanup target");
10284
+ };
10285
+ const dispose = async () => {
10286
+ checkRoot();
10287
+ let failure;
10288
+ for (let i = 0;i < 30; i++) {
10289
+ try {
10290
+ await import_promises.rm(directory, { recursive: true, force: true });
10291
+ return;
10292
+ } catch (error) {
10293
+ failure = error;
10294
+ await new Promise((r) => setTimeout(r, 100));
10295
+ }
10296
+ }
10297
+ throw failure;
10298
+ };
10299
+ try {
10300
+ const config = import_node_path2.join(directory, "config");
10301
+ await import_promises.mkdir(config, { recursive: true, mode: 448 });
10302
+ let env;
10303
+ let rulesFile;
10304
+ let skillsRoot = import_node_path2.join(config, "skills");
10305
+ let nativeRules = true;
10306
+ if (id === "agy") {
10307
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
10308
+ env = { AGY_ACP_RESOURCES_DIR: config };
10309
+ nativeRules = false;
10310
+ } else if (id === "gemini") {
10311
+ const root = import_node_path2.join(directory, "home", ".gemini");
10312
+ await import_promises.mkdir(root, { recursive: true, mode: 448 });
10313
+ rulesFile = import_node_path2.join(root, "GEMINI.md");
10314
+ skillsRoot = import_node_path2.join(root, "skills");
10315
+ env = { GEMINI_CLI_HOME: import_node_path2.join(directory, "home") };
10316
+ } else if (id === "claude") {
10317
+ rulesFile = import_node_path2.join(config, "CLAUDE.md");
10318
+ env = { CLAUDE_CONFIG_DIR: config };
10319
+ } else if (id === "codex-acp") {
10320
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
10321
+ env = { CODEX_HOME: config };
10322
+ } else if (id === "copilot") {
10323
+ rulesFile = import_node_path2.join(config, "copilot-instructions.md");
10324
+ env = { COPILOT_HOME: config, COPILOT_CUSTOM_INSTRUCTIONS_DIRS: config, COPILOT_SKILLS_DIRS: skillsRoot };
10325
+ await import_promises.writeFile(import_node_path2.join(config, "AGENTS.md"), text, { mode: 384 });
10326
+ } else if (id === "cursor-cli") {
10327
+ rulesFile = import_node_path2.join(config, "AGENTS.md");
10328
+ env = { CURSOR_CONFIG_DIR: config };
10329
+ nativeRules = false;
10330
+ } else {
10331
+ const root = import_node_path2.join(directory, "xdg-config", "opencode");
10332
+ await import_promises.mkdir(root, { recursive: true, mode: 448 });
10333
+ rulesFile = import_node_path2.join(root, "AGENTS.md");
10334
+ skillsRoot = import_node_path2.join(root, "skills");
10335
+ 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") };
10336
+ if (id === "opencode")
10337
+ env.OPENCODE_CONFIG_DIR = root;
10338
+ const skills = id === "opencode" ? { paths: [skillsRoot] } : [skillsRoot];
10339
+ await import_promises.writeFile(import_node_path2.join(root, "opencode.json"), JSON.stringify({ instructions: [rulesFile], skills }), { mode: 384 });
10340
+ }
10341
+ await import_promises.writeFile(rulesFile, text, { mode: 384 });
10342
+ const input = import_node_path2.join(resources, "skills");
10343
+ try {
10344
+ const info = await import_promises.lstat(input);
10345
+ if (info.isSymbolicLink() || !info.isDirectory())
10346
+ throw new Error("Skill root must be a regular directory");
10347
+ const physical = await import_promises.realpath(input);
10348
+ const copy = async (from, to) => {
10349
+ await import_promises.mkdir(to, { recursive: true, mode: 448 });
10350
+ for (const entry of await import_promises.readdir(from, { withFileTypes: true })) {
10351
+ const src = import_node_path2.join(from, entry.name);
10352
+ const info = await import_promises.lstat(src);
10353
+ if (info.isSymbolicLink())
10354
+ throw new Error("Skill symlink is not allowed");
10355
+ const actual = await import_promises.realpath(src);
10356
+ const rel = import_node_path2.relative(physical, actual);
10357
+ if (rel.startsWith(".." + import_node_path2.sep) || rel === ".." || import_node_path2.isAbsolute(rel))
10358
+ throw new Error("Skill path escapes resources");
10359
+ if (info.isDirectory())
10360
+ await copy(src, import_node_path2.join(to, entry.name));
10361
+ else if (info.isFile() && entry.name.toLowerCase().endsWith(".md"))
10362
+ await import_promises.writeFile(import_node_path2.join(to, entry.name), await import_promises.readFile(src), { mode: 384 });
10363
+ }
10364
+ };
10365
+ await copy(input, skillsRoot);
10366
+ } catch (error) {
10367
+ if (error.code !== "ENOENT" || import_node_fs2.existsSync(input))
10368
+ throw error;
10369
+ }
10370
+ return { directory, env, rulesFile, nativeRules, dispose };
10371
+ } catch (error) {
10372
+ await dispose();
10373
+ throw error;
10374
+ }
10375
+ }
10376
+
10377
+ // src/session/available-commands.ts
10378
+ function normalizeCommand(raw) {
10379
+ if (!raw || typeof raw !== "object")
10380
+ return null;
10381
+ const r = raw;
10382
+ if (typeof r.name !== "string" || !r.name.trim())
10383
+ return null;
10384
+ const out = {
10385
+ name: r.name.trim(),
10386
+ description: typeof r.description === "string" ? r.description : ""
10387
+ };
10388
+ const input = r.input;
10389
+ if (input && typeof input === "object" && typeof input.hint === "string") {
10390
+ out.input = { hint: input.hint };
10391
+ }
10392
+ if (r._meta && typeof r._meta === "object")
10393
+ out._meta = r._meta;
10394
+ return out;
10395
+ }
10396
+ function extractAvailableCommands(params) {
10397
+ if (!params || typeof params !== "object")
10398
+ return null;
10399
+ const p = params;
10400
+ if (typeof p.sessionId !== "string" || !p.update)
10401
+ return null;
10402
+ if (p.update.sessionUpdate !== "available_commands_update")
10403
+ return null;
10404
+ const list = Array.isArray(p.update.availableCommands) ? p.update.availableCommands : [];
10405
+ const commands = list.map(normalizeCommand).filter((c) => c !== null);
10406
+ return { sessionId: p.sessionId, commands };
10407
+ }
10408
+ class AvailableCommandsCache {
10409
+ bySession = new Map;
10410
+ waiters = new Map;
10411
+ observe(params) {
10412
+ const hit = extractAvailableCommands(params);
10413
+ if (!hit)
10414
+ return false;
10415
+ this.bySession.set(hit.sessionId, hit.commands);
10416
+ const ws = this.waiters.get(hit.sessionId);
10417
+ if (ws) {
10418
+ this.waiters.delete(hit.sessionId);
10419
+ for (const w of ws)
10420
+ w(hit.commands);
10421
+ }
10422
+ return true;
10423
+ }
10424
+ get(sessionId) {
10425
+ return this.bySession.get(sessionId);
10426
+ }
10427
+ wait(sessionId, timeoutMs = 150) {
10428
+ const cur = this.bySession.get(sessionId);
10429
+ if (cur || timeoutMs <= 0)
10430
+ return Promise.resolve(cur);
10431
+ return new Promise((resolve) => {
10432
+ const done = (c) => {
10433
+ clearTimeout(timer);
10434
+ const list = this.waiters.get(sessionId);
10435
+ if (list) {
10436
+ const i = list.indexOf(fn);
10437
+ if (i >= 0)
10438
+ list.splice(i, 1);
10439
+ if (list.length === 0)
10440
+ this.waiters.delete(sessionId);
10441
+ }
10442
+ resolve(c);
10443
+ };
10444
+ const fn = (c) => done(c);
10445
+ const timer = setTimeout(() => done(undefined), timeoutMs);
10446
+ const list = this.waiters.get(sessionId) ?? [];
10447
+ list.push(fn);
10448
+ this.waiters.set(sessionId, list);
10449
+ });
10450
+ }
10451
+ delete(sessionId) {
10452
+ this.bySession.delete(sessionId);
10453
+ }
10454
+ clear() {
10455
+ this.bySession.clear();
10456
+ }
10457
+ }
10458
+
10459
+ // src/session/quota.ts
10460
+ function parseRateLimitsFromStatusText(text, runtimeId = "unknown") {
10461
+ if (!text || typeof text !== "string")
10462
+ return null;
10463
+ const lines = text.split(/\r?\n/);
10464
+ let account;
10465
+ const windows = [];
10466
+ let credits;
10467
+ let status = "ok";
10468
+ let message;
10469
+ if (/account (?:disabled|banned|suspended)|suspended|banned/i.test(text)) {
10470
+ status = "banned";
10471
+ message = "账号已封禁或暂停使用 (Account banned / suspended)";
10472
+ } else if (/RESOURCE_EXHAUSTED|quota reached|rate limit exceeded|429/i.test(text)) {
10473
+ status = "exhausted";
10474
+ message = "额度已用尽 (Quota / Rate limit reached)";
10475
+ } else if (/unauthorized|authentication failed|invalid api key/i.test(text)) {
10476
+ status = "unauthorized";
10477
+ message = "认证失效 (Unauthorized / Invalid credentials)";
10478
+ }
10479
+ for (const rawLine of lines) {
10480
+ const line = rawLine.replace(/\*\*/g, "").trim();
10481
+ if (!line)
10482
+ continue;
10483
+ const accMatch = line.match(/^Account\s*[::]\s*([^()]+?)(?:\s*\(([^)]+)\))?$/i);
10484
+ if (accMatch) {
10485
+ account = {
10486
+ plan: accMatch[1].trim(),
10487
+ email: accMatch[2]?.trim()
10488
+ };
10489
+ continue;
10490
+ }
10491
+ const credMatch = line.match(/(?:\b|^)(?:[\w\s-]*?credits?)\s*[::]\s*(unlimited|[\d.]+)/i);
10492
+ if (credMatch) {
10493
+ const val = credMatch[1].trim();
10494
+ credits = val.toLowerCase() === "unlimited" ? { unlimited: true, balance: "unlimited" } : { balance: Number(val) || val, unlimited: false };
10495
+ continue;
10496
+ }
10497
+ const winMatch = line.match(/(?:(?:[\w-]+\s+)?([\w\s-]+?(?:limit|spend limit|window)))\s*[::]\s*(\d+(?:\.\d+)?)%\s*(?:left|remaining)(?:\s*\((?:resets\s*(?:at\s*)?([^)]+)|([^)]+))\))?/i);
10498
+ if (winMatch) {
10499
+ const label = winMatch[1].trim();
10500
+ const pct = parseFloat(winMatch[2]);
10501
+ const resetsAt = (winMatch[3] || winMatch[4] || "").trim() || undefined;
10502
+ let windowDurationMins;
10503
+ const lower = label.toLowerCase();
10504
+ if (/5h|5-hour/i.test(lower))
10505
+ windowDurationMins = 300;
10506
+ else if (/week/i.test(lower))
10507
+ windowDurationMins = 10080;
10508
+ else if (/month/i.test(lower))
10509
+ windowDurationMins = 43200;
10510
+ else if (/day|24h/i.test(lower))
10511
+ windowDurationMins = 1440;
10512
+ else if (/(\d+)\s*h/i.test(lower)) {
10513
+ const m = lower.match(/(\d+)\s*h/);
10514
+ if (m)
10515
+ windowDurationMins = parseInt(m[1], 10) * 60;
10516
+ }
10517
+ windows.push({
10518
+ label,
10519
+ percentLeft: pct,
10520
+ usedPercent: Math.max(0, 100 - pct),
10521
+ resetsAt,
10522
+ windowDurationMins
10523
+ });
10524
+ continue;
10525
+ }
10526
+ const fastMatch = line.match(/(?:fast requests?|requests?)\s*[::]\s*(\d+)\s*\/\s*(\d+)/i);
10527
+ if (fastMatch) {
10528
+ const used = parseInt(fastMatch[1], 10);
10529
+ const total = parseInt(fastMatch[2], 10);
10530
+ const left = Math.max(0, total - used);
10531
+ const pct = total > 0 ? Math.round(left / total * 100) : 0;
10532
+ windows.push({
10533
+ label: "Fast requests",
10534
+ percentLeft: pct,
10535
+ usedPercent: total > 0 ? Math.round(used / total * 100) : 0,
10536
+ used,
10537
+ total
10538
+ });
10539
+ continue;
10540
+ }
10541
+ }
10542
+ if (!windows.length && !credits && !account && status === "ok") {
10543
+ return null;
10544
+ }
10545
+ const primary = windows.find((w) => /5h|5-hour|hour|primary|fast/i.test(w.label)) || windows[0];
10546
+ const secondary = windows.find((w) => w !== primary && /week|month|secondary/i.test(w.label)) || windows.find((w) => w !== primary);
10547
+ const extraWindows = windows.filter((w) => w !== primary && w !== secondary);
10548
+ if (primary && primary.percentLeft <= 10 && status === "ok") {
10549
+ status = "warning";
10550
+ }
10551
+ return {
10552
+ runtimeId,
10553
+ account,
10554
+ primaryWindow: primary,
10555
+ secondaryWindow: secondary,
10556
+ extraWindows: extraWindows.length ? extraWindows : undefined,
10557
+ credits,
10558
+ status,
10559
+ message,
10560
+ rawText: text,
10561
+ updatedAt: Date.now()
10562
+ };
10563
+ }
10564
+
10565
+ class QuotaCache {
10566
+ bySession = new Map;
10567
+ byRuntime = new Map;
10568
+ observe(params, defaultRuntimeId = "unknown") {
10569
+ if (!params || typeof params !== "object")
10570
+ return null;
10571
+ const p = params;
10572
+ const sessionId = typeof p.sessionId === "string" ? p.sessionId : undefined;
10573
+ let textToParse = "";
10574
+ if (p.update?.content && p.update.content.type === "text" && typeof p.update.content.text === "string") {
10575
+ textToParse = p.update.content.text;
10576
+ } else if (p.update?.message?.content && Array.isArray(p.update.message.content)) {
10577
+ textToParse = p.update.message.content.filter((c) => c && c.type === "text" && typeof c.text === "string").map((c) => c.text).join(`
10578
+ `);
10579
+ }
10580
+ if (!textToParse)
10581
+ return null;
10582
+ if (!/(?:limit|credits?|Account:|5h|resets|banned|suspended|quota)/i.test(textToParse)) {
10583
+ return null;
10584
+ }
10585
+ const quota = parseRateLimitsFromStatusText(textToParse, defaultRuntimeId);
10586
+ if (quota) {
10587
+ if (sessionId)
10588
+ this.bySession.set(sessionId, quota);
10589
+ this.byRuntime.set(defaultRuntimeId, quota);
10590
+ return quota;
10591
+ }
10592
+ return null;
10593
+ }
10594
+ set(quota, sessionId) {
10595
+ if (sessionId)
10596
+ this.bySession.set(sessionId, quota);
10597
+ this.byRuntime.set(quota.runtimeId, quota);
10598
+ }
10599
+ get(sessionId, runtimeId) {
10600
+ if (sessionId && this.bySession.has(sessionId)) {
10601
+ return this.bySession.get(sessionId);
10602
+ }
10603
+ if (runtimeId && this.byRuntime.has(runtimeId)) {
10604
+ return this.byRuntime.get(runtimeId);
10605
+ }
10606
+ return;
10607
+ }
10608
+ clear() {
10609
+ this.bySession.clear();
10610
+ this.byRuntime.clear();
10611
+ }
10612
+ }
10613
+
10614
+ // src/runtimes/codex/quota.ts
10615
+ var import_node_fs4 = require("node:fs");
10616
+ var import_node_path4 = require("node:path");
10617
+ var import_node_child_process = require("node:child_process");
10618
+ var import_node_readline = __toESM(require("node:readline"), 1);
10619
+
10620
+ // src/runtimes/codex/codex-auth-preflight.ts
10621
+ var import_node_fs3 = require("node:fs");
10622
+ var import_node_os2 = require("node:os");
10623
+ var import_node_path3 = require("node:path");
10624
+ function emptyAcpAuthPreflight() {
10625
+ return {
10626
+ codexHome: "",
10627
+ hasCodexHome: false,
10628
+ hasAuthFile: false,
10629
+ hasApiKeyEnv: false,
10630
+ looksLoggedIn: false
10631
+ };
10318
10632
  }
10319
10633
  function resolveCodexHome() {
10320
10634
  const fromEnv = process.env.CODEX_HOME?.trim();
10321
10635
  if (fromEnv)
10322
10636
  return fromEnv;
10323
- return import_node_path.join(import_node_os.homedir(), ".codex");
10637
+ return import_node_path3.join(import_node_os2.homedir(), ".codex");
10324
10638
  }
10325
10639
  function probeCodexAuth() {
10326
10640
  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"));
10641
+ const hasCodexHome = import_node_fs3.existsSync(codexHome);
10642
+ const hasAuthFile = import_node_fs3.existsSync(import_node_path3.join(codexHome, "auth.json"));
10329
10643
  const hasApiKeyEnv = Boolean(process.env.CODEX_API_KEY?.trim() || process.env.OPENAI_API_KEY?.trim());
10330
10644
  return {
10331
10645
  codexHome,
@@ -10375,7 +10689,7 @@ async function queryCodexAppServer(timeoutMs = 1e4) {
10375
10689
  };
10376
10690
  timer = setTimeout(() => cleanup(null), timeoutMs);
10377
10691
  try {
10378
- const cmd = process.platform === "win32" ? "codex" : import_node_fs2.existsSync("/mnt/c/Users") ? "codex.exe" : "codex";
10692
+ const cmd = process.platform === "win32" ? "codex" : import_node_fs4.existsSync("/mnt/c/Users") ? "codex.exe" : "codex";
10379
10693
  proc = import_node_child_process.spawn(cmd, ["app-server"], {
10380
10694
  stdio: ["pipe", "pipe", "pipe"],
10381
10695
  shell: process.platform === "win32",
@@ -10446,13 +10760,13 @@ function formatEpochTime(epochSeconds) {
10446
10760
  }
10447
10761
  async function probeCodexQuota(options) {
10448
10762
  const codexHome = resolveCodexHome();
10449
- const authPath = import_node_path2.join(codexHome, "auth.json");
10763
+ const authPath = import_node_path4.join(codexHome, "auth.json");
10450
10764
  let accountEmail;
10451
10765
  let accountPlan = "Codex Free / Local";
10452
10766
  let isLoggedIn = false;
10453
- if (import_node_fs2.existsSync(authPath)) {
10767
+ if (import_node_fs4.existsSync(authPath)) {
10454
10768
  try {
10455
- const authData = JSON.parse(import_node_fs2.readFileSync(authPath, "utf8"));
10769
+ const authData = JSON.parse(import_node_fs4.readFileSync(authPath, "utf8"));
10456
10770
  if (authData.OPENAI_API_KEY) {
10457
10771
  isLoggedIn = true;
10458
10772
  accountPlan = "OpenAI API Key";
@@ -10542,9 +10856,93 @@ async function probeCodexQuota(options) {
10542
10856
  };
10543
10857
  }
10544
10858
 
10545
- // src/runtimes/codex/index.ts
10546
- var import_promises2 = require("node:fs/promises");
10547
- var import_node_path5 = require("node:path");
10859
+ // src/runtimes/codex/index.ts
10860
+ var import_promises3 = require("node:fs/promises");
10861
+ var import_node_path7 = require("node:path");
10862
+ var import_node_os4 = require("node:os");
10863
+ var import_node_fs6 = require("node:fs");
10864
+ var import_node_crypto2 = require("node:crypto");
10865
+
10866
+ // src/resources/config-text.ts
10867
+ function mergeCodexConfigJson(input) {
10868
+ const block = (input.hostBlock ?? "").trim();
10869
+ if (!block)
10870
+ return { ok: false, reason: "empty-block" };
10871
+ const raw = (input.existingRaw ?? "").trim();
10872
+ if (!raw) {
10873
+ return { ok: true, json: JSON.stringify({ developer_instructions: block }), preservedUserInstructions: false };
10874
+ }
10875
+ let parsed;
10876
+ try {
10877
+ parsed = JSON.parse(raw);
10878
+ } catch {
10879
+ return { ok: false, reason: "invalid-json" };
10880
+ }
10881
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
10882
+ return { ok: false, reason: "invalid-json" };
10883
+ }
10884
+ const merged = { ...parsed };
10885
+ const existing = merged["developer_instructions"];
10886
+ if (existing === undefined) {
10887
+ merged["developer_instructions"] = block;
10888
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: false };
10889
+ }
10890
+ if (typeof existing !== "string") {
10891
+ return { ok: false, reason: "conflicting-value" };
10892
+ }
10893
+ const kept = existing.trim();
10894
+ merged["developer_instructions"] = kept ? `${block}
10895
+
10896
+ ${kept}` : block;
10897
+ return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: kept !== "" };
10898
+ }
10899
+ function mergeConfigTomlPreserving(input) {
10900
+ const block = (input.replacementBlock ?? "").trim() ? `${input.replacementBlock.trim()}
10901
+ ` : "";
10902
+ if (!input.existingText || !input.existingText.trim())
10903
+ return block;
10904
+ if (/"""|'''/.test(input.existingText) || /^\s*\[.*["'].*\]|^\s*\[\[|^\s*["'](?:model|model_provider)["']\s*=/m.test(input.existingText)) {
10905
+ throw new Error("复杂 TOML 配置需要结构化合并,已保留原文件");
10906
+ }
10907
+ const topKeys = new Set(input.managedTopKeys);
10908
+ const tables = new Set(input.managedTables);
10909
+ const out = [];
10910
+ let inManagedTable = false;
10911
+ let inAnyTable = false;
10912
+ for (const line of input.existingText.split(`
10913
+ `)) {
10914
+ const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(line)?.[1]?.trim() ?? null;
10915
+ if (header !== null) {
10916
+ inAnyTable = true;
10917
+ inManagedTable = tables.has(header);
10918
+ if (!inManagedTable)
10919
+ out.push(line);
10920
+ continue;
10921
+ }
10922
+ if (inManagedTable)
10923
+ continue;
10924
+ if (!inAnyTable) {
10925
+ const key = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1];
10926
+ if (key && topKeys.has(key))
10927
+ continue;
10928
+ }
10929
+ out.push(line);
10930
+ }
10931
+ const kept = out.join(`
10932
+ `).trim();
10933
+ if (!kept)
10934
+ return block;
10935
+ const tableAt = block.search(/^\s*\[/m);
10936
+ if (tableAt < 0)
10937
+ return block + `
10938
+ ` + kept + `
10939
+ `;
10940
+ return block.slice(0, tableAt).trimEnd() + `
10941
+
10942
+ ` + kept + `
10943
+
10944
+ ` + block.slice(tableAt);
10945
+ }
10548
10946
 
10549
10947
  // src/runtimes/codex/codex-provider-home.ts
10550
10948
  var INKDOWN_PROVIDER_ID = "inkdown-custom";
@@ -10576,13 +10974,13 @@ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
10576
10974
  }
10577
10975
 
10578
10976
  // src/runtimes/codex/codex-provider.ts
10579
- var import_promises = require("node:fs/promises");
10580
- var import_node_fs3 = require("node:fs");
10581
- var import_node_path4 = require("node:path");
10977
+ var import_promises2 = require("node:fs/promises");
10978
+ var import_node_fs5 = require("node:fs");
10979
+ var import_node_path6 = require("node:path");
10582
10980
 
10583
10981
  // src/client/acp-paths.ts
10584
- var import_node_os2 = require("node:os");
10585
- var import_node_path3 = require("node:path");
10982
+ var import_node_os3 = require("node:os");
10983
+ var import_node_path5 = require("node:path");
10586
10984
  function getDefaultAgentDataDir() {
10587
10985
  if (process.env.INKDOWN_DATA_DIR) {
10588
10986
  return process.env.INKDOWN_DATA_DIR;
@@ -10591,27 +10989,27 @@ function getDefaultAgentDataDir() {
10591
10989
  return process.env.ACP_DATA_DIR;
10592
10990
  }
10593
10991
  if (process.platform === "win32") {
10594
- return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path3.join(import_node_os2.homedir(), "AppData", "Local", "inkdown");
10992
+ return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path5.join(import_node_os3.homedir(), "AppData", "Local", "inkdown");
10595
10993
  }
10596
10994
  if (process.platform === "darwin") {
10597
- return import_node_path3.join(import_node_os2.homedir(), "Library", "Application Support", "inkdown");
10995
+ return import_node_path5.join(import_node_os3.homedir(), "Library", "Application Support", "inkdown");
10598
10996
  }
10599
- return process.env.XDG_DATA_HOME || import_node_path3.join(import_node_os2.homedir(), ".local", "share", "inkdown");
10997
+ return process.env.XDG_DATA_HOME || import_node_path5.join(import_node_os3.homedir(), ".local", "share", "inkdown");
10600
10998
  }
10601
10999
 
10602
11000
  // src/runtimes/codex/codex-provider.ts
10603
11001
  function providerFilePath(dir) {
10604
- return import_node_path4.join(dir, "agent", "provider.json");
11002
+ return import_node_path6.join(dir, "agent", "provider.json");
10605
11003
  }
10606
11004
  function providerHomePath(dir) {
10607
- return import_node_path4.join(dir, "agent", "codex-home");
11005
+ return import_node_path6.join(dir, "agent", "codex-home");
10608
11006
  }
10609
11007
  async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
10610
11008
  const file = providerFilePath(dir);
10611
- if (!import_node_fs3.existsSync(file))
11009
+ if (!import_node_fs5.existsSync(file))
10612
11010
  return null;
10613
11011
  try {
10614
- const raw = JSON.parse(await import_promises.readFile(file, "utf8"));
11012
+ const raw = JSON.parse(await import_promises2.readFile(file, "utf8"));
10615
11013
  if (typeof raw.baseUrl !== "string" || typeof raw.model !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
10616
11014
  return null;
10617
11015
  }
@@ -10633,8 +11031,20 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
10633
11031
  // src/runtimes/codex/index.ts
10634
11032
  async function provisionCustomProviderCodexHome(provider, codexHome) {
10635
11033
  try {
10636
- await import_promises2.mkdir(codexHome, { recursive: true });
10637
- await import_promises2.writeFile(import_node_path5.join(codexHome, "config.toml"), buildCustomProviderConfigToml(provider), "utf8");
11034
+ await import_promises3.mkdir(codexHome, { recursive: true });
11035
+ let existing = null;
11036
+ try {
11037
+ existing = await import_promises3.readFile(import_node_path7.join(codexHome, "config.toml"), "utf8");
11038
+ } catch (error) {
11039
+ if (error.code !== "ENOENT")
11040
+ throw error;
11041
+ }
11042
+ await import_promises3.writeFile(import_node_path7.join(codexHome, "config.toml"), mergeConfigTomlPreserving({
11043
+ existingText: existing,
11044
+ managedTopKeys: ["model", "model_provider"],
11045
+ managedTables: [`model_providers.${INKDOWN_PROVIDER_ID}`],
11046
+ replacementBlock: buildCustomProviderConfigToml(provider)
11047
+ }), "utf8");
10638
11048
  return true;
10639
11049
  } catch (error) {
10640
11050
  console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
@@ -10644,6 +11054,78 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
10644
11054
  var codexAdapter = {
10645
11055
  id: "codex-acp",
10646
11056
  probeQuota: async (options) => probeCodexQuota(options),
11057
+ supportedBridgeVersions: ["2.2.2"],
11058
+ prepareAppResources: async ({ directory, workspaceRoot, env: overrideEnv }) => {
11059
+ const load = readAppResourcesDir(directory);
11060
+ const skillsFound = load.skills.map((s) => s.name);
11061
+ const rulesText = readAppRulesText(directory);
11062
+ if (!rulesText) {
11063
+ return {
11064
+ report: {
11065
+ rulesApplied: false,
11066
+ rulesChars: 0,
11067
+ profileDigest: null,
11068
+ skillsFound,
11069
+ reason: "rules-missing"
11070
+ }
11071
+ };
11072
+ }
11073
+ const env = { ...process.env, ...overrideEnv };
11074
+ const notApplied = (reason) => ({ report: {
11075
+ rulesApplied: false,
11076
+ rulesPrepared: false,
11077
+ skillsApplied: false,
11078
+ rulesChars: rulesText.length,
11079
+ profileDigest: digestAppResources(load),
11080
+ skillsFound,
11081
+ reason
11082
+ } });
11083
+ if (!load.directoryReadable)
11084
+ return notApplied("invalid-resource-directory");
11085
+ if (env.CODEX_PATH)
11086
+ return notApplied("execution-not-verified");
11087
+ const codexHome = env.CODEX_HOME || import_node_path7.join(import_node_os4.homedir(), ".codex");
11088
+ try {
11089
+ await import_promises3.readFile(import_node_path7.join(codexHome, "config.toml"));
11090
+ return notApplied("effective-config-not-verified");
11091
+ } catch (error) {
11092
+ if (error.code !== "ENOENT")
11093
+ return notApplied("effective-config-not-verified");
11094
+ }
11095
+ for (let dir = workspaceRoot;dir; ) {
11096
+ if (import_node_fs6.existsSync(import_node_path7.join(dir, ".codex", "config.toml")))
11097
+ return notApplied("effective-config-not-verified");
11098
+ if (import_node_fs6.existsSync(import_node_path7.join(dir, ".git")))
11099
+ break;
11100
+ const parent = import_node_path7.dirname(dir);
11101
+ if (parent === dir)
11102
+ break;
11103
+ dir = parent;
11104
+ }
11105
+ const merged = mergeCodexConfigJson({ existingRaw: env["CODEX_CONFIG"], hostBlock: rulesText });
11106
+ if (!merged.ok) {
11107
+ return {
11108
+ report: {
11109
+ rulesApplied: false,
11110
+ rulesChars: rulesText.length,
11111
+ profileDigest: digestAppResources(load),
11112
+ skillsFound,
11113
+ reason: merged.reason === "invalid-json" ? "invalid-codex-config" : "conflicting-codex-config"
11114
+ }
11115
+ };
11116
+ }
11117
+ return {
11118
+ env: { CODEX_CONFIG: merged.json },
11119
+ report: {
11120
+ rulesApplied: false,
11121
+ rulesPrepared: true,
11122
+ skillsApplied: false,
11123
+ rulesChars: rulesText.length,
11124
+ profileDigest: import_node_crypto2.createHash("sha256").update(JSON.stringify([digestAppResources(load), codexHome, workspaceRoot, merged.json])).digest("hex"),
11125
+ skillsFound
11126
+ }
11127
+ };
11128
+ },
10647
11129
  probeAuth: () => {
10648
11130
  return probeCodexAuth();
10649
11131
  },
@@ -10660,11 +11142,73 @@ var codexAdapter = {
10660
11142
  }
10661
11143
  };
10662
11144
 
10663
- // src/runtimes/claude/quota.ts
10664
- var import_node_fs4 = require("node:fs");
10665
- var import_node_os3 = require("node:os");
10666
- var import_node_path6 = require("node:path");
11145
+ // src/resources/runtime-bindings.ts
11146
+ var import_node_path8 = require("node:path");
10667
11147
  var import_node_child_process2 = require("node:child_process");
11148
+ var import_node_util = require("node:util");
11149
+ function prepareCompatibilityResources(directory, reason) {
11150
+ const load = readAppResourcesDir(directory);
11151
+ return { report: {
11152
+ rulesApplied: false,
11153
+ rulesPrepared: false,
11154
+ skillsApplied: false,
11155
+ rulesChars: load.rules?.chars ?? 0,
11156
+ profileDigest: digestAppResources(load),
11157
+ skillsFound: load.skills.map((s) => s.name),
11158
+ reason
11159
+ } };
11160
+ }
11161
+ function mergeOpenCodeAppConfig(raw, directory) {
11162
+ const value = raw?.trim() ? JSON.parse(raw) : {};
11163
+ if (!value || typeof value !== "object" || Array.isArray(value))
11164
+ throw new Error("invalid-opencode-config");
11165
+ const config = value;
11166
+ if (config.instructions !== undefined && (!Array.isArray(config.instructions) || config.instructions.some((v) => typeof v !== "string")))
11167
+ throw new Error("invalid-opencode-instructions");
11168
+ if (config.skills !== undefined && (!config.skills || typeof config.skills !== "object" || Array.isArray(config.skills)))
11169
+ throw new Error("invalid-opencode-skills");
11170
+ const skills = config.skills ?? {};
11171
+ if (skills.paths !== undefined && (!Array.isArray(skills.paths) || skills.paths.some((v) => typeof v !== "string")))
11172
+ throw new Error("invalid-opencode-skill-paths");
11173
+ return JSON.stringify({
11174
+ ...config,
11175
+ instructions: [...new Set([...config.instructions ?? [], import_node_path8.join(directory, "AGENTS.md")])],
11176
+ skills: { ...skills, paths: [...new Set([...skills.paths ?? [], import_node_path8.join(directory, "skills")])] }
11177
+ });
11178
+ }
11179
+ async function prepareOpenCodeResources(input) {
11180
+ const prep = prepareCompatibilityResources(input.directory, "native-entry-not-verified");
11181
+ if (!input.command || !readAppRulesText(input.directory))
11182
+ return prep;
11183
+ try {
11184
+ const { stdout } = await import_node_util.promisify(import_node_child_process2.execFile)(input.command, ["--version"], { env: input.env, timeout: 8000, windowsHide: true });
11185
+ if (stdout.trim() !== "1.18.35")
11186
+ return prep;
11187
+ const json = mergeOpenCodeAppConfig(input.env?.OPENCODE_CONFIG_CONTENT, input.directory);
11188
+ return { env: { OPENCODE_CONFIG_CONTENT: json }, report: { ...prep.report, rulesPrepared: true, reason: undefined } };
11189
+ } catch {
11190
+ return { ...prep, report: { ...prep.report, reason: "native-config-prepare-failed" } };
11191
+ }
11192
+ }
11193
+ function prepareClaudeResources(directory) {
11194
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
11195
+ return { ...prep, report: { ...prep.report, rulesPrepared: !!readAppRulesText(directory) } };
11196
+ }
11197
+ function claudeResourceSessionMeta(directory) {
11198
+ const text = readAppRulesText(directory);
11199
+ if (!text)
11200
+ return;
11201
+ return {
11202
+ systemPrompt: { type: "preset", preset: "claude_code", append: text },
11203
+ claudeCode: { options: { plugins: [{ type: "local", path: directory }] } }
11204
+ };
11205
+ }
11206
+
11207
+ // src/runtimes/claude/quota.ts
11208
+ var import_node_fs7 = require("node:fs");
11209
+ var import_node_os5 = require("node:os");
11210
+ var import_node_path9 = require("node:path");
11211
+ var import_node_child_process3 = require("node:child_process");
10668
11212
  var cachedClaudeAuth = null;
10669
11213
  async function queryClaudeAuthStatus(timeoutMs = 1200) {
10670
11214
  if (cachedClaudeAuth && Date.now() - cachedClaudeAuth.time < 30000) {
@@ -10672,7 +11216,7 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
10672
11216
  }
10673
11217
  return new Promise((resolve) => {
10674
11218
  try {
10675
- import_node_child_process2.execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
11219
+ import_node_child_process3.execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
10676
11220
  if (!stdout)
10677
11221
  return resolve(null);
10678
11222
  try {
@@ -10690,15 +11234,15 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
10690
11234
  }
10691
11235
  async function probeClaudeQuota(options) {
10692
11236
  const claudeHome = resolveClaudeHome();
10693
- const claudeJsonPath = import_node_path6.join(import_node_os3.homedir(), ".claude.json");
10694
- const credsPath = import_node_path6.join(claudeHome, ".credentials.json");
11237
+ const claudeJsonPath = import_node_path9.join(import_node_os5.homedir(), ".claude.json");
11238
+ const credsPath = import_node_path9.join(claudeHome, ".credentials.json");
10695
11239
  let isLoggedIn = false;
10696
11240
  let isBanned = false;
10697
11241
  let accountEmail;
10698
11242
  let plan = "Claude Free / Default";
10699
- if (import_node_fs4.existsSync(claudeJsonPath)) {
11243
+ if (import_node_fs7.existsSync(claudeJsonPath)) {
10700
11244
  try {
10701
- const data = JSON.parse(import_node_fs4.readFileSync(claudeJsonPath, "utf8"));
11245
+ const data = JSON.parse(import_node_fs7.readFileSync(claudeJsonPath, "utf8"));
10702
11246
  if (data.oauthAccount) {
10703
11247
  isLoggedIn = true;
10704
11248
  accountEmail = data.oauthAccount.emailAddress;
@@ -10709,9 +11253,9 @@ async function probeClaudeQuota(options) {
10709
11253
  }
10710
11254
  } catch {}
10711
11255
  }
10712
- if (import_node_fs4.existsSync(credsPath)) {
11256
+ if (import_node_fs7.existsSync(credsPath)) {
10713
11257
  try {
10714
- const creds = JSON.parse(import_node_fs4.readFileSync(credsPath, "utf8"));
11258
+ const creds = JSON.parse(import_node_fs7.readFileSync(credsPath, "utf8"));
10715
11259
  if (creds.accessToken || creds.sessionKey)
10716
11260
  isLoggedIn = true;
10717
11261
  } catch {}
@@ -10763,19 +11307,19 @@ async function probeClaudeQuota(options) {
10763
11307
  }
10764
11308
 
10765
11309
  // src/runtimes/claude/index.ts
10766
- var import_node_fs5 = require("node:fs");
10767
- var import_node_os4 = require("node:os");
10768
- var import_node_path7 = require("node:path");
11310
+ var import_node_fs8 = require("node:fs");
11311
+ var import_node_os6 = require("node:os");
11312
+ var import_node_path10 = require("node:path");
10769
11313
  function resolveClaudeHome() {
10770
11314
  const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
10771
11315
  if (fromEnv)
10772
11316
  return fromEnv;
10773
- return import_node_path7.join(import_node_os4.homedir(), ".claude");
11317
+ return import_node_path10.join(import_node_os6.homedir(), ".claude");
10774
11318
  }
10775
11319
  function probeClaudeAuth() {
10776
11320
  const claudeHome = resolveClaudeHome();
10777
- const hasCodexHome = import_node_fs5.existsSync(claudeHome);
10778
- 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"));
11321
+ const hasCodexHome = import_node_fs8.existsSync(claudeHome);
11322
+ 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"));
10779
11323
  const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
10780
11324
  return {
10781
11325
  codexHome: claudeHome,
@@ -10787,6 +11331,9 @@ function probeClaudeAuth() {
10787
11331
  }
10788
11332
  var claudeAdapter = {
10789
11333
  id: "claude",
11334
+ supportedBridgeVersions: ["0.91.0"],
11335
+ prepareAppResources: async ({ directory }) => prepareClaudeResources(directory),
11336
+ appResourceSessionMeta: claudeResourceSessionMeta,
10790
11337
  probeAuth: () => probeClaudeAuth(),
10791
11338
  probeQuota: async (options) => probeClaudeQuota(options),
10792
11339
  orderAuthMethods: (methods) => methods,
@@ -10794,16 +11341,16 @@ var claudeAdapter = {
10794
11341
  };
10795
11342
 
10796
11343
  // src/runtimes/gemini/index.ts
10797
- var import_node_fs6 = require("node:fs");
10798
- var import_node_os5 = require("node:os");
10799
- var import_node_path8 = require("node:path");
11344
+ var import_node_fs9 = require("node:fs");
11345
+ var import_node_os7 = require("node:os");
11346
+ var import_node_path11 = require("node:path");
10800
11347
  function resolveGeminiHome() {
10801
- return import_node_path8.join(import_node_os5.homedir(), ".gemini");
11348
+ return import_node_path11.join(import_node_os7.homedir(), ".gemini");
10802
11349
  }
10803
11350
  function probeGeminiAuth() {
10804
11351
  const geminiHome = resolveGeminiHome();
10805
- const hasCodexHome = import_node_fs6.existsSync(geminiHome);
10806
- const hasAuthFile = import_node_fs6.existsSync(import_node_path8.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
11352
+ const hasCodexHome = import_node_fs9.existsSync(geminiHome);
11353
+ const hasAuthFile = import_node_fs9.existsSync(import_node_path11.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
10807
11354
  const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
10808
11355
  return {
10809
11356
  codexHome: geminiHome,
@@ -10815,24 +11362,25 @@ function probeGeminiAuth() {
10815
11362
  }
10816
11363
  var geminiAdapter = {
10817
11364
  id: "gemini",
11365
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-would-isolate-auth"),
10818
11366
  probeAuth: () => probeGeminiAuth(),
10819
11367
  orderAuthMethods: (methods) => methods,
10820
11368
  canSkipInteractiveAuth: () => false
10821
11369
  };
10822
11370
 
10823
11371
  // src/runtimes/copilot/index.ts
10824
- var import_node_fs7 = require("node:fs");
10825
- var import_node_os6 = require("node:os");
10826
- var import_node_path9 = require("node:path");
11372
+ var import_node_fs10 = require("node:fs");
11373
+ var import_node_os8 = require("node:os");
11374
+ var import_node_path12 = require("node:path");
10827
11375
  function resolveCopilotHome() {
10828
11376
  const fromEnv = process.env.COPILOT_HOME?.trim();
10829
11377
  if (fromEnv)
10830
11378
  return fromEnv;
10831
- return import_node_path9.join(import_node_os6.homedir(), ".copilot");
11379
+ return import_node_path12.join(import_node_os8.homedir(), ".copilot");
10832
11380
  }
10833
11381
  function hasCopilotLogin(home) {
10834
11382
  try {
10835
- const raw = import_node_fs7.readFileSync(import_node_path9.join(home, "config.json"), "utf8");
11383
+ const raw = import_node_fs10.readFileSync(import_node_path12.join(home, "config.json"), "utf8");
10836
11384
  const parsed = JSON.parse(raw);
10837
11385
  return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
10838
11386
  } catch {
@@ -10841,7 +11389,7 @@ function hasCopilotLogin(home) {
10841
11389
  }
10842
11390
  function probeCopilotAuth() {
10843
11391
  const copilotHome = resolveCopilotHome();
10844
- const hasCodexHome = import_node_fs7.existsSync(copilotHome);
11392
+ const hasCodexHome = import_node_fs10.existsSync(copilotHome);
10845
11393
  const hasAuthFile = hasCopilotLogin(copilotHome);
10846
11394
  const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
10847
11395
  return {
@@ -10854,20 +11402,21 @@ function probeCopilotAuth() {
10854
11402
  }
10855
11403
  var copilotAdapter = {
10856
11404
  id: "copilot",
11405
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-entry-not-verified"),
10857
11406
  probeAuth: () => probeCopilotAuth(),
10858
11407
  orderAuthMethods: (methods) => methods,
10859
11408
  canSkipInteractiveAuth: () => false
10860
11409
  };
10861
11410
 
10862
11411
  // src/runtimes/opencode/quota.ts
10863
- var import_node_fs8 = require("node:fs");
10864
- var import_node_child_process3 = require("node:child_process");
11412
+ var import_node_fs11 = require("node:fs");
11413
+ var import_node_child_process4 = require("node:child_process");
10865
11414
  var os = __toESM(require("node:os"), 1);
10866
11415
  var path = __toESM(require("node:path"), 1);
10867
11416
  function resolveOpencodeAuthPath() {
10868
11417
  const candidates = resolveOpencodeAuthCandidates();
10869
11418
  for (const c of candidates) {
10870
- if (import_node_fs8.existsSync(c))
11419
+ if (import_node_fs11.existsSync(c))
10871
11420
  return c;
10872
11421
  }
10873
11422
  return candidates[0] ?? null;
@@ -10879,7 +11428,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
10879
11428
  }
10880
11429
  return new Promise((resolve) => {
10881
11430
  try {
10882
- import_node_child_process3.execFile("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
11431
+ import_node_child_process4.execFile("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
10883
11432
  if (!stdout)
10884
11433
  return resolve(null);
10885
11434
  try {
@@ -10898,7 +11447,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
10898
11447
  async function queryOpencodeAuthList(timeoutMs = 1200) {
10899
11448
  return new Promise((resolve) => {
10900
11449
  try {
10901
- import_node_child_process3.execFile("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
11450
+ import_node_child_process4.execFile("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
10902
11451
  if (!stdout)
10903
11452
  return resolve([]);
10904
11453
  const lines = stdout.split(`
@@ -10918,7 +11467,7 @@ function readLocalOpencodeCredentials() {
10918
11467
  path.join(home, ".config", "opencode", "opencode.db")
10919
11468
  ].filter(Boolean);
10920
11469
  for (const dbPath of dbPaths) {
10921
- if (!import_node_fs8.existsSync(dbPath))
11470
+ if (!import_node_fs11.existsSync(dbPath))
10922
11471
  continue;
10923
11472
  try {
10924
11473
  let rows = [];
@@ -10947,7 +11496,7 @@ function readLocalOpencodeCredentials() {
10947
11496
  }
10948
11497
  } catch {
10949
11498
  try {
10950
- const buf = import_node_fs8.readFileSync(dbPath, "utf8");
11499
+ const buf = import_node_fs11.readFileSync(dbPath, "utf8");
10951
11500
  const emailMatch = buf.match(/"email"\s*:\s*"([^"]+)"/);
10952
11501
  const tokenMatch = buf.match(/"access"\s*:\s*"(st_[a-zA-Z0-9_\\-]+)"/);
10953
11502
  const orgMatch = buf.match(/"orgID"\s*:\s*"(wrk_[a-zA-Z0-9_\\-]+)"/);
@@ -11071,9 +11620,9 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
11071
11620
  let accountEmail = dbCreds.email;
11072
11621
  let accountName = dbCreds.name;
11073
11622
  let plan = "OpenCode Community";
11074
- if (authPath && import_node_fs8.existsSync(authPath)) {
11623
+ if (authPath && import_node_fs11.existsSync(authPath)) {
11075
11624
  try {
11076
- const data = JSON.parse(import_node_fs8.readFileSync(authPath, "utf8"));
11625
+ const data = JSON.parse(import_node_fs11.readFileSync(authPath, "utf8"));
11077
11626
  if (data && typeof data === "object") {
11078
11627
  const keys = Object.keys(data);
11079
11628
  if (keys.length > 0) {
@@ -11133,16 +11682,16 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
11133
11682
  }
11134
11683
 
11135
11684
  // src/runtimes/opencode/index.ts
11136
- var import_node_fs9 = require("node:fs");
11137
- var import_node_os7 = require("node:os");
11138
- var import_node_path10 = require("node:path");
11685
+ var import_node_fs12 = require("node:fs");
11686
+ var import_node_os9 = require("node:os");
11687
+ var import_node_path13 = require("node:path");
11139
11688
  function pickEnv(env, key) {
11140
11689
  return env?.[key]?.trim() ?? "";
11141
11690
  }
11142
11691
  function resolveOpencodeAuthCandidates(overrides) {
11143
11692
  const platform = overrides?.platform ?? process.platform;
11144
11693
  const env = overrides?.env ?? process.env;
11145
- const home = overrides?.home ?? import_node_os7.homedir();
11694
+ const home = overrides?.home ?? import_node_os9.homedir();
11146
11695
  const seen = new Set;
11147
11696
  const out = [];
11148
11697
  const push = (p) => {
@@ -11153,27 +11702,27 @@ function resolveOpencodeAuthCandidates(overrides) {
11153
11702
  };
11154
11703
  const xdg = pickEnv(env, "XDG_DATA_HOME");
11155
11704
  if (xdg)
11156
- push(import_node_path10.join(xdg, "opencode", "auth.json"));
11705
+ push(import_node_path13.join(xdg, "opencode", "auth.json"));
11157
11706
  if (platform === "win32") {
11158
- const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path10.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
11707
+ const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path13.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
11159
11708
  if (localAppData)
11160
- push(import_node_path10.join(localAppData, "opencode", "auth.json"));
11709
+ push(import_node_path13.join(localAppData, "opencode", "auth.json"));
11161
11710
  const userProfile = pickEnv(env, "USERPROFILE") || home;
11162
11711
  if (userProfile)
11163
- push(import_node_path10.join(userProfile, ".local", "share", "opencode", "auth.json"));
11712
+ push(import_node_path13.join(userProfile, ".local", "share", "opencode", "auth.json"));
11164
11713
  } else if (home) {
11165
- push(import_node_path10.join(home, ".local", "share", "opencode", "auth.json"));
11714
+ push(import_node_path13.join(home, ".local", "share", "opencode", "auth.json"));
11166
11715
  }
11167
11716
  return out;
11168
11717
  }
11169
11718
  function resolveOpencodeAuthFile() {
11170
- return resolveOpencodeAuthCandidates()[0] ?? import_node_path10.join(import_node_os7.homedir(), ".local", "share", "opencode", "auth.json");
11719
+ return resolveOpencodeAuthCandidates()[0] ?? import_node_path13.join(import_node_os9.homedir(), ".local", "share", "opencode", "auth.json");
11171
11720
  }
11172
11721
  function isValidOpencodeAuthFile(authFile) {
11173
11722
  try {
11174
- if (!authFile || !import_node_fs9.existsSync(authFile))
11723
+ if (!authFile || !import_node_fs12.existsSync(authFile))
11175
11724
  return false;
11176
- const raw = import_node_fs9.readFileSync(authFile, "utf8").trim();
11725
+ const raw = import_node_fs12.readFileSync(authFile, "utf8").trim();
11177
11726
  if (!raw)
11178
11727
  return false;
11179
11728
  const parsed = JSON.parse(raw);
@@ -11191,7 +11740,7 @@ function probeOpencodeAuth(overrides) {
11191
11740
  for (const candidate of candidates) {
11192
11741
  let exists = false;
11193
11742
  try {
11194
- exists = import_node_fs9.existsSync(candidate);
11743
+ exists = import_node_fs12.existsSync(candidate);
11195
11744
  } catch {
11196
11745
  exists = false;
11197
11746
  }
@@ -11204,10 +11753,10 @@ function probeOpencodeAuth(overrides) {
11204
11753
  validFile = candidate;
11205
11754
  }
11206
11755
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
11207
- const authDir = import_node_path10.dirname(authFile);
11756
+ const authDir = import_node_path13.dirname(authFile);
11208
11757
  let hasCodexHome = false;
11209
11758
  try {
11210
- hasCodexHome = import_node_fs9.existsSync(authDir);
11759
+ hasCodexHome = import_node_fs12.existsSync(authDir);
11211
11760
  } catch {
11212
11761
  hasCodexHome = false;
11213
11762
  }
@@ -11222,6 +11771,8 @@ function probeOpencodeAuth(overrides) {
11222
11771
  }
11223
11772
  var opencodeAdapter = {
11224
11773
  id: "opencode",
11774
+ supportedBridgeVersions: ["1.18.35"],
11775
+ prepareAppResources: prepareOpenCodeResources,
11225
11776
  probeAuth: () => probeOpencodeAuth(),
11226
11777
  probeQuota: async () => probeOpencodeQuota(),
11227
11778
  orderAuthMethods: (methods) => methods,
@@ -11232,6 +11783,7 @@ var opencodeAdapter = {
11232
11783
  // src/runtimes/opencode-v2/index.ts
11233
11784
  var opencodeV2Adapter = {
11234
11785
  id: "opencode-v2",
11786
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
11235
11787
  probeAuth: () => probeOpencodeAuth(),
11236
11788
  orderAuthMethods: (methods) => methods,
11237
11789
  canSkipInteractiveAuth: () => false,
@@ -11261,27 +11813,27 @@ async function probeCursorQuota() {
11261
11813
  };
11262
11814
  }
11263
11815
  // src/runtimes/cursor/index.ts
11264
- var import_node_fs10 = require("node:fs");
11265
- var import_node_os8 = require("node:os");
11266
- var import_node_path11 = require("node:path");
11816
+ var import_node_fs13 = require("node:fs");
11817
+ var import_node_os10 = require("node:os");
11818
+ var import_node_path14 = require("node:path");
11267
11819
  function cursorLocalAppData(env) {
11268
11820
  const local = env.LOCALAPPDATA?.trim();
11269
11821
  if (local)
11270
11822
  return local;
11271
11823
  const profile = env.USERPROFILE?.trim();
11272
- return profile ? import_node_path11.join(profile, "AppData", "Local") : "";
11824
+ return profile ? import_node_path14.join(profile, "AppData", "Local") : "";
11273
11825
  }
11274
11826
  function isOnPath(command, env, platform) {
11275
11827
  const pathValue = env.PATH ?? env.Path ?? "";
11276
11828
  if (!pathValue.trim())
11277
11829
  return false;
11278
- const sep = platform === "win32" ? ";" : import_node_path11.delimiter;
11830
+ const sep = platform === "win32" ? ";" : import_node_path14.delimiter;
11279
11831
  for (const dir of pathValue.split(sep)) {
11280
11832
  const trimmed = dir.trim().replace(/^"|"$/g, "");
11281
11833
  if (!trimmed)
11282
11834
  continue;
11283
11835
  try {
11284
- if (import_node_fs10.existsSync(import_node_path11.join(trimmed, command)))
11836
+ if (import_node_fs13.existsSync(import_node_path14.join(trimmed, command)))
11285
11837
  return true;
11286
11838
  } catch {}
11287
11839
  }
@@ -11290,19 +11842,19 @@ function isOnPath(command, env, platform) {
11290
11842
  function resolveDirectCursorCommand(platform, env, home) {
11291
11843
  if (platform === "win32") {
11292
11844
  const localAppData = cursorLocalAppData(env);
11293
- return localAppData ? import_node_path11.join(localAppData, "cursor-agent", "agent.cmd") : "";
11845
+ return localAppData ? import_node_path14.join(localAppData, "cursor-agent", "agent.cmd") : "";
11294
11846
  }
11295
- return home ? import_node_path11.join(home, ".local", "bin", "agent") : "";
11847
+ return home ? import_node_path14.join(home, ".local", "bin", "agent") : "";
11296
11848
  }
11297
11849
  function resolveCursorSpawnCommand(overrides) {
11298
11850
  const args = ["acp"];
11299
11851
  const platform = overrides?.platform ?? process.platform;
11300
11852
  const env = overrides?.env ?? process.env;
11301
- const home = overrides?.home ?? import_node_os8.homedir();
11853
+ const home = overrides?.home ?? import_node_os10.homedir();
11302
11854
  const binary = platform === "win32" ? "agent.cmd" : "agent";
11303
11855
  const direct = resolveDirectCursorCommand(platform, env, home);
11304
11856
  try {
11305
- if (direct && import_node_fs10.existsSync(direct))
11857
+ if (direct && import_node_fs13.existsSync(direct))
11306
11858
  return { command: direct, args };
11307
11859
  } catch {}
11308
11860
  if (isOnPath(binary, env, platform))
@@ -11317,12 +11869,12 @@ function cursorRoamingAppData(env, home) {
11317
11869
  if (roaming)
11318
11870
  return roaming;
11319
11871
  const profile = pickEnv2(env, "USERPROFILE") || home;
11320
- return profile ? import_node_path11.join(profile, "AppData", "Roaming") : "";
11872
+ return profile ? import_node_path14.join(profile, "AppData", "Roaming") : "";
11321
11873
  }
11322
11874
  function resolveCursorAuthCandidates(overrides) {
11323
11875
  const platform = overrides?.platform ?? process.platform;
11324
11876
  const env = overrides?.env ?? process.env;
11325
- const home = overrides?.home ?? import_node_os8.homedir();
11877
+ const home = overrides?.home ?? import_node_os10.homedir();
11326
11878
  const seen = new Set;
11327
11879
  const out = [];
11328
11880
  const push = (p) => {
@@ -11333,16 +11885,16 @@ function resolveCursorAuthCandidates(overrides) {
11333
11885
  };
11334
11886
  const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
11335
11887
  if (xdg)
11336
- push(import_node_path11.join(xdg, "cursor", "auth.json"));
11888
+ push(import_node_path14.join(xdg, "cursor", "auth.json"));
11337
11889
  if (platform === "win32") {
11338
11890
  const profile = pickEnv2(env, "USERPROFILE") || home;
11339
11891
  if (profile)
11340
- push(import_node_path11.join(profile, ".config", "cursor", "auth.json"));
11892
+ push(import_node_path14.join(profile, ".config", "cursor", "auth.json"));
11341
11893
  const roaming = cursorRoamingAppData(env, home);
11342
11894
  if (roaming)
11343
- push(import_node_path11.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
11895
+ push(import_node_path14.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
11344
11896
  } else if (home) {
11345
- push(import_node_path11.join(home, ".config", "cursor", "auth.json"));
11897
+ push(import_node_path14.join(home, ".config", "cursor", "auth.json"));
11346
11898
  }
11347
11899
  return out;
11348
11900
  }
@@ -11353,9 +11905,9 @@ function isValidCursorAuthFile(authFile) {
11353
11905
  try {
11354
11906
  if (!authFile || isStorageHintPath(authFile))
11355
11907
  return false;
11356
- if (!import_node_fs10.existsSync(authFile))
11908
+ if (!import_node_fs13.existsSync(authFile))
11357
11909
  return false;
11358
- const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
11910
+ const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
11359
11911
  if (!raw)
11360
11912
  return false;
11361
11913
  const parsed = JSON.parse(raw);
@@ -11373,9 +11925,9 @@ function isHintCursorStorageFile(authFile) {
11373
11925
  try {
11374
11926
  if (!authFile || !isStorageHintPath(authFile))
11375
11927
  return false;
11376
- if (!import_node_fs10.existsSync(authFile))
11928
+ if (!import_node_fs13.existsSync(authFile))
11377
11929
  return false;
11378
- const raw = import_node_fs10.readFileSync(authFile, "utf8").trim();
11930
+ const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
11379
11931
  if (!raw)
11380
11932
  return false;
11381
11933
  const parsed = JSON.parse(raw);
@@ -11391,7 +11943,7 @@ function isValidCursorCandidate(authFile) {
11391
11943
  }
11392
11944
  function probeCursorAuth(overrides) {
11393
11945
  const env = overrides?.env ?? process.env;
11394
- const home = overrides?.home ?? import_node_os8.homedir();
11946
+ const home = overrides?.home ?? import_node_os10.homedir();
11395
11947
  const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
11396
11948
  const candidates = resolveCursorAuthCandidates(overrides);
11397
11949
  let firstExisting = null;
@@ -11399,7 +11951,7 @@ function probeCursorAuth(overrides) {
11399
11951
  for (const candidate of candidates) {
11400
11952
  let exists = false;
11401
11953
  try {
11402
- exists = import_node_fs10.existsSync(candidate);
11954
+ exists = import_node_fs13.existsSync(candidate);
11403
11955
  } catch {
11404
11956
  exists = false;
11405
11957
  }
@@ -11411,12 +11963,12 @@ function probeCursorAuth(overrides) {
11411
11963
  if (isValidCursorCandidate(candidate))
11412
11964
  validFile = candidate;
11413
11965
  }
11414
- const fallback = home ? import_node_path11.join(home, ".config", "cursor", "auth.json") : "";
11966
+ const fallback = home ? import_node_path14.join(home, ".config", "cursor", "auth.json") : "";
11415
11967
  const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
11416
- const authDir = authFile ? import_node_path11.dirname(authFile) : "";
11968
+ const authDir = authFile ? import_node_path14.dirname(authFile) : "";
11417
11969
  let hasCodexHome = false;
11418
11970
  try {
11419
- hasCodexHome = authDir ? import_node_fs10.existsSync(authDir) : false;
11971
+ hasCodexHome = authDir ? import_node_fs13.existsSync(authDir) : false;
11420
11972
  } catch {
11421
11973
  hasCodexHome = false;
11422
11974
  }
@@ -11430,6 +11982,7 @@ function probeCursorAuth(overrides) {
11430
11982
  }
11431
11983
  var cursorAdapter = {
11432
11984
  id: "cursor-cli",
11985
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-does-not-guarantee-rules"),
11433
11986
  probeAuth: () => probeCursorAuth(),
11434
11987
  probeQuota: async () => probeCursorQuota(),
11435
11988
  resolveSpawnCommand: () => resolveCursorSpawnCommand(),
@@ -11478,6 +12031,7 @@ function probeDeepseekAuth() {
11478
12031
  }
11479
12032
  var deepseekAdapter = {
11480
12033
  id: "deepseek",
12034
+ prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
11481
12035
  probeAuth: () => probeDeepseekAuth(),
11482
12036
  resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
11483
12037
  resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
@@ -11486,13 +12040,13 @@ var deepseekAdapter = {
11486
12040
  };
11487
12041
 
11488
12042
  // src/runtimes/agy/quota.ts
11489
- var import_node_fs11 = require("node:fs");
11490
- var import_node_path12 = require("node:path");
11491
- var import_node_child_process4 = require("node:child_process");
12043
+ var import_node_fs14 = require("node:fs");
12044
+ var import_node_path15 = require("node:path");
12045
+ var import_node_child_process5 = require("node:child_process");
11492
12046
  var os2 = __toESM(require("node:os"), 1);
11493
12047
  function resolveGeminiHome2() {
11494
12048
  const home = process.env.USERPROFILE || process.env.HOME || "";
11495
- return import_node_path12.join(home, ".gemini");
12049
+ return import_node_path15.join(home, ".gemini");
11496
12050
  }
11497
12051
  function resolveAntigravityAccount() {
11498
12052
  if (process.env.GOOGLE_ACCOUNT?.trim()) {
@@ -11505,14 +12059,14 @@ function resolveAntigravityAccount() {
11505
12059
  }
11506
12060
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
11507
12061
  const candidates = [
11508
- process.env.APPDATA ? import_node_path12.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
11509
- import_node_path12.join(home, ".config", "Antigravity", "app_storage.json"),
11510
- import_node_path12.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
12062
+ process.env.APPDATA ? import_node_path15.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
12063
+ import_node_path15.join(home, ".config", "Antigravity", "app_storage.json"),
12064
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
11511
12065
  ].filter(Boolean);
11512
12066
  for (const file of candidates) {
11513
12067
  try {
11514
- if (import_node_fs11.existsSync(file)) {
11515
- const raw = import_node_fs11.readFileSync(file, "utf8");
12068
+ if (import_node_fs14.existsSync(file)) {
12069
+ const raw = import_node_fs14.readFileSync(file, "utf8");
11516
12070
  const json = JSON.parse(raw);
11517
12071
  const username = json["jetski.onboarding.lastLoginUsername"];
11518
12072
  if (username && typeof username === "string" && username.trim()) {
@@ -11533,30 +12087,30 @@ function resolveAntigravityAccount() {
11533
12087
  }
11534
12088
  function resolveAntigravityLanguageServer() {
11535
12089
  const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
11536
- const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path12.join(home, "AppData", "Roaming") : "");
12090
+ const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path15.join(home, "AppData", "Roaming") : "");
11537
12091
  const baseDirs = [
11538
- appData ? import_node_path12.join(appData, "Antigravity IDE", "logs") : null,
11539
- appData ? import_node_path12.join(appData, "Antigravity", "logs") : null,
11540
- import_node_path12.join(home, ".config", "Antigravity IDE", "logs"),
11541
- import_node_path12.join(home, ".config", "Antigravity", "logs"),
11542
- import_node_path12.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
11543
- import_node_path12.join(home, "Library", "Application Support", "Antigravity", "logs")
12092
+ appData ? import_node_path15.join(appData, "Antigravity IDE", "logs") : null,
12093
+ appData ? import_node_path15.join(appData, "Antigravity", "logs") : null,
12094
+ import_node_path15.join(home, ".config", "Antigravity IDE", "logs"),
12095
+ import_node_path15.join(home, ".config", "Antigravity", "logs"),
12096
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
12097
+ import_node_path15.join(home, "Library", "Application Support", "Antigravity", "logs")
11544
12098
  ].filter(Boolean);
11545
12099
  for (const base of baseDirs) {
11546
12100
  try {
11547
- if (!import_node_fs11.existsSync(base))
12101
+ if (!import_node_fs14.existsSync(base))
11548
12102
  continue;
11549
- const sessionDirs = import_node_fs11.readdirSync(base).map((d) => {
12103
+ const sessionDirs = import_node_fs14.readdirSync(base).map((d) => {
11550
12104
  try {
11551
- return { name: d, time: import_node_fs11.statSync(import_node_path12.join(base, d)).mtimeMs };
12105
+ return { name: d, time: import_node_fs14.statSync(import_node_path15.join(base, d)).mtimeMs };
11552
12106
  } catch {
11553
12107
  return null;
11554
12108
  }
11555
12109
  }).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
11556
12110
  for (const s of sessionDirs) {
11557
- const logFile = import_node_path12.join(base, s.name, "ls-main.log");
11558
- if (import_node_fs11.existsSync(logFile)) {
11559
- const content = import_node_fs11.readFileSync(logFile, "utf8");
12111
+ const logFile = import_node_path15.join(base, s.name, "ls-main.log");
12112
+ if (import_node_fs14.existsSync(logFile)) {
12113
+ const content = import_node_fs14.readFileSync(logFile, "utf8");
11560
12114
  const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
11561
12115
  const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
11562
12116
  if (csrfMatch && portMatch) {
@@ -11572,13 +12126,13 @@ function resolveAntigravityLanguageServer() {
11572
12126
  try {
11573
12127
  let out = "";
11574
12128
  if (process.platform === "win32") {
11575
- out = import_node_child_process4.execFileSync("powershell", [
12129
+ out = import_node_child_process5.execFileSync("powershell", [
11576
12130
  "-NoProfile",
11577
12131
  "-Command",
11578
12132
  `Get-CimInstance Win32_Process -Filter "Name like '%language_server%'" | Select-Object -ExpandProperty CommandLine`
11579
12133
  ], { encoding: "utf8", timeout: 4000, windowsHide: true });
11580
12134
  } else {
11581
- out = import_node_child_process4.execFileSync("ps", ["aux"], { encoding: "utf8", timeout: 4000 });
12135
+ out = import_node_child_process5.execFileSync("ps", ["aux"], { encoding: "utf8", timeout: 4000 });
11582
12136
  }
11583
12137
  const lines = out.split(/\r?\n/);
11584
12138
  for (const l of lines) {
@@ -11615,7 +12169,7 @@ async function probeAgyQuota(options) {
11615
12169
  }
11616
12170
  } catch {
11617
12171
  try {
11618
- const raw = import_node_child_process4.execFileSync(process.platform === "win32" ? "curl.exe" : "curl", [
12172
+ const raw = import_node_child_process5.execFileSync(process.platform === "win32" ? "curl.exe" : "curl", [
11619
12173
  "-k",
11620
12174
  "-s",
11621
12175
  "-X",
@@ -11713,7 +12267,7 @@ async function probeAgyQuota(options) {
11713
12267
  } catch {}
11714
12268
  }
11715
12269
  const geminiHome = resolveGeminiHome2();
11716
- const hasAgyDir = import_node_fs11.existsSync(import_node_path12.join(geminiHome, "antigravity")) || import_node_fs11.existsSync(import_node_path12.join(geminiHome, "antigravity-cli"));
12270
+ const hasAgyDir = import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity")) || import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity-cli"));
11717
12271
  const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
11718
12272
  const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
11719
12273
  if (!isAvailable) {
@@ -11785,6 +12339,12 @@ function probeAgyAuth() {
11785
12339
  }
11786
12340
  var agyAdapter = {
11787
12341
  id: "agy",
12342
+ prepareAppResources: async ({ directory }) => {
12343
+ const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
12344
+ return { ...prep, env: { AGY_ACP_RESOURCES_DIR: directory }, report: { ...prep.report, rulesPrepared: prep.report.rulesChars > 0 } };
12345
+ },
12346
+ appResourceSessionMeta: (directory) => ({ appResources: { directory } }),
12347
+ supportedBridgeVersions: ["0.1.24"],
11788
12348
  probeAuth: () => probeAgyAuth(),
11789
12349
  probeQuota: (options) => probeAgyQuota(options),
11790
12350
  orderAuthMethods: (methods) => methods,
@@ -11824,7 +12384,10 @@ function getAcpRuntimeAdapter(runtimeId) {
11824
12384
  }
11825
12385
 
11826
12386
  // src/process/process-manager.ts
11827
- var import_node_child_process5 = require("node:child_process");
12387
+ var import_node_child_process6 = require("node:child_process");
12388
+ function processKey(runtimeId, scopeKey) {
12389
+ return scopeKey ? `${scopeKey}:${runtimeId}` : runtimeId;
12390
+ }
11828
12391
  var active = new Map;
11829
12392
  var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
11830
12393
  function isSpawnedAcpProcessAlive(handle) {
@@ -11835,7 +12398,7 @@ function killProcessTree(pid) {
11835
12398
  if (process.platform !== "win32")
11836
12399
  return;
11837
12400
  try {
11838
- import_node_child_process5.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
12401
+ import_node_child_process6.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
11839
12402
  windowsHide: true,
11840
12403
  timeout: 8000
11841
12404
  });
@@ -11855,7 +12418,8 @@ function spawnAcpProcess(options) {
11855
12418
  if (!options.runtime?.id || !options.runtime.command || !Array.isArray(options.runtime.args)) {
11856
12419
  throw new Error(`ACP 运行时模板缺失 command/args: ${options.runtime?.id ?? "(empty)"}`);
11857
12420
  }
11858
- const existing = active.get(options.runtime.id);
12421
+ const key = processKey(options.runtime.id, options.scopeKey);
12422
+ const existing = active.get(key);
11859
12423
  if (existing) {
11860
12424
  existing.kill();
11861
12425
  }
@@ -11878,7 +12442,7 @@ function spawnAcpProcess(options) {
11878
12442
  } else {
11879
12443
  delete env.NO_BROWSER;
11880
12444
  }
11881
- const child = import_node_child_process5.spawn(file, options.runtime.args, {
12445
+ const child = import_node_child_process6.spawn(file, options.runtime.args, {
11882
12446
  cwd: options.cwd,
11883
12447
  env,
11884
12448
  stdio: ["pipe", "pipe", "pipe"],
@@ -11916,6 +12480,9 @@ function spawnAcpProcess(options) {
11916
12480
  });
11917
12481
  const handle = {
11918
12482
  runtimeId: options.runtime.id,
12483
+ scopeKey: options.scopeKey,
12484
+ executionContext: options.executionContext,
12485
+ profileTag: options.profileTag ?? null,
11919
12486
  child,
11920
12487
  spawnedAt: Date.now(),
11921
12488
  stderrTail,
@@ -11933,7 +12500,7 @@ function spawnAcpProcess(options) {
11933
12500
  } catch {}
11934
12501
  }
11935
12502
  }
11936
- active.delete(options.runtime.id);
12503
+ active.delete(key);
11937
12504
  }
11938
12505
  };
11939
12506
  child.on("exit", (code, signal) => {
@@ -11941,90 +12508,57 @@ function spawnAcpProcess(options) {
11941
12508
  if (rest)
11942
12509
  pushStderrTailLine(rest);
11943
12510
  stderrBuffer = "";
11944
- active.delete(options.runtime.id);
12511
+ if (active.get(key) === handle)
12512
+ active.delete(key);
11945
12513
  options.onExit?.(code, signal);
11946
12514
  });
11947
- active.set(options.runtime.id, handle);
12515
+ active.set(key, handle);
11948
12516
  return handle;
11949
12517
  }
11950
-
11951
- // src/client/sdk-client.ts
11952
- var import_node_stream = require("node:stream");
11953
- var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
11954
- function createSdkStreamHandle(child) {
11955
- const stdoutBridge = new import_node_stream.PassThrough;
11956
- const stdinBridge = new import_node_stream.PassThrough;
11957
- child.stdout.pipe(stdoutBridge);
11958
- stdinBridge.pipe(child.stdin, { end: false });
11959
- const output = import_node_stream.Writable.toWeb(stdinBridge);
11960
- const input = import_node_stream.Readable.toWeb(stdoutBridge);
11961
- const stream = ndJsonStream2(output, input);
11962
- let disposed = false;
11963
- return {
11964
- stream,
11965
- dispose: () => {
11966
- if (disposed)
11967
- return;
11968
- disposed = true;
11969
- try {
11970
- child.stdout.unpipe(stdoutBridge);
11971
- } catch {}
11972
- try {
11973
- stdinBridge.unpipe(child.stdin);
11974
- } catch {}
11975
- try {
11976
- stdoutBridge.destroy();
11977
- } catch {}
11978
- try {
11979
- stdinBridge.destroy();
11980
- } catch {}
11981
- }
11982
- };
11983
- }
11984
- function connectSdkClient(child, configure, runtimeId) {
11985
- if (runtimeId && true) {
11986
- console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
12518
+ function getLiveAcpProcess(runtimeId, query = {}) {
12519
+ const key = processKey(runtimeId, query.scopeKey);
12520
+ const handle = active.get(key);
12521
+ if (!handle)
12522
+ return;
12523
+ if (!isSpawnedAcpProcessAlive(handle)) {
12524
+ active.delete(key);
12525
+ return;
11987
12526
  }
11988
- const app = client({ name: "inkdown" });
11989
- configure(app);
11990
- const streamHandle = createSdkStreamHandle(child);
11991
- const connection = app.connect(streamHandle.stream);
11992
- return { app, connection, streamHandle };
11993
- }
11994
- async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
11995
- const controller = new AbortController;
11996
- let timer;
11997
- try {
11998
- const pending = agent.request(method, params, {
11999
- cancellationSignal: controller.signal
12000
- });
12001
- const timeout = new Promise((_, reject) => {
12002
- timer = setTimeout(() => {
12003
- controller.abort();
12004
- reject(new Error(`请求超时: ${method}`));
12005
- }, timeoutMs);
12006
- timer.unref?.();
12007
- });
12008
- return await Promise.race([pending, timeout]);
12009
- } finally {
12010
- if (timer !== undefined)
12011
- clearTimeout(timer);
12527
+ if (query.executionContext !== undefined && (handle.executionContext ?? null) !== query.executionContext) {
12528
+ return;
12012
12529
  }
12530
+ if (query.expectedTag !== undefined && (handle.profileTag ?? null) !== query.expectedTag)
12531
+ return;
12532
+ return handle;
12533
+ }
12534
+ function tryReuseLiveAcpProcess(runtimeId, query = {}) {
12535
+ const hit = getLiveAcpProcess(runtimeId, query);
12536
+ if (hit)
12537
+ return { status: "hit", handle: hit };
12538
+ if (query.expectedTag === undefined)
12539
+ return { status: "miss" };
12540
+ const stale = getLiveAcpProcess(runtimeId, { scopeKey: query.scopeKey, executionContext: query.executionContext });
12541
+ if (!stale)
12542
+ return { status: "miss" };
12543
+ if (query.isBusy?.(stale))
12544
+ return { status: "busy", handle: stale };
12545
+ stale.kill();
12546
+ return { status: "miss" };
12013
12547
  }
12014
12548
 
12015
12549
  // src/client/acp-fs.ts
12016
- var import_promises3 = require("node:fs/promises");
12017
- var import_node_path13 = require("node:path");
12018
12550
  var import_promises4 = require("node:fs/promises");
12551
+ var import_node_path16 = require("node:path");
12552
+ var import_promises5 = require("node:fs/promises");
12019
12553
  var MAX_READ_BYTES = 2 * 1024 * 1024;
12020
12554
  var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
12021
12555
  function isBinaryDocumentPath(filePath) {
12022
- return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path13.extname(filePath).toLowerCase());
12556
+ return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path16.extname(filePath).toLowerCase());
12023
12557
  }
12024
12558
  function assertPathInsideWorkspace(filePath, workspaceRoot) {
12025
- const root = import_node_path13.resolve(workspaceRoot);
12026
- const target = import_node_path13.resolve(filePath);
12027
- const rootWithSep = root.endsWith(import_node_path13.sep) ? root : root + import_node_path13.sep;
12559
+ const root = import_node_path16.resolve(workspaceRoot);
12560
+ const target = import_node_path16.resolve(filePath);
12561
+ const rootWithSep = root.endsWith(import_node_path16.sep) ? root : root + import_node_path16.sep;
12028
12562
  if (target !== root && !target.startsWith(rootWithSep)) {
12029
12563
  throw new Error(`路径不在工作区内: ${filePath}`);
12030
12564
  }
@@ -12035,8 +12569,8 @@ async function acpReadTextFile(params) {
12035
12569
  throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
12036
12570
  }
12037
12571
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
12038
- await import_promises3.access(abs);
12039
- let content = await import_promises3.readFile(abs, "utf-8");
12572
+ await import_promises4.access(abs);
12573
+ let content = await import_promises4.readFile(abs, "utf-8");
12040
12574
  if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
12041
12575
  content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
12042
12576
  content += `
@@ -12055,8 +12589,8 @@ async function acpReadTextFile(params) {
12055
12589
  }
12056
12590
  async function acpWriteTextFile(params) {
12057
12591
  const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
12058
- await import_promises4.mkdir(import_node_path13.dirname(abs), { recursive: true });
12059
- await import_promises3.writeFile(abs, params.content, "utf-8");
12592
+ await import_promises5.mkdir(import_node_path16.dirname(abs), { recursive: true });
12593
+ await import_promises4.writeFile(abs, params.content, "utf-8");
12060
12594
  return {};
12061
12595
  }
12062
12596
 
@@ -12383,6 +12917,25 @@ function isTransientAcpTransportError(error) {
12383
12917
  async function restoreOrCreateAcpSession(input) {
12384
12918
  const resumeId = input.resumeSessionId?.trim() || null;
12385
12919
  const restoreAttempts = [];
12920
+ let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
12921
+ let nativeSessionAccepted = false;
12922
+ const request = async (method, params) => {
12923
+ if (!input.sessionMeta)
12924
+ return input.request(method, params);
12925
+ try {
12926
+ const result = await input.request(method, { ...params, _meta: input.sessionMeta });
12927
+ nativeSessionAccepted = true;
12928
+ return result;
12929
+ } catch (error) {
12930
+ const rejected = error instanceof RequestError && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
12931
+ if (!rejected || isTransientAcpTransportError(error))
12932
+ throw error;
12933
+ log("warn", "native resource options failed; retry without extension");
12934
+ const result = await input.request(method, params);
12935
+ nativeSessionAccepted = false;
12936
+ return result;
12937
+ }
12938
+ };
12386
12939
  const delayMs = input.retryDelayMs ?? 250;
12387
12940
  const log = input.log ?? ((level, message, data) => {
12388
12941
  if (level === "info" && false)
@@ -12404,7 +12957,7 @@ async function restoreOrCreateAcpSession(input) {
12404
12957
  maxTries
12405
12958
  });
12406
12959
  try {
12407
- const result = await input.request(rpcMethod, {
12960
+ const result = await request(rpcMethod, {
12408
12961
  sessionId: resumeId,
12409
12962
  cwd: input.cwd,
12410
12963
  mcpServers: input.mcpServers ?? []
@@ -12443,7 +12996,7 @@ async function restoreOrCreateAcpSession(input) {
12443
12996
  mcpServers: input.mcpServers ?? []
12444
12997
  };
12445
12998
  try {
12446
- return await input.request("session/new", baseParams);
12999
+ return await request("session/new", baseParams);
12447
13000
  } catch (firstError) {
12448
13001
  if ((input.mcpServers ?? []).length === 0)
12449
13002
  throw firstError;
@@ -12451,10 +13004,12 @@ async function restoreOrCreateAcpSession(input) {
12451
13004
  error: errorMessage(firstError)
12452
13005
  });
12453
13006
  try {
12454
- return await input.request("session/new", {
13007
+ const result = await request("session/new", {
12455
13008
  cwd: input.cwd,
12456
13009
  mcpServers: []
12457
13010
  });
13011
+ mcpServersAccepted = false;
13012
+ return result;
12458
13013
  } catch {
12459
13014
  throw firstError;
12460
13015
  }
@@ -12470,6 +13025,8 @@ async function restoreOrCreateAcpSession(input) {
12470
13025
  configOptions: withModelsFallback(resumed),
12471
13026
  restoreMethod: "resume",
12472
13027
  sessionRestored: true,
13028
+ mcpServersAccepted,
13029
+ nativeSessionAccepted,
12473
13030
  requestedSessionId: resumeId,
12474
13031
  restoreAttempts
12475
13032
  };
@@ -12488,6 +13045,8 @@ async function restoreOrCreateAcpSession(input) {
12488
13045
  configOptions: withModelsFallback(loaded),
12489
13046
  restoreMethod: "load",
12490
13047
  sessionRestored: true,
13048
+ mcpServersAccepted,
13049
+ nativeSessionAccepted,
12491
13050
  requestedSessionId: resumeId,
12492
13051
  restoreAttempts
12493
13052
  };
@@ -12509,14 +13068,16 @@ async function restoreOrCreateAcpSession(input) {
12509
13068
  configOptions: withModelsFallback(sessionResult),
12510
13069
  restoreMethod: "new",
12511
13070
  sessionRestored: false,
13071
+ mcpServersAccepted,
13072
+ nativeSessionAccepted,
12512
13073
  requestedSessionId: resumeId ?? undefined,
12513
13074
  restoreAttempts
12514
13075
  };
12515
13076
  }
12516
13077
 
12517
13078
  // src/client/acp-terminal.ts
12518
- var import_node_child_process6 = require("node:child_process");
12519
- var import_node_crypto = require("node:crypto");
13079
+ var import_node_child_process7 = require("node:child_process");
13080
+ var import_node_crypto3 = require("node:crypto");
12520
13081
 
12521
13082
  // src/transport/terminal-output-buffer.ts
12522
13083
  function truncateOutputFromStart(text, byteLimit) {
@@ -12568,14 +13129,14 @@ class AcpTerminalManager {
12568
13129
  throw new Error("terminal/create 需要 command");
12569
13130
  const cwd = resolveCwd(params.cwd, params.workspaceRoot);
12570
13131
  const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : DEFAULT_OUTPUT_BYTE_LIMIT;
12571
- const child = import_node_child_process6.spawn(command, params.args ?? [], {
13132
+ const child = import_node_child_process7.spawn(command, params.args ?? [], {
12572
13133
  cwd,
12573
13134
  env: buildEnv(params.env),
12574
13135
  windowsHide: true,
12575
13136
  shell: false,
12576
13137
  stdio: ["ignore", "pipe", "pipe"]
12577
13138
  });
12578
- const id = `term_${import_node_crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;
13139
+ const id = `term_${import_node_crypto3.randomUUID().replace(/-/g, "").slice(0, 12)}`;
12579
13140
  const record = {
12580
13141
  id,
12581
13142
  sessionId: params.sessionId,
@@ -12664,7 +13225,7 @@ class AcpTerminalManager {
12664
13225
  return;
12665
13226
  if (process.platform === "win32") {
12666
13227
  try {
12667
- import_node_child_process6.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
13228
+ import_node_child_process7.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
12668
13229
  windowsHide: true,
12669
13230
  stdio: "ignore"
12670
13231
  });
@@ -12699,9 +13260,9 @@ class AcpTerminalManager {
12699
13260
  }
12700
13261
 
12701
13262
  // src/client/acp-proxy-service.ts
12702
- var import_promises5 = require("node:fs/promises");
12703
- var import_node_fs12 = require("node:fs");
12704
- var import_node_path14 = require("node:path");
13263
+ var import_promises6 = require("node:fs/promises");
13264
+ var import_node_fs15 = require("node:fs");
13265
+ var import_node_path17 = require("node:path");
12705
13266
  var DEFAULT_ACP_PROXY_SETTINGS = {
12706
13267
  enabled: false,
12707
13268
  host: "127.0.0.1",
@@ -12710,14 +13271,14 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
12710
13271
  var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
12711
13272
  var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
12712
13273
  function proxyFilePath(dir) {
12713
- return import_node_path14.join(dir, "agent", "proxy.json");
13274
+ return import_node_path17.join(dir, "agent", "proxy.json");
12714
13275
  }
12715
13276
  async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
12716
13277
  const file = proxyFilePath(dir);
12717
- if (!import_node_fs12.existsSync(file))
13278
+ if (!import_node_fs15.existsSync(file))
12718
13279
  return { ...DEFAULT_ACP_PROXY_SETTINGS };
12719
13280
  try {
12720
- const raw = JSON.parse(await import_promises5.readFile(file, "utf8"));
13281
+ const raw = JSON.parse(await import_promises6.readFile(file, "utf8"));
12721
13282
  return {
12722
13283
  enabled: raw.enabled === true,
12723
13284
  host: typeof raw.host === "string" && raw.host.trim() ? raw.host : DEFAULT_ACP_PROXY_SETTINGS.host,
@@ -12746,6 +13307,109 @@ function buildAcpProxySpawnEnv(settings) {
12746
13307
  };
12747
13308
  }
12748
13309
 
13310
+ // src/session/compat-guide.ts
13311
+ var COMPAT_CONTEXT_TAG = "acp-compat-context";
13312
+ function shortDigest(digest) {
13313
+ return digest ? digest.slice(0, 16) : "none";
13314
+ }
13315
+ function buildCompatGuideText(input) {
13316
+ const hasRules = (input.rulesText ?? "").trim() !== "";
13317
+ const hasSkills = input.skills.length > 0;
13318
+ if (!hasRules && !hasSkills)
13319
+ return null;
13320
+ const lines = [];
13321
+ 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.", "");
13322
+ if (hasRules) {
13323
+ lines.push("--- host rules (same source as the host app, delivered once per session) ---", "");
13324
+ lines.push(input.rulesText.trim(), "");
13325
+ }
13326
+ if (hasSkills) {
13327
+ lines.push("--- host skills catalog (names and descriptions only; read full text on demand) ---", "");
13328
+ for (const skill of input.skills) {
13329
+ lines.push(`- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`);
13330
+ }
13331
+ 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.");
13332
+ lines.push("");
13333
+ }
13334
+ lines.push(`</${COMPAT_CONTEXT_TAG}>`);
13335
+ return lines.join(`
13336
+ `);
13337
+ }
13338
+ function compatDeliveryKey(sessionId, generation, digest) {
13339
+ return `${generation}:${sessionId}:${digest ?? "none"}`;
13340
+ }
13341
+
13342
+ // src/mcp/app-skills-mcp.ts
13343
+ var import_node_path18 = require("node:path");
13344
+ var import_node_url = require("node:url");
13345
+ var import_node_fs16 = require("node:fs");
13346
+ var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
13347
+ var APP_SKILLS_TOOLS = [
13348
+ {
13349
+ name: "app_list_skills",
13350
+ 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.",
13351
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
13352
+ },
13353
+ {
13354
+ name: "app_read_skill",
13355
+ 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).",
13356
+ inputSchema: {
13357
+ type: "object",
13358
+ properties: {
13359
+ name: { type: "string", description: "Exact skill name from app_list_skills" },
13360
+ ref: {
13361
+ type: "string",
13362
+ description: "Optional same-directory relative Markdown file (default SKILL.md)"
13363
+ }
13364
+ },
13365
+ required: ["name"],
13366
+ additionalProperties: false
13367
+ }
13368
+ }
13369
+ ];
13370
+ function buildAppSkillsMcpServer(directory, opts) {
13371
+ return {
13372
+ name: opts?.name ?? APP_SKILLS_MCP_SERVER_NAME,
13373
+ command: process.execPath,
13374
+ env: process.versions.electron ? [{ name: "ELECTRON_RUN_AS_NODE", value: "1" }] : [],
13375
+ args: [opts?.runnerPath ?? resolveAppSkillsRunnerPath(), directory]
13376
+ };
13377
+ }
13378
+ function resolveAppSkillsRunnerPath(fromFile) {
13379
+ const base = fromFile ?? import_node_url.fileURLToPath("file:///home/runner/work/acp-client/acp-client/src/mcp/app-skills-mcp.ts");
13380
+ const candidates = [
13381
+ import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.cjs"),
13382
+ import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.ts")
13383
+ ];
13384
+ for (const candidate of candidates) {
13385
+ if (import_node_fs16.existsSync(candidate))
13386
+ return candidate;
13387
+ }
13388
+ throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
13389
+ }
13390
+
13391
+ // src/client/acp-client.ts
13392
+ var import_node_crypto4 = require("node:crypto");
13393
+
13394
+ // src/resources/eligibility.ts
13395
+ var NATIVE_ELIGIBLE_BRIDGE_VERSIONS = {
13396
+ "codex-acp": ["2.2.2"],
13397
+ opencode: ["1.18.35"],
13398
+ claude: ["0.91.0"],
13399
+ agy: ["0.1.24"]
13400
+ };
13401
+ function isSupportedBridgeVersion(runtimeId, version) {
13402
+ const versions = NATIVE_ELIGIBLE_BRIDGE_VERSIONS[(runtimeId ?? "").trim()];
13403
+ if (!versions)
13404
+ return { eligible: false, reason: "runtime-not-verified" };
13405
+ const normalized = version?.trim().replace(/^v/, "");
13406
+ if (!normalized)
13407
+ return { eligible: false, reason: "unknown-bridge-version" };
13408
+ if (!versions.includes(normalized))
13409
+ return { eligible: false, reason: "unsupported-bridge-version" };
13410
+ return { eligible: true };
13411
+ }
13412
+
12749
13413
  // src/session/session-capabilities.ts
12750
13414
  function parseLoadSessionSupported(caps) {
12751
13415
  return caps.loadSession === true;
@@ -12768,11 +13432,13 @@ class AcpSessionHandle {
12768
13432
  client;
12769
13433
  restoreMethod;
12770
13434
  configOptions;
12771
- constructor(sessionId, client, restoreMethod, configOptions) {
13435
+ resourceReport;
13436
+ constructor(sessionId, client, restoreMethod, configOptions, resourceReport) {
12772
13437
  this.sessionId = sessionId;
12773
13438
  this.client = client;
12774
13439
  this.restoreMethod = restoreMethod;
12775
13440
  this.configOptions = configOptions;
13441
+ this.resourceReport = resourceReport;
12776
13442
  }
12777
13443
  async prompt(promptText, options) {
12778
13444
  return this.client.promptSession(this.sessionId, promptText, options);
@@ -12801,6 +13467,10 @@ class AcpClient {
12801
13467
  clientInfo;
12802
13468
  dataDir;
12803
13469
  extraEnv;
13470
+ configurationScope;
13471
+ sessionConfig = null;
13472
+ resourcesDir;
13473
+ processScopeKey = import_node_crypto4.randomUUID();
12804
13474
  callbacks;
12805
13475
  terminals = new AcpTerminalManager;
12806
13476
  processHandle = null;
@@ -12808,6 +13478,17 @@ class AcpClient {
12808
13478
  sdkConnection = null;
12809
13479
  streamHandle = null;
12810
13480
  initResponse = null;
13481
+ inflightPrompts = new Set;
13482
+ resourcePrep = null;
13483
+ connectionGen = 0;
13484
+ attachSkillsMcp;
13485
+ sessionLedger = new Map;
13486
+ compatSentKeys = new Set;
13487
+ compatSnapshots = new Map;
13488
+ get resourceReport() {
13489
+ const report = this.resourcePrep?.report;
13490
+ return report ? { ...report, skillsFound: [...report.skillsFound] } : null;
13491
+ }
12811
13492
  constructor(options) {
12812
13493
  this.workspaceRoot = options.workspaceRoot;
12813
13494
  this.clientInfo = {
@@ -12816,6 +13497,14 @@ class AcpClient {
12816
13497
  };
12817
13498
  this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
12818
13499
  this.extraEnv = options.env ?? {};
13500
+ if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
13501
+ throw new Error("resources.directory 必须是本机绝对路径");
13502
+ }
13503
+ this.configurationScope = options.resources?.configurationScope ?? "overlay";
13504
+ if (!["overlay", "session"].includes(this.configurationScope))
13505
+ throw new Error("Invalid resources.configurationScope");
13506
+ this.resourcesDir = options.resources?.directory ?? null;
13507
+ this.attachSkillsMcp = options.resources?.attachSkillsMcp !== false;
12819
13508
  this.callbacks = options.callbacks ?? {};
12820
13509
  const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
12821
13510
  this.adapter = getAcpRuntimeAdapter(runtimeId);
@@ -12842,6 +13531,14 @@ class AcpClient {
12842
13531
  return this.initResponse;
12843
13532
  }
12844
13533
  async connect() {
13534
+ if (this.inflightPrompts.size > 0)
13535
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
13536
+ if (this.isConnected && this.initResponse)
13537
+ return ok({ status: this.status, init: this.initResponse });
13538
+ if (this.currentStatus === "connecting")
13539
+ return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在连接" });
13540
+ this.connectionGen += 1;
13541
+ const connectGen = this.connectionGen;
12845
13542
  try {
12846
13543
  this.setStatus("connecting");
12847
13544
  const blocker = this.adapter.resolveSpawnBlocker?.();
@@ -12867,16 +13564,105 @@ class AcpClient {
12867
13564
  ...baseEnv,
12868
13565
  env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
12869
13566
  };
13567
+ let resourceEnv = {};
13568
+ let profileTag = null;
13569
+ if (this.resourcesDir && this.configurationScope === "session") {
13570
+ const profile = await createSessionConfigHome(this.runtimeInfo.id, this.resourcesDir);
13571
+ if (connectGen !== this.connectionGen || this.status !== "connecting") {
13572
+ await profile.dispose();
13573
+ return err({ code: "CANCELLED", message: "连接已取消" });
13574
+ }
13575
+ this.sessionConfig = profile;
13576
+ resourceEnv = this.sessionConfig.env;
13577
+ const load = readAppResourcesDir(this.resourcesDir);
13578
+ this.resourcePrep = { profileTag: null, report: {
13579
+ rulesApplied: false,
13580
+ rulesPrepared: false,
13581
+ skillsApplied: false,
13582
+ rulesChars: load.rules?.chars ?? 0,
13583
+ profileDigest: digestAppResources(load),
13584
+ skillsFound: load.skills.map((s) => s.name),
13585
+ configurationScope: "session",
13586
+ configurationDirectory: this.sessionConfig.directory,
13587
+ configurationRulesFile: this.sessionConfig.rulesFile,
13588
+ reason: this.sessionConfig.nativeRules ? "isolated-config-not-runtime-verified" : "isolated-config-rule-discovery-not-verified"
13589
+ } };
13590
+ } else if (this.resourcesDir && this.adapter.prepareAppResources) {
13591
+ try {
13592
+ const prep = await this.adapter.prepareAppResources({
13593
+ directory: this.resourcesDir,
13594
+ command: effectiveRuntime.command,
13595
+ workspaceRoot: this.workspaceRoot,
13596
+ env: { ...process.env, ...spawnEnv.env }
13597
+ });
13598
+ if (prep.env)
13599
+ resourceEnv = prep.env;
13600
+ prep.report.rulesPrepared = prep.report.rulesPrepared ?? prep.report.rulesApplied;
13601
+ prep.report.rulesApplied = false;
13602
+ prep.report.skillsApplied = false;
13603
+ const digest = prep.report.profileDigest;
13604
+ profileTag = digest ? `${this.runtimeInfo.id}:resources@${digest.slice(0, 16)}` : null;
13605
+ this.resourcePrep = { profileTag, report: prep.report };
13606
+ } catch (error) {
13607
+ this.resourcePrep = {
13608
+ profileTag: null,
13609
+ report: {
13610
+ rulesApplied: false,
13611
+ rulesChars: 0,
13612
+ profileDigest: null,
13613
+ skillsFound: [],
13614
+ reason: "prepare-failed"
13615
+ }
13616
+ };
13617
+ this.callbacks.onLog?.("warn", "应用资源准备失败,已回退兼容", {
13618
+ error: error instanceof Error ? error.message : String(error)
13619
+ });
13620
+ }
13621
+ } else {
13622
+ const load = this.resourcesDir ? readAppResourcesDir(this.resourcesDir) : null;
13623
+ this.resourcePrep = load ? { profileTag: null, report: {
13624
+ rulesApplied: false,
13625
+ rulesPrepared: false,
13626
+ skillsApplied: false,
13627
+ rulesChars: load.rules?.chars ?? 0,
13628
+ profileDigest: digestAppResources(load),
13629
+ skillsFound: load.skills.map((s) => s.name),
13630
+ reason: "runtime-not-supported"
13631
+ } } : null;
13632
+ }
13633
+ const finalEnv = { ...spawnEnv.env, ...resourceEnv };
12870
13634
  await this.adapter.beforeSpawn?.();
12871
- const processHandle = spawnAcpProcess({
13635
+ if (connectGen !== this.connectionGen || this.status !== "connecting")
13636
+ return err({ code: "CANCELLED", message: "连接已取消" });
13637
+ let reuseDegraded = false;
13638
+ let reusedHandle = null;
13639
+ if (profileTag) {
13640
+ const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
13641
+ expectedTag: profileTag,
13642
+ scopeKey: this.processScopeKey,
13643
+ isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
13644
+ });
13645
+ if (reuse.status === "hit") {
13646
+ reusedHandle = reuse.handle;
13647
+ } else if (reuse.status === "busy") {
13648
+ reusedHandle = reuse.handle;
13649
+ reuseDegraded = true;
13650
+ this.callbacks.onLog?.("warn", "应用资源摘要已变更但旧进程正忙,沿用旧进程并降级,新摘要下次冷启动生效");
13651
+ }
13652
+ }
13653
+ const processHandle = reusedHandle ?? spawnAcpProcess({
12872
13654
  runtime: effectiveRuntime,
12873
13655
  cwd: this.workspaceRoot,
12874
- env: spawnEnv.env,
13656
+ scopeKey: this.processScopeKey,
13657
+ env: finalEnv,
12875
13658
  envRemove: spawnEnv.envRemove,
13659
+ profileTag,
12876
13660
  onStderrLine: (line) => {
12877
13661
  this.callbacks.onStderrLine?.(line);
12878
13662
  },
12879
13663
  onExit: (code, signal) => {
13664
+ if (this.connectionGen !== connectGen)
13665
+ return;
12880
13666
  this.callbacks.onLog?.("warn", `Agent 进程已退出 (code: ${code}, signal: ${signal})`);
12881
13667
  if (this.status === "connected" || this.status === "connecting") {
12882
13668
  this.disconnect("Agent 进程异常终止");
@@ -12927,9 +13713,28 @@ class AcpClient {
12927
13713
  }
12928
13714
  });
12929
13715
  this.initResponse = initResp;
13716
+ if (this.resourcePrep) {
13717
+ const agentInfo = initResp?.agentInfo;
13718
+ const bridgeVersion = typeof agentInfo?.version === "string" ? agentInfo.version : undefined;
13719
+ const supported = isSupportedBridgeVersion(this.runtimeInfo.id, bridgeVersion).eligible && (this.adapter.supportedBridgeVersions?.includes(bridgeVersion?.replace(/^v/, "") ?? "") ?? false);
13720
+ this.resourcePrep.report.bridgeVersion = bridgeVersion;
13721
+ this.resourcePrep.report.bridgeSupported = supported;
13722
+ if (this.processHandle)
13723
+ this.processHandle.bridgeVersion = bridgeVersion;
13724
+ if (supported && this.resourcePrep.report.reason === "native-session-version-not-verified")
13725
+ delete this.resourcePrep.report.reason;
13726
+ if (!supported) {
13727
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "unsupported-bridge-version";
13728
+ }
13729
+ if (reuseDegraded) {
13730
+ this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "busy-deferred-stale-rules";
13731
+ }
13732
+ }
12930
13733
  this.setStatus("connected");
12931
13734
  return ok({ status: "connected", init: initResp });
12932
13735
  } catch (e) {
13736
+ if (connectGen !== this.connectionGen)
13737
+ return err({ code: "CANCELLED", message: "连接已被新请求取代" });
12933
13738
  const message = e instanceof Error ? e.message : String(e);
12934
13739
  this.setStatus("error", message);
12935
13740
  await this.disconnect(message);
@@ -12968,6 +13773,29 @@ class AcpClient {
12968
13773
  const resumeSupported = Boolean(init && parseResumeSessionSupported(init.agentCapabilities));
12969
13774
  const loadSupported = Boolean(init && parseLoadSessionSupported(init.agentCapabilities));
12970
13775
  try {
13776
+ let skillsExposed = "none";
13777
+ let mcpServers = options?.mcpServers ?? [];
13778
+ if (this.resourcesDir && this.attachSkillsMcp) {
13779
+ try {
13780
+ const descriptor = buildAppSkillsMcpServer(this.resourcesDir);
13781
+ const callerNames = new Set;
13782
+ for (const entry of mcpServers) {
13783
+ if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
13784
+ callerNames.add(entry.name);
13785
+ }
13786
+ }
13787
+ if (callerNames.has(descriptor.name)) {
13788
+ this.callbacks.onLog?.("warn", "调用方已有同名技能 MCP 服务,保留调用方版本", { name: descriptor.name });
13789
+ } else {
13790
+ mcpServers = [...mcpServers, descriptor];
13791
+ skillsExposed = "mcp-exposed";
13792
+ }
13793
+ } catch (error) {
13794
+ this.callbacks.onLog?.("warn", "技能 MCP 描述符构建失败,本次会话无技能 MCP", {
13795
+ error: error instanceof Error ? error.message : String(error)
13796
+ });
13797
+ }
13798
+ }
12971
13799
  const openResult = await restoreOrCreateAcpSession({
12972
13800
  request: async (method, params) => {
12973
13801
  return sdkRequest(agent, method, params);
@@ -12976,12 +13804,27 @@ class AcpClient {
12976
13804
  resumeSessionId: options?.resumeSessionId ?? null,
12977
13805
  resumeSupported,
12978
13806
  loadSupported,
12979
- mcpServers: options?.mcpServers ?? [],
13807
+ mcpServers,
13808
+ sessionMeta: (!this.sessionConfig || this.runtimeInfo.id === "agy") && this.resourcesDir && this.resourcePrep?.report.bridgeSupported ? this.adapter.appResourceSessionMeta?.(this.resourcesDir) : undefined,
12980
13809
  log: (level, msg, meta) => {
12981
13810
  this.callbacks.onLog?.(level, msg, meta);
12982
13811
  }
12983
13812
  });
12984
- const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions);
13813
+ if (!openResult.mcpServersAccepted)
13814
+ skillsExposed = "none";
13815
+ this.sessionLedger.set(openResult.sessionId, {
13816
+ restoreMethod: openResult.restoreMethod,
13817
+ gen: this.connectionGen,
13818
+ skillsExposed,
13819
+ nativeRules: openResult.nativeSessionAccepted
13820
+ });
13821
+ const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions, this.resourcePrep?.report ? {
13822
+ ...this.resourcePrep.report,
13823
+ skillsFound: [...this.resourcePrep.report.skillsFound],
13824
+ skillsExposed,
13825
+ rulesApplied: openResult.nativeSessionAccepted || !this.adapter.appResourceSessionMeta && openResult.restoreMethod === "new" && this.resourcePrep.report.bridgeSupported === true && this.resourcePrep.report.rulesPrepared === true,
13826
+ ...openResult.restoreMethod !== "new" && !openResult.nativeSessionAccepted ? { reason: "session-restored-not-verified" } : {}
13827
+ } : null);
12985
13828
  return ok(handle);
12986
13829
  } catch (e) {
12987
13830
  const message = e instanceof Error ? e.message : String(e);
@@ -12992,6 +13835,7 @@ class AcpClient {
12992
13835
  if (!this.sdkConnection?.agent) {
12993
13836
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
12994
13837
  }
13838
+ this.inflightPrompts.add(sessionId);
12995
13839
  try {
12996
13840
  const prompt = [{ type: "text", text: promptText }];
12997
13841
  for (const image of options?.images ?? []) {
@@ -12999,16 +13843,52 @@ class AcpClient {
12999
13843
  continue;
13000
13844
  prompt.push({ type: "image", mimeType: image.mimeType, data: image.data });
13001
13845
  }
13846
+ const compat = this.buildCompatPrepend(sessionId);
13847
+ const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
13002
13848
  const response = await sdkRequest(this.sdkConnection.agent, methods.agent.session.prompt, {
13003
13849
  sessionId,
13004
- prompt
13850
+ prompt: blocks
13005
13851
  }, options?.timeoutMs);
13006
13852
  return ok(response);
13007
13853
  } catch (e) {
13008
13854
  const message = e instanceof Error ? e.message : String(e);
13009
13855
  return err({ code: "ACP_PROTOCOL_ERROR", message });
13856
+ } finally {
13857
+ this.inflightPrompts.delete(sessionId);
13010
13858
  }
13011
13859
  }
13860
+ buildCompatPrepend(sessionId) {
13861
+ if (!this.resourcesDir)
13862
+ return null;
13863
+ if (this.sessionConfig?.nativeRules)
13864
+ return null;
13865
+ const entry = this.sessionLedger.get(sessionId);
13866
+ if (!entry)
13867
+ return null;
13868
+ const connReport = this.resourcePrep?.report;
13869
+ const nativelyDelivered = entry.nativeRules || !this.adapter.appResourceSessionMeta && entry.restoreMethod === "new" && entry.gen === this.connectionGen && connReport?.rulesPrepared === true && connReport?.bridgeSupported === true;
13870
+ if (nativelyDelivered)
13871
+ return null;
13872
+ const load = readAppResourcesDir(this.resourcesDir);
13873
+ const rulesText = readAppRulesText(this.resourcesDir);
13874
+ const digest = digestAppResources(load);
13875
+ const key = compatDeliveryKey(sessionId, this.connectionGen, digest);
13876
+ if (this.compatSentKeys.has(key))
13877
+ return null;
13878
+ const text = buildCompatGuideText({
13879
+ rulesText,
13880
+ skills: load.skills.map((s) => ({ name: s.name, description: s.description })),
13881
+ skillsViaMcp: entry.skillsExposed === "mcp-exposed",
13882
+ digest,
13883
+ sessionId,
13884
+ generation: this.connectionGen
13885
+ });
13886
+ if (!text)
13887
+ return null;
13888
+ this.compatSnapshots.set(key, { text, digest });
13889
+ this.compatSentKeys.add(key);
13890
+ return text;
13891
+ }
13012
13892
  async setSessionConfigOption(sessionId, configId, value) {
13013
13893
  if (!this.sdkConnection?.agent) {
13014
13894
  return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
@@ -13027,6 +13907,16 @@ class AcpClient {
13027
13907
  }
13028
13908
  async disconnect(reason) {
13029
13909
  this.setStatus("disconnected", reason);
13910
+ this.resourcePrep = null;
13911
+ const capabilities = this.initResponse?.agentCapabilities?.sessionCapabilities;
13912
+ if (capabilities?.close && this.sdkConnection?.agent) {
13913
+ const failed = await closeAcpSessions(this.sdkConnection.agent, this.sessionLedger.keys());
13914
+ if (failed.length)
13915
+ this.callbacks.onLog?.("warn", "Session close failed before process teardown", { count: failed.length });
13916
+ }
13917
+ this.sessionLedger.clear();
13918
+ this.compatSentKeys.clear();
13919
+ this.compatSnapshots.clear();
13030
13920
  try {
13031
13921
  this.streamHandle?.dispose();
13032
13922
  this.sdkConnection?.close();
@@ -13042,6 +13932,15 @@ class AcpClient {
13042
13932
  } catch {}
13043
13933
  this.processHandle = null;
13044
13934
  }
13935
+ const config = this.sessionConfig;
13936
+ this.sessionConfig = null;
13937
+ if (config) {
13938
+ try {
13939
+ await config.dispose();
13940
+ } catch {
13941
+ this.callbacks.onLog?.("warn", "Session configuration cleanup failed; directory retained", { directory: config.directory });
13942
+ }
13943
+ }
13045
13944
  }
13046
13945
  setStatus(status, detail) {
13047
13946
  this.status = status;