@yitom/acp-client 0.1.8 → 0.1.10

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.8";
39
+ var ACP_CLIENT_VERSION = "0.1.10";
40
40
  // src/contracts/index.ts
41
41
  function ok(value) {
42
42
  return { ok: true, value };
@@ -175,479 +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/resources/session-config.ts
179
- var import_node_fs2 = require("node:fs");
180
- var import_promises = require("node:fs/promises");
181
- var import_node_os = require("node:os");
182
- var import_node_path2 = require("node:path");
183
-
184
- // src/resources/app-resources.ts
185
- var import_node_crypto = require("node:crypto");
186
- var import_node_fs = require("node:fs");
187
- var import_node_path = require("node:path");
188
- var APP_RULES_FILE = "AGENTS.md";
189
- var APP_SKILLS_DIR = "skills";
190
- var APP_SKILL_FILE = "SKILL.md";
191
- function parseSkillFrontmatter(text) {
192
- const lines = text.split(`
193
- `);
194
- if (lines[0]?.trim() !== "---")
195
- return {};
196
- const out = {};
197
- for (let i = 1;i < lines.length; i += 1) {
198
- const line = lines[i] ?? "";
199
- if (line.trim() === "---")
200
- break;
201
- const cut = line.indexOf(":");
202
- if (cut <= 0)
203
- continue;
204
- const key = line.slice(0, cut).trim().toLowerCase();
205
- if (key !== "name" && key !== "description")
206
- continue;
207
- const value = line.slice(cut + 1).trim().replace(/^['"]|['"]$/g, "");
208
- if (value)
209
- out[key] = value;
210
- }
211
- return out;
212
- }
213
- function sha256Hex(text) {
214
- return import_node_crypto.createHash("sha256").update(text, "utf8").digest("hex");
215
- }
216
- function readTextFile(path) {
217
- try {
218
- if (!import_node_fs.statSync(path).isFile())
219
- return null;
220
- const text = import_node_fs.readFileSync(path, "utf8");
221
- return text.trim() ? text : null;
222
- } catch {
223
- return null;
224
- }
225
- }
226
- function readAppResourcesDir(directory) {
227
- const warnings = [];
228
- if (!import_node_path.isAbsolute(directory))
229
- return { directoryReadable: false, rules: null, skills: [], warnings: ["资源目录必须是本机绝对路径"] };
230
- let directoryReadable = false;
231
- try {
232
- directoryReadable = import_node_fs.statSync(directory).isDirectory();
233
- } catch {
234
- directoryReadable = false;
235
- }
236
- if (!directoryReadable) {
237
- return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
238
- }
239
- let rules = null;
240
- const rulesText = readTextFile(import_node_path.join(directory, APP_RULES_FILE));
241
- if (rulesText === null) {
242
- warnings.push(`缺常驻规则: ${APP_RULES_FILE}`);
243
- } else {
244
- rules = { chars: rulesText.length, digest: sha256Hex(`app-rules-v1
245
- ${rulesText}`) };
246
- }
247
- const skills = [];
248
- const skillsRoot = import_node_path.join(directory, APP_SKILLS_DIR);
249
- let skillNames = [];
250
- try {
251
- if (import_node_fs.statSync(skillsRoot).isDirectory()) {
252
- skillNames = import_node_fs.readdirSync(skillsRoot).filter((name) => {
253
- try {
254
- return import_node_fs.statSync(import_node_path.join(skillsRoot, name)).isDirectory();
255
- } catch {
256
- return false;
257
- }
258
- });
259
- }
260
- } catch {
261
- skillNames = [];
262
- }
263
- for (const name of skillNames.sort()) {
264
- const rel = `${APP_SKILLS_DIR}/${name}/${APP_SKILL_FILE}`;
265
- const text = readTextFile(import_node_path.join(directory, rel));
266
- if (text === null) {
267
- warnings.push(`技能缺正文已跳过: ${rel}`);
268
- continue;
269
- }
270
- const front = parseSkillFrontmatter(text);
271
- const skillName = front.name || name;
272
- if (skills.some((s) => s.name === skillName)) {
273
- warnings.push(`技能重名已跳过(保留首个): ${skillName}`);
274
- continue;
275
- }
276
- const description = front.description || "";
277
- skills.push({
278
- name: skillName,
279
- description,
280
- path: rel,
281
- chars: text.length,
282
- digest: sha256Hex(`app-skill-v1
283
- ${skillName}
284
- ${description}
285
- ${text}`)
286
- });
287
- }
288
- return { directoryReadable: true, rules, skills, warnings };
289
- }
290
- function digestAppResources(load) {
291
- if (!load.rules)
292
- return null;
293
- const skillPart = load.skills.map((s) => `${s.name}:${s.digest}`).join(`
294
- `);
295
- return sha256Hex(`app-resources-v1
296
- ${load.rules.digest}
297
- ${skillPart}`);
298
- }
299
- function readAppRulesText(directory) {
300
- return readTextFile(import_node_path.join(directory, APP_RULES_FILE));
301
- }
302
- function isAbsolutePathLike(path) {
303
- return import_node_path.isAbsolute(path);
304
- }
305
-
306
- // src/resources/session-config.ts
307
- async function createSessionConfigHome(runtime, resources) {
308
- if (!import_node_path2.isAbsolute(resources))
309
- throw new Error("Resources must be an absolute path");
310
- const id = runtime === "cursor" ? "cursor-cli" : runtime;
311
- const supported = ["agy", "codex-acp", "claude", "gemini", "copilot", "cursor-cli", "opencode", "opencode-v2"];
312
- if (!supported.includes(id))
313
- throw new Error("Session configuration home is not verified for runtime: " + runtime);
314
- const text = readAppRulesText(resources);
315
- if (!text)
316
- throw new Error("Session configuration requires nonempty AGENTS.md");
317
- const parent = import_node_path2.resolve(import_node_os.tmpdir());
318
- const directory = await import_promises.mkdtemp(import_node_path2.join(parent, "acp-session-config-"));
319
- const checkRoot = () => {
320
- if (import_node_path2.resolve(directory) === parent || !import_node_path2.resolve(directory).startsWith(parent + import_node_path2.sep) || !import_node_path2.relative(parent, directory).startsWith("acp-session-config-"))
321
- throw new Error("Unsafe configuration cleanup target");
322
- };
323
- const dispose = async () => {
324
- checkRoot();
325
- let failure;
326
- for (let i = 0;i < 30; i++) {
327
- try {
328
- await import_promises.rm(directory, { recursive: true, force: true });
329
- return;
330
- } catch (error) {
331
- failure = error;
332
- await new Promise((r) => setTimeout(r, 100));
333
- }
334
- }
335
- throw failure;
336
- };
337
- try {
338
- const config = import_node_path2.join(directory, "config");
339
- await import_promises.mkdir(config, { recursive: true, mode: 448 });
340
- let env;
341
- let rulesFile;
342
- let skillsRoot = import_node_path2.join(config, "skills");
343
- let nativeRules = true;
344
- if (id === "agy") {
345
- rulesFile = import_node_path2.join(config, "AGENTS.md");
346
- env = { AGY_ACP_RESOURCES_DIR: config };
347
- nativeRules = false;
348
- } else if (id === "gemini") {
349
- const root = import_node_path2.join(directory, "home", ".gemini");
350
- await import_promises.mkdir(root, { recursive: true, mode: 448 });
351
- rulesFile = import_node_path2.join(root, "GEMINI.md");
352
- skillsRoot = import_node_path2.join(root, "skills");
353
- env = { GEMINI_CLI_HOME: import_node_path2.join(directory, "home") };
354
- } else if (id === "claude") {
355
- rulesFile = import_node_path2.join(config, "CLAUDE.md");
356
- env = { CLAUDE_CONFIG_DIR: config };
357
- } else if (id === "codex-acp") {
358
- rulesFile = import_node_path2.join(config, "AGENTS.md");
359
- env = { CODEX_HOME: config };
360
- } else if (id === "copilot") {
361
- rulesFile = import_node_path2.join(config, "copilot-instructions.md");
362
- env = { COPILOT_HOME: config, COPILOT_CUSTOM_INSTRUCTIONS_DIRS: config, COPILOT_SKILLS_DIRS: skillsRoot };
363
- await import_promises.writeFile(import_node_path2.join(config, "AGENTS.md"), text, { mode: 384 });
364
- } else if (id === "cursor-cli") {
365
- rulesFile = import_node_path2.join(config, "AGENTS.md");
366
- env = { CURSOR_CONFIG_DIR: config };
367
- nativeRules = false;
368
- } else {
369
- const root = import_node_path2.join(directory, "xdg-config", "opencode");
370
- await import_promises.mkdir(root, { recursive: true, mode: 448 });
371
- rulesFile = import_node_path2.join(root, "AGENTS.md");
372
- skillsRoot = import_node_path2.join(root, "skills");
373
- env = { XDG_CONFIG_HOME: import_node_path2.join(directory, "xdg-config"), XDG_DATA_HOME: import_node_path2.join(directory, "xdg-data"), XDG_CACHE_HOME: import_node_path2.join(directory, "xdg-cache"), XDG_STATE_HOME: import_node_path2.join(directory, "xdg-state") };
374
- if (id === "opencode")
375
- env.OPENCODE_CONFIG_DIR = root;
376
- const skills = id === "opencode" ? { paths: [skillsRoot] } : [skillsRoot];
377
- await import_promises.writeFile(import_node_path2.join(root, "opencode.json"), JSON.stringify({ instructions: [rulesFile], skills }), { mode: 384 });
378
- }
379
- await import_promises.writeFile(rulesFile, text, { mode: 384 });
380
- const input = import_node_path2.join(resources, "skills");
381
- try {
382
- const info = await import_promises.lstat(input);
383
- if (info.isSymbolicLink() || !info.isDirectory())
384
- throw new Error("Skill root must be a regular directory");
385
- const physical = await import_promises.realpath(input);
386
- const copy = async (from, to) => {
387
- await import_promises.mkdir(to, { recursive: true, mode: 448 });
388
- for (const entry of await import_promises.readdir(from, { withFileTypes: true })) {
389
- const src = import_node_path2.join(from, entry.name);
390
- const info = await import_promises.lstat(src);
391
- if (info.isSymbolicLink())
392
- throw new Error("Skill symlink is not allowed");
393
- const actual = await import_promises.realpath(src);
394
- const rel = import_node_path2.relative(physical, actual);
395
- if (rel.startsWith(".." + import_node_path2.sep) || rel === ".." || import_node_path2.isAbsolute(rel))
396
- throw new Error("Skill path escapes resources");
397
- if (info.isDirectory())
398
- await copy(src, import_node_path2.join(to, entry.name));
399
- else if (info.isFile() && entry.name.toLowerCase().endsWith(".md"))
400
- await import_promises.writeFile(import_node_path2.join(to, entry.name), await import_promises.readFile(src), { mode: 384 });
401
- }
402
- };
403
- await copy(input, skillsRoot);
404
- } catch (error) {
405
- if (error.code !== "ENOENT" || import_node_fs2.existsSync(input))
406
- throw error;
407
- }
408
- return { directory, env, rulesFile, nativeRules, dispose };
409
- } catch (error) {
410
- await dispose();
411
- throw error;
412
- }
413
- }
414
-
415
- // src/session/available-commands.ts
416
- function normalizeCommand(raw) {
417
- if (!raw || typeof raw !== "object")
418
- return null;
419
- const r = raw;
420
- if (typeof r.name !== "string" || !r.name.trim())
421
- return null;
422
- const out = {
423
- name: r.name.trim(),
424
- description: typeof r.description === "string" ? r.description : ""
425
- };
426
- const input = r.input;
427
- if (input && typeof input === "object" && typeof input.hint === "string") {
428
- out.input = { hint: input.hint };
429
- }
430
- if (r._meta && typeof r._meta === "object")
431
- out._meta = r._meta;
432
- return out;
433
- }
434
- function extractAvailableCommands(params) {
435
- if (!params || typeof params !== "object")
436
- return null;
437
- const p = params;
438
- if (typeof p.sessionId !== "string" || !p.update)
439
- return null;
440
- if (p.update.sessionUpdate !== "available_commands_update")
441
- return null;
442
- const list = Array.isArray(p.update.availableCommands) ? p.update.availableCommands : [];
443
- const commands = list.map(normalizeCommand).filter((c) => c !== null);
444
- return { sessionId: p.sessionId, commands };
445
- }
446
- class AvailableCommandsCache {
447
- bySession = new Map;
448
- waiters = new Map;
449
- observe(params) {
450
- const hit = extractAvailableCommands(params);
451
- if (!hit)
452
- return false;
453
- this.bySession.set(hit.sessionId, hit.commands);
454
- const ws = this.waiters.get(hit.sessionId);
455
- if (ws) {
456
- this.waiters.delete(hit.sessionId);
457
- for (const w of ws)
458
- w(hit.commands);
459
- }
460
- return true;
461
- }
462
- get(sessionId) {
463
- return this.bySession.get(sessionId);
464
- }
465
- wait(sessionId, timeoutMs = 150) {
466
- const cur = this.bySession.get(sessionId);
467
- if (cur || timeoutMs <= 0)
468
- return Promise.resolve(cur);
469
- return new Promise((resolve) => {
470
- const done = (c) => {
471
- clearTimeout(timer);
472
- const list = this.waiters.get(sessionId);
473
- if (list) {
474
- const i = list.indexOf(fn);
475
- if (i >= 0)
476
- list.splice(i, 1);
477
- if (list.length === 0)
478
- this.waiters.delete(sessionId);
479
- }
480
- resolve(c);
481
- };
482
- const fn = (c) => done(c);
483
- const timer = setTimeout(() => done(undefined), timeoutMs);
484
- const list = this.waiters.get(sessionId) ?? [];
485
- list.push(fn);
486
- this.waiters.set(sessionId, list);
487
- });
488
- }
489
- delete(sessionId) {
490
- this.bySession.delete(sessionId);
491
- }
492
- clear() {
493
- this.bySession.clear();
494
- }
495
- }
496
-
497
- // src/session/quota.ts
498
- function parseRateLimitsFromStatusText(text, runtimeId = "unknown") {
499
- if (!text || typeof text !== "string")
500
- return null;
501
- const lines = text.split(/\r?\n/);
502
- let account;
503
- const windows = [];
504
- let credits;
505
- let status = "ok";
506
- let message;
507
- if (/account (?:disabled|banned|suspended)|suspended|banned/i.test(text)) {
508
- status = "banned";
509
- message = "账号已封禁或暂停使用 (Account banned / suspended)";
510
- } else if (/RESOURCE_EXHAUSTED|quota reached|rate limit exceeded|429/i.test(text)) {
511
- status = "exhausted";
512
- message = "额度已用尽 (Quota / Rate limit reached)";
513
- } else if (/unauthorized|authentication failed|invalid api key/i.test(text)) {
514
- status = "unauthorized";
515
- message = "认证失效 (Unauthorized / Invalid credentials)";
516
- }
517
- for (const rawLine of lines) {
518
- const line = rawLine.replace(/\*\*/g, "").trim();
519
- if (!line)
520
- continue;
521
- const accMatch = line.match(/^Account\s*[::]\s*([^()]+?)(?:\s*\(([^)]+)\))?$/i);
522
- if (accMatch) {
523
- account = {
524
- plan: accMatch[1].trim(),
525
- email: accMatch[2]?.trim()
526
- };
527
- continue;
528
- }
529
- const credMatch = line.match(/(?:\b|^)(?:[\w\s-]*?credits?)\s*[::]\s*(unlimited|[\d.]+)/i);
530
- if (credMatch) {
531
- const val = credMatch[1].trim();
532
- credits = val.toLowerCase() === "unlimited" ? { unlimited: true, balance: "unlimited" } : { balance: Number(val) || val, unlimited: false };
533
- continue;
534
- }
535
- 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);
536
- if (winMatch) {
537
- const label = winMatch[1].trim();
538
- const pct = parseFloat(winMatch[2]);
539
- const resetsAt = (winMatch[3] || winMatch[4] || "").trim() || undefined;
540
- let windowDurationMins;
541
- const lower = label.toLowerCase();
542
- if (/5h|5-hour/i.test(lower))
543
- windowDurationMins = 300;
544
- else if (/week/i.test(lower))
545
- windowDurationMins = 10080;
546
- else if (/month/i.test(lower))
547
- windowDurationMins = 43200;
548
- else if (/day|24h/i.test(lower))
549
- windowDurationMins = 1440;
550
- else if (/(\d+)\s*h/i.test(lower)) {
551
- const m = lower.match(/(\d+)\s*h/);
552
- if (m)
553
- windowDurationMins = parseInt(m[1], 10) * 60;
554
- }
555
- windows.push({
556
- label,
557
- percentLeft: pct,
558
- usedPercent: Math.max(0, 100 - pct),
559
- resetsAt,
560
- windowDurationMins
561
- });
562
- continue;
563
- }
564
- const fastMatch = line.match(/(?:fast requests?|requests?)\s*[::]\s*(\d+)\s*\/\s*(\d+)/i);
565
- if (fastMatch) {
566
- const used = parseInt(fastMatch[1], 10);
567
- const total = parseInt(fastMatch[2], 10);
568
- const left = Math.max(0, total - used);
569
- const pct = total > 0 ? Math.round(left / total * 100) : 0;
570
- windows.push({
571
- label: "Fast requests",
572
- percentLeft: pct,
573
- usedPercent: total > 0 ? Math.round(used / total * 100) : 0,
574
- used,
575
- total
576
- });
577
- continue;
578
- }
579
- }
580
- if (!windows.length && !credits && !account && status === "ok") {
581
- return null;
582
- }
583
- const primary = windows.find((w) => /5h|5-hour|hour|primary|fast/i.test(w.label)) || windows[0];
584
- const secondary = windows.find((w) => w !== primary && /week|month|secondary/i.test(w.label)) || windows.find((w) => w !== primary);
585
- const extraWindows = windows.filter((w) => w !== primary && w !== secondary);
586
- if (primary && primary.percentLeft <= 10 && status === "ok") {
587
- status = "warning";
588
- }
589
- return {
590
- runtimeId,
591
- account,
592
- primaryWindow: primary,
593
- secondaryWindow: secondary,
594
- extraWindows: extraWindows.length ? extraWindows : undefined,
595
- credits,
596
- status,
597
- message,
598
- rawText: text,
599
- updatedAt: Date.now()
600
- };
601
- }
602
-
603
- class QuotaCache {
604
- bySession = new Map;
605
- byRuntime = new Map;
606
- observe(params, defaultRuntimeId = "unknown") {
607
- if (!params || typeof params !== "object")
608
- return null;
609
- const p = params;
610
- const sessionId = typeof p.sessionId === "string" ? p.sessionId : undefined;
611
- let textToParse = "";
612
- if (p.update?.content && p.update.content.type === "text" && typeof p.update.content.text === "string") {
613
- textToParse = p.update.content.text;
614
- } else if (p.update?.message?.content && Array.isArray(p.update.message.content)) {
615
- textToParse = p.update.message.content.filter((c) => c && c.type === "text" && typeof c.text === "string").map((c) => c.text).join(`
616
- `);
617
- }
618
- if (!textToParse)
619
- return null;
620
- if (!/(?:limit|credits?|Account:|5h|resets|banned|suspended|quota)/i.test(textToParse)) {
621
- return null;
622
- }
623
- const quota = parseRateLimitsFromStatusText(textToParse, defaultRuntimeId);
624
- if (quota) {
625
- if (sessionId)
626
- this.bySession.set(sessionId, quota);
627
- this.byRuntime.set(defaultRuntimeId, quota);
628
- return quota;
629
- }
630
- return null;
631
- }
632
- set(quota, sessionId) {
633
- if (sessionId)
634
- this.bySession.set(sessionId, quota);
635
- this.byRuntime.set(quota.runtimeId, quota);
636
- }
637
- get(sessionId, runtimeId) {
638
- if (sessionId && this.bySession.has(sessionId)) {
639
- return this.bySession.get(sessionId);
640
- }
641
- if (runtimeId && this.byRuntime.has(runtimeId)) {
642
- return this.byRuntime.get(runtimeId);
643
- }
644
- return;
645
- }
646
- clear() {
647
- this.bySession.clear();
648
- this.byRuntime.clear();
649
- }
650
- }
178
+ // src/client/sdk-client.ts
179
+ var import_node_stream = require("node:stream");
651
180
 
652
181
  // node_modules/@agentclientprotocol/sdk/dist/schema/index.js
653
182
  var AGENT_METHODS = {
@@ -9883,656 +9412,1204 @@ var methods = {
9883
9412
  didSave: AGENT_METHODS.document_did_save,
9884
9413
  didFocus: AGENT_METHODS.document_did_focus
9885
9414
  }
9886
- },
9887
- client: {
9888
- session: {
9889
- requestPermission: CLIENT_METHODS.session_request_permission,
9890
- update: CLIENT_METHODS.session_update
9891
- },
9892
- fs: {
9893
- writeTextFile: CLIENT_METHODS.fs_write_text_file,
9894
- readTextFile: CLIENT_METHODS.fs_read_text_file
9895
- },
9896
- terminal: {
9897
- create: CLIENT_METHODS.terminal_create,
9898
- output: CLIENT_METHODS.terminal_output,
9899
- release: CLIENT_METHODS.terminal_release,
9900
- waitForExit: CLIENT_METHODS.terminal_wait_for_exit,
9901
- kill: CLIENT_METHODS.terminal_kill
9902
- },
9903
- elicitation: {
9904
- create: CLIENT_METHODS.elicitation_create,
9905
- complete: CLIENT_METHODS.elicitation_complete
9415
+ },
9416
+ client: {
9417
+ session: {
9418
+ requestPermission: CLIENT_METHODS.session_request_permission,
9419
+ update: CLIENT_METHODS.session_update
9420
+ },
9421
+ fs: {
9422
+ writeTextFile: CLIENT_METHODS.fs_write_text_file,
9423
+ readTextFile: CLIENT_METHODS.fs_read_text_file
9424
+ },
9425
+ terminal: {
9426
+ create: CLIENT_METHODS.terminal_create,
9427
+ output: CLIENT_METHODS.terminal_output,
9428
+ release: CLIENT_METHODS.terminal_release,
9429
+ waitForExit: CLIENT_METHODS.terminal_wait_for_exit,
9430
+ kill: CLIENT_METHODS.terminal_kill
9431
+ },
9432
+ elicitation: {
9433
+ create: CLIENT_METHODS.elicitation_create,
9434
+ complete: CLIENT_METHODS.elicitation_complete
9435
+ }
9436
+ },
9437
+ protocol: {
9438
+ cancelRequest: PROTOCOL_METHODS.cancel_request
9439
+ }
9440
+ };
9441
+ var startActiveSession = Symbol("startActiveSession");
9442
+
9443
+ class AcpContext {
9444
+ cx;
9445
+ currentRequestId;
9446
+ constructor(cx, currentRequestId) {
9447
+ this.cx = cx;
9448
+ this.currentRequestId = currentRequestId;
9449
+ }
9450
+ get requestId() {
9451
+ return this.currentRequestId;
9452
+ }
9453
+ get connectionContext() {
9454
+ return this.cx;
9455
+ }
9456
+ sendRequest(method, params, mapResponse, options) {
9457
+ return this.cx.sendRequest(method, params, mapResponse, options);
9458
+ }
9459
+ sendNotification(method, params) {
9460
+ return this.cx.sendNotification(method, params);
9461
+ }
9462
+ addDynamicHandler(handler) {
9463
+ return this.cx.addDynamicHandler(handler);
9464
+ }
9465
+ }
9466
+
9467
+ class AgentContext extends AcpContext {
9468
+ constructor(cx, requestId) {
9469
+ super(cx, requestId);
9470
+ }
9471
+ static create(cx, requestId) {
9472
+ return new AgentContext(cx, requestId);
9473
+ }
9474
+ request(method, params, options) {
9475
+ const spec = clientRequestSpecsByMethod[method];
9476
+ return this.sendRequest(method, params, spec?.mapResponse, options);
9477
+ }
9478
+ notify(method, params) {
9479
+ return this.sendNotification(method, params);
9480
+ }
9481
+ }
9482
+
9483
+ class ClientContext extends AcpContext {
9484
+ constructor(cx, requestId) {
9485
+ super(cx, requestId);
9486
+ }
9487
+ static create(cx, requestId) {
9488
+ return new ClientContext(cx, requestId);
9489
+ }
9490
+ [startActiveSession](params, options) {
9491
+ return this.sendRequest(AGENT_METHODS.session_new, params, (response) => this.attachSession(response), options);
9492
+ }
9493
+ buildSession(cwdOrRequest) {
9494
+ if (typeof cwdOrRequest === "string") {
9495
+ return SessionBuilder.create(this, {
9496
+ cwd: cwdOrRequest,
9497
+ mcpServers: []
9498
+ });
9499
+ }
9500
+ return SessionBuilder.create(this, cwdOrRequest);
9501
+ }
9502
+ attachSession(response) {
9503
+ const updates = new AsyncQueue;
9504
+ const closeSignal = this.connectionContext.signal;
9505
+ const failUpdatesOnClose = () => {
9506
+ updates.fail(closeSignal.reason ?? new Error("ACP connection closed"));
9507
+ };
9508
+ if (closeSignal.aborted) {
9509
+ failUpdatesOnClose();
9510
+ } else {
9511
+ closeSignal.addEventListener("abort", failUpdatesOnClose);
9512
+ }
9513
+ const sessionRegistration = sessionUpdateRouter(this.connectionContext).attach(response, updates);
9514
+ const closeRegistration = new HandlerRegistration(() => {
9515
+ closeSignal.removeEventListener("abort", failUpdatesOnClose);
9516
+ });
9517
+ return ActiveSession.create(this, response, updates, [
9518
+ sessionRegistration,
9519
+ closeRegistration
9520
+ ]);
9521
+ }
9522
+ request(method, params, options) {
9523
+ const spec = agentRequestSpecsByMethod[method];
9524
+ return this.sendRequest(method, params, spec?.mapResponse, options);
9525
+ }
9526
+ notify(method, params) {
9527
+ return this.sendNotification(method, params);
9528
+ }
9529
+ }
9530
+
9531
+ class AcpConnectionHandle {
9532
+ connection;
9533
+ constructor(connection) {
9534
+ this.connection = connection;
9535
+ }
9536
+ get signal() {
9537
+ return this.connection.signal;
9538
+ }
9539
+ get closed() {
9540
+ return this.connection.closed;
9541
+ }
9542
+ close(error) {
9543
+ this.connection.close(error);
9544
+ }
9545
+ }
9546
+
9547
+ class AgentConnectionHandle extends AcpConnectionHandle {
9548
+ connectHandlers;
9549
+ client;
9550
+ didStartConnectHandlers = false;
9551
+ constructor(connection, connectHandlers = []) {
9552
+ super(connection);
9553
+ this.connectHandlers = connectHandlers;
9554
+ this.client = AgentContext.create(connection.getContext());
9555
+ }
9556
+ startConnectHandlers() {
9557
+ if (this.didStartConnectHandlers) {
9558
+ return;
9559
+ }
9560
+ this.didStartConnectHandlers = true;
9561
+ runConnectHandlers(this, this.connectHandlers);
9562
+ }
9563
+ }
9564
+
9565
+ class ClientConnectionHandle extends AcpConnectionHandle {
9566
+ connectHandlers;
9567
+ agent;
9568
+ didStartConnectHandlers = false;
9569
+ constructor(connection, connectHandlers = []) {
9570
+ super(connection);
9571
+ this.connectHandlers = connectHandlers;
9572
+ this.agent = ClientContext.create(connection.getContext());
9573
+ }
9574
+ startConnectHandlers() {
9575
+ if (this.didStartConnectHandlers) {
9576
+ return;
9577
+ }
9578
+ this.didStartConnectHandlers = true;
9579
+ runConnectHandlers(this, this.connectHandlers);
9580
+ }
9581
+ }
9582
+ function agentConnection(connection, connectHandlers = []) {
9583
+ return new AgentConnectionHandle(connection, connectHandlers);
9584
+ }
9585
+ function clientConnection(connection, connectHandlers = []) {
9586
+ return new ClientConnectionHandle(connection, connectHandlers);
9587
+ }
9588
+
9589
+ class AsyncQueue {
9590
+ values = [];
9591
+ waiters = [];
9592
+ failed = false;
9593
+ failure;
9594
+ enqueue(value) {
9595
+ if (this.failed) {
9596
+ return;
9597
+ }
9598
+ const waiter = this.waiters.shift();
9599
+ if (waiter) {
9600
+ waiter.resolve(value);
9601
+ } else {
9602
+ this.values.push({ kind: "value", value });
9603
+ }
9604
+ }
9605
+ reject(error) {
9606
+ if (this.failed) {
9607
+ return;
9608
+ }
9609
+ if (this.waiters.length > 0) {
9610
+ for (const waiter of this.waiters.splice(0)) {
9611
+ waiter.reject(error);
9612
+ }
9613
+ return;
9906
9614
  }
9907
- },
9908
- protocol: {
9909
- cancelRequest: PROTOCOL_METHODS.cancel_request
9615
+ this.values.push({ kind: "error", error });
9910
9616
  }
9911
- };
9912
- var startActiveSession = Symbol("startActiveSession");
9617
+ clearErrors() {
9618
+ this.values = this.values.filter((entry) => entry.kind === "value");
9619
+ }
9620
+ fail(error) {
9621
+ if (this.failed) {
9622
+ return;
9623
+ }
9624
+ this.failed = true;
9625
+ this.failure = error;
9626
+ for (const waiter of this.waiters.splice(0)) {
9627
+ waiter.reject(error);
9628
+ }
9629
+ }
9630
+ next() {
9631
+ if (this.values.length > 0) {
9632
+ const entry = this.values.shift();
9633
+ if (entry.kind === "error") {
9634
+ return Promise.reject(entry.error);
9635
+ }
9636
+ return Promise.resolve(entry.value);
9637
+ }
9638
+ if (this.failed) {
9639
+ return Promise.reject(this.failure);
9640
+ }
9641
+ return new Promise((resolve, reject) => {
9642
+ this.waiters.push({ resolve, reject });
9643
+ });
9644
+ }
9645
+ }
9646
+ function cloneNewSessionRequest(request) {
9647
+ return {
9648
+ ...request,
9649
+ additionalDirectories: request.additionalDirectories ? [...request.additionalDirectories] : undefined,
9650
+ mcpServers: [...request.mcpServers]
9651
+ };
9652
+ }
9913
9653
 
