@yitom/acp-client 0.1.6 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/dist/app-skills-mcp-serve.cjs +291 -0
- package/dist/client/acp-client.d.ts +52 -1
- package/dist/client/session-open.d.ts +5 -0
- package/dist/contracts/quota.d.ts +2 -0
- package/dist/index.cjs +1485 -175
- package/dist/index.d.ts +5 -0
- package/dist/index.js +1474 -161
- package/dist/mcp/app-skills-mcp-serve.d.ts +1 -0
- package/dist/mcp/app-skills-mcp.d.ts +48 -0
- package/dist/process/process-manager.d.ts +51 -5
- package/dist/resources/app-resources.d.ts +91 -0
- package/dist/resources/config-text.d.ts +36 -0
- package/dist/resources/eligibility.d.ts +19 -0
- package/dist/resources/index.d.ts +5 -0
- package/dist/resources/runtime-bindings.d.ts +59 -0
- package/dist/resources/session-config.d.ts +9 -0
- package/dist/runtimes/agy/quota.d.ts +8 -0
- package/dist/runtimes/index.d.ts +17 -0
- package/dist/runtimes/opencode/quota.d.ts +1 -1
- package/dist/session/compat-guide.d.ts +33 -0
- package/dist/sidecar.cjs +1437 -156
- package/dist/version.d.ts +1 -1
- package/docs/api-reference.md +108 -0
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -70,6 +70,10 @@ __export(exports_src, {
|
|
|
70
70
|
ACP_EARLY_EXIT_WINDOW_MS: () => ACP_EARLY_EXIT_WINDOW_MS,
|
|
71
71
|
ACP_SDK_REQUEST_TIMEOUT_MS: () => ACP_SDK_REQUEST_TIMEOUT_MS,
|
|
72
72
|
AGY_ACP_NPM_PACKAGE: () => AGY_ACP_NPM_PACKAGE,
|
|
73
|
+
APP_RESOURCE_CAPABILITIES: () => APP_RESOURCE_CAPABILITIES,
|
|
74
|
+
APP_RULES_FILE: () => APP_RULES_FILE,
|
|
75
|
+
APP_SKILLS_DIR: () => APP_SKILLS_DIR,
|
|
76
|
+
APP_SKILL_FILE: () => APP_SKILL_FILE,
|
|
73
77
|
AcpClient: () => AcpClient,
|
|
74
78
|
AcpSessionHandle: () => AcpSessionHandle,
|
|
75
79
|
AcpTerminalManager: () => AcpTerminalManager,
|
|
@@ -88,6 +92,7 @@ __export(exports_src, {
|
|
|
88
92
|
INKDOWN_VIRTUAL_DIR: () => INKDOWN_VIRTUAL_DIR,
|
|
89
93
|
INKDOWN_VIRTUAL_RESOURCES: () => INKDOWN_VIRTUAL_RESOURCES,
|
|
90
94
|
LEGACY_ZED_CODEX_ACP_NPM_PACKAGE: () => LEGACY_ZED_CODEX_ACP_NPM_PACKAGE,
|
|
95
|
+
NATIVE_ELIGIBLE_BRIDGE_VERSIONS: () => NATIVE_ELIGIBLE_BRIDGE_VERSIONS,
|
|
91
96
|
OPENCODE_CLI_NPM_PACKAGE: () => OPENCODE_CLI_NPM_PACKAGE,
|
|
92
97
|
QuotaCache: () => QuotaCache,
|
|
93
98
|
acpReadTextFile: () => acpReadTextFile,
|
|
@@ -103,15 +108,18 @@ __export(exports_src, {
|
|
|
103
108
|
callInkdownMcpTool: () => callInkdownMcpTool,
|
|
104
109
|
callInkdownTocTool: () => callInkdownTocTool,
|
|
105
110
|
claudeAdapter: () => claudeAdapter,
|
|
111
|
+
claudeResourceSessionMeta: () => claudeResourceSessionMeta,
|
|
106
112
|
clearAcpProvider: () => clearAcpProvider,
|
|
107
113
|
clearCursorCatalogCache: () => clearCursorCatalogCache,
|
|
108
114
|
codexAdapter: () => codexAdapter,
|
|
109
115
|
connectSdkClient: () => connectSdkClient,
|
|
110
116
|
copilotAdapter: () => copilotAdapter,
|
|
111
117
|
createSdkStreamHandle: () => createSdkStreamHandle,
|
|
118
|
+
createSessionConfigHome: () => createSessionConfigHome,
|
|
112
119
|
cursorAdapter: () => cursorAdapter,
|
|
113
120
|
decideConnectAuth: () => decideConnectAuth,
|
|
114
121
|
deepseekAdapter: () => deepseekAdapter,
|
|
122
|
+
digestAppResources: () => digestAppResources,
|
|
115
123
|
disposeAllAcpProcesses: () => disposeAllAcpProcesses,
|
|
116
124
|
emptyAcpAuthPreflight: () => emptyAcpAuthPreflight,
|
|
117
125
|
err: () => err,
|
|
@@ -131,6 +139,7 @@ __export(exports_src, {
|
|
|
131
139
|
getDefaultAgentDataDir: () => getDefaultAgentDataDir,
|
|
132
140
|
getLiveAcpProcess: () => getLiveAcpProcess,
|
|
133
141
|
handleInkdownMcpRpc: () => handleInkdownMcpRpc,
|
|
142
|
+
isAbsolutePathLike: () => isAbsolutePathLike,
|
|
134
143
|
isAppError: () => isAppError,
|
|
135
144
|
isBinaryDocumentPath: () => isBinaryDocumentPath,
|
|
136
145
|
isCancelled: () => isCancelled,
|
|
@@ -140,11 +149,15 @@ __export(exports_src, {
|
|
|
140
149
|
isInkdownVirtualDirPath: () => isInkdownVirtualDirPath,
|
|
141
150
|
isOk: () => isOk,
|
|
142
151
|
isSpawnedAcpProcessAlive: () => isSpawnedAcpProcessAlive,
|
|
152
|
+
isSupportedBridgeVersion: () => isSupportedBridgeVersion,
|
|
143
153
|
isTransientAcpTransportError: () => isTransientAcpTransportError,
|
|
144
154
|
isValidCursorAuthFile: () => isValidCursorAuthFile,
|
|
145
155
|
isValidOpencodeAuthFile: () => isValidOpencodeAuthFile,
|
|
146
156
|
listAcpRuntimes: () => listAcpRuntimes,
|
|
147
157
|
listLiveAcpRuntimeIds: () => listLiveAcpRuntimeIds,
|
|
158
|
+
mergeCodexConfigJson: () => mergeCodexConfigJson,
|
|
159
|
+
mergeConfigTomlPreserving: () => mergeConfigTomlPreserving,
|
|
160
|
+
mergeOpenCodeAppConfig: () => mergeOpenCodeAppConfig,
|
|
148
161
|
mergeTopLevelModelsIntoConfigOptions: () => mergeTopLevelModelsIntoConfigOptions,
|
|
149
162
|
ok: () => ok,
|
|
150
163
|
opencodeAdapter: () => opencodeAdapter,
|
|
@@ -158,7 +171,11 @@ __export(exports_src, {
|
|
|
158
171
|
parsePromptCapabilities: () => parsePromptCapabilities,
|
|
159
172
|
parseRateLimitsFromStatusText: () => parseRateLimitsFromStatusText,
|
|
160
173
|
parseResumeSessionSupported: () => parseResumeSessionSupported,
|
|
174
|
+
parseSkillFrontmatter: () => parseSkillFrontmatter,
|
|
161
175
|
pickAllowOptionId: () => pickAllowOptionId,
|
|
176
|
+
prepareClaudeResources: () => prepareClaudeResources,
|
|
177
|
+
prepareCompatibilityResources: () => prepareCompatibilityResources,
|
|
178
|
+
prepareOpenCodeResources: () => prepareOpenCodeResources,
|
|
162
179
|
probeAgyAuth: () => probeAgyAuth,
|
|
163
180
|
probeClaudeAuth: () => probeClaudeAuth,
|
|
164
181
|
probeClaudeQuota: () => probeClaudeQuota,
|
|
@@ -173,6 +190,8 @@ __export(exports_src, {
|
|
|
173
190
|
probeOpencodeQuota: () => probeOpencodeQuota,
|
|
174
191
|
provisionCustomProviderCodexHome: () => provisionCustomProviderCodexHome,
|
|
175
192
|
readAcpProxySettings: () => readAcpProxySettings,
|
|
193
|
+
readAppResourcesDir: () => readAppResourcesDir,
|
|
194
|
+
readAppRulesText: () => readAppRulesText,
|
|
176
195
|
readStoredAcpProvider: () => readStoredAcpProvider,
|
|
177
196
|
registerAcpClientHandlers: () => registerAcpClientHandlers,
|
|
178
197
|
resolveClaudeHome: () => resolveClaudeHome,
|
|
@@ -188,6 +207,7 @@ __export(exports_src, {
|
|
|
188
207
|
resolveOpencodeAuthCandidates: () => resolveOpencodeAuthCandidates,
|
|
189
208
|
resolveOpencodeAuthFile: () => resolveOpencodeAuthFile,
|
|
190
209
|
resolveOpencodeAuthPath: () => resolveOpencodeAuthPath,
|
|
210
|
+
resolveRuntimeEligibility: () => resolveRuntimeEligibility,
|
|
191
211
|
restoreOrCreateAcpSession: () => restoreOrCreateAcpSession,
|
|
192
212
|
runConnectAuthGate: () => runConnectAuthGate,
|
|
193
213
|
saveAcpProvider: () => saveAcpProvider,
|
|
@@ -198,6 +218,7 @@ __export(exports_src, {
|
|
|
198
218
|
synthesizeModelOptionFromTopLevelModels: () => synthesizeModelOptionFromTopLevelModels,
|
|
199
219
|
toAppError: () => toAppError,
|
|
200
220
|
truncateOutputFromStart: () => truncateOutputFromStart,
|
|
221
|
+
tryReuseLiveAcpProcess: () => tryReuseLiveAcpProcess,
|
|
201
222
|
withAcpEarlyExitDetail: () => withAcpEarlyExitDetail
|
|
202
223
|
});
|
|
203
224
|
module.exports = __toCommonJS(exports_src);
|
|
@@ -363,7 +384,244 @@ function findBuiltinAcpRuntime(id) {
|
|
|
363
384
|
return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
|
|
364
385
|
}
|
|
365
386
|
// src/version.ts
|
|
366
|
-
var ACP_CLIENT_VERSION = "0.1.
|
|
387
|
+
var ACP_CLIENT_VERSION = "0.1.8";
|
|
388
|
+
// src/resources/session-config.ts
|
|
389
|
+
var import_node_fs2 = require("node:fs");
|
|
390
|
+
var import_promises = require("node:fs/promises");
|
|
391
|
+
var import_node_os = require("node:os");
|
|
392
|
+
var import_node_path2 = require("node:path");
|
|
393
|
+
|
|
394
|
+
// src/resources/app-resources.ts
|
|
395
|
+
var import_node_crypto = require("node:crypto");
|
|
396
|
+
var import_node_fs = require("node:fs");
|
|
397
|
+
var import_node_path = require("node:path");
|
|
398
|
+
var APP_RULES_FILE = "AGENTS.md";
|
|
399
|
+
var APP_SKILLS_DIR = "skills";
|
|
400
|
+
var APP_SKILL_FILE = "SKILL.md";
|
|
401
|
+
function parseSkillFrontmatter(text) {
|
|
402
|
+
const lines = text.split(`
|
|
403
|
+
`);
|
|
404
|
+
if (lines[0]?.trim() !== "---")
|
|
405
|
+
return {};
|
|
406
|
+
const out = {};
|
|
407
|
+
for (let i = 1;i < lines.length; i += 1) {
|
|
408
|
+
const line = lines[i] ?? "";
|
|
409
|
+
if (line.trim() === "---")
|
|
410
|
+
break;
|
|
411
|
+
const cut = line.indexOf(":");
|
|
412
|
+
if (cut <= 0)
|
|
413
|
+
continue;
|
|
414
|
+
const key = line.slice(0, cut).trim().toLowerCase();
|
|
415
|
+
if (key !== "name" && key !== "description")
|
|
416
|
+
continue;
|
|
417
|
+
const value = line.slice(cut + 1).trim().replace(/^['"]|['"]$/g, "");
|
|
418
|
+
if (value)
|
|
419
|
+
out[key] = value;
|
|
420
|
+
}
|
|
421
|
+
return out;
|
|
422
|
+
}
|
|
423
|
+
function sha256Hex(text) {
|
|
424
|
+
return import_node_crypto.createHash("sha256").update(text, "utf8").digest("hex");
|
|
425
|
+
}
|
|
426
|
+
function readTextFile(path) {
|
|
427
|
+
try {
|
|
428
|
+
if (!import_node_fs.statSync(path).isFile())
|
|
429
|
+
return null;
|
|
430
|
+
const text = import_node_fs.readFileSync(path, "utf8");
|
|
431
|
+
return text.trim() ? text : null;
|
|
432
|
+
} catch {
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
function readAppResourcesDir(directory) {
|
|
437
|
+
const warnings = [];
|
|
438
|
+
if (!import_node_path.isAbsolute(directory))
|
|
439
|
+
return { directoryReadable: false, rules: null, skills: [], warnings: ["资源目录必须是本机绝对路径"] };
|
|
440
|
+
let directoryReadable = false;
|
|
441
|
+
try {
|
|
442
|
+
directoryReadable = import_node_fs.statSync(directory).isDirectory();
|
|
443
|
+
} catch {
|
|
444
|
+
directoryReadable = false;
|
|
445
|
+
}
|
|
446
|
+
if (!directoryReadable) {
|
|
447
|
+
return { directoryReadable: false, rules: null, skills: [], warnings: [`资源目录不可读: ${directory}`] };
|
|
448
|
+
}
|
|
449
|
+
let rules = null;
|
|
450
|
+
const rulesText = readTextFile(import_node_path.join(directory, APP_RULES_FILE));
|
|
451
|
+
if (rulesText === null) {
|
|
452
|
+
warnings.push(`缺常驻规则: ${APP_RULES_FILE}`);
|
|
453
|
+
} else {
|
|
454
|
+
rules = { chars: rulesText.length, digest: sha256Hex(`app-rules-v1
|
|
455
|
+
${rulesText}`) };
|
|
456
|
+
}
|
|
457
|
+
const skills = [];
|
|
458
|
+
const skillsRoot = import_node_path.join(directory, APP_SKILLS_DIR);
|
|
459
|
+
let skillNames = [];
|
|
460
|
+
try {
|
|
461
|
+
if (import_node_fs.statSync(skillsRoot).isDirectory()) {
|
|
462
|
+
skillNames = import_node_fs.readdirSync(skillsRoot).filter((name) => {
|
|
463
|
+
try {
|
|
464
|
+
return import_node_fs.statSync(import_node_path.join(skillsRoot, name)).isDirectory();
|
|
465
|
+
} catch {
|
|
466
|
+
return false;
|
|
467
|
+
}
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
} catch {
|
|
471
|
+
skillNames = [];
|
|
472
|
+
}
|
|
473
|
+
for (const name of skillNames.sort()) {
|
|
474
|
+
const rel = `${APP_SKILLS_DIR}/${name}/${APP_SKILL_FILE}`;
|
|
475
|
+
const text = readTextFile(import_node_path.join(directory, rel));
|
|
476
|
+
if (text === null) {
|
|
477
|
+
warnings.push(`技能缺正文已跳过: ${rel}`);
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
const front = parseSkillFrontmatter(text);
|
|
481
|
+
const skillName = front.name || name;
|
|
482
|
+
if (skills.some((s) => s.name === skillName)) {
|
|
483
|
+
warnings.push(`技能重名已跳过(保留首个): ${skillName}`);
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
const description = front.description || "";
|
|
487
|
+
skills.push({
|
|
488
|
+
name: skillName,
|
|
489
|
+
description,
|
|
490
|
+
path: rel,
|
|
491
|
+
chars: text.length,
|
|
492
|
+
digest: sha256Hex(`app-skill-v1
|
|
493
|
+
${skillName}
|
|
494
|
+
${description}
|
|
495
|
+
${text}`)
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
return { directoryReadable: true, rules, skills, warnings };
|
|
499
|
+
}
|
|
500
|
+
function digestAppResources(load) {
|
|
501
|
+
if (!load.rules)
|
|
502
|
+
return null;
|
|
503
|
+
const skillPart = load.skills.map((s) => `${s.name}:${s.digest}`).join(`
|
|
504
|
+
`);
|
|
505
|
+
return sha256Hex(`app-resources-v1
|
|
506
|
+
${load.rules.digest}
|
|
507
|
+
${skillPart}`);
|
|
508
|
+
}
|
|
509
|
+
function readAppRulesText(directory) {
|
|
510
|
+
return readTextFile(import_node_path.join(directory, APP_RULES_FILE));
|
|
511
|
+
}
|
|
512
|
+
function isAbsolutePathLike(path) {
|
|
513
|
+
return import_node_path.isAbsolute(path);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// src/resources/session-config.ts
|
|
517
|
+
async function createSessionConfigHome(runtime, resources) {
|
|
518
|
+
if (!import_node_path2.isAbsolute(resources))
|
|
519
|
+
throw new Error("Resources must be an absolute path");
|
|
520
|
+
const id = runtime === "cursor" ? "cursor-cli" : runtime;
|
|
521
|
+
const supported = ["agy", "codex-acp", "claude", "gemini", "copilot", "cursor-cli", "opencode", "opencode-v2"];
|
|
522
|
+
if (!supported.includes(id))
|
|
523
|
+
throw new Error("Session configuration home is not verified for runtime: " + runtime);
|
|
524
|
+
const text = readAppRulesText(resources);
|
|
525
|
+
if (!text)
|
|
526
|
+
throw new Error("Session configuration requires nonempty AGENTS.md");
|
|
527
|
+
const parent = import_node_path2.resolve(import_node_os.tmpdir());
|
|
528
|
+
const directory = await import_promises.mkdtemp(import_node_path2.join(parent, "acp-session-config-"));
|
|
529
|
+
const checkRoot = () => {
|
|
530
|
+
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-"))
|
|
531
|
+
throw new Error("Unsafe configuration cleanup target");
|
|
532
|
+
};
|
|
533
|
+
const dispose = async () => {
|
|
534
|
+
checkRoot();
|
|
535
|
+
let failure;
|
|
536
|
+
for (let i = 0;i < 30; i++) {
|
|
537
|
+
try {
|
|
538
|
+
await import_promises.rm(directory, { recursive: true, force: true });
|
|
539
|
+
return;
|
|
540
|
+
} catch (error) {
|
|
541
|
+
failure = error;
|
|
542
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
throw failure;
|
|
546
|
+
};
|
|
547
|
+
try {
|
|
548
|
+
const config = import_node_path2.join(directory, "config");
|
|
549
|
+
await import_promises.mkdir(config, { recursive: true, mode: 448 });
|
|
550
|
+
let env;
|
|
551
|
+
let rulesFile;
|
|
552
|
+
let skillsRoot = import_node_path2.join(config, "skills");
|
|
553
|
+
let nativeRules = true;
|
|
554
|
+
if (id === "agy") {
|
|
555
|
+
rulesFile = import_node_path2.join(config, "AGENTS.md");
|
|
556
|
+
env = { AGY_ACP_RESOURCES_DIR: config };
|
|
557
|
+
nativeRules = false;
|
|
558
|
+
} else if (id === "gemini") {
|
|
559
|
+
const root = import_node_path2.join(directory, "home", ".gemini");
|
|
560
|
+
await import_promises.mkdir(root, { recursive: true, mode: 448 });
|
|
561
|
+
rulesFile = import_node_path2.join(root, "GEMINI.md");
|
|
562
|
+
skillsRoot = import_node_path2.join(root, "skills");
|
|
563
|
+
env = { GEMINI_CLI_HOME: import_node_path2.join(directory, "home") };
|
|
564
|
+
} else if (id === "claude") {
|
|
565
|
+
rulesFile = import_node_path2.join(config, "CLAUDE.md");
|
|
566
|
+
env = { CLAUDE_CONFIG_DIR: config };
|
|
567
|
+
} else if (id === "codex-acp") {
|
|
568
|
+
rulesFile = import_node_path2.join(config, "AGENTS.md");
|
|
569
|
+
env = { CODEX_HOME: config };
|
|
570
|
+
} else if (id === "copilot") {
|
|
571
|
+
rulesFile = import_node_path2.join(config, "copilot-instructions.md");
|
|
572
|
+
env = { COPILOT_HOME: config, COPILOT_CUSTOM_INSTRUCTIONS_DIRS: config, COPILOT_SKILLS_DIRS: skillsRoot };
|
|
573
|
+
await import_promises.writeFile(import_node_path2.join(config, "AGENTS.md"), text, { mode: 384 });
|
|
574
|
+
} else if (id === "cursor-cli") {
|
|
575
|
+
rulesFile = import_node_path2.join(config, "AGENTS.md");
|
|
576
|
+
env = { CURSOR_CONFIG_DIR: config };
|
|
577
|
+
nativeRules = false;
|
|
578
|
+
} else {
|
|
579
|
+
const root = import_node_path2.join(directory, "xdg-config", "opencode");
|
|
580
|
+
await import_promises.mkdir(root, { recursive: true, mode: 448 });
|
|
581
|
+
rulesFile = import_node_path2.join(root, "AGENTS.md");
|
|
582
|
+
skillsRoot = import_node_path2.join(root, "skills");
|
|
583
|
+
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") };
|
|
584
|
+
if (id === "opencode")
|
|
585
|
+
env.OPENCODE_CONFIG_DIR = root;
|
|
586
|
+
const skills = id === "opencode" ? { paths: [skillsRoot] } : [skillsRoot];
|
|
587
|
+
await import_promises.writeFile(import_node_path2.join(root, "opencode.json"), JSON.stringify({ instructions: [rulesFile], skills }), { mode: 384 });
|
|
588
|
+
}
|
|
589
|
+
await import_promises.writeFile(rulesFile, text, { mode: 384 });
|
|
590
|
+
const input = import_node_path2.join(resources, "skills");
|
|
591
|
+
try {
|
|
592
|
+
const info = await import_promises.lstat(input);
|
|
593
|
+
if (info.isSymbolicLink() || !info.isDirectory())
|
|
594
|
+
throw new Error("Skill root must be a regular directory");
|
|
595
|
+
const physical = await import_promises.realpath(input);
|
|
596
|
+
const copy = async (from, to) => {
|
|
597
|
+
await import_promises.mkdir(to, { recursive: true, mode: 448 });
|
|
598
|
+
for (const entry of await import_promises.readdir(from, { withFileTypes: true })) {
|
|
599
|
+
const src = import_node_path2.join(from, entry.name);
|
|
600
|
+
const info = await import_promises.lstat(src);
|
|
601
|
+
if (info.isSymbolicLink())
|
|
602
|
+
throw new Error("Skill symlink is not allowed");
|
|
603
|
+
const actual = await import_promises.realpath(src);
|
|
604
|
+
const rel = import_node_path2.relative(physical, actual);
|
|
605
|
+
if (rel.startsWith(".." + import_node_path2.sep) || rel === ".." || import_node_path2.isAbsolute(rel))
|
|
606
|
+
throw new Error("Skill path escapes resources");
|
|
607
|
+
if (info.isDirectory())
|
|
608
|
+
await copy(src, import_node_path2.join(to, entry.name));
|
|
609
|
+
else if (info.isFile() && entry.name.toLowerCase().endsWith(".md"))
|
|
610
|
+
await import_promises.writeFile(import_node_path2.join(to, entry.name), await import_promises.readFile(src), { mode: 384 });
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
await copy(input, skillsRoot);
|
|
614
|
+
} catch (error) {
|
|
615
|
+
if (error.code !== "ENOENT" || import_node_fs2.existsSync(input))
|
|
616
|
+
throw error;
|
|
617
|
+
}
|
|
618
|
+
return { directory, env, rulesFile, nativeRules, dispose };
|
|
619
|
+
} catch (error) {
|
|
620
|
+
await dispose();
|
|
621
|
+
throw error;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
367
625
|
// src/session/available-commands.ts
|
|
368
626
|
function normalizeCommand(raw) {
|
|
369
627
|
if (!raw || typeof raw !== "object")
|
|
@@ -611,15 +869,15 @@ class QuotaCache {
|
|
|
611
869
|
var import_sdk4 = require("@agentclientprotocol/sdk");
|
|
612
870
|
|
|
613
871
|
// src/runtimes/codex/quota.ts
|
|
614
|
-
var
|
|
615
|
-
var
|
|
872
|
+
var import_node_fs4 = require("node:fs");
|
|
873
|
+
var import_node_path4 = require("node:path");
|
|
616
874
|
var import_node_child_process = require("node:child_process");
|
|
617
875
|
var import_node_readline = __toESM(require("node:readline"), 1);
|
|
618
876
|
|
|
619
877
|
// src/runtimes/codex/codex-auth-preflight.ts
|
|
620
|
-
var
|
|
621
|
-
var
|
|
622
|
-
var
|
|
878
|
+
var import_node_fs3 = require("node:fs");
|
|
879
|
+
var import_node_os2 = require("node:os");
|
|
880
|
+
var import_node_path3 = require("node:path");
|
|
623
881
|
function emptyAcpAuthPreflight() {
|
|
624
882
|
return {
|
|
625
883
|
codexHome: "",
|
|
@@ -636,12 +894,12 @@ function resolveCodexHome() {
|
|
|
636
894
|
const fromEnv = process.env.CODEX_HOME?.trim();
|
|
637
895
|
if (fromEnv)
|
|
638
896
|
return fromEnv;
|
|
639
|
-
return
|
|
897
|
+
return import_node_path3.join(import_node_os2.homedir(), ".codex");
|
|
640
898
|
}
|
|
641
899
|
function probeCodexAuth() {
|
|
642
900
|
const codexHome = resolveCodexHome();
|
|
643
|
-
const hasCodexHome =
|
|
644
|
-
const hasAuthFile =
|
|
901
|
+
const hasCodexHome = import_node_fs3.existsSync(codexHome);
|
|
902
|
+
const hasAuthFile = import_node_fs3.existsSync(import_node_path3.join(codexHome, "auth.json"));
|
|
645
903
|
const hasApiKeyEnv = Boolean(process.env.CODEX_API_KEY?.trim() || process.env.OPENAI_API_KEY?.trim());
|
|
646
904
|
return {
|
|
647
905
|
codexHome,
|
|
@@ -665,8 +923,8 @@ function decodeJwtPayload(token) {
|
|
|
665
923
|
}
|
|
666
924
|
}
|
|
667
925
|
var cachedDynamicResult = null;
|
|
668
|
-
async function queryCodexAppServer(timeoutMs =
|
|
669
|
-
if (cachedDynamicResult && Date.now() - cachedDynamicResult.time <
|
|
926
|
+
async function queryCodexAppServer(timeoutMs = 1e4) {
|
|
927
|
+
if (cachedDynamicResult && Date.now() - cachedDynamicResult.time < 120000) {
|
|
670
928
|
return cachedDynamicResult.res;
|
|
671
929
|
}
|
|
672
930
|
return new Promise((resolve) => {
|
|
@@ -691,7 +949,8 @@ async function queryCodexAppServer(timeoutMs = 4000) {
|
|
|
691
949
|
};
|
|
692
950
|
timer = setTimeout(() => cleanup(null), timeoutMs);
|
|
693
951
|
try {
|
|
694
|
-
|
|
952
|
+
const cmd = process.platform === "win32" ? "codex" : import_node_fs4.existsSync("/mnt/c/Users") ? "codex.exe" : "codex";
|
|
953
|
+
proc = import_node_child_process.spawn(cmd, ["app-server"], {
|
|
695
954
|
stdio: ["pipe", "pipe", "pipe"],
|
|
696
955
|
shell: process.platform === "win32",
|
|
697
956
|
windowsHide: true
|
|
@@ -761,13 +1020,13 @@ function formatEpochTime(epochSeconds) {
|
|
|
761
1020
|
}
|
|
762
1021
|
async function probeCodexQuota(options) {
|
|
763
1022
|
const codexHome = resolveCodexHome();
|
|
764
|
-
const authPath =
|
|
1023
|
+
const authPath = import_node_path4.join(codexHome, "auth.json");
|
|
765
1024
|
let accountEmail;
|
|
766
1025
|
let accountPlan = "Codex Free / Local";
|
|
767
1026
|
let isLoggedIn = false;
|
|
768
|
-
if (
|
|
1027
|
+
if (import_node_fs4.existsSync(authPath)) {
|
|
769
1028
|
try {
|
|
770
|
-
const authData = JSON.parse(
|
|
1029
|
+
const authData = JSON.parse(import_node_fs4.readFileSync(authPath, "utf8"));
|
|
771
1030
|
if (authData.OPENAI_API_KEY) {
|
|
772
1031
|
isLoggedIn = true;
|
|
773
1032
|
accountPlan = "OpenAI API Key";
|
|
@@ -792,7 +1051,7 @@ async function probeCodexQuota(options) {
|
|
|
792
1051
|
isLoggedIn = true;
|
|
793
1052
|
accountPlan = "API Key (Env)";
|
|
794
1053
|
}
|
|
795
|
-
const dynamic = await queryCodexAppServer(
|
|
1054
|
+
const dynamic = await queryCodexAppServer(1e4);
|
|
796
1055
|
if (dynamic) {
|
|
797
1056
|
isLoggedIn = true;
|
|
798
1057
|
if (dynamic.account?.email)
|
|
@@ -858,8 +1117,92 @@ async function probeCodexQuota(options) {
|
|
|
858
1117
|
}
|
|
859
1118
|
|
|
860
1119
|
// src/runtimes/codex/index.ts
|
|
861
|
-
var
|
|
862
|
-
var
|
|
1120
|
+
var import_promises3 = require("node:fs/promises");
|
|
1121
|
+
var import_node_path7 = require("node:path");
|
|
1122
|
+
var import_node_os4 = require("node:os");
|
|
1123
|
+
var import_node_fs6 = require("node:fs");
|
|
1124
|
+
var import_node_crypto2 = require("node:crypto");
|
|
1125
|
+
|
|
1126
|
+
// src/resources/config-text.ts
|
|
1127
|
+
function mergeCodexConfigJson(input) {
|
|
1128
|
+
const block = (input.hostBlock ?? "").trim();
|
|
1129
|
+
if (!block)
|
|
1130
|
+
return { ok: false, reason: "empty-block" };
|
|
1131
|
+
const raw = (input.existingRaw ?? "").trim();
|
|
1132
|
+
if (!raw) {
|
|
1133
|
+
return { ok: true, json: JSON.stringify({ developer_instructions: block }), preservedUserInstructions: false };
|
|
1134
|
+
}
|
|
1135
|
+
let parsed;
|
|
1136
|
+
try {
|
|
1137
|
+
parsed = JSON.parse(raw);
|
|
1138
|
+
} catch {
|
|
1139
|
+
return { ok: false, reason: "invalid-json" };
|
|
1140
|
+
}
|
|
1141
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
1142
|
+
return { ok: false, reason: "invalid-json" };
|
|
1143
|
+
}
|
|
1144
|
+
const merged = { ...parsed };
|
|
1145
|
+
const existing = merged["developer_instructions"];
|
|
1146
|
+
if (existing === undefined) {
|
|
1147
|
+
merged["developer_instructions"] = block;
|
|
1148
|
+
return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: false };
|
|
1149
|
+
}
|
|
1150
|
+
if (typeof existing !== "string") {
|
|
1151
|
+
return { ok: false, reason: "conflicting-value" };
|
|
1152
|
+
}
|
|
1153
|
+
const kept = existing.trim();
|
|
1154
|
+
merged["developer_instructions"] = kept ? `${block}
|
|
1155
|
+
|
|
1156
|
+
${kept}` : block;
|
|
1157
|
+
return { ok: true, json: JSON.stringify(merged), preservedUserInstructions: kept !== "" };
|
|
1158
|
+
}
|
|
1159
|
+
function mergeConfigTomlPreserving(input) {
|
|
1160
|
+
const block = (input.replacementBlock ?? "").trim() ? `${input.replacementBlock.trim()}
|
|
1161
|
+
` : "";
|
|
1162
|
+
if (!input.existingText || !input.existingText.trim())
|
|
1163
|
+
return block;
|
|
1164
|
+
if (/"""|'''/.test(input.existingText) || /^\s*\[.*["'].*\]|^\s*\[\[|^\s*["'](?:model|model_provider)["']\s*=/m.test(input.existingText)) {
|
|
1165
|
+
throw new Error("复杂 TOML 配置需要结构化合并,已保留原文件");
|
|
1166
|
+
}
|
|
1167
|
+
const topKeys = new Set(input.managedTopKeys);
|
|
1168
|
+
const tables = new Set(input.managedTables);
|
|
1169
|
+
const out = [];
|
|
1170
|
+
let inManagedTable = false;
|
|
1171
|
+
let inAnyTable = false;
|
|
1172
|
+
for (const line of input.existingText.split(`
|
|
1173
|
+
`)) {
|
|
1174
|
+
const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(line)?.[1]?.trim() ?? null;
|
|
1175
|
+
if (header !== null) {
|
|
1176
|
+
inAnyTable = true;
|
|
1177
|
+
inManagedTable = tables.has(header);
|
|
1178
|
+
if (!inManagedTable)
|
|
1179
|
+
out.push(line);
|
|
1180
|
+
continue;
|
|
1181
|
+
}
|
|
1182
|
+
if (inManagedTable)
|
|
1183
|
+
continue;
|
|
1184
|
+
if (!inAnyTable) {
|
|
1185
|
+
const key = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1];
|
|
1186
|
+
if (key && topKeys.has(key))
|
|
1187
|
+
continue;
|
|
1188
|
+
}
|
|
1189
|
+
out.push(line);
|
|
1190
|
+
}
|
|
1191
|
+
const kept = out.join(`
|
|
1192
|
+
`).trim();
|
|
1193
|
+
if (!kept)
|
|
1194
|
+
return block;
|
|
1195
|
+
const tableAt = block.search(/^\s*\[/m);
|
|
1196
|
+
if (tableAt < 0)
|
|
1197
|
+
return block + `
|
|
1198
|
+
` + kept + `
|
|
1199
|
+
`;
|
|
1200
|
+
return block.slice(0, tableAt).trimEnd() + `
|
|
1201
|
+
|
|
1202
|
+
` + kept + `
|
|
1203
|
+
|
|
1204
|
+
` + block.slice(tableAt);
|
|
1205
|
+
}
|
|
863
1206
|
|
|
864
1207
|
// src/runtimes/codex/codex-provider-home.ts
|
|
865
1208
|
var INKDOWN_PROVIDER_ID = "inkdown-custom";
|
|
@@ -891,13 +1234,13 @@ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
|
|
|
891
1234
|
}
|
|
892
1235
|
|
|
893
1236
|
// src/runtimes/codex/codex-provider.ts
|
|
894
|
-
var
|
|
895
|
-
var
|
|
896
|
-
var
|
|
1237
|
+
var import_promises2 = require("node:fs/promises");
|
|
1238
|
+
var import_node_fs5 = require("node:fs");
|
|
1239
|
+
var import_node_path6 = require("node:path");
|
|
897
1240
|
|
|
898
1241
|
// src/client/acp-paths.ts
|
|
899
|
-
var
|
|
900
|
-
var
|
|
1242
|
+
var import_node_os3 = require("node:os");
|
|
1243
|
+
var import_node_path5 = require("node:path");
|
|
901
1244
|
function getDefaultAgentDataDir() {
|
|
902
1245
|
if (process.env.INKDOWN_DATA_DIR) {
|
|
903
1246
|
return process.env.INKDOWN_DATA_DIR;
|
|
@@ -906,20 +1249,20 @@ function getDefaultAgentDataDir() {
|
|
|
906
1249
|
return process.env.ACP_DATA_DIR;
|
|
907
1250
|
}
|
|
908
1251
|
if (process.platform === "win32") {
|
|
909
|
-
return process.env.LOCALAPPDATA || process.env.APPDATA ||
|
|
1252
|
+
return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path5.join(import_node_os3.homedir(), "AppData", "Local", "inkdown");
|
|
910
1253
|
}
|
|
911
1254
|
if (process.platform === "darwin") {
|
|
912
|
-
return
|
|
1255
|
+
return import_node_path5.join(import_node_os3.homedir(), "Library", "Application Support", "inkdown");
|
|
913
1256
|
}
|
|
914
|
-
return process.env.XDG_DATA_HOME ||
|
|
1257
|
+
return process.env.XDG_DATA_HOME || import_node_path5.join(import_node_os3.homedir(), ".local", "share", "inkdown");
|
|
915
1258
|
}
|
|
916
1259
|
|
|
917
1260
|
// src/runtimes/codex/codex-provider.ts
|
|
918
1261
|
function providerFilePath(dir) {
|
|
919
|
-
return
|
|
1262
|
+
return import_node_path6.join(dir, "agent", "provider.json");
|
|
920
1263
|
}
|
|
921
1264
|
function providerHomePath(dir) {
|
|
922
|
-
return
|
|
1265
|
+
return import_node_path6.join(dir, "agent", "codex-home");
|
|
923
1266
|
}
|
|
924
1267
|
function toStatus(stored) {
|
|
925
1268
|
if (!stored)
|
|
@@ -945,10 +1288,10 @@ function validate(payload) {
|
|
|
945
1288
|
}
|
|
946
1289
|
async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
|
|
947
1290
|
const file = providerFilePath(dir);
|
|
948
|
-
if (!
|
|
1291
|
+
if (!import_node_fs5.existsSync(file))
|
|
949
1292
|
return null;
|
|
950
1293
|
try {
|
|
951
|
-
const raw = JSON.parse(await
|
|
1294
|
+
const raw = JSON.parse(await import_promises2.readFile(file, "utf8"));
|
|
952
1295
|
if (typeof raw.baseUrl !== "string" || typeof raw.model !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
|
|
953
1296
|
return null;
|
|
954
1297
|
}
|
|
@@ -974,7 +1317,7 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
|
|
|
974
1317
|
const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
|
|
975
1318
|
if (!apiKey)
|
|
976
1319
|
return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
|
|
977
|
-
await
|
|
1320
|
+
await import_promises2.mkdir(import_node_path6.join(dir, "agent"), { recursive: true });
|
|
978
1321
|
const stored = {
|
|
979
1322
|
name: payload.name?.trim() || undefined,
|
|
980
1323
|
baseUrl: payload.baseUrl.trim(),
|
|
@@ -982,11 +1325,11 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
|
|
|
982
1325
|
apiKey,
|
|
983
1326
|
wireApi: payload.wireApi === "responses" ? "responses" : "chat"
|
|
984
1327
|
};
|
|
985
|
-
await
|
|
1328
|
+
await import_promises2.writeFile(file, JSON.stringify(stored, null, 2), "utf8");
|
|
986
1329
|
return ok(toStatus(stored));
|
|
987
1330
|
}
|
|
988
1331
|
async function clearAcpProvider(dir = getDefaultAgentDataDir()) {
|
|
989
|
-
await
|
|
1332
|
+
await import_promises2.rm(providerFilePath(dir), { force: true });
|
|
990
1333
|
return ok(undefined);
|
|
991
1334
|
}
|
|
992
1335
|
function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
|
|
@@ -996,8 +1339,20 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
|
|
|
996
1339
|
// src/runtimes/codex/index.ts
|
|
997
1340
|
async function provisionCustomProviderCodexHome(provider, codexHome) {
|
|
998
1341
|
try {
|
|
999
|
-
await
|
|
1000
|
-
|
|
1342
|
+
await import_promises3.mkdir(codexHome, { recursive: true });
|
|
1343
|
+
let existing = null;
|
|
1344
|
+
try {
|
|
1345
|
+
existing = await import_promises3.readFile(import_node_path7.join(codexHome, "config.toml"), "utf8");
|
|
1346
|
+
} catch (error) {
|
|
1347
|
+
if (error.code !== "ENOENT")
|
|
1348
|
+
throw error;
|
|
1349
|
+
}
|
|
1350
|
+
await import_promises3.writeFile(import_node_path7.join(codexHome, "config.toml"), mergeConfigTomlPreserving({
|
|
1351
|
+
existingText: existing,
|
|
1352
|
+
managedTopKeys: ["model", "model_provider"],
|
|
1353
|
+
managedTables: [`model_providers.${INKDOWN_PROVIDER_ID}`],
|
|
1354
|
+
replacementBlock: buildCustomProviderConfigToml(provider)
|
|
1355
|
+
}), "utf8");
|
|
1001
1356
|
return true;
|
|
1002
1357
|
} catch (error) {
|
|
1003
1358
|
console.error("[acp] 自定义供应商 config.toml 写入失败,回落本机登录", error);
|
|
@@ -1007,6 +1362,78 @@ async function provisionCustomProviderCodexHome(provider, codexHome) {
|
|
|
1007
1362
|
var codexAdapter = {
|
|
1008
1363
|
id: "codex-acp",
|
|
1009
1364
|
probeQuota: async (options) => probeCodexQuota(options),
|
|
1365
|
+
supportedBridgeVersions: ["2.2.2"],
|
|
1366
|
+
prepareAppResources: async ({ directory, workspaceRoot, env: overrideEnv }) => {
|
|
1367
|
+
const load = readAppResourcesDir(directory);
|
|
1368
|
+
const skillsFound = load.skills.map((s) => s.name);
|
|
1369
|
+
const rulesText = readAppRulesText(directory);
|
|
1370
|
+
if (!rulesText) {
|
|
1371
|
+
return {
|
|
1372
|
+
report: {
|
|
1373
|
+
rulesApplied: false,
|
|
1374
|
+
rulesChars: 0,
|
|
1375
|
+
profileDigest: null,
|
|
1376
|
+
skillsFound,
|
|
1377
|
+
reason: "rules-missing"
|
|
1378
|
+
}
|
|
1379
|
+
};
|
|
1380
|
+
}
|
|
1381
|
+
const env = { ...process.env, ...overrideEnv };
|
|
1382
|
+
const notApplied = (reason) => ({ report: {
|
|
1383
|
+
rulesApplied: false,
|
|
1384
|
+
rulesPrepared: false,
|
|
1385
|
+
skillsApplied: false,
|
|
1386
|
+
rulesChars: rulesText.length,
|
|
1387
|
+
profileDigest: digestAppResources(load),
|
|
1388
|
+
skillsFound,
|
|
1389
|
+
reason
|
|
1390
|
+
} });
|
|
1391
|
+
if (!load.directoryReadable)
|
|
1392
|
+
return notApplied("invalid-resource-directory");
|
|
1393
|
+
if (env.CODEX_PATH)
|
|
1394
|
+
return notApplied("execution-not-verified");
|
|
1395
|
+
const codexHome = env.CODEX_HOME || import_node_path7.join(import_node_os4.homedir(), ".codex");
|
|
1396
|
+
try {
|
|
1397
|
+
await import_promises3.readFile(import_node_path7.join(codexHome, "config.toml"));
|
|
1398
|
+
return notApplied("effective-config-not-verified");
|
|
1399
|
+
} catch (error) {
|
|
1400
|
+
if (error.code !== "ENOENT")
|
|
1401
|
+
return notApplied("effective-config-not-verified");
|
|
1402
|
+
}
|
|
1403
|
+
for (let dir = workspaceRoot;dir; ) {
|
|
1404
|
+
if (import_node_fs6.existsSync(import_node_path7.join(dir, ".codex", "config.toml")))
|
|
1405
|
+
return notApplied("effective-config-not-verified");
|
|
1406
|
+
if (import_node_fs6.existsSync(import_node_path7.join(dir, ".git")))
|
|
1407
|
+
break;
|
|
1408
|
+
const parent = import_node_path7.dirname(dir);
|
|
1409
|
+
if (parent === dir)
|
|
1410
|
+
break;
|
|
1411
|
+
dir = parent;
|
|
1412
|
+
}
|
|
1413
|
+
const merged = mergeCodexConfigJson({ existingRaw: env["CODEX_CONFIG"], hostBlock: rulesText });
|
|
1414
|
+
if (!merged.ok) {
|
|
1415
|
+
return {
|
|
1416
|
+
report: {
|
|
1417
|
+
rulesApplied: false,
|
|
1418
|
+
rulesChars: rulesText.length,
|
|
1419
|
+
profileDigest: digestAppResources(load),
|
|
1420
|
+
skillsFound,
|
|
1421
|
+
reason: merged.reason === "invalid-json" ? "invalid-codex-config" : "conflicting-codex-config"
|
|
1422
|
+
}
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
return {
|
|
1426
|
+
env: { CODEX_CONFIG: merged.json },
|
|
1427
|
+
report: {
|
|
1428
|
+
rulesApplied: false,
|
|
1429
|
+
rulesPrepared: true,
|
|
1430
|
+
skillsApplied: false,
|
|
1431
|
+
rulesChars: rulesText.length,
|
|
1432
|
+
profileDigest: import_node_crypto2.createHash("sha256").update(JSON.stringify([digestAppResources(load), codexHome, workspaceRoot, merged.json])).digest("hex"),
|
|
1433
|
+
skillsFound
|
|
1434
|
+
}
|
|
1435
|
+
};
|
|
1436
|
+
},
|
|
1010
1437
|
probeAuth: () => {
|
|
1011
1438
|
return probeCodexAuth();
|
|
1012
1439
|
},
|
|
@@ -1023,11 +1450,84 @@ var codexAdapter = {
|
|
|
1023
1450
|
}
|
|
1024
1451
|
};
|
|
1025
1452
|
|
|
1026
|
-
// src/
|
|
1027
|
-
var
|
|
1028
|
-
var import_node_os3 = require("node:os");
|
|
1029
|
-
var import_node_path6 = require("node:path");
|
|
1453
|
+
// src/resources/runtime-bindings.ts
|
|
1454
|
+
var import_node_path8 = require("node:path");
|
|
1030
1455
|
var import_node_child_process2 = require("node:child_process");
|
|
1456
|
+
var import_node_util = require("node:util");
|
|
1457
|
+
var APP_RESOURCE_CAPABILITIES = {
|
|
1458
|
+
"codex-acp": { entry: "CODEX_CONFIG", strategy: "native-overlay", configHome: "CODEX_HOME" },
|
|
1459
|
+
opencode: { entry: "OPENCODE_CONFIG_CONTENT", strategy: "native-overlay", configHome: "OPENCODE_CONFIG_DIR" },
|
|
1460
|
+
"opencode-v2": { entry: null, strategy: "compatibility", configHome: null },
|
|
1461
|
+
claude: { entry: "_meta.systemPrompt + _meta.claudeCode.options.plugins", strategy: "native-session", configHome: "CLAUDE_CONFIG_DIR" },
|
|
1462
|
+
gemini: { entry: null, strategy: "compatibility", configHome: "GEMINI_CLI_HOME" },
|
|
1463
|
+
copilot: { entry: null, strategy: "compatibility", configHome: "COPILOT_HOME", candidateEntry: "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" },
|
|
1464
|
+
"cursor-cli": { entry: null, strategy: "compatibility", configHome: "CURSOR_CONFIG_DIR" },
|
|
1465
|
+
agy: { entry: "_meta.appResources.directory", strategy: "native-session", configHome: null },
|
|
1466
|
+
deepseek: { entry: null, strategy: "compatibility", configHome: null }
|
|
1467
|
+
};
|
|
1468
|
+
function prepareCompatibilityResources(directory, reason) {
|
|
1469
|
+
const load = readAppResourcesDir(directory);
|
|
1470
|
+
return { report: {
|
|
1471
|
+
rulesApplied: false,
|
|
1472
|
+
rulesPrepared: false,
|
|
1473
|
+
skillsApplied: false,
|
|
1474
|
+
rulesChars: load.rules?.chars ?? 0,
|
|
1475
|
+
profileDigest: digestAppResources(load),
|
|
1476
|
+
skillsFound: load.skills.map((s) => s.name),
|
|
1477
|
+
reason
|
|
1478
|
+
} };
|
|
1479
|
+
}
|
|
1480
|
+
function mergeOpenCodeAppConfig(raw, directory) {
|
|
1481
|
+
const value = raw?.trim() ? JSON.parse(raw) : {};
|
|
1482
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
1483
|
+
throw new Error("invalid-opencode-config");
|
|
1484
|
+
const config = value;
|
|
1485
|
+
if (config.instructions !== undefined && (!Array.isArray(config.instructions) || config.instructions.some((v) => typeof v !== "string")))
|
|
1486
|
+
throw new Error("invalid-opencode-instructions");
|
|
1487
|
+
if (config.skills !== undefined && (!config.skills || typeof config.skills !== "object" || Array.isArray(config.skills)))
|
|
1488
|
+
throw new Error("invalid-opencode-skills");
|
|
1489
|
+
const skills = config.skills ?? {};
|
|
1490
|
+
if (skills.paths !== undefined && (!Array.isArray(skills.paths) || skills.paths.some((v) => typeof v !== "string")))
|
|
1491
|
+
throw new Error("invalid-opencode-skill-paths");
|
|
1492
|
+
return JSON.stringify({
|
|
1493
|
+
...config,
|
|
1494
|
+
instructions: [...new Set([...config.instructions ?? [], import_node_path8.join(directory, "AGENTS.md")])],
|
|
1495
|
+
skills: { ...skills, paths: [...new Set([...skills.paths ?? [], import_node_path8.join(directory, "skills")])] }
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
async function prepareOpenCodeResources(input) {
|
|
1499
|
+
const prep = prepareCompatibilityResources(input.directory, "native-entry-not-verified");
|
|
1500
|
+
if (!input.command || !readAppRulesText(input.directory))
|
|
1501
|
+
return prep;
|
|
1502
|
+
try {
|
|
1503
|
+
const { stdout } = await import_node_util.promisify(import_node_child_process2.execFile)(input.command, ["--version"], { env: input.env, timeout: 8000, windowsHide: true });
|
|
1504
|
+
if (stdout.trim() !== "1.18.35")
|
|
1505
|
+
return prep;
|
|
1506
|
+
const json = mergeOpenCodeAppConfig(input.env?.OPENCODE_CONFIG_CONTENT, input.directory);
|
|
1507
|
+
return { env: { OPENCODE_CONFIG_CONTENT: json }, report: { ...prep.report, rulesPrepared: true, reason: undefined } };
|
|
1508
|
+
} catch {
|
|
1509
|
+
return { ...prep, report: { ...prep.report, reason: "native-config-prepare-failed" } };
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
function prepareClaudeResources(directory) {
|
|
1513
|
+
const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
|
|
1514
|
+
return { ...prep, report: { ...prep.report, rulesPrepared: !!readAppRulesText(directory) } };
|
|
1515
|
+
}
|
|
1516
|
+
function claudeResourceSessionMeta(directory) {
|
|
1517
|
+
const text = readAppRulesText(directory);
|
|
1518
|
+
if (!text)
|
|
1519
|
+
return;
|
|
1520
|
+
return {
|
|
1521
|
+
systemPrompt: { type: "preset", preset: "claude_code", append: text },
|
|
1522
|
+
claudeCode: { options: { plugins: [{ type: "local", path: directory }] } }
|
|
1523
|
+
};
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
// src/runtimes/claude/quota.ts
|
|
1527
|
+
var import_node_fs7 = require("node:fs");
|
|
1528
|
+
var import_node_os5 = require("node:os");
|
|
1529
|
+
var import_node_path9 = require("node:path");
|
|
1530
|
+
var import_node_child_process3 = require("node:child_process");
|
|
1031
1531
|
var cachedClaudeAuth = null;
|
|
1032
1532
|
async function queryClaudeAuthStatus(timeoutMs = 1200) {
|
|
1033
1533
|
if (cachedClaudeAuth && Date.now() - cachedClaudeAuth.time < 30000) {
|
|
@@ -1035,7 +1535,7 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
|
|
|
1035
1535
|
}
|
|
1036
1536
|
return new Promise((resolve) => {
|
|
1037
1537
|
try {
|
|
1038
|
-
|
|
1538
|
+
import_node_child_process3.execFile("claude", ["auth", "status", "--json"], { timeout: timeoutMs, windowsHide: true, shell: process.platform === "win32" }, (err, stdout) => {
|
|
1039
1539
|
if (!stdout)
|
|
1040
1540
|
return resolve(null);
|
|
1041
1541
|
try {
|
|
@@ -1053,15 +1553,15 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
|
|
|
1053
1553
|
}
|
|
1054
1554
|
async function probeClaudeQuota(options) {
|
|
1055
1555
|
const claudeHome = resolveClaudeHome();
|
|
1056
|
-
const claudeJsonPath =
|
|
1057
|
-
const credsPath =
|
|
1556
|
+
const claudeJsonPath = import_node_path9.join(import_node_os5.homedir(), ".claude.json");
|
|
1557
|
+
const credsPath = import_node_path9.join(claudeHome, ".credentials.json");
|
|
1058
1558
|
let isLoggedIn = false;
|
|
1059
1559
|
let isBanned = false;
|
|
1060
1560
|
let accountEmail;
|
|
1061
1561
|
let plan = "Claude Free / Default";
|
|
1062
|
-
if (
|
|
1562
|
+
if (import_node_fs7.existsSync(claudeJsonPath)) {
|
|
1063
1563
|
try {
|
|
1064
|
-
const data = JSON.parse(
|
|
1564
|
+
const data = JSON.parse(import_node_fs7.readFileSync(claudeJsonPath, "utf8"));
|
|
1065
1565
|
if (data.oauthAccount) {
|
|
1066
1566
|
isLoggedIn = true;
|
|
1067
1567
|
accountEmail = data.oauthAccount.emailAddress;
|
|
@@ -1072,9 +1572,9 @@ async function probeClaudeQuota(options) {
|
|
|
1072
1572
|
}
|
|
1073
1573
|
} catch {}
|
|
1074
1574
|
}
|
|
1075
|
-
if (
|
|
1575
|
+
if (import_node_fs7.existsSync(credsPath)) {
|
|
1076
1576
|
try {
|
|
1077
|
-
const creds = JSON.parse(
|
|
1577
|
+
const creds = JSON.parse(import_node_fs7.readFileSync(credsPath, "utf8"));
|
|
1078
1578
|
if (creds.accessToken || creds.sessionKey)
|
|
1079
1579
|
isLoggedIn = true;
|
|
1080
1580
|
} catch {}
|
|
@@ -1126,19 +1626,19 @@ async function probeClaudeQuota(options) {
|
|
|
1126
1626
|
}
|
|
1127
1627
|
|
|
1128
1628
|
// src/runtimes/claude/index.ts
|
|
1129
|
-
var
|
|
1130
|
-
var
|
|
1131
|
-
var
|
|
1629
|
+
var import_node_fs8 = require("node:fs");
|
|
1630
|
+
var import_node_os6 = require("node:os");
|
|
1631
|
+
var import_node_path10 = require("node:path");
|
|
1132
1632
|
function resolveClaudeHome() {
|
|
1133
1633
|
const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
1134
1634
|
if (fromEnv)
|
|
1135
1635
|
return fromEnv;
|
|
1136
|
-
return
|
|
1636
|
+
return import_node_path10.join(import_node_os6.homedir(), ".claude");
|
|
1137
1637
|
}
|
|
1138
1638
|
function probeClaudeAuth() {
|
|
1139
1639
|
const claudeHome = resolveClaudeHome();
|
|
1140
|
-
const hasCodexHome =
|
|
1141
|
-
const hasAuthFile =
|
|
1640
|
+
const hasCodexHome = import_node_fs8.existsSync(claudeHome);
|
|
1641
|
+
const hasAuthFile = import_node_fs8.existsSync(import_node_path10.join(import_node_os6.homedir(), ".claude.json")) || import_node_fs8.existsSync(import_node_path10.join(claudeHome, ".credentials.json"));
|
|
1142
1642
|
const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
|
|
1143
1643
|
return {
|
|
1144
1644
|
codexHome: claudeHome,
|
|
@@ -1150,6 +1650,9 @@ function probeClaudeAuth() {
|
|
|
1150
1650
|
}
|
|
1151
1651
|
var claudeAdapter = {
|
|
1152
1652
|
id: "claude",
|
|
1653
|
+
supportedBridgeVersions: ["0.91.0"],
|
|
1654
|
+
prepareAppResources: async ({ directory }) => prepareClaudeResources(directory),
|
|
1655
|
+
appResourceSessionMeta: claudeResourceSessionMeta,
|
|
1153
1656
|
probeAuth: () => probeClaudeAuth(),
|
|
1154
1657
|
probeQuota: async (options) => probeClaudeQuota(options),
|
|
1155
1658
|
orderAuthMethods: (methods) => methods,
|
|
@@ -1157,16 +1660,16 @@ var claudeAdapter = {
|
|
|
1157
1660
|
};
|
|
1158
1661
|
|
|
1159
1662
|
// src/runtimes/gemini/index.ts
|
|
1160
|
-
var
|
|
1161
|
-
var
|
|
1162
|
-
var
|
|
1663
|
+
var import_node_fs9 = require("node:fs");
|
|
1664
|
+
var import_node_os7 = require("node:os");
|
|
1665
|
+
var import_node_path11 = require("node:path");
|
|
1163
1666
|
function resolveGeminiHome() {
|
|
1164
|
-
return
|
|
1667
|
+
return import_node_path11.join(import_node_os7.homedir(), ".gemini");
|
|
1165
1668
|
}
|
|
1166
1669
|
function probeGeminiAuth() {
|
|
1167
1670
|
const geminiHome = resolveGeminiHome();
|
|
1168
|
-
const hasCodexHome =
|
|
1169
|
-
const hasAuthFile =
|
|
1671
|
+
const hasCodexHome = import_node_fs9.existsSync(geminiHome);
|
|
1672
|
+
const hasAuthFile = import_node_fs9.existsSync(import_node_path11.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
|
|
1170
1673
|
const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
|
|
1171
1674
|
return {
|
|
1172
1675
|
codexHome: geminiHome,
|
|
@@ -1178,24 +1681,25 @@ function probeGeminiAuth() {
|
|
|
1178
1681
|
}
|
|
1179
1682
|
var geminiAdapter = {
|
|
1180
1683
|
id: "gemini",
|
|
1684
|
+
prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-would-isolate-auth"),
|
|
1181
1685
|
probeAuth: () => probeGeminiAuth(),
|
|
1182
1686
|
orderAuthMethods: (methods) => methods,
|
|
1183
1687
|
canSkipInteractiveAuth: () => false
|
|
1184
1688
|
};
|
|
1185
1689
|
|
|
1186
1690
|
// src/runtimes/copilot/index.ts
|
|
1187
|
-
var
|
|
1188
|
-
var
|
|
1189
|
-
var
|
|
1691
|
+
var import_node_fs10 = require("node:fs");
|
|
1692
|
+
var import_node_os8 = require("node:os");
|
|
1693
|
+
var import_node_path12 = require("node:path");
|
|
1190
1694
|
function resolveCopilotHome() {
|
|
1191
1695
|
const fromEnv = process.env.COPILOT_HOME?.trim();
|
|
1192
1696
|
if (fromEnv)
|
|
1193
1697
|
return fromEnv;
|
|
1194
|
-
return
|
|
1698
|
+
return import_node_path12.join(import_node_os8.homedir(), ".copilot");
|
|
1195
1699
|
}
|
|
1196
1700
|
function hasCopilotLogin(home) {
|
|
1197
1701
|
try {
|
|
1198
|
-
const raw =
|
|
1702
|
+
const raw = import_node_fs10.readFileSync(import_node_path12.join(home, "config.json"), "utf8");
|
|
1199
1703
|
const parsed = JSON.parse(raw);
|
|
1200
1704
|
return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
|
|
1201
1705
|
} catch {
|
|
@@ -1204,7 +1708,7 @@ function hasCopilotLogin(home) {
|
|
|
1204
1708
|
}
|
|
1205
1709
|
function probeCopilotAuth() {
|
|
1206
1710
|
const copilotHome = resolveCopilotHome();
|
|
1207
|
-
const hasCodexHome =
|
|
1711
|
+
const hasCodexHome = import_node_fs10.existsSync(copilotHome);
|
|
1208
1712
|
const hasAuthFile = hasCopilotLogin(copilotHome);
|
|
1209
1713
|
const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
|
|
1210
1714
|
return {
|
|
@@ -1217,18 +1721,21 @@ function probeCopilotAuth() {
|
|
|
1217
1721
|
}
|
|
1218
1722
|
var copilotAdapter = {
|
|
1219
1723
|
id: "copilot",
|
|
1724
|
+
prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-entry-not-verified"),
|
|
1220
1725
|
probeAuth: () => probeCopilotAuth(),
|
|
1221
1726
|
orderAuthMethods: (methods) => methods,
|
|
1222
1727
|
canSkipInteractiveAuth: () => false
|
|
1223
1728
|
};
|
|
1224
1729
|
|
|
1225
1730
|
// src/runtimes/opencode/quota.ts
|
|
1226
|
-
var
|
|
1227
|
-
var
|
|
1731
|
+
var import_node_fs11 = require("node:fs");
|
|
1732
|
+
var import_node_child_process4 = require("node:child_process");
|
|
1733
|
+
var os = __toESM(require("node:os"), 1);
|
|
1734
|
+
var path = __toESM(require("node:path"), 1);
|
|
1228
1735
|
function resolveOpencodeAuthPath() {
|
|
1229
1736
|
const candidates = resolveOpencodeAuthCandidates();
|
|
1230
1737
|
for (const c of candidates) {
|
|
1231
|
-
if (
|
|
1738
|
+
if (import_node_fs11.existsSync(c))
|
|
1232
1739
|
return c;
|
|
1233
1740
|
}
|
|
1234
1741
|
return candidates[0] ?? null;
|
|
@@ -1240,7 +1747,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
|
|
|
1240
1747
|
}
|
|
1241
1748
|
return new Promise((resolve) => {
|
|
1242
1749
|
try {
|
|
1243
|
-
|
|
1750
|
+
import_node_child_process4.execFile("opencode", ["stats", "--standalone", "--cost", "--json"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
|
|
1244
1751
|
if (!stdout)
|
|
1245
1752
|
return resolve(null);
|
|
1246
1753
|
try {
|
|
@@ -1259,7 +1766,7 @@ async function queryOpencodeStats(timeoutMs = 1200) {
|
|
|
1259
1766
|
async function queryOpencodeAuthList(timeoutMs = 1200) {
|
|
1260
1767
|
return new Promise((resolve) => {
|
|
1261
1768
|
try {
|
|
1262
|
-
|
|
1769
|
+
import_node_child_process4.execFile("opencode", ["auth", "list"], { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
|
|
1263
1770
|
if (!stdout)
|
|
1264
1771
|
return resolve([]);
|
|
1265
1772
|
const lines = stdout.split(`
|
|
@@ -1271,14 +1778,170 @@ async function queryOpencodeAuthList(timeoutMs = 1200) {
|
|
|
1271
1778
|
}
|
|
1272
1779
|
});
|
|
1273
1780
|
}
|
|
1781
|
+
function readLocalOpencodeCredentials() {
|
|
1782
|
+
const home = os.homedir();
|
|
1783
|
+
const dbPaths = [
|
|
1784
|
+
path.join(home, ".local", "share", "opencode", "opencode.db"),
|
|
1785
|
+
process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "opencode", "opencode.db") : null,
|
|
1786
|
+
path.join(home, ".config", "opencode", "opencode.db")
|
|
1787
|
+
].filter(Boolean);
|
|
1788
|
+
for (const dbPath of dbPaths) {
|
|
1789
|
+
if (!import_node_fs11.existsSync(dbPath))
|
|
1790
|
+
continue;
|
|
1791
|
+
try {
|
|
1792
|
+
let rows = [];
|
|
1793
|
+
if (typeof process.versions?.bun !== "undefined") {
|
|
1794
|
+
const { Database } = require("bun:sqlite");
|
|
1795
|
+
const db = new Database(dbPath, { readonly: true });
|
|
1796
|
+
rows = db.query("SELECT integration_id, value FROM credential").all();
|
|
1797
|
+
db.close();
|
|
1798
|
+
} else {
|
|
1799
|
+
const { DatabaseSync } = require("node:sqlite");
|
|
1800
|
+
const db = new DatabaseSync(dbPath, { readOnly: true });
|
|
1801
|
+
rows = db.prepare("SELECT integration_id, value FROM credential").all();
|
|
1802
|
+
db.close();
|
|
1803
|
+
}
|
|
1804
|
+
const opencodeCred = rows.find((r) => r.integration_id === "opencode");
|
|
1805
|
+
if (opencodeCred?.value) {
|
|
1806
|
+
const parsed = JSON.parse(opencodeCred.value);
|
|
1807
|
+
const meta = parsed.metadata || {};
|
|
1808
|
+
return {
|
|
1809
|
+
email: meta.email || undefined,
|
|
1810
|
+
name: meta.email ? meta.email.split("@")[0] : meta.orgName || undefined,
|
|
1811
|
+
token: parsed.access || undefined,
|
|
1812
|
+
orgId: meta.orgID || undefined,
|
|
1813
|
+
accountId: meta.accountID || undefined
|
|
1814
|
+
};
|
|
1815
|
+
}
|
|
1816
|
+
} catch {
|
|
1817
|
+
try {
|
|
1818
|
+
const buf = import_node_fs11.readFileSync(dbPath, "utf8");
|
|
1819
|
+
const emailMatch = buf.match(/"email"\s*:\s*"([^"]+)"/);
|
|
1820
|
+
const tokenMatch = buf.match(/"access"\s*:\s*"(st_[a-zA-Z0-9_\\-]+)"/);
|
|
1821
|
+
const orgMatch = buf.match(/"orgID"\s*:\s*"(wrk_[a-zA-Z0-9_\\-]+)"/);
|
|
1822
|
+
const accMatch = buf.match(/"accountID"\s*:\s*"(acc_[a-zA-Z0-9_\\-]+)"/);
|
|
1823
|
+
if (emailMatch || tokenMatch) {
|
|
1824
|
+
return {
|
|
1825
|
+
email: emailMatch?.[1],
|
|
1826
|
+
name: emailMatch?.[1]?.split("@")[0],
|
|
1827
|
+
token: tokenMatch?.[1],
|
|
1828
|
+
orgId: orgMatch?.[1],
|
|
1829
|
+
accountId: accMatch?.[1]
|
|
1830
|
+
};
|
|
1831
|
+
}
|
|
1832
|
+
} catch {}
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
return {};
|
|
1836
|
+
}
|
|
1837
|
+
async function probeOpencodeGoOnlineQuota(creds, runtimeId = "opencode") {
|
|
1838
|
+
if (!creds.token || !creds.orgId)
|
|
1839
|
+
return null;
|
|
1840
|
+
try {
|
|
1841
|
+
const res = await fetch("https://opencode.ai/console/api/go/status", {
|
|
1842
|
+
headers: {
|
|
1843
|
+
Authorization: `Bearer ${creds.token}`,
|
|
1844
|
+
"x-opencode-org-id": creds.orgId,
|
|
1845
|
+
"x-opencode-account-id": creds.accountId || ""
|
|
1846
|
+
},
|
|
1847
|
+
signal: AbortSignal.timeout(3500)
|
|
1848
|
+
});
|
|
1849
|
+
if (!res.ok)
|
|
1850
|
+
return null;
|
|
1851
|
+
const data = await res.json();
|
|
1852
|
+
const meters = data?.access?.meters;
|
|
1853
|
+
if (!meters)
|
|
1854
|
+
return null;
|
|
1855
|
+
const formatReset = (isoStr) => {
|
|
1856
|
+
if (!isoStr)
|
|
1857
|
+
return;
|
|
1858
|
+
const diffMs = new Date(isoStr).getTime() - Date.now();
|
|
1859
|
+
if (diffMs <= 0)
|
|
1860
|
+
return "已重置";
|
|
1861
|
+
const totalMins = Math.floor(diffMs / 60000);
|
|
1862
|
+
const hours = Math.floor(totalMins / 60);
|
|
1863
|
+
const days = Math.floor(hours / 24);
|
|
1864
|
+
if (days > 0) {
|
|
1865
|
+
const remH = hours % 24;
|
|
1866
|
+
return `Resets in ${days}d ${remH}h`;
|
|
1867
|
+
}
|
|
1868
|
+
const remM = totalMins % 60;
|
|
1869
|
+
return `Resets in ${hours}h ${remM}m`;
|
|
1870
|
+
};
|
|
1871
|
+
const calcWindow = (m, label, durMins) => {
|
|
1872
|
+
if (!m || !m.limitMicroCents)
|
|
1873
|
+
return;
|
|
1874
|
+
const limit = Number(m.limitMicroCents);
|
|
1875
|
+
const used = Number(m.usedMicroCents || 0);
|
|
1876
|
+
const usedPercent = limit > 0 ? Math.round(used / limit * 100) : 0;
|
|
1877
|
+
const percentLeft = Math.max(0, 100 - usedPercent);
|
|
1878
|
+
return {
|
|
1879
|
+
label,
|
|
1880
|
+
usedPercent,
|
|
1881
|
+
percentLeft,
|
|
1882
|
+
windowDurationMins: durMins,
|
|
1883
|
+
resetsAt: formatReset(m.resetsAt)
|
|
1884
|
+
};
|
|
1885
|
+
};
|
|
1886
|
+
const rolling = calcWindow(meters.fiveHour, "Rolling", 300);
|
|
1887
|
+
const weekly = calcWindow(meters.week, "Weekly", 10080);
|
|
1888
|
+
const monthly = calcWindow(meters.month, "Monthly", 43200);
|
|
1889
|
+
let creditBalance = "$0.00";
|
|
1890
|
+
try {
|
|
1891
|
+
const bRes = await fetch("https://opencode.ai/console/api/billing/status", {
|
|
1892
|
+
headers: {
|
|
1893
|
+
Authorization: `Bearer ${creds.token}`,
|
|
1894
|
+
"x-opencode-org-id": creds.orgId,
|
|
1895
|
+
"x-opencode-account-id": creds.accountId || ""
|
|
1896
|
+
},
|
|
1897
|
+
signal: AbortSignal.timeout(2000)
|
|
1898
|
+
});
|
|
1899
|
+
if (bRes.ok) {
|
|
1900
|
+
const bData = await bRes.json();
|
|
1901
|
+
const availMicro = Number(bData.availableMicroCents || 0);
|
|
1902
|
+
creditBalance = `$${(availMicro / 1e8).toFixed(2)}`;
|
|
1903
|
+
}
|
|
1904
|
+
} catch {}
|
|
1905
|
+
const quota = {
|
|
1906
|
+
runtimeId,
|
|
1907
|
+
provider: "OpenCode",
|
|
1908
|
+
account: {
|
|
1909
|
+
email: creds.email,
|
|
1910
|
+
name: creds.name || "OpenCode User",
|
|
1911
|
+
plan: "OpenCode Go",
|
|
1912
|
+
type: "opencode"
|
|
1913
|
+
},
|
|
1914
|
+
primaryWindow: rolling,
|
|
1915
|
+
secondaryWindow: weekly,
|
|
1916
|
+
extraWindows: monthly ? [monthly] : undefined,
|
|
1917
|
+
credits: {
|
|
1918
|
+
balance: creditBalance,
|
|
1919
|
+
currency: "USD",
|
|
1920
|
+
unlimited: false
|
|
1921
|
+
},
|
|
1922
|
+
status: "ok",
|
|
1923
|
+
updatedAt: Date.now()
|
|
1924
|
+
};
|
|
1925
|
+
return quota;
|
|
1926
|
+
} catch {
|
|
1927
|
+
return null;
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1274
1930
|
async function probeOpencodeQuota(runtimeId = "opencode") {
|
|
1931
|
+
const dbCreds = readLocalOpencodeCredentials();
|
|
1932
|
+
if (dbCreds.token) {
|
|
1933
|
+
const goQuota = await probeOpencodeGoOnlineQuota(dbCreds, runtimeId);
|
|
1934
|
+
if (goQuota)
|
|
1935
|
+
return goQuota;
|
|
1936
|
+
}
|
|
1275
1937
|
const authPath = resolveOpencodeAuthPath();
|
|
1276
|
-
let isLoggedIn =
|
|
1277
|
-
let accountEmail;
|
|
1938
|
+
let isLoggedIn = Boolean(dbCreds.token || dbCreds.email);
|
|
1939
|
+
let accountEmail = dbCreds.email;
|
|
1940
|
+
let accountName = dbCreds.name;
|
|
1278
1941
|
let plan = "OpenCode Community";
|
|
1279
|
-
if (authPath &&
|
|
1942
|
+
if (authPath && import_node_fs11.existsSync(authPath)) {
|
|
1280
1943
|
try {
|
|
1281
|
-
const data = JSON.parse(
|
|
1944
|
+
const data = JSON.parse(import_node_fs11.readFileSync(authPath, "utf8"));
|
|
1282
1945
|
if (data && typeof data === "object") {
|
|
1283
1946
|
const keys = Object.keys(data);
|
|
1284
1947
|
if (keys.length > 0) {
|
|
@@ -1298,7 +1961,9 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
|
|
|
1298
1961
|
if (authList.length > 0) {
|
|
1299
1962
|
isLoggedIn = true;
|
|
1300
1963
|
const providers = authList.map((l) => l.split(/\s{2,}/)[0]).filter(Boolean);
|
|
1301
|
-
if (providers.
|
|
1964
|
+
if (providers.some((p) => p.toLowerCase().includes("go"))) {
|
|
1965
|
+
plan = "OpenCode Go";
|
|
1966
|
+
} else if (providers.length > 0) {
|
|
1302
1967
|
plan = `OpenCode (${providers.join(", ")})`;
|
|
1303
1968
|
}
|
|
1304
1969
|
}
|
|
@@ -1317,7 +1982,7 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
|
|
|
1317
1982
|
let credits;
|
|
1318
1983
|
if (stats && typeof stats.cost === "number") {
|
|
1319
1984
|
credits = {
|
|
1320
|
-
balance: stats.cost > 0 ? `$${stats.cost.toFixed(2)} spent` : "0.00"
|
|
1985
|
+
balance: stats.cost > 0 ? `$${stats.cost.toFixed(2)} spent` : "$0.00"
|
|
1321
1986
|
};
|
|
1322
1987
|
}
|
|
1323
1988
|
return {
|
|
@@ -1325,6 +1990,7 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
|
|
|
1325
1990
|
provider: "OpenCode",
|
|
1326
1991
|
account: {
|
|
1327
1992
|
email: accountEmail,
|
|
1993
|
+
name: accountName,
|
|
1328
1994
|
plan,
|
|
1329
1995
|
type: "provider_oauth"
|
|
1330
1996
|
},
|
|
@@ -1335,16 +2001,16 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
|
|
|
1335
2001
|
}
|
|
1336
2002
|
|
|
1337
2003
|
// src/runtimes/opencode/index.ts
|
|
1338
|
-
var
|
|
1339
|
-
var
|
|
1340
|
-
var
|
|
2004
|
+
var import_node_fs12 = require("node:fs");
|
|
2005
|
+
var import_node_os9 = require("node:os");
|
|
2006
|
+
var import_node_path13 = require("node:path");
|
|
1341
2007
|
function pickEnv(env, key) {
|
|
1342
2008
|
return env?.[key]?.trim() ?? "";
|
|
1343
2009
|
}
|
|
1344
2010
|
function resolveOpencodeAuthCandidates(overrides) {
|
|
1345
2011
|
const platform = overrides?.platform ?? process.platform;
|
|
1346
2012
|
const env = overrides?.env ?? process.env;
|
|
1347
|
-
const home = overrides?.home ??
|
|
2013
|
+
const home = overrides?.home ?? import_node_os9.homedir();
|
|
1348
2014
|
const seen = new Set;
|
|
1349
2015
|
const out = [];
|
|
1350
2016
|
const push = (p) => {
|
|
@@ -1355,27 +2021,27 @@ function resolveOpencodeAuthCandidates(overrides) {
|
|
|
1355
2021
|
};
|
|
1356
2022
|
const xdg = pickEnv(env, "XDG_DATA_HOME");
|
|
1357
2023
|
if (xdg)
|
|
1358
|
-
push(
|
|
2024
|
+
push(import_node_path13.join(xdg, "opencode", "auth.json"));
|
|
1359
2025
|
if (platform === "win32") {
|
|
1360
|
-
const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ?
|
|
2026
|
+
const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path13.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
|
|
1361
2027
|
if (localAppData)
|
|
1362
|
-
push(
|
|
2028
|
+
push(import_node_path13.join(localAppData, "opencode", "auth.json"));
|
|
1363
2029
|
const userProfile = pickEnv(env, "USERPROFILE") || home;
|
|
1364
2030
|
if (userProfile)
|
|
1365
|
-
push(
|
|
2031
|
+
push(import_node_path13.join(userProfile, ".local", "share", "opencode", "auth.json"));
|
|
1366
2032
|
} else if (home) {
|
|
1367
|
-
push(
|
|
2033
|
+
push(import_node_path13.join(home, ".local", "share", "opencode", "auth.json"));
|
|
1368
2034
|
}
|
|
1369
2035
|
return out;
|
|
1370
2036
|
}
|
|
1371
2037
|
function resolveOpencodeAuthFile() {
|
|
1372
|
-
return resolveOpencodeAuthCandidates()[0] ??
|
|
2038
|
+
return resolveOpencodeAuthCandidates()[0] ?? import_node_path13.join(import_node_os9.homedir(), ".local", "share", "opencode", "auth.json");
|
|
1373
2039
|
}
|
|
1374
2040
|
function isValidOpencodeAuthFile(authFile) {
|
|
1375
2041
|
try {
|
|
1376
|
-
if (!authFile || !
|
|
2042
|
+
if (!authFile || !import_node_fs12.existsSync(authFile))
|
|
1377
2043
|
return false;
|
|
1378
|
-
const raw =
|
|
2044
|
+
const raw = import_node_fs12.readFileSync(authFile, "utf8").trim();
|
|
1379
2045
|
if (!raw)
|
|
1380
2046
|
return false;
|
|
1381
2047
|
const parsed = JSON.parse(raw);
|
|
@@ -1393,7 +2059,7 @@ function probeOpencodeAuth(overrides) {
|
|
|
1393
2059
|
for (const candidate of candidates) {
|
|
1394
2060
|
let exists = false;
|
|
1395
2061
|
try {
|
|
1396
|
-
exists =
|
|
2062
|
+
exists = import_node_fs12.existsSync(candidate);
|
|
1397
2063
|
} catch {
|
|
1398
2064
|
exists = false;
|
|
1399
2065
|
}
|
|
@@ -1406,10 +2072,10 @@ function probeOpencodeAuth(overrides) {
|
|
|
1406
2072
|
validFile = candidate;
|
|
1407
2073
|
}
|
|
1408
2074
|
const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
|
|
1409
|
-
const authDir =
|
|
2075
|
+
const authDir = import_node_path13.dirname(authFile);
|
|
1410
2076
|
let hasCodexHome = false;
|
|
1411
2077
|
try {
|
|
1412
|
-
hasCodexHome =
|
|
2078
|
+
hasCodexHome = import_node_fs12.existsSync(authDir);
|
|
1413
2079
|
} catch {
|
|
1414
2080
|
hasCodexHome = false;
|
|
1415
2081
|
}
|
|
@@ -1424,6 +2090,8 @@ function probeOpencodeAuth(overrides) {
|
|
|
1424
2090
|
}
|
|
1425
2091
|
var opencodeAdapter = {
|
|
1426
2092
|
id: "opencode",
|
|
2093
|
+
supportedBridgeVersions: ["1.18.35"],
|
|
2094
|
+
prepareAppResources: prepareOpenCodeResources,
|
|
1427
2095
|
probeAuth: () => probeOpencodeAuth(),
|
|
1428
2096
|
probeQuota: async () => probeOpencodeQuota(),
|
|
1429
2097
|
orderAuthMethods: (methods) => methods,
|
|
@@ -1434,6 +2102,7 @@ var opencodeAdapter = {
|
|
|
1434
2102
|
// src/runtimes/opencode-v2/index.ts
|
|
1435
2103
|
var opencodeV2Adapter = {
|
|
1436
2104
|
id: "opencode-v2",
|
|
2105
|
+
prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
|
|
1437
2106
|
probeAuth: () => probeOpencodeAuth(),
|
|
1438
2107
|
orderAuthMethods: (methods) => methods,
|
|
1439
2108
|
canSkipInteractiveAuth: () => false,
|
|
@@ -1464,28 +2133,28 @@ async function probeCursorQuota() {
|
|
|
1464
2133
|
}
|
|
1465
2134
|
|
|
1466
2135
|
// src/runtimes/cursor/index.ts
|
|
1467
|
-
var
|
|
1468
|
-
var
|
|
1469
|
-
var
|
|
1470
|
-
var
|
|
2136
|
+
var import_node_child_process5 = require("node:child_process");
|
|
2137
|
+
var import_node_fs13 = require("node:fs");
|
|
2138
|
+
var import_node_os10 = require("node:os");
|
|
2139
|
+
var import_node_path14 = require("node:path");
|
|
1471
2140
|
function cursorLocalAppData(env) {
|
|
1472
2141
|
const local = env.LOCALAPPDATA?.trim();
|
|
1473
2142
|
if (local)
|
|
1474
2143
|
return local;
|
|
1475
2144
|
const profile = env.USERPROFILE?.trim();
|
|
1476
|
-
return profile ?
|
|
2145
|
+
return profile ? import_node_path14.join(profile, "AppData", "Local") : "";
|
|
1477
2146
|
}
|
|
1478
2147
|
function isOnPath(command, env, platform) {
|
|
1479
2148
|
const pathValue = env.PATH ?? env.Path ?? "";
|
|
1480
2149
|
if (!pathValue.trim())
|
|
1481
2150
|
return false;
|
|
1482
|
-
const sep = platform === "win32" ? ";" :
|
|
2151
|
+
const sep = platform === "win32" ? ";" : import_node_path14.delimiter;
|
|
1483
2152
|
for (const dir of pathValue.split(sep)) {
|
|
1484
2153
|
const trimmed = dir.trim().replace(/^"|"$/g, "");
|
|
1485
2154
|
if (!trimmed)
|
|
1486
2155
|
continue;
|
|
1487
2156
|
try {
|
|
1488
|
-
if (
|
|
2157
|
+
if (import_node_fs13.existsSync(import_node_path14.join(trimmed, command)))
|
|
1489
2158
|
return true;
|
|
1490
2159
|
} catch {}
|
|
1491
2160
|
}
|
|
@@ -1494,24 +2163,24 @@ function isOnPath(command, env, platform) {
|
|
|
1494
2163
|
function resolveDirectCursorCommand(platform, env, home) {
|
|
1495
2164
|
if (platform === "win32") {
|
|
1496
2165
|
const localAppData = cursorLocalAppData(env);
|
|
1497
|
-
return localAppData ?
|
|
2166
|
+
return localAppData ? import_node_path14.join(localAppData, "cursor-agent", "agent.cmd") : "";
|
|
1498
2167
|
}
|
|
1499
|
-
return home ?
|
|
2168
|
+
return home ? import_node_path14.join(home, ".local", "bin", "agent") : "";
|
|
1500
2169
|
}
|
|
1501
2170
|
function resolveCursorCommand(overrides) {
|
|
1502
2171
|
const args = ["acp"];
|
|
1503
2172
|
const platform = overrides?.platform ?? process.platform;
|
|
1504
2173
|
const env = overrides?.env ?? process.env;
|
|
1505
|
-
const home = overrides?.home ??
|
|
2174
|
+
const home = overrides?.home ?? import_node_os10.homedir();
|
|
1506
2175
|
if (platform === "win32") {
|
|
1507
2176
|
const directCmd = resolveDirectCursorCommand(platform, env, home);
|
|
1508
|
-
if (directCmd &&
|
|
2177
|
+
if (directCmd && import_node_fs13.existsSync(directCmd)) {
|
|
1509
2178
|
return { command: directCmd, args };
|
|
1510
2179
|
}
|
|
1511
2180
|
return { command: "agent.cmd", args };
|
|
1512
2181
|
}
|
|
1513
2182
|
const directBin = resolveDirectCursorCommand(platform, env, home);
|
|
1514
|
-
if (directBin &&
|
|
2183
|
+
if (directBin && import_node_fs13.existsSync(directBin)) {
|
|
1515
2184
|
return { command: directBin, args };
|
|
1516
2185
|
}
|
|
1517
2186
|
return { command: "agent", args };
|
|
@@ -1520,11 +2189,11 @@ function resolveCursorSpawnCommand(overrides) {
|
|
|
1520
2189
|
const args = ["acp"];
|
|
1521
2190
|
const platform = overrides?.platform ?? process.platform;
|
|
1522
2191
|
const env = overrides?.env ?? process.env;
|
|
1523
|
-
const home = overrides?.home ??
|
|
2192
|
+
const home = overrides?.home ?? import_node_os10.homedir();
|
|
1524
2193
|
const binary = platform === "win32" ? "agent.cmd" : "agent";
|
|
1525
2194
|
const direct = resolveDirectCursorCommand(platform, env, home);
|
|
1526
2195
|
try {
|
|
1527
|
-
if (direct &&
|
|
2196
|
+
if (direct && import_node_fs13.existsSync(direct))
|
|
1528
2197
|
return { command: direct, args };
|
|
1529
2198
|
} catch {}
|
|
1530
2199
|
if (isOnPath(binary, env, platform))
|
|
@@ -1546,12 +2215,12 @@ function cursorRoamingAppData(env, home) {
|
|
|
1546
2215
|
if (roaming)
|
|
1547
2216
|
return roaming;
|
|
1548
2217
|
const profile = pickEnv2(env, "USERPROFILE") || home;
|
|
1549
|
-
return profile ?
|
|
2218
|
+
return profile ? import_node_path14.join(profile, "AppData", "Roaming") : "";
|
|
1550
2219
|
}
|
|
1551
2220
|
function resolveCursorAuthCandidates(overrides) {
|
|
1552
2221
|
const platform = overrides?.platform ?? process.platform;
|
|
1553
2222
|
const env = overrides?.env ?? process.env;
|
|
1554
|
-
const home = overrides?.home ??
|
|
2223
|
+
const home = overrides?.home ?? import_node_os10.homedir();
|
|
1555
2224
|
const seen = new Set;
|
|
1556
2225
|
const out = [];
|
|
1557
2226
|
const push = (p) => {
|
|
@@ -1562,16 +2231,16 @@ function resolveCursorAuthCandidates(overrides) {
|
|
|
1562
2231
|
};
|
|
1563
2232
|
const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
|
|
1564
2233
|
if (xdg)
|
|
1565
|
-
push(
|
|
2234
|
+
push(import_node_path14.join(xdg, "cursor", "auth.json"));
|
|
1566
2235
|
if (platform === "win32") {
|
|
1567
2236
|
const profile = pickEnv2(env, "USERPROFILE") || home;
|
|
1568
2237
|
if (profile)
|
|
1569
|
-
push(
|
|
2238
|
+
push(import_node_path14.join(profile, ".config", "cursor", "auth.json"));
|
|
1570
2239
|
const roaming = cursorRoamingAppData(env, home);
|
|
1571
2240
|
if (roaming)
|
|
1572
|
-
push(
|
|
2241
|
+
push(import_node_path14.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
|
|
1573
2242
|
} else if (home) {
|
|
1574
|
-
push(
|
|
2243
|
+
push(import_node_path14.join(home, ".config", "cursor", "auth.json"));
|
|
1575
2244
|
}
|
|
1576
2245
|
return out;
|
|
1577
2246
|
}
|
|
@@ -1582,9 +2251,9 @@ function isValidCursorAuthFile(authFile) {
|
|
|
1582
2251
|
try {
|
|
1583
2252
|
if (!authFile || isStorageHintPath(authFile))
|
|
1584
2253
|
return false;
|
|
1585
|
-
if (!
|
|
2254
|
+
if (!import_node_fs13.existsSync(authFile))
|
|
1586
2255
|
return false;
|
|
1587
|
-
const raw =
|
|
2256
|
+
const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
|
|
1588
2257
|
if (!raw)
|
|
1589
2258
|
return false;
|
|
1590
2259
|
const parsed = JSON.parse(raw);
|
|
@@ -1602,9 +2271,9 @@ function isHintCursorStorageFile(authFile) {
|
|
|
1602
2271
|
try {
|
|
1603
2272
|
if (!authFile || !isStorageHintPath(authFile))
|
|
1604
2273
|
return false;
|
|
1605
|
-
if (!
|
|
2274
|
+
if (!import_node_fs13.existsSync(authFile))
|
|
1606
2275
|
return false;
|
|
1607
|
-
const raw =
|
|
2276
|
+
const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
|
|
1608
2277
|
if (!raw)
|
|
1609
2278
|
return false;
|
|
1610
2279
|
const parsed = JSON.parse(raw);
|
|
@@ -1620,7 +2289,7 @@ function isValidCursorCandidate(authFile) {
|
|
|
1620
2289
|
}
|
|
1621
2290
|
function probeCursorAuth(overrides) {
|
|
1622
2291
|
const env = overrides?.env ?? process.env;
|
|
1623
|
-
const home = overrides?.home ??
|
|
2292
|
+
const home = overrides?.home ?? import_node_os10.homedir();
|
|
1624
2293
|
const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
|
|
1625
2294
|
const candidates = resolveCursorAuthCandidates(overrides);
|
|
1626
2295
|
let firstExisting = null;
|
|
@@ -1628,7 +2297,7 @@ function probeCursorAuth(overrides) {
|
|
|
1628
2297
|
for (const candidate of candidates) {
|
|
1629
2298
|
let exists = false;
|
|
1630
2299
|
try {
|
|
1631
|
-
exists =
|
|
2300
|
+
exists = import_node_fs13.existsSync(candidate);
|
|
1632
2301
|
} catch {
|
|
1633
2302
|
exists = false;
|
|
1634
2303
|
}
|
|
@@ -1640,12 +2309,12 @@ function probeCursorAuth(overrides) {
|
|
|
1640
2309
|
if (isValidCursorCandidate(candidate))
|
|
1641
2310
|
validFile = candidate;
|
|
1642
2311
|
}
|
|
1643
|
-
const fallback = home ?
|
|
2312
|
+
const fallback = home ? import_node_path14.join(home, ".config", "cursor", "auth.json") : "";
|
|
1644
2313
|
const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
|
|
1645
|
-
const authDir = authFile ?
|
|
2314
|
+
const authDir = authFile ? import_node_path14.dirname(authFile) : "";
|
|
1646
2315
|
let hasCodexHome = false;
|
|
1647
2316
|
try {
|
|
1648
|
-
hasCodexHome = authDir ?
|
|
2317
|
+
hasCodexHome = authDir ? import_node_fs13.existsSync(authDir) : false;
|
|
1649
2318
|
} catch {
|
|
1650
2319
|
hasCodexHome = false;
|
|
1651
2320
|
}
|
|
@@ -1659,6 +2328,7 @@ function probeCursorAuth(overrides) {
|
|
|
1659
2328
|
}
|
|
1660
2329
|
var cursorAdapter = {
|
|
1661
2330
|
id: "cursor-cli",
|
|
2331
|
+
prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "config-home-does-not-guarantee-rules"),
|
|
1662
2332
|
probeAuth: () => probeCursorAuth(),
|
|
1663
2333
|
probeQuota: async () => probeCursorQuota(),
|
|
1664
2334
|
resolveSpawnCommand: () => resolveCursorSpawnCommand(),
|
|
@@ -1709,7 +2379,7 @@ function getCursorCatalogIds(execFile, overrides) {
|
|
|
1709
2379
|
}
|
|
1710
2380
|
try {
|
|
1711
2381
|
const shell = command.toLowerCase().endsWith(".cmd");
|
|
1712
|
-
const result =
|
|
2382
|
+
const result = import_node_child_process5.spawnSync(command, ["--list-models"], {
|
|
1713
2383
|
encoding: "utf8",
|
|
1714
2384
|
timeout: 6000,
|
|
1715
2385
|
windowsHide: true,
|
|
@@ -1772,6 +2442,7 @@ function probeDeepseekAuth() {
|
|
|
1772
2442
|
}
|
|
1773
2443
|
var deepseekAdapter = {
|
|
1774
2444
|
id: "deepseek",
|
|
2445
|
+
prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
|
|
1775
2446
|
probeAuth: () => probeDeepseekAuth(),
|
|
1776
2447
|
resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
|
|
1777
2448
|
resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
|
|
@@ -1780,23 +2451,242 @@ var deepseekAdapter = {
|
|
|
1780
2451
|
};
|
|
1781
2452
|
|
|
1782
2453
|
// src/runtimes/agy/quota.ts
|
|
1783
|
-
var
|
|
1784
|
-
var
|
|
2454
|
+
var import_node_fs14 = require("node:fs");
|
|
2455
|
+
var import_node_path15 = require("node:path");
|
|
2456
|
+
var import_node_child_process6 = require("node:child_process");
|
|
2457
|
+
var os2 = __toESM(require("node:os"), 1);
|
|
1785
2458
|
function resolveGeminiHome2() {
|
|
1786
2459
|
const home = process.env.USERPROFILE || process.env.HOME || "";
|
|
1787
|
-
return
|
|
2460
|
+
return import_node_path15.join(home, ".gemini");
|
|
2461
|
+
}
|
|
2462
|
+
function resolveAntigravityAccount() {
|
|
2463
|
+
if (process.env.GOOGLE_ACCOUNT?.trim()) {
|
|
2464
|
+
const email = process.env.GOOGLE_ACCOUNT.trim();
|
|
2465
|
+
return { email, name: email.split("@")[0] };
|
|
2466
|
+
}
|
|
2467
|
+
if (process.env.ANTIGRAVITY_ACCOUNT?.trim()) {
|
|
2468
|
+
const email = process.env.ANTIGRAVITY_ACCOUNT.trim();
|
|
2469
|
+
return { email, name: email.split("@")[0] };
|
|
2470
|
+
}
|
|
2471
|
+
const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
|
|
2472
|
+
const candidates = [
|
|
2473
|
+
process.env.APPDATA ? import_node_path15.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
|
|
2474
|
+
import_node_path15.join(home, ".config", "Antigravity", "app_storage.json"),
|
|
2475
|
+
import_node_path15.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
|
|
2476
|
+
].filter(Boolean);
|
|
2477
|
+
for (const file of candidates) {
|
|
2478
|
+
try {
|
|
2479
|
+
if (import_node_fs14.existsSync(file)) {
|
|
2480
|
+
const raw = import_node_fs14.readFileSync(file, "utf8");
|
|
2481
|
+
const json = JSON.parse(raw);
|
|
2482
|
+
const username = json["jetski.onboarding.lastLoginUsername"];
|
|
2483
|
+
if (username && typeof username === "string" && username.trim()) {
|
|
2484
|
+
const u = username.trim();
|
|
2485
|
+
return {
|
|
2486
|
+
email: u,
|
|
2487
|
+
name: u.includes("@") ? u.split("@")[0] : u
|
|
2488
|
+
};
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
} catch {}
|
|
2492
|
+
}
|
|
2493
|
+
const osUser = process.env.USERNAME || process.env.USER;
|
|
2494
|
+
if (osUser?.trim()) {
|
|
2495
|
+
return { name: osUser.trim() };
|
|
2496
|
+
}
|
|
2497
|
+
return {};
|
|
2498
|
+
}
|
|
2499
|
+
function resolveAntigravityLanguageServer() {
|
|
2500
|
+
const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
|
|
2501
|
+
const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path15.join(home, "AppData", "Roaming") : "");
|
|
2502
|
+
const baseDirs = [
|
|
2503
|
+
appData ? import_node_path15.join(appData, "Antigravity IDE", "logs") : null,
|
|
2504
|
+
appData ? import_node_path15.join(appData, "Antigravity", "logs") : null,
|
|
2505
|
+
import_node_path15.join(home, ".config", "Antigravity IDE", "logs"),
|
|
2506
|
+
import_node_path15.join(home, ".config", "Antigravity", "logs"),
|
|
2507
|
+
import_node_path15.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
|
|
2508
|
+
import_node_path15.join(home, "Library", "Application Support", "Antigravity", "logs")
|
|
2509
|
+
].filter(Boolean);
|
|
2510
|
+
for (const base of baseDirs) {
|
|
2511
|
+
try {
|
|
2512
|
+
if (!import_node_fs14.existsSync(base))
|
|
2513
|
+
continue;
|
|
2514
|
+
const sessionDirs = import_node_fs14.readdirSync(base).map((d) => {
|
|
2515
|
+
try {
|
|
2516
|
+
return { name: d, time: import_node_fs14.statSync(import_node_path15.join(base, d)).mtimeMs };
|
|
2517
|
+
} catch {
|
|
2518
|
+
return null;
|
|
2519
|
+
}
|
|
2520
|
+
}).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
|
|
2521
|
+
for (const s of sessionDirs) {
|
|
2522
|
+
const logFile = import_node_path15.join(base, s.name, "ls-main.log");
|
|
2523
|
+
if (import_node_fs14.existsSync(logFile)) {
|
|
2524
|
+
const content = import_node_fs14.readFileSync(logFile, "utf8");
|
|
2525
|
+
const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
|
|
2526
|
+
const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
|
|
2527
|
+
if (csrfMatch && portMatch) {
|
|
2528
|
+
return {
|
|
2529
|
+
port: parseInt(portMatch[1], 10),
|
|
2530
|
+
csrfToken: csrfMatch[1]
|
|
2531
|
+
};
|
|
2532
|
+
}
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
} catch {}
|
|
2536
|
+
}
|
|
2537
|
+
try {
|
|
2538
|
+
let out = "";
|
|
2539
|
+
if (process.platform === "win32") {
|
|
2540
|
+
out = import_node_child_process6.execFileSync("powershell", [
|
|
2541
|
+
"-NoProfile",
|
|
2542
|
+
"-Command",
|
|
2543
|
+
`Get-CimInstance Win32_Process -Filter "Name like '%language_server%'" | Select-Object -ExpandProperty CommandLine`
|
|
2544
|
+
], { encoding: "utf8", timeout: 4000, windowsHide: true });
|
|
2545
|
+
} else {
|
|
2546
|
+
out = import_node_child_process6.execFileSync("ps", ["aux"], { encoding: "utf8", timeout: 4000 });
|
|
2547
|
+
}
|
|
2548
|
+
const lines = out.split(/\r?\n/);
|
|
2549
|
+
for (const l of lines) {
|
|
2550
|
+
const portMatch = l.match(/--https_server_port\s+(\d+)/);
|
|
2551
|
+
const csrfMatch = l.match(/--csrf_token\s+([a-f0-9\-]+)/);
|
|
2552
|
+
if (portMatch && csrfMatch) {
|
|
2553
|
+
return { port: parseInt(portMatch[1], 10), csrfToken: csrfMatch[1] };
|
|
2554
|
+
}
|
|
2555
|
+
}
|
|
2556
|
+
} catch {}
|
|
2557
|
+
return null;
|
|
1788
2558
|
}
|
|
1789
2559
|
async function probeAgyQuota(options) {
|
|
2560
|
+
const acc = resolveAntigravityAccount();
|
|
2561
|
+
const lsInfo = resolveAntigravityLanguageServer();
|
|
2562
|
+
if (lsInfo) {
|
|
2563
|
+
try {
|
|
2564
|
+
let data = null;
|
|
2565
|
+
const prevReject = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
|
|
2566
|
+
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
|
|
2567
|
+
try {
|
|
2568
|
+
const res = await fetch(`https://127.0.0.1:${lsInfo.port}/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary`, {
|
|
2569
|
+
method: "POST",
|
|
2570
|
+
headers: {
|
|
2571
|
+
"Content-Type": "application/json",
|
|
2572
|
+
"x-codeium-csrf-token": lsInfo.csrfToken
|
|
2573
|
+
},
|
|
2574
|
+
body: JSON.stringify({}),
|
|
2575
|
+
signal: AbortSignal.timeout(4000),
|
|
2576
|
+
tls: { rejectUnauthorized: false }
|
|
2577
|
+
});
|
|
2578
|
+
if (res.ok) {
|
|
2579
|
+
data = await res.json();
|
|
2580
|
+
}
|
|
2581
|
+
} catch {
|
|
2582
|
+
try {
|
|
2583
|
+
const raw = import_node_child_process6.execFileSync(process.platform === "win32" ? "curl.exe" : "curl", [
|
|
2584
|
+
"-k",
|
|
2585
|
+
"-s",
|
|
2586
|
+
"-X",
|
|
2587
|
+
"POST",
|
|
2588
|
+
"-H",
|
|
2589
|
+
"Content-Type: application/json",
|
|
2590
|
+
"-H",
|
|
2591
|
+
`x-codeium-csrf-token: ${lsInfo.csrfToken}`,
|
|
2592
|
+
"-d",
|
|
2593
|
+
"{}",
|
|
2594
|
+
`https://127.0.0.1:${lsInfo.port}/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary`
|
|
2595
|
+
], { encoding: "utf8", timeout: 4000 });
|
|
2596
|
+
data = JSON.parse(raw);
|
|
2597
|
+
} catch {}
|
|
2598
|
+
} finally {
|
|
2599
|
+
if (prevReject !== undefined) {
|
|
2600
|
+
process.env.NODE_TLS_REJECT_UNAUTHORIZED = prevReject;
|
|
2601
|
+
} else {
|
|
2602
|
+
delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
if (data?.response?.groups) {
|
|
2606
|
+
const groups = data.response.groups;
|
|
2607
|
+
const formatReset = (isoStr, fallbackDesc) => {
|
|
2608
|
+
if (fallbackDesc && fallbackDesc.includes("it will fully refresh in ")) {
|
|
2609
|
+
const m = fallbackDesc.match(/it will fully refresh in (.+?)\.?$/);
|
|
2610
|
+
if (m?.[1])
|
|
2611
|
+
return `Resets in ${m[1].trim()}`;
|
|
2612
|
+
}
|
|
2613
|
+
if (!isoStr)
|
|
2614
|
+
return;
|
|
2615
|
+
const diffMs = new Date(isoStr).getTime() - Date.now();
|
|
2616
|
+
if (diffMs <= 0)
|
|
2617
|
+
return "已重置";
|
|
2618
|
+
const totalMins = Math.floor(diffMs / 60000);
|
|
2619
|
+
const hours = Math.floor(totalMins / 60);
|
|
2620
|
+
const days = Math.floor(hours / 24);
|
|
2621
|
+
if (days > 0)
|
|
2622
|
+
return `Resets in ${days}d ${hours % 24}h`;
|
|
2623
|
+
return `Resets in ${hours}h ${totalMins % 60}m`;
|
|
2624
|
+
};
|
|
2625
|
+
const toWindow = (b, groupName, label, durMins) => {
|
|
2626
|
+
if (!b)
|
|
2627
|
+
return;
|
|
2628
|
+
const frac = typeof b.remainingFraction === "number" ? b.remainingFraction : 1;
|
|
2629
|
+
const percentLeft = Math.max(0, Math.min(100, Math.round(frac * 100)));
|
|
2630
|
+
const usedPercent = 100 - percentLeft;
|
|
2631
|
+
return {
|
|
2632
|
+
label,
|
|
2633
|
+
group: groupName,
|
|
2634
|
+
percentLeft,
|
|
2635
|
+
usedPercent,
|
|
2636
|
+
windowDurationMins: durMins,
|
|
2637
|
+
resetsAt: formatReset(b.resetTime, b.description)
|
|
2638
|
+
};
|
|
2639
|
+
};
|
|
2640
|
+
const geminiGroup = groups.find((g) => g.displayName?.toLowerCase().includes("gemini"));
|
|
2641
|
+
const thirdPartyGroup = groups.find((g) => g.displayName?.toLowerCase().includes("claude") || g.displayName?.toLowerCase().includes("gpt"));
|
|
2642
|
+
const gemini5h = geminiGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("five hour") || b.bucketId?.includes("5h") || b.window === "5h");
|
|
2643
|
+
const geminiWeekly = geminiGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("weekly") || b.bucketId?.includes("weekly") || b.window === "weekly");
|
|
2644
|
+
const tp5h = thirdPartyGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("five hour") || b.bucketId?.includes("5h") || b.window === "5h");
|
|
2645
|
+
const tpWeekly = thirdPartyGroup?.buckets?.find((b) => b.displayName?.toLowerCase().includes("weekly") || b.bucketId?.includes("weekly") || b.window === "weekly");
|
|
2646
|
+
const primaryWindow = toWindow(gemini5h, "Gemini Models", "5-Hour limit", 300) || {
|
|
2647
|
+
label: "5-Hour limit",
|
|
2648
|
+
group: "Gemini Models",
|
|
2649
|
+
percentLeft: 100,
|
|
2650
|
+
usedPercent: 0,
|
|
2651
|
+
windowDurationMins: 300
|
|
2652
|
+
};
|
|
2653
|
+
const secondaryWindow = toWindow(geminiWeekly, "Gemini Models", "Weekly limit", 10080);
|
|
2654
|
+
const extraWindows = [
|
|
2655
|
+
toWindow(tp5h, "Claude and GPT models", "5-Hour limit", 300),
|
|
2656
|
+
toWindow(tpWeekly, "Claude and GPT models", "Weekly limit", 10080)
|
|
2657
|
+
].filter(Boolean);
|
|
2658
|
+
return {
|
|
2659
|
+
runtimeId: "agy",
|
|
2660
|
+
provider: "Google Antigravity",
|
|
2661
|
+
account: {
|
|
2662
|
+
email: acc.email,
|
|
2663
|
+
name: acc.name || "Google Developer",
|
|
2664
|
+
plan: "Google AI Pro",
|
|
2665
|
+
type: "gemini"
|
|
2666
|
+
},
|
|
2667
|
+
primaryWindow,
|
|
2668
|
+
secondaryWindow,
|
|
2669
|
+
extraWindows: extraWindows.length > 0 ? extraWindows : undefined,
|
|
2670
|
+
credits: {
|
|
2671
|
+
unlimited: true,
|
|
2672
|
+
balance: "unlimited"
|
|
2673
|
+
},
|
|
2674
|
+
status: "ok",
|
|
2675
|
+
updatedAt: Date.now()
|
|
2676
|
+
};
|
|
2677
|
+
}
|
|
2678
|
+
} catch {}
|
|
2679
|
+
}
|
|
1790
2680
|
const geminiHome = resolveGeminiHome2();
|
|
1791
|
-
const hasAgyDir =
|
|
2681
|
+
const hasAgyDir = import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity")) || import_node_fs14.existsSync(import_node_path15.join(geminiHome, "antigravity-cli"));
|
|
1792
2682
|
const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
|
|
1793
|
-
const isAvailable = hasAgyDir || hasApiKey;
|
|
2683
|
+
const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
|
|
1794
2684
|
if (!isAvailable) {
|
|
1795
2685
|
return {
|
|
1796
2686
|
runtimeId: "agy",
|
|
1797
2687
|
provider: "Google Antigravity",
|
|
1798
2688
|
status: "unauthorized",
|
|
1799
|
-
message: "
|
|
2689
|
+
message: "未检测到 Antigravity 登录凭据",
|
|
1800
2690
|
updatedAt: Date.now()
|
|
1801
2691
|
};
|
|
1802
2692
|
}
|
|
@@ -1804,21 +2694,41 @@ async function probeAgyQuota(options) {
|
|
|
1804
2694
|
runtimeId: "agy",
|
|
1805
2695
|
provider: "Google Antigravity",
|
|
1806
2696
|
account: {
|
|
1807
|
-
|
|
2697
|
+
email: acc.email,
|
|
2698
|
+
name: acc.name || "Google Developer",
|
|
2699
|
+
plan: "Google AI Pro",
|
|
1808
2700
|
type: "gemini"
|
|
1809
2701
|
},
|
|
1810
2702
|
primaryWindow: {
|
|
1811
2703
|
label: "5-Hour limit",
|
|
2704
|
+
group: "Gemini Models",
|
|
1812
2705
|
percentLeft: 100,
|
|
1813
2706
|
usedPercent: 0,
|
|
1814
2707
|
windowDurationMins: 300
|
|
1815
2708
|
},
|
|
1816
2709
|
secondaryWindow: {
|
|
1817
2710
|
label: "Weekly limit",
|
|
2711
|
+
group: "Gemini Models",
|
|
1818
2712
|
percentLeft: 100,
|
|
1819
2713
|
usedPercent: 0,
|
|
1820
2714
|
windowDurationMins: 10080
|
|
1821
2715
|
},
|
|
2716
|
+
extraWindows: [
|
|
2717
|
+
{
|
|
2718
|
+
label: "5-Hour limit",
|
|
2719
|
+
group: "Claude and GPT models",
|
|
2720
|
+
percentLeft: 100,
|
|
2721
|
+
usedPercent: 0,
|
|
2722
|
+
windowDurationMins: 300
|
|
2723
|
+
},
|
|
2724
|
+
{
|
|
2725
|
+
label: "Weekly limit",
|
|
2726
|
+
group: "Claude and GPT models",
|
|
2727
|
+
percentLeft: 100,
|
|
2728
|
+
usedPercent: 0,
|
|
2729
|
+
windowDurationMins: 10080
|
|
2730
|
+
}
|
|
2731
|
+
],
|
|
1822
2732
|
credits: {
|
|
1823
2733
|
unlimited: true,
|
|
1824
2734
|
balance: "unlimited"
|
|
@@ -1840,6 +2750,12 @@ function probeAgyAuth() {
|
|
|
1840
2750
|
}
|
|
1841
2751
|
var agyAdapter = {
|
|
1842
2752
|
id: "agy",
|
|
2753
|
+
prepareAppResources: async ({ directory }) => {
|
|
2754
|
+
const prep = prepareCompatibilityResources(directory, "native-session-version-not-verified");
|
|
2755
|
+
return { ...prep, env: { AGY_ACP_RESOURCES_DIR: directory }, report: { ...prep.report, rulesPrepared: prep.report.rulesChars > 0 } };
|
|
2756
|
+
},
|
|
2757
|
+
appResourceSessionMeta: (directory) => ({ appResources: { directory } }),
|
|
2758
|
+
supportedBridgeVersions: ["0.1.24"],
|
|
1843
2759
|
probeAuth: () => probeAgyAuth(),
|
|
1844
2760
|
probeQuota: (options) => probeAgyQuota(options),
|
|
1845
2761
|
orderAuthMethods: (methods) => methods,
|
|
@@ -1879,7 +2795,10 @@ function getAcpRuntimeAdapter(runtimeId) {
|
|
|
1879
2795
|
}
|
|
1880
2796
|
|
|
1881
2797
|
// src/process/process-manager.ts
|
|
1882
|
-
var
|
|
2798
|
+
var import_node_child_process7 = require("node:child_process");
|
|
2799
|
+
function processKey(runtimeId, scopeKey) {
|
|
2800
|
+
return scopeKey ? `${scopeKey}:${runtimeId}` : runtimeId;
|
|
2801
|
+
}
|
|
1883
2802
|
var active = new Map;
|
|
1884
2803
|
var ACP_EARLY_EXIT_WINDOW_MS = 3000;
|
|
1885
2804
|
var ACP_EARLY_EXIT_STDERR_TAIL_LINES = 20;
|
|
@@ -1891,7 +2810,7 @@ function killProcessTree(pid) {
|
|
|
1891
2810
|
if (process.platform !== "win32")
|
|
1892
2811
|
return;
|
|
1893
2812
|
try {
|
|
1894
|
-
|
|
2813
|
+
import_node_child_process7.spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
|
|
1895
2814
|
windowsHide: true,
|
|
1896
2815
|
timeout: 8000
|
|
1897
2816
|
});
|
|
@@ -1911,7 +2830,8 @@ function spawnAcpProcess(options) {
|
|
|
1911
2830
|
if (!options.runtime?.id || !options.runtime.command || !Array.isArray(options.runtime.args)) {
|
|
1912
2831
|
throw new Error(`ACP 运行时模板缺失 command/args: ${options.runtime?.id ?? "(empty)"}`);
|
|
1913
2832
|
}
|
|
1914
|
-
const
|
|
2833
|
+
const key = processKey(options.runtime.id, options.scopeKey);
|
|
2834
|
+
const existing = active.get(key);
|
|
1915
2835
|
if (existing) {
|
|
1916
2836
|
existing.kill();
|
|
1917
2837
|
}
|
|
@@ -1934,7 +2854,7 @@ function spawnAcpProcess(options) {
|
|
|
1934
2854
|
} else {
|
|
1935
2855
|
delete env.NO_BROWSER;
|
|
1936
2856
|
}
|
|
1937
|
-
const child =
|
|
2857
|
+
const child = import_node_child_process7.spawn(file, options.runtime.args, {
|
|
1938
2858
|
cwd: options.cwd,
|
|
1939
2859
|
env,
|
|
1940
2860
|
stdio: ["pipe", "pipe", "pipe"],
|
|
@@ -1972,6 +2892,9 @@ function spawnAcpProcess(options) {
|
|
|
1972
2892
|
});
|
|
1973
2893
|
const handle = {
|
|
1974
2894
|
runtimeId: options.runtime.id,
|
|
2895
|
+
scopeKey: options.scopeKey,
|
|
2896
|
+
executionContext: options.executionContext,
|
|
2897
|
+
profileTag: options.profileTag ?? null,
|
|
1975
2898
|
child,
|
|
1976
2899
|
spawnedAt: Date.now(),
|
|
1977
2900
|
stderrTail,
|
|
@@ -1989,7 +2912,7 @@ function spawnAcpProcess(options) {
|
|
|
1989
2912
|
} catch {}
|
|
1990
2913
|
}
|
|
1991
2914
|
}
|
|
1992
|
-
active.delete(
|
|
2915
|
+
active.delete(key);
|
|
1993
2916
|
}
|
|
1994
2917
|
};
|
|
1995
2918
|
child.on("exit", (code, signal) => {
|
|
@@ -1997,10 +2920,11 @@ function spawnAcpProcess(options) {
|
|
|
1997
2920
|
if (rest)
|
|
1998
2921
|
pushStderrTailLine(rest);
|
|
1999
2922
|
stderrBuffer = "";
|
|
2000
|
-
active.
|
|
2923
|
+
if (active.get(key) === handle)
|
|
2924
|
+
active.delete(key);
|
|
2001
2925
|
options.onExit?.(code, signal);
|
|
2002
2926
|
});
|
|
2003
|
-
active.set(
|
|
2927
|
+
active.set(key, handle);
|
|
2004
2928
|
return handle;
|
|
2005
2929
|
}
|
|
2006
2930
|
function getAcpEarlyExitStderrDetail(handle, _now = Date.now()) {
|
|
@@ -2028,27 +2952,47 @@ function disposeAllAcpProcesses() {
|
|
|
2028
2952
|
}
|
|
2029
2953
|
active.clear();
|
|
2030
2954
|
}
|
|
2031
|
-
function getActiveAcpProcess(runtimeId) {
|
|
2032
|
-
return active.get(runtimeId);
|
|
2955
|
+
function getActiveAcpProcess(runtimeId, scopeKey) {
|
|
2956
|
+
return active.get(processKey(runtimeId, scopeKey));
|
|
2033
2957
|
}
|
|
2034
2958
|
function listLiveAcpRuntimeIds() {
|
|
2035
|
-
const ids =
|
|
2036
|
-
for (const
|
|
2959
|
+
const ids = new Set;
|
|
2960
|
+
for (const handle of active.values()) {
|
|
2037
2961
|
if (isSpawnedAcpProcessAlive(handle))
|
|
2038
|
-
ids.
|
|
2962
|
+
ids.add(handle.runtimeId);
|
|
2039
2963
|
}
|
|
2040
|
-
return ids.sort();
|
|
2964
|
+
return [...ids].sort();
|
|
2041
2965
|
}
|
|
2042
|
-
function getLiveAcpProcess(runtimeId) {
|
|
2043
|
-
const
|
|
2966
|
+
function getLiveAcpProcess(runtimeId, query = {}) {
|
|
2967
|
+
const key = processKey(runtimeId, query.scopeKey);
|
|
2968
|
+
const handle = active.get(key);
|
|
2044
2969
|
if (!handle)
|
|
2045
2970
|
return;
|
|
2046
2971
|
if (!isSpawnedAcpProcessAlive(handle)) {
|
|
2047
|
-
active.delete(
|
|
2972
|
+
active.delete(key);
|
|
2048
2973
|
return;
|
|
2049
2974
|
}
|
|
2975
|
+
if (query.executionContext !== undefined && (handle.executionContext ?? null) !== query.executionContext) {
|
|
2976
|
+
return;
|
|
2977
|
+
}
|
|
2978
|
+
if (query.expectedTag !== undefined && (handle.profileTag ?? null) !== query.expectedTag)
|
|
2979
|
+
return;
|
|
2050
2980
|
return handle;
|
|
2051
2981
|
}
|
|
2982
|
+
function tryReuseLiveAcpProcess(runtimeId, query = {}) {
|
|
2983
|
+
const hit = getLiveAcpProcess(runtimeId, query);
|
|
2984
|
+
if (hit)
|
|
2985
|
+
return { status: "hit", handle: hit };
|
|
2986
|
+
if (query.expectedTag === undefined)
|
|
2987
|
+
return { status: "miss" };
|
|
2988
|
+
const stale = getLiveAcpProcess(runtimeId, { scopeKey: query.scopeKey, executionContext: query.executionContext });
|
|
2989
|
+
if (!stale)
|
|
2990
|
+
return { status: "miss" };
|
|
2991
|
+
if (query.isBusy?.(stale))
|
|
2992
|
+
return { status: "busy", handle: stale };
|
|
2993
|
+
stale.kill();
|
|
2994
|
+
return { status: "miss" };
|
|
2995
|
+
}
|
|
2052
2996
|
|
|
2053
2997
|
// src/client/sdk-client.ts
|
|
2054
2998
|
var import_node_stream = require("node:stream");
|
|
@@ -2119,18 +3063,18 @@ async function sdkRequest(agent, method, params, timeoutMs = ACP_SDK_REQUEST_TIM
|
|
|
2119
3063
|
var import_sdk2 = require("@agentclientprotocol/sdk");
|
|
2120
3064
|
|
|
2121
3065
|
// src/client/acp-fs.ts
|
|
2122
|
-
var import_promises3 = require("node:fs/promises");
|
|
2123
|
-
var import_node_path13 = require("node:path");
|
|
2124
3066
|
var import_promises4 = require("node:fs/promises");
|
|
3067
|
+
var import_node_path16 = require("node:path");
|
|
3068
|
+
var import_promises5 = require("node:fs/promises");
|
|
2125
3069
|
var MAX_READ_BYTES = 2 * 1024 * 1024;
|
|
2126
3070
|
var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
|
|
2127
3071
|
function isBinaryDocumentPath(filePath) {
|
|
2128
|
-
return BINARY_DOCUMENT_EXTENSIONS.has(
|
|
3072
|
+
return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path16.extname(filePath).toLowerCase());
|
|
2129
3073
|
}
|
|
2130
3074
|
function assertPathInsideWorkspace(filePath, workspaceRoot) {
|
|
2131
|
-
const root =
|
|
2132
|
-
const target =
|
|
2133
|
-
const rootWithSep = root.endsWith(
|
|
3075
|
+
const root = import_node_path16.resolve(workspaceRoot);
|
|
3076
|
+
const target = import_node_path16.resolve(filePath);
|
|
3077
|
+
const rootWithSep = root.endsWith(import_node_path16.sep) ? root : root + import_node_path16.sep;
|
|
2134
3078
|
if (target !== root && !target.startsWith(rootWithSep)) {
|
|
2135
3079
|
throw new Error(`路径不在工作区内: ${filePath}`);
|
|
2136
3080
|
}
|
|
@@ -2141,8 +3085,8 @@ async function acpReadTextFile(params) {
|
|
|
2141
3085
|
throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
|
|
2142
3086
|
}
|
|
2143
3087
|
const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
|
|
2144
|
-
await
|
|
2145
|
-
let content = await
|
|
3088
|
+
await import_promises4.access(abs);
|
|
3089
|
+
let content = await import_promises4.readFile(abs, "utf-8");
|
|
2146
3090
|
if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
|
|
2147
3091
|
content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
|
|
2148
3092
|
content += `
|
|
@@ -2161,8 +3105,8 @@ async function acpReadTextFile(params) {
|
|
|
2161
3105
|
}
|
|
2162
3106
|
async function acpWriteTextFile(params) {
|
|
2163
3107
|
const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
|
|
2164
|
-
await
|
|
2165
|
-
await
|
|
3108
|
+
await import_promises5.mkdir(import_node_path16.dirname(abs), { recursive: true });
|
|
3109
|
+
await import_promises4.writeFile(abs, params.content, "utf-8");
|
|
2166
3110
|
return {};
|
|
2167
3111
|
}
|
|
2168
3112
|
|
|
@@ -2522,6 +3466,25 @@ function isTransientAcpTransportError(error) {
|
|
|
2522
3466
|
async function restoreOrCreateAcpSession(input) {
|
|
2523
3467
|
const resumeId = input.resumeSessionId?.trim() || null;
|
|
2524
3468
|
const restoreAttempts = [];
|
|
3469
|
+
let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
|
|
3470
|
+
let nativeSessionAccepted = false;
|
|
3471
|
+
const request = async (method, params) => {
|
|
3472
|
+
if (!input.sessionMeta)
|
|
3473
|
+
return input.request(method, params);
|
|
3474
|
+
try {
|
|
3475
|
+
const result = await input.request(method, { ...params, _meta: input.sessionMeta });
|
|
3476
|
+
nativeSessionAccepted = true;
|
|
3477
|
+
return result;
|
|
3478
|
+
} catch (error) {
|
|
3479
|
+
const rejected = error instanceof import_sdk3.RequestError && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
|
|
3480
|
+
if (!rejected || isTransientAcpTransportError(error))
|
|
3481
|
+
throw error;
|
|
3482
|
+
log("warn", "native resource options failed; retry without extension");
|
|
3483
|
+
const result = await input.request(method, params);
|
|
3484
|
+
nativeSessionAccepted = false;
|
|
3485
|
+
return result;
|
|
3486
|
+
}
|
|
3487
|
+
};
|
|
2525
3488
|
const delayMs = input.retryDelayMs ?? 250;
|
|
2526
3489
|
const log = input.log ?? ((level, message, data) => {
|
|
2527
3490
|
if (level === "info" && false)
|
|
@@ -2543,7 +3506,7 @@ async function restoreOrCreateAcpSession(input) {
|
|
|
2543
3506
|
maxTries
|
|
2544
3507
|
});
|
|
2545
3508
|
try {
|
|
2546
|
-
const result = await
|
|
3509
|
+
const result = await request(rpcMethod, {
|
|
2547
3510
|
sessionId: resumeId,
|
|
2548
3511
|
cwd: input.cwd,
|
|
2549
3512
|
mcpServers: input.mcpServers ?? []
|
|
@@ -2582,7 +3545,7 @@ async function restoreOrCreateAcpSession(input) {
|
|
|
2582
3545
|
mcpServers: input.mcpServers ?? []
|
|
2583
3546
|
};
|
|
2584
3547
|
try {
|
|
2585
|
-
return await
|
|
3548
|
+
return await request("session/new", baseParams);
|
|
2586
3549
|
} catch (firstError) {
|
|
2587
3550
|
if ((input.mcpServers ?? []).length === 0)
|
|
2588
3551
|
throw firstError;
|
|
@@ -2590,10 +3553,12 @@ async function restoreOrCreateAcpSession(input) {
|
|
|
2590
3553
|
error: errorMessage(firstError)
|
|
2591
3554
|
});
|
|
2592
3555
|
try {
|
|
2593
|
-
|
|
3556
|
+
const result = await request("session/new", {
|
|
2594
3557
|
cwd: input.cwd,
|
|
2595
3558
|
mcpServers: []
|
|
2596
3559
|
});
|
|
3560
|
+
mcpServersAccepted = false;
|
|
3561
|
+
return result;
|
|
2597
3562
|
} catch {
|
|
2598
3563
|
throw firstError;
|
|
2599
3564
|
}
|
|
@@ -2609,6 +3574,8 @@ async function restoreOrCreateAcpSession(input) {
|
|
|
2609
3574
|
configOptions: withModelsFallback(resumed),
|
|
2610
3575
|
restoreMethod: "resume",
|
|
2611
3576
|
sessionRestored: true,
|
|
3577
|
+
mcpServersAccepted,
|
|
3578
|
+
nativeSessionAccepted,
|
|
2612
3579
|
requestedSessionId: resumeId,
|
|
2613
3580
|
restoreAttempts
|
|
2614
3581
|
};
|
|
@@ -2627,6 +3594,8 @@ async function restoreOrCreateAcpSession(input) {
|
|
|
2627
3594
|
configOptions: withModelsFallback(loaded),
|
|
2628
3595
|
restoreMethod: "load",
|
|
2629
3596
|
sessionRestored: true,
|
|
3597
|
+
mcpServersAccepted,
|
|
3598
|
+
nativeSessionAccepted,
|
|
2630
3599
|
requestedSessionId: resumeId,
|
|
2631
3600
|
restoreAttempts
|
|
2632
3601
|
};
|
|
@@ -2648,14 +3617,16 @@ async function restoreOrCreateAcpSession(input) {
|
|
|
2648
3617
|
configOptions: withModelsFallback(sessionResult),
|
|
2649
3618
|
restoreMethod: "new",
|
|
2650
3619
|
sessionRestored: false,
|
|
3620
|
+
mcpServersAccepted,
|
|
3621
|
+
nativeSessionAccepted,
|
|
2651
3622
|
requestedSessionId: resumeId ?? undefined,
|
|
2652
3623
|
restoreAttempts
|
|
2653
3624
|
};
|
|
2654
3625
|
}
|
|
2655
3626
|
|
|
2656
3627
|
// src/client/acp-terminal.ts
|
|
2657
|
-
var
|
|
2658
|
-
var
|
|
3628
|
+
var import_node_child_process8 = require("node:child_process");
|
|
3629
|
+
var import_node_crypto3 = require("node:crypto");
|
|
2659
3630
|
|
|
2660
3631
|
// src/transport/terminal-output-buffer.ts
|
|
2661
3632
|
function truncateOutputFromStart(text, byteLimit) {
|
|
@@ -2707,14 +3678,14 @@ class AcpTerminalManager {
|
|
|
2707
3678
|
throw new Error("terminal/create 需要 command");
|
|
2708
3679
|
const cwd = resolveCwd(params.cwd, params.workspaceRoot);
|
|
2709
3680
|
const outputByteLimit = typeof params.outputByteLimit === "number" && params.outputByteLimit > 0 ? params.outputByteLimit : DEFAULT_OUTPUT_BYTE_LIMIT;
|
|
2710
|
-
const child =
|
|
3681
|
+
const child = import_node_child_process8.spawn(command, params.args ?? [], {
|
|
2711
3682
|
cwd,
|
|
2712
3683
|
env: buildEnv(params.env),
|
|
2713
3684
|
windowsHide: true,
|
|
2714
3685
|
shell: false,
|
|
2715
3686
|
stdio: ["ignore", "pipe", "pipe"]
|
|
2716
3687
|
});
|
|
2717
|
-
const id = `term_${
|
|
3688
|
+
const id = `term_${import_node_crypto3.randomUUID().replace(/-/g, "").slice(0, 12)}`;
|
|
2718
3689
|
const record = {
|
|
2719
3690
|
id,
|
|
2720
3691
|
sessionId: params.sessionId,
|
|
@@ -2803,7 +3774,7 @@ class AcpTerminalManager {
|
|
|
2803
3774
|
return;
|
|
2804
3775
|
if (process.platform === "win32") {
|
|
2805
3776
|
try {
|
|
2806
|
-
|
|
3777
|
+
import_node_child_process8.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
|
|
2807
3778
|
windowsHide: true,
|
|
2808
3779
|
stdio: "ignore"
|
|
2809
3780
|
});
|
|
@@ -2838,9 +3809,9 @@ class AcpTerminalManager {
|
|
|
2838
3809
|
}
|
|
2839
3810
|
|
|
2840
3811
|
// src/client/acp-proxy-service.ts
|
|
2841
|
-
var
|
|
2842
|
-
var
|
|
2843
|
-
var
|
|
3812
|
+
var import_promises6 = require("node:fs/promises");
|
|
3813
|
+
var import_node_fs15 = require("node:fs");
|
|
3814
|
+
var import_node_path17 = require("node:path");
|
|
2844
3815
|
var DEFAULT_ACP_PROXY_SETTINGS = {
|
|
2845
3816
|
enabled: false,
|
|
2846
3817
|
host: "127.0.0.1",
|
|
@@ -2849,7 +3820,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
|
|
|
2849
3820
|
var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
|
|
2850
3821
|
var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
|
|
2851
3822
|
function proxyFilePath(dir) {
|
|
2852
|
-
return
|
|
3823
|
+
return import_node_path17.join(dir, "agent", "proxy.json");
|
|
2853
3824
|
}
|
|
2854
3825
|
function validate2(settings) {
|
|
2855
3826
|
if (!settings.host.trim())
|
|
@@ -2861,10 +3832,10 @@ function validate2(settings) {
|
|
|
2861
3832
|
}
|
|
2862
3833
|
async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
|
|
2863
3834
|
const file = proxyFilePath(dir);
|
|
2864
|
-
if (!
|
|
3835
|
+
if (!import_node_fs15.existsSync(file))
|
|
2865
3836
|
return { ...DEFAULT_ACP_PROXY_SETTINGS };
|
|
2866
3837
|
try {
|
|
2867
|
-
const raw = JSON.parse(await
|
|
3838
|
+
const raw = JSON.parse(await import_promises6.readFile(file, "utf8"));
|
|
2868
3839
|
return {
|
|
2869
3840
|
enabled: raw.enabled === true,
|
|
2870
3841
|
host: typeof raw.host === "string" && raw.host.trim() ? raw.host : DEFAULT_ACP_PROXY_SETTINGS.host,
|
|
@@ -2883,8 +3854,8 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
|
|
|
2883
3854
|
host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
|
|
2884
3855
|
port: payload.port
|
|
2885
3856
|
};
|
|
2886
|
-
await
|
|
2887
|
-
await
|
|
3857
|
+
await import_promises6.mkdir(import_node_path17.join(dir, "agent"), { recursive: true });
|
|
3858
|
+
await import_promises6.writeFile(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
|
|
2888
3859
|
return ok(stored);
|
|
2889
3860
|
}
|
|
2890
3861
|
function buildAcpProxySpawnEnv(settings) {
|
|
@@ -2906,6 +3877,116 @@ function buildAcpProxySpawnEnv(settings) {
|
|
|
2906
3877
|
};
|
|
2907
3878
|
}
|
|
2908
3879
|
|
|
3880
|
+
// src/session/compat-guide.ts
|
|
3881
|
+
var COMPAT_CONTEXT_TAG = "acp-compat-context";
|
|
3882
|
+
function shortDigest(digest) {
|
|
3883
|
+
return digest ? digest.slice(0, 16) : "none";
|
|
3884
|
+
}
|
|
3885
|
+
function buildCompatGuideText(input) {
|
|
3886
|
+
const hasRules = (input.rulesText ?? "").trim() !== "";
|
|
3887
|
+
const hasSkills = input.skills.length > 0;
|
|
3888
|
+
if (!hasRules && !hasSkills)
|
|
3889
|
+
return null;
|
|
3890
|
+
const lines = [];
|
|
3891
|
+
lines.push(`<${COMPAT_CONTEXT_TAG} mode="compatibility" profile="${shortDigest(input.digest)}" session="${input.sessionId}" gen="${input.generation}">`, "NOTE FOR THE MODEL: the block below is host-provided context delivered over the user channel", "(compatibility mode). It is NOT a system or developer instruction and does not override them.", "");
|
|
3892
|
+
if (hasRules) {
|
|
3893
|
+
lines.push("--- host rules (same source as the host app, delivered once per session) ---", "");
|
|
3894
|
+
lines.push(input.rulesText.trim(), "");
|
|
3895
|
+
}
|
|
3896
|
+
if (hasSkills) {
|
|
3897
|
+
lines.push("--- host skills catalog (names and descriptions only; read full text on demand) ---", "");
|
|
3898
|
+
for (const skill of input.skills) {
|
|
3899
|
+
lines.push(`- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`);
|
|
3900
|
+
}
|
|
3901
|
+
lines.push("", input.skillsViaMcp ? "Read a skill body with the app_read_skill MCP tool before claiming its content." : "Skill bodies are available on request; ask the host if no skill tool is listed.");
|
|
3902
|
+
lines.push("");
|
|
3903
|
+
}
|
|
3904
|
+
lines.push(`</${COMPAT_CONTEXT_TAG}>`);
|
|
3905
|
+
return lines.join(`
|
|
3906
|
+
`);
|
|
3907
|
+
}
|
|
3908
|
+
function compatDeliveryKey(sessionId, generation, digest) {
|
|
3909
|
+
return `${generation}:${sessionId}:${digest ?? "none"}`;
|
|
3910
|
+
}
|
|
3911
|
+
|
|
3912
|
+
// src/mcp/app-skills-mcp.ts
|
|
3913
|
+
var import_node_path18 = require("node:path");
|
|
3914
|
+
var import_node_url = require("node:url");
|
|
3915
|
+
var import_node_fs16 = require("node:fs");
|
|
3916
|
+
var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
|
|
3917
|
+
var APP_SKILLS_TOOLS = [
|
|
3918
|
+
{
|
|
3919
|
+
name: "app_list_skills",
|
|
3920
|
+
description: "List host skill catalog (names and one-line descriptions). " + "Call this first to discover available skills; then read a body with app_read_skill before claiming its content. " + "Skill bodies are never inlined here—always read on demand.",
|
|
3921
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false }
|
|
3922
|
+
},
|
|
3923
|
+
{
|
|
3924
|
+
name: "app_read_skill",
|
|
3925
|
+
description: "Read one registered skill body by exact name from app_list_skills. " + "Optional ref reads another Markdown file in the same skill directory " + "(same-directory relative .md only; anything else is rejected).",
|
|
3926
|
+
inputSchema: {
|
|
3927
|
+
type: "object",
|
|
3928
|
+
properties: {
|
|
3929
|
+
name: { type: "string", description: "Exact skill name from app_list_skills" },
|
|
3930
|
+
ref: {
|
|
3931
|
+
type: "string",
|
|
3932
|
+
description: "Optional same-directory relative Markdown file (default SKILL.md)"
|
|
3933
|
+
}
|
|
3934
|
+
},
|
|
3935
|
+
required: ["name"],
|
|
3936
|
+
additionalProperties: false
|
|
3937
|
+
}
|
|
3938
|
+
}
|
|
3939
|
+
];
|
|
3940
|
+
function buildAppSkillsMcpServer(directory, opts) {
|
|
3941
|
+
return {
|
|
3942
|
+
name: opts?.name ?? APP_SKILLS_MCP_SERVER_NAME,
|
|
3943
|
+
command: process.execPath,
|
|
3944
|
+
env: process.versions.electron ? [{ name: "ELECTRON_RUN_AS_NODE", value: "1" }] : [],
|
|
3945
|
+
args: [opts?.runnerPath ?? resolveAppSkillsRunnerPath(), directory]
|
|
3946
|
+
};
|
|
3947
|
+
}
|
|
3948
|
+
function resolveAppSkillsRunnerPath(fromFile) {
|
|
3949
|
+
const base = fromFile ?? import_node_url.fileURLToPath("file:///home/runner/work/acp-client/acp-client/src/mcp/app-skills-mcp.ts");
|
|
3950
|
+
const candidates = [
|
|
3951
|
+
import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.cjs"),
|
|
3952
|
+
import_node_path18.join(import_node_path18.dirname(base), "app-skills-mcp-serve.ts")
|
|
3953
|
+
];
|
|
3954
|
+
for (const candidate of candidates) {
|
|
3955
|
+
if (import_node_fs16.existsSync(candidate))
|
|
3956
|
+
return candidate;
|
|
3957
|
+
}
|
|
3958
|
+
throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
|
|
3959
|
+
}
|
|
3960
|
+
|
|
3961
|
+
// src/client/acp-client.ts
|
|
3962
|
+
var import_node_crypto4 = require("node:crypto");
|
|
3963
|
+
|
|
3964
|
+
// src/resources/eligibility.ts
|
|
3965
|
+
var NATIVE_ELIGIBLE_BRIDGE_VERSIONS = {
|
|
3966
|
+
"codex-acp": ["2.2.2"],
|
|
3967
|
+
opencode: ["1.18.35"],
|
|
3968
|
+
claude: ["0.91.0"],
|
|
3969
|
+
agy: ["0.1.24"]
|
|
3970
|
+
};
|
|
3971
|
+
function resolveRuntimeEligibility(runtimeId) {
|
|
3972
|
+
const id = (runtimeId ?? "").trim();
|
|
3973
|
+
if (!id || !(id in NATIVE_ELIGIBLE_BRIDGE_VERSIONS)) {
|
|
3974
|
+
return { eligible: false, reason: "runtime-not-verified" };
|
|
3975
|
+
}
|
|
3976
|
+
return { eligible: true };
|
|
3977
|
+
}
|
|
3978
|
+
function isSupportedBridgeVersion(runtimeId, version) {
|
|
3979
|
+
const versions = NATIVE_ELIGIBLE_BRIDGE_VERSIONS[(runtimeId ?? "").trim()];
|
|
3980
|
+
if (!versions)
|
|
3981
|
+
return { eligible: false, reason: "runtime-not-verified" };
|
|
3982
|
+
const normalized = version?.trim().replace(/^v/, "");
|
|
3983
|
+
if (!normalized)
|
|
3984
|
+
return { eligible: false, reason: "unknown-bridge-version" };
|
|
3985
|
+
if (!versions.includes(normalized))
|
|
3986
|
+
return { eligible: false, reason: "unsupported-bridge-version" };
|
|
3987
|
+
return { eligible: true };
|
|
3988
|
+
}
|
|
3989
|
+
|
|
2909
3990
|
// src/session/session-capabilities.ts
|
|
2910
3991
|
function parseLoadSessionSupported(caps) {
|
|
2911
3992
|
return caps.loadSession === true;
|
|
@@ -2942,11 +4023,13 @@ class AcpSessionHandle {
|
|
|
2942
4023
|
client;
|
|
2943
4024
|
restoreMethod;
|
|
2944
4025
|
configOptions;
|
|
2945
|
-
|
|
4026
|
+
resourceReport;
|
|
4027
|
+
constructor(sessionId, client, restoreMethod, configOptions, resourceReport) {
|
|
2946
4028
|
this.sessionId = sessionId;
|
|
2947
4029
|
this.client = client;
|
|
2948
4030
|
this.restoreMethod = restoreMethod;
|
|
2949
4031
|
this.configOptions = configOptions;
|
|
4032
|
+
this.resourceReport = resourceReport;
|
|
2950
4033
|
}
|
|
2951
4034
|
async prompt(promptText, options) {
|
|
2952
4035
|
return this.client.promptSession(this.sessionId, promptText, options);
|
|
@@ -2975,6 +4058,10 @@ class AcpClient {
|
|
|
2975
4058
|
clientInfo;
|
|
2976
4059
|
dataDir;
|
|
2977
4060
|
extraEnv;
|
|
4061
|
+
configurationScope;
|
|
4062
|
+
sessionConfig = null;
|
|
4063
|
+
resourcesDir;
|
|
4064
|
+
processScopeKey = import_node_crypto4.randomUUID();
|
|
2978
4065
|
callbacks;
|
|
2979
4066
|
terminals = new AcpTerminalManager;
|
|
2980
4067
|
processHandle = null;
|
|
@@ -2982,6 +4069,17 @@ class AcpClient {
|
|
|
2982
4069
|
sdkConnection = null;
|
|
2983
4070
|
streamHandle = null;
|
|
2984
4071
|
initResponse = null;
|
|
4072
|
+
inflightPrompts = new Set;
|
|
4073
|
+
resourcePrep = null;
|
|
4074
|
+
connectionGen = 0;
|
|
4075
|
+
attachSkillsMcp;
|
|
4076
|
+
sessionLedger = new Map;
|
|
4077
|
+
compatSentKeys = new Set;
|
|
4078
|
+
compatSnapshots = new Map;
|
|
4079
|
+
get resourceReport() {
|
|
4080
|
+
const report = this.resourcePrep?.report;
|
|
4081
|
+
return report ? { ...report, skillsFound: [...report.skillsFound] } : null;
|
|
4082
|
+
}
|
|
2985
4083
|
constructor(options) {
|
|
2986
4084
|
this.workspaceRoot = options.workspaceRoot;
|
|
2987
4085
|
this.clientInfo = {
|
|
@@ -2990,6 +4088,14 @@ class AcpClient {
|
|
|
2990
4088
|
};
|
|
2991
4089
|
this.dataDir = options.dataDir ?? getDefaultAgentDataDir();
|
|
2992
4090
|
this.extraEnv = options.env ?? {};
|
|
4091
|
+
if (options.resources && !isAbsolutePathLike(options.resources.directory)) {
|
|
4092
|
+
throw new Error("resources.directory 必须是本机绝对路径");
|
|
4093
|
+
}
|
|
4094
|
+
this.configurationScope = options.resources?.configurationScope ?? "overlay";
|
|
4095
|
+
if (!["overlay", "session"].includes(this.configurationScope))
|
|
4096
|
+
throw new Error("Invalid resources.configurationScope");
|
|
4097
|
+
this.resourcesDir = options.resources?.directory ?? null;
|
|
4098
|
+
this.attachSkillsMcp = options.resources?.attachSkillsMcp !== false;
|
|
2993
4099
|
this.callbacks = options.callbacks ?? {};
|
|
2994
4100
|
const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
|
|
2995
4101
|
this.adapter = getAcpRuntimeAdapter(runtimeId);
|
|
@@ -3016,6 +4122,14 @@ class AcpClient {
|
|
|
3016
4122
|
return this.initResponse;
|
|
3017
4123
|
}
|
|
3018
4124
|
async connect() {
|
|
4125
|
+
if (this.inflightPrompts.size > 0)
|
|
4126
|
+
return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在回答,请结束后重新连接" });
|
|
4127
|
+
if (this.isConnected && this.initResponse)
|
|
4128
|
+
return ok({ status: this.status, init: this.initResponse });
|
|
4129
|
+
if (this.currentStatus === "connecting")
|
|
4130
|
+
return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在连接" });
|
|
4131
|
+
this.connectionGen += 1;
|
|
4132
|
+
const connectGen = this.connectionGen;
|
|
3019
4133
|
try {
|
|
3020
4134
|
this.setStatus("connecting");
|
|
3021
4135
|
const blocker = this.adapter.resolveSpawnBlocker?.();
|
|
@@ -3041,16 +4155,105 @@ class AcpClient {
|
|
|
3041
4155
|
...baseEnv,
|
|
3042
4156
|
env: { ...baseEnv.env ?? {}, ...this.extraEnv ?? {} }
|
|
3043
4157
|
};
|
|
4158
|
+
let resourceEnv = {};
|
|
4159
|
+
let profileTag = null;
|
|
4160
|
+
if (this.resourcesDir && this.configurationScope === "session") {
|
|
4161
|
+
const profile = await createSessionConfigHome(this.runtimeInfo.id, this.resourcesDir);
|
|
4162
|
+
if (connectGen !== this.connectionGen || this.status !== "connecting") {
|
|
4163
|
+
await profile.dispose();
|
|
4164
|
+
return err({ code: "CANCELLED", message: "连接已取消" });
|
|
4165
|
+
}
|
|
4166
|
+
this.sessionConfig = profile;
|
|
4167
|
+
resourceEnv = this.sessionConfig.env;
|
|
4168
|
+
const load = readAppResourcesDir(this.resourcesDir);
|
|
4169
|
+
this.resourcePrep = { profileTag: null, report: {
|
|
4170
|
+
rulesApplied: false,
|
|
4171
|
+
rulesPrepared: false,
|
|
4172
|
+
skillsApplied: false,
|
|
4173
|
+
rulesChars: load.rules?.chars ?? 0,
|
|
4174
|
+
profileDigest: digestAppResources(load),
|
|
4175
|
+
skillsFound: load.skills.map((s) => s.name),
|
|
4176
|
+
configurationScope: "session",
|
|
4177
|
+
configurationDirectory: this.sessionConfig.directory,
|
|
4178
|
+
configurationRulesFile: this.sessionConfig.rulesFile,
|
|
4179
|
+
reason: this.sessionConfig.nativeRules ? "isolated-config-not-runtime-verified" : "isolated-config-rule-discovery-not-verified"
|
|
4180
|
+
} };
|
|
4181
|
+
} else if (this.resourcesDir && this.adapter.prepareAppResources) {
|
|
4182
|
+
try {
|
|
4183
|
+
const prep = await this.adapter.prepareAppResources({
|
|
4184
|
+
directory: this.resourcesDir,
|
|
4185
|
+
command: effectiveRuntime.command,
|
|
4186
|
+
workspaceRoot: this.workspaceRoot,
|
|
4187
|
+
env: { ...process.env, ...spawnEnv.env }
|
|
4188
|
+
});
|
|
4189
|
+
if (prep.env)
|
|
4190
|
+
resourceEnv = prep.env;
|
|
4191
|
+
prep.report.rulesPrepared = prep.report.rulesPrepared ?? prep.report.rulesApplied;
|
|
4192
|
+
prep.report.rulesApplied = false;
|
|
4193
|
+
prep.report.skillsApplied = false;
|
|
4194
|
+
const digest = prep.report.profileDigest;
|
|
4195
|
+
profileTag = digest ? `${this.runtimeInfo.id}:resources@${digest.slice(0, 16)}` : null;
|
|
4196
|
+
this.resourcePrep = { profileTag, report: prep.report };
|
|
4197
|
+
} catch (error) {
|
|
4198
|
+
this.resourcePrep = {
|
|
4199
|
+
profileTag: null,
|
|
4200
|
+
report: {
|
|
4201
|
+
rulesApplied: false,
|
|
4202
|
+
rulesChars: 0,
|
|
4203
|
+
profileDigest: null,
|
|
4204
|
+
skillsFound: [],
|
|
4205
|
+
reason: "prepare-failed"
|
|
4206
|
+
}
|
|
4207
|
+
};
|
|
4208
|
+
this.callbacks.onLog?.("warn", "应用资源准备失败,已回退兼容", {
|
|
4209
|
+
error: error instanceof Error ? error.message : String(error)
|
|
4210
|
+
});
|
|
4211
|
+
}
|
|
4212
|
+
} else {
|
|
4213
|
+
const load = this.resourcesDir ? readAppResourcesDir(this.resourcesDir) : null;
|
|
4214
|
+
this.resourcePrep = load ? { profileTag: null, report: {
|
|
4215
|
+
rulesApplied: false,
|
|
4216
|
+
rulesPrepared: false,
|
|
4217
|
+
skillsApplied: false,
|
|
4218
|
+
rulesChars: load.rules?.chars ?? 0,
|
|
4219
|
+
profileDigest: digestAppResources(load),
|
|
4220
|
+
skillsFound: load.skills.map((s) => s.name),
|
|
4221
|
+
reason: "runtime-not-supported"
|
|
4222
|
+
} } : null;
|
|
4223
|
+
}
|
|
4224
|
+
const finalEnv = { ...spawnEnv.env, ...resourceEnv };
|
|
3044
4225
|
await this.adapter.beforeSpawn?.();
|
|
3045
|
-
|
|
4226
|
+
if (connectGen !== this.connectionGen || this.status !== "connecting")
|
|
4227
|
+
return err({ code: "CANCELLED", message: "连接已取消" });
|
|
4228
|
+
let reuseDegraded = false;
|
|
4229
|
+
let reusedHandle = null;
|
|
4230
|
+
if (profileTag) {
|
|
4231
|
+
const reuse = tryReuseLiveAcpProcess(this.runtimeInfo.id, {
|
|
4232
|
+
expectedTag: profileTag,
|
|
4233
|
+
scopeKey: this.processScopeKey,
|
|
4234
|
+
isBusy: (h) => this.inflightPrompts.size > 0 && this.processHandle === h
|
|
4235
|
+
});
|
|
4236
|
+
if (reuse.status === "hit") {
|
|
4237
|
+
reusedHandle = reuse.handle;
|
|
4238
|
+
} else if (reuse.status === "busy") {
|
|
4239
|
+
reusedHandle = reuse.handle;
|
|
4240
|
+
reuseDegraded = true;
|
|
4241
|
+
this.callbacks.onLog?.("warn", "应用资源摘要已变更但旧进程正忙,沿用旧进程并降级,新摘要下次冷启动生效");
|
|
4242
|
+
}
|
|
4243
|
+
}
|
|
4244
|
+
const processHandle = reusedHandle ?? spawnAcpProcess({
|
|
3046
4245
|
runtime: effectiveRuntime,
|
|
3047
4246
|
cwd: this.workspaceRoot,
|
|
3048
|
-
|
|
4247
|
+
scopeKey: this.processScopeKey,
|
|
4248
|
+
env: finalEnv,
|
|
3049
4249
|
envRemove: spawnEnv.envRemove,
|
|
4250
|
+
profileTag,
|
|
3050
4251
|
onStderrLine: (line) => {
|
|
3051
4252
|
this.callbacks.onStderrLine?.(line);
|
|
3052
4253
|
},
|
|
3053
4254
|
onExit: (code, signal) => {
|
|
4255
|
+
if (this.connectionGen !== connectGen)
|
|
4256
|
+
return;
|
|
3054
4257
|
this.callbacks.onLog?.("warn", `Agent 进程已退出 (code: ${code}, signal: ${signal})`);
|
|
3055
4258
|
if (this.status === "connected" || this.status === "connecting") {
|
|
3056
4259
|
this.disconnect("Agent 进程异常终止");
|
|
@@ -3101,9 +4304,28 @@ class AcpClient {
|
|
|
3101
4304
|
}
|
|
3102
4305
|
});
|
|
3103
4306
|
this.initResponse = initResp;
|
|
4307
|
+
if (this.resourcePrep) {
|
|
4308
|
+
const agentInfo = initResp?.agentInfo;
|
|
4309
|
+
const bridgeVersion = typeof agentInfo?.version === "string" ? agentInfo.version : undefined;
|
|
4310
|
+
const supported = isSupportedBridgeVersion(this.runtimeInfo.id, bridgeVersion).eligible && (this.adapter.supportedBridgeVersions?.includes(bridgeVersion?.replace(/^v/, "") ?? "") ?? false);
|
|
4311
|
+
this.resourcePrep.report.bridgeVersion = bridgeVersion;
|
|
4312
|
+
this.resourcePrep.report.bridgeSupported = supported;
|
|
4313
|
+
if (this.processHandle)
|
|
4314
|
+
this.processHandle.bridgeVersion = bridgeVersion;
|
|
4315
|
+
if (supported && this.resourcePrep.report.reason === "native-session-version-not-verified")
|
|
4316
|
+
delete this.resourcePrep.report.reason;
|
|
4317
|
+
if (!supported) {
|
|
4318
|
+
this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "unsupported-bridge-version";
|
|
4319
|
+
}
|
|
4320
|
+
if (reuseDegraded) {
|
|
4321
|
+
this.resourcePrep.report.reason = this.resourcePrep.report.reason ?? "busy-deferred-stale-rules";
|
|
4322
|
+
}
|
|
4323
|
+
}
|
|
3104
4324
|
this.setStatus("connected");
|
|
3105
4325
|
return ok({ status: "connected", init: initResp });
|
|
3106
4326
|
} catch (e) {
|
|
4327
|
+
if (connectGen !== this.connectionGen)
|
|
4328
|
+
return err({ code: "CANCELLED", message: "连接已被新请求取代" });
|
|
3107
4329
|
const message = e instanceof Error ? e.message : String(e);
|
|
3108
4330
|
this.setStatus("error", message);
|
|
3109
4331
|
await this.disconnect(message);
|
|
@@ -3142,6 +4364,29 @@ class AcpClient {
|
|
|
3142
4364
|
const resumeSupported = Boolean(init && parseResumeSessionSupported(init.agentCapabilities));
|
|
3143
4365
|
const loadSupported = Boolean(init && parseLoadSessionSupported(init.agentCapabilities));
|
|
3144
4366
|
try {
|
|
4367
|
+
let skillsExposed = "none";
|
|
4368
|
+
let mcpServers = options?.mcpServers ?? [];
|
|
4369
|
+
if (this.resourcesDir && this.attachSkillsMcp) {
|
|
4370
|
+
try {
|
|
4371
|
+
const descriptor = buildAppSkillsMcpServer(this.resourcesDir);
|
|
4372
|
+
const callerNames = new Set;
|
|
4373
|
+
for (const entry of mcpServers) {
|
|
4374
|
+
if (entry !== null && typeof entry === "object" && typeof entry.name === "string") {
|
|
4375
|
+
callerNames.add(entry.name);
|
|
4376
|
+
}
|
|
4377
|
+
}
|
|
4378
|
+
if (callerNames.has(descriptor.name)) {
|
|
4379
|
+
this.callbacks.onLog?.("warn", "调用方已有同名技能 MCP 服务,保留调用方版本", { name: descriptor.name });
|
|
4380
|
+
} else {
|
|
4381
|
+
mcpServers = [...mcpServers, descriptor];
|
|
4382
|
+
skillsExposed = "mcp-exposed";
|
|
4383
|
+
}
|
|
4384
|
+
} catch (error) {
|
|
4385
|
+
this.callbacks.onLog?.("warn", "技能 MCP 描述符构建失败,本次会话无技能 MCP", {
|
|
4386
|
+
error: error instanceof Error ? error.message : String(error)
|
|
4387
|
+
});
|
|
4388
|
+
}
|
|
4389
|
+
}
|
|
3145
4390
|
const openResult = await restoreOrCreateAcpSession({
|
|
3146
4391
|
request: async (method, params) => {
|
|
3147
4392
|
return sdkRequest(agent, method, params);
|
|
@@ -3150,12 +4395,27 @@ class AcpClient {
|
|
|
3150
4395
|
resumeSessionId: options?.resumeSessionId ?? null,
|
|
3151
4396
|
resumeSupported,
|
|
3152
4397
|
loadSupported,
|
|
3153
|
-
mcpServers
|
|
4398
|
+
mcpServers,
|
|
4399
|
+
sessionMeta: (!this.sessionConfig || this.runtimeInfo.id === "agy") && this.resourcesDir && this.resourcePrep?.report.bridgeSupported ? this.adapter.appResourceSessionMeta?.(this.resourcesDir) : undefined,
|
|
3154
4400
|
log: (level, msg, meta) => {
|
|
3155
4401
|
this.callbacks.onLog?.(level, msg, meta);
|
|
3156
4402
|
}
|
|
3157
4403
|
});
|
|
3158
|
-
|
|
4404
|
+
if (!openResult.mcpServersAccepted)
|
|
4405
|
+
skillsExposed = "none";
|
|
4406
|
+
this.sessionLedger.set(openResult.sessionId, {
|
|
4407
|
+
restoreMethod: openResult.restoreMethod,
|
|
4408
|
+
gen: this.connectionGen,
|
|
4409
|
+
skillsExposed,
|
|
4410
|
+
nativeRules: openResult.nativeSessionAccepted
|
|
4411
|
+
});
|
|
4412
|
+
const handle = new AcpSessionHandle(openResult.sessionId, this, openResult.restoreMethod, openResult.configOptions, this.resourcePrep?.report ? {
|
|
4413
|
+
...this.resourcePrep.report,
|
|
4414
|
+
skillsFound: [...this.resourcePrep.report.skillsFound],
|
|
4415
|
+
skillsExposed,
|
|
4416
|
+
rulesApplied: openResult.nativeSessionAccepted || !this.adapter.appResourceSessionMeta && openResult.restoreMethod === "new" && this.resourcePrep.report.bridgeSupported === true && this.resourcePrep.report.rulesPrepared === true,
|
|
4417
|
+
...openResult.restoreMethod !== "new" && !openResult.nativeSessionAccepted ? { reason: "session-restored-not-verified" } : {}
|
|
4418
|
+
} : null);
|
|
3159
4419
|
return ok(handle);
|
|
3160
4420
|
} catch (e) {
|
|
3161
4421
|
const message = e instanceof Error ? e.message : String(e);
|
|
@@ -3166,6 +4426,7 @@ class AcpClient {
|
|
|
3166
4426
|
if (!this.sdkConnection?.agent) {
|
|
3167
4427
|
return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
|
|
3168
4428
|
}
|
|
4429
|
+
this.inflightPrompts.add(sessionId);
|
|
3169
4430
|
try {
|
|
3170
4431
|
const prompt = [{ type: "text", text: promptText }];
|
|
3171
4432
|
for (const image of options?.images ?? []) {
|
|
@@ -3173,16 +4434,52 @@ class AcpClient {
|
|
|
3173
4434
|
continue;
|
|
3174
4435
|
prompt.push({ type: "image", mimeType: image.mimeType, data: image.data });
|
|
3175
4436
|
}
|
|
4437
|
+
const compat = this.buildCompatPrepend(sessionId);
|
|
4438
|
+
const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
|
|
3176
4439
|
const response = await sdkRequest(this.sdkConnection.agent, import_sdk4.methods.agent.session.prompt, {
|
|
3177
4440
|
sessionId,
|
|
3178
|
-
prompt
|
|
4441
|
+
prompt: blocks
|
|
3179
4442
|
}, options?.timeoutMs);
|
|
3180
4443
|
return ok(response);
|
|
3181
4444
|
} catch (e) {
|
|
3182
4445
|
const message = e instanceof Error ? e.message : String(e);
|
|
3183
4446
|
return err({ code: "ACP_PROTOCOL_ERROR", message });
|
|
4447
|
+
} finally {
|
|
4448
|
+
this.inflightPrompts.delete(sessionId);
|
|
3184
4449
|
}
|
|
3185
4450
|
}
|
|
4451
|
+
buildCompatPrepend(sessionId) {
|
|
4452
|
+
if (!this.resourcesDir)
|
|
4453
|
+
return null;
|
|
4454
|
+
if (this.sessionConfig?.nativeRules)
|
|
4455
|
+
return null;
|
|
4456
|
+
const entry = this.sessionLedger.get(sessionId);
|
|
4457
|
+
if (!entry)
|
|
4458
|
+
return null;
|
|
4459
|
+
const connReport = this.resourcePrep?.report;
|
|
4460
|
+
const nativelyDelivered = entry.nativeRules || !this.adapter.appResourceSessionMeta && entry.restoreMethod === "new" && entry.gen === this.connectionGen && connReport?.rulesPrepared === true && connReport?.bridgeSupported === true;
|
|
4461
|
+
if (nativelyDelivered)
|
|
4462
|
+
return null;
|
|
4463
|
+
const load = readAppResourcesDir(this.resourcesDir);
|
|
4464
|
+
const rulesText = readAppRulesText(this.resourcesDir);
|
|
4465
|
+
const digest = digestAppResources(load);
|
|
4466
|
+
const key = compatDeliveryKey(sessionId, this.connectionGen, digest);
|
|
4467
|
+
if (this.compatSentKeys.has(key))
|
|
4468
|
+
return null;
|
|
4469
|
+
const text = buildCompatGuideText({
|
|
4470
|
+
rulesText,
|
|
4471
|
+
skills: load.skills.map((s) => ({ name: s.name, description: s.description })),
|
|
4472
|
+
skillsViaMcp: entry.skillsExposed === "mcp-exposed",
|
|
4473
|
+
digest,
|
|
4474
|
+
sessionId,
|
|
4475
|
+
generation: this.connectionGen
|
|
4476
|
+
});
|
|
4477
|
+
if (!text)
|
|
4478
|
+
return null;
|
|
4479
|
+
this.compatSnapshots.set(key, { text, digest });
|
|
4480
|
+
this.compatSentKeys.add(key);
|
|
4481
|
+
return text;
|
|
4482
|
+
}
|
|
3186
4483
|
async setSessionConfigOption(sessionId, configId, value) {
|
|
3187
4484
|
if (!this.sdkConnection?.agent) {
|
|
3188
4485
|
return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
|
|
@@ -3201,6 +4498,10 @@ class AcpClient {
|
|
|
3201
4498
|
}
|
|
3202
4499
|
async disconnect(reason) {
|
|
3203
4500
|
this.setStatus("disconnected", reason);
|
|
4501
|
+
this.resourcePrep = null;
|
|
4502
|
+
this.sessionLedger.clear();
|
|
4503
|
+
this.compatSentKeys.clear();
|
|
4504
|
+
this.compatSnapshots.clear();
|
|
3204
4505
|
try {
|
|
3205
4506
|
this.streamHandle?.dispose();
|
|
3206
4507
|
this.sdkConnection?.close();
|
|
@@ -3216,6 +4517,15 @@ class AcpClient {
|
|
|
3216
4517
|
} catch {}
|
|
3217
4518
|
this.processHandle = null;
|
|
3218
4519
|
}
|
|
4520
|
+
const config = this.sessionConfig;
|
|
4521
|
+
this.sessionConfig = null;
|
|
4522
|
+
if (config) {
|
|
4523
|
+
try {
|
|
4524
|
+
await config.dispose();
|
|
4525
|
+
} catch {
|
|
4526
|
+
this.callbacks.onLog?.("warn", "Session configuration cleanup failed; directory retained", { directory: config.directory });
|
|
4527
|
+
}
|
|
4528
|
+
}
|
|
3219
4529
|
}
|
|
3220
4530
|
setStatus(status, detail) {
|
|
3221
4531
|
this.status = status;
|