9914
- class AcpContext {
9654
+ class SessionBuilder {
9915
9655
  cx;
9916
- currentRequestId;
9917
- constructor(cx, currentRequestId) {
9656
+ request;
9657
+ constructor(cx, request) {
9918
9658
  this.cx = cx;
9919
- this.currentRequestId = currentRequestId;
9659
+ this.request = cloneNewSessionRequest(request);
9920
9660
  }
9921
- get requestId() {
9922
- return this.currentRequestId;
9661
+ static create(cx, request) {
9662
+ return new SessionBuilder(cx, request);
9923
9663
  }
9924
- get connectionContext() {
9925
- return this.cx;
9664
+ toRequest() {
9665
+ return cloneNewSessionRequest(this.request);
9926
9666
  }
9927
- sendRequest(method, params, mapResponse, options) {
9928
- return this.cx.sendRequest(method, params, mapResponse, options);
9667
+ withAdditionalDirectories(additionalDirectories) {
9668
+ this.request = {
9669
+ ...this.request,
9670
+ additionalDirectories: [...additionalDirectories]
9671
+ };
9672
+ return this;
9929
9673
  }
9930
- sendNotification(method, params) {
9931
- return this.cx.sendNotification(method, params);
9674
+ withMcpServer(mcpServer) {
9675
+ this.request = {
9676
+ ...this.request,
9677
+ mcpServers: [...this.request.mcpServers, mcpServer]
9678
+ };
9679
+ return this;
9932
9680
  }
9933
- addDynamicHandler(handler) {
9934
- return this.cx.addDynamicHandler(handler);
9681
+ async start(options) {
9682
+ return this.cx[startActiveSession](this.toRequest(), options);
9683
+ }
9684
+ async withSession(op) {
9685
+ const session = await this.start();
9686
+ try {
9687
+ return await op(session);
9688
+ } finally {
9689
+ session.dispose();
9690
+ }
9691
+ }
9692
+ }
9693
+
9694
+ class ActiveSession {
9695
+ cx;
9696
+ sessionResponse;
9697
+ updates;
9698
+ registrations;
9699
+ constructor(cx, sessionResponse, updates, registrations) {
9700
+ this.cx = cx;
9701
+ this.sessionResponse = sessionResponse;
9702
+ this.updates = updates;
9703
+ this.registrations = registrations;
9704
+ }
9705
+ static create(cx, sessionResponse, updates, registrations) {
9706
+ return new ActiveSession(cx, sessionResponse, updates, registrations);
9707
+ }
9708
+ get sessionId() {
9709
+ return this.sessionResponse.sessionId;
9710
+ }
9711
+ get modes() {
9712
+ return this.sessionResponse.modes;
9713
+ }
9714
+ get meta() {
9715
+ return this.sessionResponse._meta;
9716
+ }
9717
+ get newSessionResponse() {
9718
+ return this.sessionResponse;
9719
+ }
9720
+ prompt(prompt, options) {
9721
+ this.updates.clearErrors();
9722
+ const response = this.cx.request(AGENT_METHODS.session_prompt, {
9723
+ sessionId: this.sessionId,
9724
+ prompt: this.promptBlocks(prompt)
9725
+ }, options);
9726
+ response.then((value) => {
9727
+ this.updates.enqueue({
9728
+ kind: "stop",
9729
+ response: value,
9730
+ stopReason: value.stopReason
9731
+ });
9732
+ }, (error) => {
9733
+ this.updates.reject(error);
9734
+ });
9735
+ return response;
9736
+ }
9737
+ nextUpdate() {
9738
+ return this.updates.next();
9739
+ }
9740
+ async readText() {
9741
+ let output = "";
9742
+ for (;; ) {
9743
+ const message = await this.nextUpdate();
9744
+ if (message.kind === "stop") {
9745
+ return output;
9746
+ }
9747
+ const { update } = message;
9748
+ if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") {
9749
+ output += update.content.text;
9750
+ }
9751
+ }
9752
+ }
9753
+ dispose() {
9754
+ for (const registration of this.registrations.splice(0)) {
9755
+ registration.dispose();
9756
+ }
9757
+ this.updates.fail(new Error("Active session disposed"));
9758
+ }
9759
+ [Symbol.dispose]() {
9760
+ this.dispose();
9761
+ }
9762
+ promptBlocks(prompt) {
9763
+ if (typeof prompt === "string") {
9764
+ return [{ type: "text", text: prompt }];
9765
+ }
9766
+ if (Array.isArray(prompt)) {
9767
+ return prompt;
9768
+ }
9769
+ return [prompt];
9770
+ }
9771
+ }
9772
+ function parseParams(parser, params) {
9773
+ if (!parser) {
9774
+ return params;
9775
+ }
9776
+ if (typeof parser === "function") {
9777
+ return parser(params);
9778
+ }
9779
+ return parser.parse(params);
9780
+ }
9781
+ function requestSpec(method, params, mapResponse) {
9782
+ return { method, params, mapResponse };
9783
+ }
9784
+ function notificationSpec(method, params) {
9785
+ return { method, params };
9786
+ }
9787
+ function registerAppRequest(builder, spec, context, handler) {
9788
+ builder.onReceiveRequest(spec.method, (params) => parseParams(spec.params, params), async (params, responder, cx) => {
9789
+ const response = await handler(context(params, cx, responder.signal, responder.id));
9790
+ await responder.respond(spec.mapResponse ? spec.mapResponse(response) : response);
9791
+ });
9792
+ }
9793
+ function registerAppNotification(builder, spec, context, handler) {
9794
+ builder.onReceiveNotification(spec.method, (params) => parseParams(spec.params, params), (params, cx) => handler(context(params, cx, cx.signal)));
9795
+ }
9796
+ function specsByMethod(specs) {
9797
+ const byMethod = {};
9798
+ for (const spec of Object.values(specs)) {
9799
+ byMethod[spec.method] = spec;
9935
9800
  }
9801
+ return byMethod;
9802
+ }
9803
+ var agentRequestSpecs = {
9804
+ initialize: requestSpec(AGENT_METHODS.initialize, zInitializeRequest),
9805
+ newSession: requestSpec(AGENT_METHODS.session_new, zNewSessionRequest),
9806
+ loadSession: requestSpec(AGENT_METHODS.session_load, zLoadSessionRequest, emptyObjectResponse),
9807
+ unstable_forkSession: requestSpec(AGENT_METHODS.session_fork, zForkSessionRequest),
9808
+ listSessions: requestSpec(AGENT_METHODS.session_list, zListSessionsRequest),
9809
+ deleteSession: requestSpec(AGENT_METHODS.session_delete, zDeleteSessionRequest, emptyObjectResponse),
9810
+ resumeSession: requestSpec(AGENT_METHODS.session_resume, zResumeSessionRequest),
9811
+ closeSession: requestSpec(AGENT_METHODS.session_close, zCloseSessionRequest, emptyObjectResponse),
9812
+ setSessionMode: requestSpec(AGENT_METHODS.session_set_mode, zSetSessionModeRequest, emptyObjectResponse),
9813
+ setSessionConfigOption: requestSpec(AGENT_METHODS.session_set_config_option, zSetSessionConfigOptionRequest),
9814
+ authenticate: requestSpec(AGENT_METHODS.authenticate, zAuthenticateRequest, emptyObjectResponse),
9815
+ unstable_listProviders: requestSpec(AGENT_METHODS.providers_list, zListProvidersRequest),
9816
+ unstable_setProvider: requestSpec(AGENT_METHODS.providers_set, zSetProviderRequest, emptyObjectResponse),
9817
+ unstable_disableProvider: requestSpec(AGENT_METHODS.providers_disable, zDisableProviderRequest, emptyObjectResponse),
9818
+ logout: requestSpec(AGENT_METHODS.logout, zLogoutRequest, emptyObjectResponse),
9819
+ prompt: requestSpec(AGENT_METHODS.session_prompt, zPromptRequest),
9820
+ unstable_startNes: requestSpec(AGENT_METHODS.nes_start, zStartNesRequest),
9821
+ unstable_suggestNes: requestSpec(AGENT_METHODS.nes_suggest, zSuggestNesRequest),
9822
+ unstable_closeNes: requestSpec(AGENT_METHODS.nes_close, zCloseNesRequest, emptyObjectResponse)
9823
+ };
9824
+ var agentNotificationSpecs = {
9825
+ cancel: notificationSpec(AGENT_METHODS.session_cancel, zCancelNotification),
9826
+ unstable_didOpenDocument: notificationSpec(AGENT_METHODS.document_did_open, zDidOpenDocumentNotification),
9827
+ unstable_didChangeDocument: notificationSpec(AGENT_METHODS.document_did_change, zDidChangeDocumentNotification),
9828
+ unstable_didCloseDocument: notificationSpec(AGENT_METHODS.document_did_close, zDidCloseDocumentNotification),
9829
+ unstable_didSaveDocument: notificationSpec(AGENT_METHODS.document_did_save, zDidSaveDocumentNotification),
9830
+ unstable_didFocusDocument: notificationSpec(AGENT_METHODS.document_did_focus, zDidFocusDocumentNotification),
9831
+ unstable_acceptNes: notificationSpec(AGENT_METHODS.nes_accept, zAcceptNesNotification),
9832
+ unstable_rejectNes: notificationSpec(AGENT_METHODS.nes_reject, zRejectNesNotification)
9833
+ };
9834
+ var clientRequestSpecs = {
9835
+ requestPermission: requestSpec(CLIENT_METHODS.session_request_permission, zRequestPermissionRequest),
9836
+ writeTextFile: requestSpec(CLIENT_METHODS.fs_write_text_file, zWriteTextFileRequest, emptyObjectResponse),
9837
+ readTextFile: requestSpec(CLIENT_METHODS.fs_read_text_file, zReadTextFileRequest),
9838
+ createTerminal: requestSpec(CLIENT_METHODS.terminal_create, zCreateTerminalRequest),
9839
+ terminalOutput: requestSpec(CLIENT_METHODS.terminal_output, zTerminalOutputRequest),
9840
+ releaseTerminal: requestSpec(CLIENT_METHODS.terminal_release, zReleaseTerminalRequest, emptyObjectResponse),
9841
+ waitForTerminalExit: requestSpec(CLIENT_METHODS.terminal_wait_for_exit, zWaitForTerminalExitRequest),
9842
+ killTerminal: requestSpec(CLIENT_METHODS.terminal_kill, zKillTerminalRequest, emptyObjectResponse),
9843
+ createElicitation: requestSpec(CLIENT_METHODS.elicitation_create, zCreateElicitationRequest)
9844
+ };
9845
+ var clientNotificationSpecs = {
9846
+ sessionUpdate: notificationSpec(CLIENT_METHODS.session_update, zSessionNotification),
9847
+ completeElicitation: notificationSpec(CLIENT_METHODS.elicitation_complete, zCompleteElicitationNotification)
9848
+ };
9849
+ var agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs);
9850
+ var agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs);
9851
+ var clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs);
9852
+ var clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs);
9853
+ function clientRequestContext(params, agent, signal, requestId) {
9854
+ return {
9855
+ params,
9856
+ requestId,
9857
+ signal,
9858
+ agent
9859
+ };
9936
9860
  }
9937
-
9938
- class AgentContext extends AcpContext {
9939
- constructor(cx, requestId) {
9940
- super(cx, requestId);
9941
- }
9942
- static create(cx, requestId) {
9943
- return new AgentContext(cx, requestId);
9944
- }
9945
- request(method, params, options) {
9946
- const spec = clientRequestSpecsByMethod[method];
9947
- return this.sendRequest(method, params, spec?.mapResponse, options);
9948
- }
9949
- notify(method, params) {
9950
- return this.sendNotification(method, params);
9951
- }
9861
+ function clientNotificationContext(params, agent, signal) {
9862
+ return {
9863
+ params,
9864
+ signal,
9865
+ agent
9866
+ };
9952
9867
  }
9953
9868
 
9954
- class ClientContext extends AcpContext {
9955
- constructor(cx, requestId) {
9956
- super(cx, requestId);
9957
- }
9958
- static create(cx, requestId) {
9959
- return new ClientContext(cx, requestId);
9960
- }
9961
- [startActiveSession](params, options) {
9962
- return this.sendRequest(AGENT_METHODS.session_new, params, (response) => this.attachSession(response), options);
9963
- }
9964
- buildSession(cwdOrRequest) {
9965
- if (typeof cwdOrRequest === "string") {
9966
- return SessionBuilder.create(this, {
9967
- cwd: cwdOrRequest,
9968
- mcpServers: []
9969
- });
9869
+ class SessionUpdateRouter {
9870
+ activeSessions = new Map;
9871
+ handleMessage(message) {
9872
+ if (message.kind !== "notification" || message.method !== CLIENT_METHODS.session_update) {
9873
+ return Handled.no(message);
9970
9874
  }
9971
- return SessionBuilder.create(this, cwdOrRequest);
9972
- }
9973
- attachSession(response) {
9974
- const updates = new AsyncQueue;
9975
- const closeSignal = this.connectionContext.signal;
9976
- const failUpdatesOnClose = () => {
9977
- updates.fail(closeSignal.reason ?? new Error("ACP connection closed"));
9875
+ const notification = zSessionNotification.parse(message.params);
9876
+ const update = {
9877
+ kind: "session_update",
9878
+ notification,
9879
+ update: notification.update
9978
9880
  };
9979
- if (closeSignal.aborted) {
9980
- failUpdatesOnClose();
9981
- } else {
9982
- closeSignal.addEventListener("abort", failUpdatesOnClose);
9881
+ const activeSessions = this.activeSessions.get(notification.sessionId);
9882
+ if (activeSessions && activeSessions.size > 0) {
9883
+ for (const session of activeSessions) {
9884
+ session.enqueue(update);
9885
+ }
9983
9886
  }
9984
- const sessionRegistration = sessionUpdateRouter(this.connectionContext).attach(response, updates);
9985
- const closeRegistration = new HandlerRegistration(() => {
9986
- closeSignal.removeEventListener("abort", failUpdatesOnClose);
9987
- });
9988
- return ActiveSession.create(this, response, updates, [
9989
- sessionRegistration,
9990
- closeRegistration
9991
- ]);
9992
- }
9993
- request(method, params, options) {
9994
- const spec = agentRequestSpecsByMethod[method];
9995
- return this.sendRequest(method, params, spec?.mapResponse, options);
9996
- }
9997
- notify(method, params) {
9998
- return this.sendNotification(method, params);
9999
- }
10000
- }
10001
-
10002
- class AcpConnectionHandle {
10003
- connection;
10004
- constructor(connection) {
10005
- this.connection = connection;
10006
- }
10007
- get signal() {
10008
- return this.connection.signal;
10009
- }
10010
- get closed() {
10011
- return this.connection.closed;
9887
+ return Handled.no(message);
10012
9888
  }
10013
- close(error) {
10014
- this.connection.close(error);
9889
+ attach(response, updates) {
9890
+ const sessions = this.activeSessions.get(response.sessionId) ?? new Set;
9891
+ sessions.add(updates);
9892
+ this.activeSessions.set(response.sessionId, sessions);
9893
+ return new HandlerRegistration(() => {
9894
+ sessions.delete(updates);
9895
+ if (sessions.size === 0) {
9896
+ this.activeSessions.delete(response.sessionId);
9897
+ }
9898
+ });
10015
9899
  }
10016
9900
  }
10017
-
10018
- class AgentConnectionHandle extends AcpConnectionHandle {
10019
- connectHandlers;
10020
- client;
10021
- didStartConnectHandlers = false;
10022
- constructor(connection, connectHandlers = []) {
10023
- super(connection);
10024
- this.connectHandlers = connectHandlers;
10025
- this.client = AgentContext.create(connection.getContext());
10026
- }
10027
- startConnectHandlers() {
10028
- if (this.didStartConnectHandlers) {
10029
- return;
10030
- }
10031
- this.didStartConnectHandlers = true;
10032
- runConnectHandlers(this, this.connectHandlers);
9901
+ var sessionUpdateRouters = new WeakMap;
9902
+ function sessionUpdateRouter(cx) {
9903
+ let router = sessionUpdateRouters.get(cx);
9904
+ if (!router) {
9905
+ router = new SessionUpdateRouter;
9906
+ sessionUpdateRouters.set(cx, router);
10033
9907
  }
9908
+ return router;
10034
9909
  }
10035
-
10036
- class ClientConnectionHandle extends AcpConnectionHandle {
10037
- connectHandlers;
10038
- agent;
10039
- didStartConnectHandlers = false;
10040
- constructor(connection, connectHandlers = []) {
10041
- super(connection);
10042
- this.connectHandlers = connectHandlers;
10043
- this.agent = ClientContext.create(connection.getContext());
10044
- }
10045
- startConnectHandlers() {
10046
- if (this.didStartConnectHandlers) {
10047
- return;
9910
+ function runConnectHandlers(connection, handlers) {
9911
+ for (const handler of handlers) {
9912
+ let result;
9913
+ try {
9914
+ result = handler(connection);
9915
+ } catch (error) {
9916
+ connection.close(error);
9917
+ throw error;
10048
9918
  }
10049
- this.didStartConnectHandlers = true;
10050
- runConnectHandlers(this, this.connectHandlers);
9919
+ Promise.resolve(result).catch((error) => {
9920
+ connection.close(error);
9921
+ });
10051
9922
  }
10052
9923
  }
10053
- function agentConnection(connection, connectHandlers = []) {
10054
- return new AgentConnectionHandle(connection, connectHandlers);
10055
- }
10056
- function clientConnection(connection, connectHandlers = []) {
10057
- return new ClientConnectionHandle(connection, connectHandlers);
9924
+ var appBuilder = Symbol("appBuilder");
9925
+ var runAgentConnectHandlers = Symbol("runAgentConnectHandlers");
9926
+ var runClientConnectHandlers = Symbol("runClientConnectHandlers");
9927
+ var stableConnectionOptions = { allowBatches: false };
9928
+ function client(options) {
9929
+ return new ClientApp(options);
10058
9930
  }
10059
9931
 
10060
- class AsyncQueue {
10061
- values = [];
10062
- waiters = [];
10063
- failed = false;
10064
- failure;
10065
- enqueue(value) {
10066
- if (this.failed) {
10067
- return;
10068
- }
10069
- const waiter = this.waiters.shift();
10070
- if (waiter) {
10071
- waiter.resolve(value);
10072
- } else {
10073
- this.values.push({ kind: "value", value });
9932
+ class ClientApp {
9933
+ builder = Connection.builder();
9934
+ connectHandlers = [];
9935
+ constructor(options = {}) {
9936
+ if (options.name) {
9937
+ this.builder.name(options.name);
10074
9938
  }
9939
+ this.builder.withHandler({
9940
+ handleMessage: (message, cx) => sessionUpdateRouter(cx).handleMessage(message),
9941
+ describe: () => "client-session-update-router"
9942
+ });
10075
9943
  }
10076
- reject(error) {
10077
- if (this.failed) {
10078
- return;
9944
+ [appBuilder]() {
9945
+ return this.builder;
9946
+ }
9947
+ [runClientConnectHandlers](connection) {
9948
+ runConnectHandlers(connection, this.connectHandlers);
9949
+ }
9950
+ connect(target) {
9951
+ return this.connectConnection(target).connection;
9952
+ }
9953
+ connectWith(target, op) {
9954
+ const { rawConnection, connection } = this.connectConnection(target);
9955
+ return rawConnection.runUntil(() => op(connection.agent));
9956
+ }
9957
+ onConnect(handler) {
9958
+ this.connectHandlers.push(handler);
9959
+ return this;
9960
+ }
9961
+ onRequest(method, handlerOrParams, handler) {
9962
+ if (handler) {
9963
+ return this.request({ method, params: handlerOrParams }, handler);
10079
9964
  }
10080
- if (this.waiters.length > 0) {
10081
- for (const waiter of this.waiters.splice(0)) {
10082
- waiter.reject(error);
10083
- }
10084
- return;
9965
+ const spec = clientRequestSpecsByMethod[method];
9966
+ if (!spec) {
9967
+ throw new Error(`Unknown ACP request method '${method}'. Pass a params parser for custom methods.`);
10085
9968
  }
10086
- this.values.push({ kind: "error", error });
10087
- }
10088
- clearErrors() {
10089
- this.values = this.values.filter((entry) => entry.kind === "value");
9969
+ return this.request(spec, handlerOrParams);
10090
9970
  }
10091
- fail(error) {
10092
- if (this.failed) {
10093
- return;
9971
+ onNotification(method, handlerOrParams, handler) {
9972
+ if (handler) {
9973
+ return this.notification({ method, params: handlerOrParams }, handler);
10094
9974
  }
10095
- this.failed = true;
10096
- this.failure = error;
10097
- for (const waiter of this.waiters.splice(0)) {
10098
- waiter.reject(error);
9975
+ const spec = clientNotificationSpecsByMethod[method];
9976
+ if (!spec) {
9977
+ throw new Error(`Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`);
10099
9978
  }
9979
+ return this.notification(spec, handlerOrParams);
10100
9980
  }
10101
- next() {
10102
- if (this.values.length > 0) {
10103
- const entry = this.values.shift();
10104
- if (entry.kind === "error") {
10105
- return Promise.reject(entry.error);
10106
- }
10107
- return Promise.resolve(entry.value);
9981
+ request(spec, handler) {
9982
+ registerAppRequest(this.builder, spec, (params, cx, signal, requestId) => clientRequestContext(params, ClientContext.create(cx, requestId), signal, requestId), handler);
9983
+ return this;
9984
+ }
9985
+ notification(spec, handler) {
9986
+ registerAppNotification(this.builder, spec, (params, cx, signal) => clientNotificationContext(params, ClientContext.create(cx), signal), handler);
9987
+ return this;
9988
+ }
9989
+ connectConnection(target) {
9990
+ if (isStream(target)) {
9991
+ const state = this.openStreamConnection(target);
9992
+ this[runClientConnectHandlers](state.connection);
9993
+ return state;
10108
9994
  }
10109
- if (this.failed) {
10110
- return Promise.reject(this.failure);
9995
+ const [thisStream, peerStream] = memoryStreamPair();
9996
+ const peerRawConnection = target[appBuilder]().connect(peerStream, stableConnectionOptions);
9997
+ const peerConnection = agentConnection(peerRawConnection);
9998
+ const state = this.openStreamConnection(thisStream);
9999
+ state.rawConnection.closed.then(() => peerConnection.close());
10000
+ peerRawConnection.closed.then(() => state.connection.close());
10001
+ try {
10002
+ target[runAgentConnectHandlers](peerConnection);
10003
+ this[runClientConnectHandlers](state.connection);
10004
+ } catch (error) {
10005
+ peerConnection.close(error);
10006
+ state.connection.close(error);
10007
+ throw error;
10111
10008
  }
10112
- return new Promise((resolve, reject) => {
10113
- this.waiters.push({ resolve, reject });
10114
- });
10009
+ return state;
10010
+ }
10011
+ openStreamConnection(stream) {
10012
+ const rawConnection = this.builder.connect(stream, stableConnectionOptions);
10013
+ return {
10014
+ rawConnection,
10015
+ connection: clientConnection(rawConnection, this.connectHandlers)
10016
+ };
10115
10017
  }
10116
10018
  }
10117
- function cloneNewSessionRequest(request) {
10019
+ var legacyAgentRequestMethods = new Set([
10020
+ AGENT_METHODS.initialize,
10021
+ AGENT_METHODS.authenticate,
10022
+ AGENT_METHODS.providers_list,
10023
+ AGENT_METHODS.providers_set,
10024
+ AGENT_METHODS.providers_disable,
10025
+ AGENT_METHODS.session_new,
10026
+ AGENT_METHODS.session_load,
10027
+ AGENT_METHODS.session_set_mode,
10028
+ AGENT_METHODS.session_set_config_option,
10029
+ AGENT_METHODS.session_prompt,
10030
+ AGENT_METHODS.session_list,
10031
+ AGENT_METHODS.session_delete,
10032
+ AGENT_METHODS.session_fork,
10033
+ AGENT_METHODS.session_resume,
10034
+ AGENT_METHODS.session_close,
10035
+ AGENT_METHODS.logout,
10036
+ AGENT_METHODS.nes_start,
10037
+ AGENT_METHODS.nes_suggest,
10038
+ AGENT_METHODS.nes_close
10039
+ ]);
10040
+ var legacyAgentNotificationMethods = new Set([
10041
+ AGENT_METHODS.session_cancel,
10042
+ AGENT_METHODS.nes_accept,
10043
+ AGENT_METHODS.nes_reject,
10044
+ AGENT_METHODS.document_did_open,
10045
+ AGENT_METHODS.document_did_change,
10046
+ AGENT_METHODS.document_did_close,
10047
+ AGENT_METHODS.document_did_save,
10048
+ AGENT_METHODS.document_did_focus
10049
+ ]);
10050
+ var legacyClientRequestMethods = new Set([
10051
+ CLIENT_METHODS.session_request_permission,
10052
+ CLIENT_METHODS.fs_write_text_file,
10053
+ CLIENT_METHODS.fs_read_text_file,
10054
+ CLIENT_METHODS.terminal_create,
10055
+ CLIENT_METHODS.terminal_output,
10056
+ CLIENT_METHODS.terminal_release,
10057
+ CLIENT_METHODS.terminal_wait_for_exit,
10058
+ CLIENT_METHODS.terminal_kill,
10059
+ CLIENT_METHODS.elicitation_create
10060
+ ]);
10061
+ var legacyClientNotificationMethods = new Set([
10062
+ CLIENT_METHODS.session_update,
10063
+ CLIENT_METHODS.elicitation_complete
10064
+ ]);
10065
+
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;
10118
10077
  return {
10119
- ...request,
10120
- additionalDirectories: request.additionalDirectories ? [...request.additionalDirectories] : undefined,
10121
- mcpServers: [...request.mcpServers]
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
+ }
10122
10096
  };
10123
10097
  }
10124
-
10125
- class SessionBuilder {
10126
- cx;
10127
- request;
10128
- constructor(cx, request) {
10129
- this.cx = cx;
10130
- this.request = cloneNewSessionRequest(request);
10131
- }
10132
- static create(cx, request) {
10133
- return new SessionBuilder(cx, request);
10134
- }
10135
- toRequest() {
10136
- return cloneNewSessionRequest(this.request);
10137
- }
10138
- withAdditionalDirectories(additionalDirectories) {
10139
- this.request = {
10140
- ...this.request,
10141
- additionalDirectories: [...additionalDirectories]
10142
- };
10143
- return this;
10144
- }
10145
- withMcpServer(mcpServer) {
10146
- this.request = {
10147
- ...this.request,
10148
- mcpServers: [...this.request.mcpServers, mcpServer]
10149
- };
10150
- return this;
10098
+ function connectSdkClient(child, configure, runtimeId) {
10099
+ if (runtimeId && true) {
10100
+ console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
10151
10101
  }
10152
- async start(options) {
10153
- return this.cx[startActiveSession](this.toRequest(), options);
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);
10154
10126
  }
10155
- async withSession(op) {
10156
- const session = await this.start();
10127
+ }
10128
+ async function closeAcpSessions(agent, sessionIds, timeoutMs = 2000) {
10129
+ const failed = [];
10130
+ await Promise.all([...new Set(sessionIds)].map(async (sessionId) => {
10157
10131
  try {
10158
- return await op(session);
10159
- } finally {
10160
- session.dispose();
10132
+ await sdkRequest(agent, "session/close", { sessionId }, timeoutMs);
10133
+ } catch {
10134
+ failed.push(sessionId);
10161
10135
  }
10162
- }
10136
+ }));
10137
+ return failed;
10163
10138
  }
10164
10139
 
10165
- class ActiveSession {
10166
- cx;
10167
- sessionResponse;
10168
- updates;
10169
- registrations;
10170
- constructor(cx, sessionResponse, updates, registrations) {
10171
- this.cx = cx;
10172
- this.sessionResponse = sessionResponse;
10173
- this.updates = updates;
10174
- this.registrations = registrations;
10175
- }
10176
- static create(cx, sessionResponse, updates, registrations) {
10177
- return new ActiveSession(cx, sessionResponse, updates, registrations);
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;
10178
10172
  }
10179
- get sessionId() {
10180
- return this.sessionResponse.sessionId;
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;
10181
10186
  }
10182
- get modes() {
10183
- return this.sessionResponse.modes;
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;
10184
10197
  }
10185
- get meta() {
10186
- return this.sessionResponse._meta;
10198
+ if (!directoryReadable) {
10199
+ return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
10187
10200
  }
10188
- get newSessionResponse() {
10189
- return this.sessionResponse;
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}`) };
10190
10208
  }
10191
- prompt(prompt, options) {
10192
- this.updates.clearErrors();
10193
- const response = this.cx.request(AGENT_METHODS.session_prompt, {
10194
- sessionId: this.sessionId,
10195
- prompt: this.promptBlocks(prompt)
10196
- }, options);
10197
- response.then((value) => {
10198
- this.updates.enqueue({
10199
- kind: "stop",
10200
- response: value,
10201
- stopReason: value.stopReason
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
+ }
10202
10220
  });
10203
- }, (error) => {
10204
- this.updates.reject(error);
10205
- });
10206
- return response;
10207
- }
10208
- nextUpdate() {
10209
- return this.updates.next();
10210
- }
10211
- async readText() {
10212
- let output = "";
10213
- for (;; ) {
10214
- const message = await this.nextUpdate();
10215
- if (message.kind === "stop") {
10216
- return output;
10217
- }
10218
- const { update } = message;
10219
- if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") {
10220
- output += update.content.text;
10221
- }
10222
- }
10223
- }
10224
- dispose() {
10225
- for (const registration of this.registrations.splice(0)) {
10226
- registration.dispose();
10227
10221
  }
10228
- this.updates.fail(new Error("Active session disposed"));
10229
- }
10230
- [Symbol.dispose]() {
10231
- this.dispose();
10222
+ } catch {
10223
+ skillNames = [];
10232
10224
  }
10233
- promptBlocks(prompt) {
10234
- if (typeof prompt === "string") {
10235
- return [{ type: "text", text: prompt }];
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;
10236
10231
  }
10237
- if (Array.isArray(prompt)) {
10238
- return prompt;
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;
10239
10237
  }
10240
- return [prompt];
10241
- }
10242
- }
10243
- function parseParams(parser, params) {
10244
- if (!parser) {
10245
- return params;
10246
- }
10247
- if (typeof parser === "function") {
10248
- return parser(params);
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
10249
  }
10250
- return parser.parse(params);
10251
- }
10252
- function requestSpec(method, params, mapResponse) {
10253
- return { method, params, mapResponse };
10254
- }
10255
- function notificationSpec(method, params) {
10256
- return { method, params };
10250
+ return { directoryReadable: true, rules, skills, warnings };
10257
10251
  }
10258
- function registerAppRequest(builder, spec, context, handler) {
10259
- builder.onReceiveRequest(spec.method, (params) => parseParams(spec.params, params), async (params, responder, cx) => {
10260
- const response = await handler(context(params, cx, responder.signal, responder.id));
10261
- await responder.respond(spec.mapResponse ? spec.mapResponse(response) : response);
10262
- });
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}`);
10263
10260
  }
10264
- function registerAppNotification(builder, spec, context, handler) {
10265
- builder.onReceiveNotification(spec.method, (params) => parseParams(spec.params, params), (params, cx) => handler(context(params, cx, cx.signal)));
10261
+ function readAppRulesText(directory) {
10262
+ return readTextFile(import_node_path.join(directory, APP_RULES_FILE));
10266
10263
  }
10267
- function specsByMethod(specs) {
10268
- const byMethod = {};
10269
- for (const spec of Object.values(specs)) {
10270
- byMethod[spec.method] = spec;
10271
- }
10272
- return byMethod;
10264
+ function isAbsolutePathLike(path) {
10265
+ return import_node_path.isAbsolute(path);
10273
10266
  }
10274
- var agentRequestSpecs = {
10275
- initialize: requestSpec(AGENT_METHODS.initialize, zInitializeRequest),
10276
- newSession: requestSpec(AGENT_METHODS.session_new, zNewSessionRequest),
10277
- loadSession: requestSpec(AGENT_METHODS.session_load, zLoadSessionRequest, emptyObjectResponse),
10278
- unstable_forkSession: requestSpec(AGENT_METHODS.session_fork, zForkSessionRequest),
10279
- listSessions: requestSpec(AGENT_METHODS.session_list, zListSessionsRequest),
10280
- deleteSession: requestSpec(AGENT_METHODS.session_delete, zDeleteSessionRequest, emptyObjectResponse),
10281
- resumeSession: requestSpec(AGENT_METHODS.session_resume, zResumeSessionRequest),
10282
- closeSession: requestSpec(AGENT_METHODS.session_close, zCloseSessionRequest, emptyObjectResponse),
10283
- setSessionMode: requestSpec(AGENT_METHODS.session_set_mode, zSetSessionModeRequest, emptyObjectResponse),
10284
- setSessionConfigOption: requestSpec(AGENT_METHODS.session_set_config_option, zSetSessionConfigOptionRequest),
10285
- authenticate: requestSpec(AGENT_METHODS.authenticate, zAuthenticateRequest, emptyObjectResponse),
10286
- unstable_listProviders: requestSpec(AGENT_METHODS.providers_list, zListProvidersRequest),
10287
- unstable_setProvider: requestSpec(AGENT_METHODS.providers_set, zSetProviderRequest, emptyObjectResponse),
10288
- unstable_disableProvider: requestSpec(AGENT_METHODS.providers_disable, zDisableProviderRequest, emptyObjectResponse),
10289
- logout: requestSpec(AGENT_METHODS.logout, zLogoutRequest, emptyObjectResponse),
10290
- prompt: requestSpec(AGENT_METHODS.session_prompt, zPromptRequest),
10291
- unstable_startNes: requestSpec(AGENT_METHODS.nes_start, zStartNesRequest),
10292
- unstable_suggestNes: requestSpec(AGENT_METHODS.nes_suggest, zSuggestNesRequest),
10293
- unstable_closeNes: requestSpec(AGENT_METHODS.nes_close, zCloseNesRequest, emptyObjectResponse)
10294
- };
10295
- var agentNotificationSpecs = {
10296
- cancel: notificationSpec(AGENT_METHODS.session_cancel, zCancelNotification),
10297
- unstable_didOpenDocument: notificationSpec(AGENT_METHODS.document_did_open, zDidOpenDocumentNotification),
10298
- unstable_didChangeDocument: notificationSpec(AGENT_METHODS.document_did_change, zDidChangeDocumentNotification),
10299
- unstable_didCloseDocument: notificationSpec(AGENT_METHODS.document_did_close, zDidCloseDocumentNotification),
10300
- unstable_didSaveDocument: notificationSpec(AGENT_METHODS.document_did_save, zDidSaveDocumentNotification),
10301
- unstable_didFocusDocument: notificationSpec(AGENT_METHODS.document_did_focus, zDidFocusDocumentNotification),
10302
- unstable_acceptNes: notificationSpec(AGENT_METHODS.nes_accept, zAcceptNesNotification),
10303
- unstable_rejectNes: notificationSpec(AGENT_METHODS.nes_reject, zRejectNesNotification)
10304
- };
10305
- var clientRequestSpecs = {
10306
- requestPermission: requestSpec(CLIENT_METHODS.session_request_permission, zRequestPermissionRequest),
10307
- writeTextFile: requestSpec(CLIENT_METHODS.fs_write_text_file, zWriteTextFileRequest, emptyObjectResponse),
10308
- readTextFile: requestSpec(CLIENT_METHODS.fs_read_text_file, zReadTextFileRequest),
10309
- createTerminal: requestSpec(CLIENT_METHODS.terminal_create, zCreateTerminalRequest),
10310
- terminalOutput: requestSpec(CLIENT_METHODS.terminal_output, zTerminalOutputRequest),
10311
- releaseTerminal: requestSpec(CLIENT_METHODS.terminal_release, zReleaseTerminalRequest, emptyObjectResponse),
10312
- waitForTerminalExit: requestSpec(CLIENT_METHODS.terminal_wait_for_exit, zWaitForTerminalExitRequest),
10313
- killTerminal: requestSpec(CLIENT_METHODS.terminal_kill, zKillTerminalRequest, emptyObjectResponse),
10314
- createElicitation: requestSpec(CLIENT_METHODS.elicitation_create, zCreateElicitationRequest)
10315
- };
10316
- var clientNotificationSpecs = {
10317
- sessionUpdate: notificationSpec(CLIENT_METHODS.session_update, zSessionNotification),
10318
- completeElicitation: notificationSpec(CLIENT_METHODS.elicitation_complete, zCompleteElicitationNotification)
10319
- };
10320
- var agentRequestSpecsByMethod = specsByMethod(agentRequestSpecs);
10321
- var agentNotificationSpecsByMethod = specsByMethod(agentNotificationSpecs);
10322
- var clientRequestSpecsByMethod = specsByMethod(clientRequestSpecs);
10323
- var clientNotificationSpecsByMethod = specsByMethod(clientNotificationSpecs);
10324
- function clientRequestContext(params, agent, signal, requestId) {
10325
- return {
10326
- params,
10327
- requestId,
10328
- signal,
10329
- agent
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");
10330
10284
  };
10331
- }
10332
- function clientNotificationContext(params, agent, signal) {
10333
- return {
10334
- params,
10335
- signal,
10336
- agent
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;
10337
10298
  };
10338
- }
10339
-
10340
- class SessionUpdateRouter {
10341
- activeSessions = new Map;
10342
- handleMessage(message) {
10343
- if (message.kind !== "notification" || message.method !== CLIENT_METHODS.session_update) {
10344
- return Handled.no(message);
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 });
10345
10340
  }
10346
- const notification = zSessionNotification.parse(message.params);
10347
- const update = {
10348
- kind: "session_update",
10349
- notification,
10350
- update: notification.update
10351
- };
10352
- const activeSessions = this.activeSessions.get(notification.sessionId);
10353
- if (activeSessions && activeSessions.size > 0) {
10354
- for (const session of activeSessions) {
10355
- session.enqueue(update);
10356
- }
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;
10357
10369
  }
10358
- return Handled.no(message);
10359
- }
10360
- attach(response, updates) {
10361
- const sessions = this.activeSessions.get(response.sessionId) ?? new Set;
10362
- sessions.add(updates);
10363
- this.activeSessions.set(response.sessionId, sessions);
10364
- return new HandlerRegistration(() => {
10365
- sessions.delete(updates);
10366
- if (sessions.size === 0) {
10367
- this.activeSessions.delete(response.sessionId);
10368
- }
10369
- });
10370
+ return { directory, env, rulesFile, nativeRules, dispose };
10371
+ } catch (error) {
10372
+ await dispose();
10373
+ throw error;
10370
10374
  }
10371
10375
  }
10372
- var sessionUpdateRouters = new WeakMap;
10373
- function sessionUpdateRouter(cx) {
10374
- let router = sessionUpdateRouters.get(cx);
10375
- if (!router) {
10376
- router = new SessionUpdateRouter;
10377
- sessionUpdateRouters.set(cx, router);
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 };
10378
10391
  }
10379
- return router;
10392
+ if (r._meta && typeof r._meta === "object")
10393
+ out._meta = r._meta;
10394
+ return out;
10380
10395
  }
10381
- function runConnectHandlers(connection, handlers) {
10382
- for (const handler of handlers) {
10383
- let result;
10384
- try {
10385
- result = handler(connection);
10386
- } catch (error) {
10387
- connection.close(error);
10388
- throw error;
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);
10389
10421
  }
10390
- Promise.resolve(result).catch((error) => {
10391
- connection.close(error);
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);
10392
10449
  });
10393
10450
  }
10394
- }
10395
- var appBuilder = Symbol("appBuilder");
10396
- var runAgentConnectHandlers = Symbol("runAgentConnectHandlers");
10397
- var runClientConnectHandlers = Symbol("runClientConnectHandlers");
10398
- var stableConnectionOptions = { allowBatches: false };
10399
- function client(options) {
10400
- return new ClientApp(options);
10451
+ delete(sessionId) {
10452
+ this.bySession.delete(sessionId);
10453
+ }
10454
+ clear() {
10455
+ this.bySession.clear();
10456
+ }
10401
10457
  }
10402
10458
 
10403
- class ClientApp {
10404
- builder = Connection.builder();
10405
- connectHandlers = [];
10406
- constructor(options = {}) {
10407
- if (options.name) {
10408
- this.builder.name(options.name);
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;
10409
10540
  }
10410
- this.builder.withHandler({
10411
- handleMessage: (message, cx) => sessionUpdateRouter(cx).handleMessage(message),
10412
- describe: () => "client-session-update-router"
10413
- });
10414
- }
10415
- [appBuilder]() {
10416
- return this.builder;
10417
- }
10418
- [runClientConnectHandlers](connection) {
10419
- runConnectHandlers(connection, this.connectHandlers);
10420
- }
10421
- connect(target) {
10422
- return this.connectConnection(target).connection;
10423
10541
  }
10424
- connectWith(target, op) {
10425
- const { rawConnection, connection } = this.connectConnection(target);
10426
- return rawConnection.runUntil(() => op(connection.agent));
10542
+ if (!windows.length && !credits && !account && status === "ok") {
10543
+ return null;
10427
10544
  }
10428
- onConnect(handler) {
10429
- this.connectHandlers.push(handler);
10430
- return this;
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";
10431
10550
  }
10432
- onRequest(method, handlerOrParams, handler) {
10433
- if (handler) {
10434
- return this.request({ method, params: handlerOrParams }, handler);
10435
- }
10436
- const spec = clientRequestSpecsByMethod[method];
10437
- if (!spec) {
10438
- throw new Error(`Unknown ACP request method '${method}'. Pass a params parser for custom methods.`);
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
+ `);
10439
10579
  }
10440
- return this.request(spec, handlerOrParams);
10441
- }
10442
- onNotification(method, handlerOrParams, handler) {
10443
- if (handler) {
10444
- return this.notification({ method, params: handlerOrParams }, handler);
10580
+ if (!textToParse)
10581
+ return null;
10582
+ if (!/(?:limit|credits?|Account:|5h|resets|banned|suspended|quota)/i.test(textToParse)) {
10583
+ return null;
10445
10584
  }
10446
- const spec = clientNotificationSpecsByMethod[method];
10447
- if (!spec) {
10448
- throw new Error(`Unknown ACP notification method '${method}'. Pass a params parser for custom methods.`);
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;
10449
10591
  }
10450
- return this.notification(spec, handlerOrParams);
10451
- }
10452
- request(spec, handler) {
10453
- registerAppRequest(this.builder, spec, (params, cx, signal, requestId) => clientRequestContext(params, ClientContext.create(cx, requestId), signal, requestId), handler);
10454
- return this;
10592
+ return null;
10455
10593
  }
10456
- notification(spec, handler) {
10457
- registerAppNotification(this.builder, spec, (params, cx, signal) => clientNotificationContext(params, ClientContext.create(cx), signal), handler);
10458
- return this;
10594
+ set(quota, sessionId) {
10595
+ if (sessionId)
10596
+ this.bySession.set(sessionId, quota);
10597
+ this.byRuntime.set(quota.runtimeId, quota);
10459
10598
  }
10460
- connectConnection(target) {
10461
- if (isStream(target)) {
10462
- const state = this.openStreamConnection(target);
10463
- this[runClientConnectHandlers](state.connection);
10464
- return state;
10599
+ get(sessionId, runtimeId) {
10600
+ if (sessionId && this.bySession.has(sessionId)) {
10601
+ return this.bySession.get(sessionId);
10465
10602
  }
10466
- const [thisStream, peerStream] = memoryStreamPair();
10467
- const peerRawConnection = target[appBuilder]().connect(peerStream, stableConnectionOptions);
10468
- const peerConnection = agentConnection(peerRawConnection);
10469
- const state = this.openStreamConnection(thisStream);
10470
- state.rawConnection.closed.then(() => peerConnection.close());
10471
- peerRawConnection.closed.then(() => state.connection.close());
10472
- try {
10473
- target[runAgentConnectHandlers](peerConnection);
10474
- this[runClientConnectHandlers](state.connection);
10475
- } catch (error) {
10476
- peerConnection.close(error);
10477
- state.connection.close(error);
10478
- throw error;
10603
+ if (runtimeId && this.byRuntime.has(runtimeId)) {
10604
+ return this.byRuntime.get(runtimeId);
10479
10605
  }
10480
- return state;
10606
+ return;
10481
10607
  }
10482
- openStreamConnection(stream) {
10483
- const rawConnection = this.builder.connect(stream, stableConnectionOptions);
10484
- return {
10485
- rawConnection,
10486
- connection: clientConnection(rawConnection, this.connectHandlers)
10487
- };
10608
+ clear() {
10609
+ this.bySession.clear();
10610
+ this.byRuntime.clear();
10488
10611
  }
10489
10612
  }
10490
- var legacyAgentRequestMethods = new Set([
10491
- AGENT_METHODS.initialize,
10492
- AGENT_METHODS.authenticate,
10493
- AGENT_METHODS.providers_list,
10494
- AGENT_METHODS.providers_set,
10495
- AGENT_METHODS.providers_disable,
10496
- AGENT_METHODS.session_new,
10497
- AGENT_METHODS.session_load,
10498
- AGENT_METHODS.session_set_mode,
10499
- AGENT_METHODS.session_set_config_option,
10500
- AGENT_METHODS.session_prompt,
10501
- AGENT_METHODS.session_list,
10502
- AGENT_METHODS.session_delete,
10503
- AGENT_METHODS.session_fork,
10504
- AGENT_METHODS.session_resume,
10505
- AGENT_METHODS.session_close,
10506
- AGENT_METHODS.logout,
10507
- AGENT_METHODS.nes_start,
10508
- AGENT_METHODS.nes_suggest,
10509
- AGENT_METHODS.nes_close
10510
- ]);
10511
- var legacyAgentNotificationMethods = new Set([
10512
- AGENT_METHODS.session_cancel,
10513
- AGENT_METHODS.nes_accept,
10514
- AGENT_METHODS.nes_reject,
10515
- AGENT_METHODS.document_did_open,
10516
- AGENT_METHODS.document_did_change,
10517
- AGENT_METHODS.document_did_close,
10518
- AGENT_METHODS.document_did_save,
10519
- AGENT_METHODS.document_did_focus
10520
- ]);
10521
- var legacyClientRequestMethods = new Set([
10522
- CLIENT_METHODS.session_request_permission,
10523
- CLIENT_METHODS.fs_write_text_file,
10524
- CLIENT_METHODS.fs_read_text_file,
10525
- CLIENT_METHODS.terminal_create,
10526
- CLIENT_METHODS.terminal_output,
10527
- CLIENT_METHODS.terminal_release,
10528
- CLIENT_METHODS.terminal_wait_for_exit,
10529
- CLIENT_METHODS.terminal_kill,
10530
- CLIENT_METHODS.elicitation_create
10531
- ]);
10532
- var legacyClientNotificationMethods = new Set([
10533
- CLIENT_METHODS.session_update,
10534
- CLIENT_METHODS.elicitation_complete
10535
- ]);
10536
10613
 
10537
10614
  // src/runtimes/codex/quota.ts
10538
10615
  var import_node_fs4 = require("node:fs");
@@ -12267,7 +12344,7 @@ var agyAdapter = {
12267
12344
  return { ...prep, env: { AGY_ACP_RESOURCES_DIR: directory }, report: { ...prep.report, rulesPrepared: prep.report.rulesChars > 0 } };
12268
12345
  },
12269
12346
  appResourceSessionMeta: (directory) => ({ appResources: { directory } }),
12270
- supportedBridgeVersions: ["0.1.24"],
12347
+ supportedBridgeVersions: ["0.1.24", "0.1.25"],
12271
12348
  probeAuth: () => probeAgyAuth(),
12272
12349
  probeQuota: (options) => probeAgyQuota(options),
12273
12350
  orderAuthMethods: (methods) => methods,
@@ -12469,70 +12546,6 @@ function tryReuseLiveAcpProcess(runtimeId, query = {}) {
12469
12546
  return { status: "miss" };
12470
12547
  }
12471
12548
 
12472
- // src/client/sdk-client.ts
12473
- var import_node_stream = require("node:stream");
12474
- var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
12475
- function createSdkStreamHandle(child) {
12476
- const stdoutBridge = new import_node_stream.PassThrough;
12477
- const stdinBridge = new import_node_stream.PassThrough;
12478
- child.stdout.pipe(stdoutBridge);
12479
- stdinBridge.pipe(child.stdin, { end: false });
12480
- const output = import_node_stream.Writable.toWeb(stdinBridge);
12481
- const input = import_node_stream.Readable.toWeb(stdoutBridge);
12482
- const stream = ndJsonStream2(output, input);
12483
- let disposed = false;
12484
- return {
12485
- stream,
12486
- dispose: () => {
12487
- if (disposed)
12488
- return;
12489
- disposed = true;
12490
- try {
12491
- child.stdout.unpipe(stdoutBridge);
12492
- } catch {}
12493
- try {
12494
- stdinBridge.unpipe(child.stdin);
12495
- } catch {}
12496
- try {
12497
- stdoutBridge.destroy();
12498
- } catch {}
12499
- try {
12500
- stdinBridge.destroy();
12501
- } catch {}
12502
- }
12503
- };
12504
- }
12505
- function connectSdkClient(child, configure, runtimeId) {
12506
- if (runtimeId && true) {
12507
- console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
12508
- }
12509
- const app = client({ name: "inkdown" });
12510
- configure(app);
12511
- const streamHandle = createSdkStreamHandle(child);
12512
- const connection = app.connect(streamHandle.stream);
12513
- return { app, connection, streamHandle };
12514
- }
12515
- async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIMEOUT_MS) {
12516
- const controller = new AbortController;
12517
- let timer;
12518
- try {
12519
- const pending = agent.request(method, params, {
12520
- cancellationSignal: controller.signal
12521
- });
12522
- const timeout = new Promise((_, reject) => {
12523
- timer = setTimeout(() => {
12524
- controller.abort();
12525
- reject(new Error(`请求超时: ${method}`));
12526
- }, timeoutMs);
12527
- timer.unref?.();
12528
- });
12529
- return await Promise.race([pending, timeout]);
12530
- } finally {
12531
- if (timer !== undefined)
12532
- clearTimeout(timer);
12533
- }
12534
- }
12535
-
12536
12549
  // src/client/acp-fs.ts
12537
12550
  var import_promises4 = require("node:fs/promises");
12538
12551
  var import_node_path16 = require("node:path");
@@ -13383,7 +13396,7 @@ var NATIVE_ELIGIBLE_BRIDGE_VERSIONS = {
13383
13396
  "codex-acp": ["2.2.2"],
13384
13397
  opencode: ["1.18.35"],
13385
13398
  claude: ["0.91.0"],
13386
- agy: ["0.1.24"]
13399
+ agy: ["0.1.24", "0.1.25"]
13387
13400
  };
13388
13401
  function isSupportedBridgeVersion(runtimeId, version) {
13389
13402
  const versions = NATIVE_ELIGIBLE_BRIDGE_VERSIONS[(runtimeId ?? "").trim()];
@@ -13895,6 +13908,12 @@ class AcpClient {
13895
13908
  async disconnect(reason) {
13896
13909
  this.setStatus("disconnected", reason);
13897
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
+ }
13898
13917
  this.sessionLedger.clear();
13899
13918
  this.compatSentKeys.clear();
13900
13919
  this.compatSnapshots.clear();