@yitom/acp-client 0.1.12 → 0.1.14
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 +19 -20
- package/dist/client/acp-client.d.ts +17 -2
- package/dist/client/client-handlers.d.ts +3 -3
- package/dist/client/mcp-session-recovery.d.ts +47 -0
- package/dist/client/sdk-client.d.ts +2 -6
- package/dist/client/session-open.d.ts +14 -7
- package/dist/index.cjs +1476 -775
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3706 -3006
- package/dist/mcp/connection-health.d.ts +21 -0
- package/dist/resources/app-resources.d.ts +0 -7
- package/dist/resources/runtime-bindings.d.ts +1 -6
- package/dist/runtimes/codex/codex-auth-preflight.d.ts +1 -1
- package/dist/runtimes/codex/codex-code-mode-home.d.ts +54 -0
- package/dist/runtimes/codex/index.d.ts +1 -0
- package/dist/runtimes/deepseek/index.d.ts +10 -6
- package/dist/runtimes/deepseek/quota.d.ts +42 -0
- package/dist/session/code-mode.d.ts +30 -0
- package/dist/sidecar.cjs +3929 -3148
- package/dist/version.d.ts +1 -1
- package/docs/adding-an-agent.md +14 -0
- package/docs/api-reference.md +61 -0
- package/package.json +7 -5
package/dist/index.cjs
CHANGED
|
@@ -75,6 +75,8 @@ __export(exports_src, {
|
|
|
75
75
|
APP_SKILLS_DIR: () => APP_SKILLS_DIR,
|
|
76
76
|
APP_SKILL_FILE: () => APP_SKILL_FILE,
|
|
77
77
|
AcpClient: () => AcpClient,
|
|
78
|
+
AcpMcpRecoveryCancelledError: () => AcpMcpRecoveryCancelledError,
|
|
79
|
+
AcpMcpSessionRecovery: () => AcpMcpSessionRecovery,
|
|
78
80
|
AcpSessionHandle: () => AcpSessionHandle,
|
|
79
81
|
AcpTerminalManager: () => AcpTerminalManager,
|
|
80
82
|
AvailableCommandsCache: () => AvailableCommandsCache,
|
|
@@ -92,6 +94,7 @@ __export(exports_src, {
|
|
|
92
94
|
INKDOWN_VIRTUAL_DIR: () => INKDOWN_VIRTUAL_DIR,
|
|
93
95
|
INKDOWN_VIRTUAL_RESOURCES: () => INKDOWN_VIRTUAL_RESOURCES,
|
|
94
96
|
LEGACY_ZED_CODEX_ACP_NPM_PACKAGE: () => LEGACY_ZED_CODEX_ACP_NPM_PACKAGE,
|
|
97
|
+
McpConnectionHealth: () => McpConnectionHealth,
|
|
95
98
|
NATIVE_ELIGIBLE_BRIDGE_VERSIONS: () => NATIVE_ELIGIBLE_BRIDGE_VERSIONS,
|
|
96
99
|
OPENCODE_CLI_NPM_PACKAGE: () => OPENCODE_CLI_NPM_PACKAGE,
|
|
97
100
|
QuotaCache: () => QuotaCache,
|
|
@@ -112,6 +115,7 @@ __export(exports_src, {
|
|
|
112
115
|
clearAcpProvider: () => clearAcpProvider,
|
|
113
116
|
clearCursorCatalogCache: () => clearCursorCatalogCache,
|
|
114
117
|
closeAcpSessions: () => closeAcpSessions,
|
|
118
|
+
codeModeSessionMeta: () => codeModeSessionMeta,
|
|
115
119
|
codexAdapter: () => codexAdapter,
|
|
116
120
|
connectSdkClient: () => connectSdkClient,
|
|
117
121
|
copilotAdapter: () => copilotAdapter,
|
|
@@ -140,6 +144,7 @@ __export(exports_src, {
|
|
|
140
144
|
getDefaultAgentDataDir: () => getDefaultAgentDataDir,
|
|
141
145
|
getLiveAcpProcess: () => getLiveAcpProcess,
|
|
142
146
|
handleInkdownMcpRpc: () => handleInkdownMcpRpc,
|
|
147
|
+
hasDeepseekHarnessCredentials: () => hasDeepseekHarnessCredentials,
|
|
143
148
|
isAbsolutePathLike: () => isAbsolutePathLike,
|
|
144
149
|
isAppError: () => isAppError,
|
|
145
150
|
isAuthenticationRequired: () => isAuthenticationRequired,
|
|
@@ -160,13 +165,14 @@ __export(exports_src, {
|
|
|
160
165
|
mergeCodexConfigJson: () => mergeCodexConfigJson,
|
|
161
166
|
mergeConfigTomlPreserving: () => mergeConfigTomlPreserving,
|
|
162
167
|
mergeOpenCodeAppConfig: () => mergeOpenCodeAppConfig,
|
|
163
|
-
|
|
168
|
+
mergeSessionMeta: () => mergeSessionMeta,
|
|
164
169
|
mergeTopLevelModelsIntoConfigOptions: () => mergeTopLevelModelsIntoConfigOptions,
|
|
165
170
|
ok: () => ok,
|
|
166
171
|
opencodeAdapter: () => opencodeAdapter,
|
|
167
172
|
opencodeV2Adapter: () => opencodeV2Adapter,
|
|
168
173
|
orderSilentAuthMethodIds: () => orderSilentAuthMethodIds,
|
|
169
174
|
parseAcpConfigOptions: () => parseAcpConfigOptions,
|
|
175
|
+
parseCodeModeModes: () => parseCodeModeModes,
|
|
170
176
|
parseCursorCatalogOutput: () => parseCursorCatalogOutput,
|
|
171
177
|
parseInkdownVirtualPath: () => parseInkdownVirtualPath,
|
|
172
178
|
parseLoadSessionSupported: () => parseLoadSessionSupported,
|
|
@@ -191,6 +197,7 @@ __export(exports_src, {
|
|
|
191
197
|
probeGeminiAuth: () => probeGeminiAuth,
|
|
192
198
|
probeOpencodeAuth: () => probeOpencodeAuth,
|
|
193
199
|
probeOpencodeQuota: () => probeOpencodeQuota,
|
|
200
|
+
provisionCodexCodeModeHome: () => provisionCodexCodeModeHome,
|
|
194
201
|
provisionCustomProviderCodexHome: () => provisionCustomProviderCodexHome,
|
|
195
202
|
readAcpProxySettings: () => readAcpProxySettings,
|
|
196
203
|
readAppResourcesDir: () => readAppResourcesDir,
|
|
@@ -198,17 +205,18 @@ __export(exports_src, {
|
|
|
198
205
|
readStoredAcpProvider: () => readStoredAcpProvider,
|
|
199
206
|
registerAcpClientHandlers: () => registerAcpClientHandlers,
|
|
200
207
|
requestSessionWithResources: () => requestSessionWithResources,
|
|
208
|
+
resolveAppCodexHome: () => resolveAppCodexHome,
|
|
201
209
|
resolveClaudeHome: () => resolveClaudeHome,
|
|
202
210
|
resolveCodexHome: () => resolveCodexHome,
|
|
203
211
|
resolveCopilotHome: () => resolveCopilotHome,
|
|
204
212
|
resolveCursorAuthCandidates: () => resolveCursorAuthCandidates,
|
|
205
213
|
resolveCursorCommand: () => resolveCursorCommand,
|
|
206
214
|
resolveCursorSpawnCommand: () => resolveCursorSpawnCommand,
|
|
215
|
+
resolveDeepseekHarnessHome: () => resolveDeepseekHarnessHome,
|
|
207
216
|
resolveDeepseekPackage: () => resolveDeepseekPackage,
|
|
208
217
|
resolveDeepseekSpawnBlocker: () => resolveDeepseekSpawnBlocker,
|
|
209
218
|
resolveDeepseekSpawnCommand: () => resolveDeepseekSpawnCommand,
|
|
210
219
|
resolveGeminiHome: () => resolveGeminiHome,
|
|
211
|
-
resolveOpenCodeQuestionMode: () => resolveOpenCodeQuestionMode,
|
|
212
220
|
resolveOpencodeAuthCandidates: () => resolveOpencodeAuthCandidates,
|
|
213
221
|
resolveOpencodeAuthFile: () => resolveOpencodeAuthFile,
|
|
214
222
|
resolveOpencodeAuthPath: () => resolveOpencodeAuthPath,
|
|
@@ -220,11 +228,13 @@ __export(exports_src, {
|
|
|
220
228
|
sdkRequest: () => sdkRequest,
|
|
221
229
|
shouldPromptAuthWizard: () => shouldPromptAuthWizard,
|
|
222
230
|
spawnAcpProcess: () => spawnAcpProcess,
|
|
231
|
+
supportsCodeMode: () => supportsCodeMode,
|
|
223
232
|
synthesizeModelOptionFromTopLevelModels: () => synthesizeModelOptionFromTopLevelModels,
|
|
224
233
|
toAppError: () => toAppError,
|
|
225
234
|
truncateOutputFromStart: () => truncateOutputFromStart,
|
|
226
235
|
tryReuseLiveAcpProcess: () => tryReuseLiveAcpProcess,
|
|
227
|
-
withAcpEarlyExitDetail: () => withAcpEarlyExitDetail
|
|
236
|
+
withAcpEarlyExitDetail: () => withAcpEarlyExitDetail,
|
|
237
|
+
withCodeModeEnabled: () => withCodeModeEnabled
|
|
228
238
|
});
|
|
229
239
|
module.exports = __toCommonJS(exports_src);
|
|
230
240
|
|
|
@@ -389,21 +399,544 @@ function findBuiltinAcpRuntime(id) {
|
|
|
389
399
|
return BUILTIN_ACP_RUNTIMES.find((item) => item.id === id);
|
|
390
400
|
}
|
|
391
401
|
// src/version.ts
|
|
392
|
-
var ACP_CLIENT_VERSION = "0.1.
|
|
402
|
+
var ACP_CLIENT_VERSION = "0.1.14";
|
|
403
|
+
// src/client/session-open.ts
|
|
404
|
+
var import_sdk = require("@agentclientprotocol/sdk");
|
|
405
|
+
|
|
406
|
+
// src/session/config-options.ts
|
|
407
|
+
function coerceOptionValue(raw) {
|
|
408
|
+
if (typeof raw === "string")
|
|
409
|
+
return raw || null;
|
|
410
|
+
if (typeof raw === "number" && Number.isFinite(raw))
|
|
411
|
+
return String(raw);
|
|
412
|
+
if (typeof raw === "boolean")
|
|
413
|
+
return String(raw);
|
|
414
|
+
return null;
|
|
415
|
+
}
|
|
416
|
+
function coerceCurrentValue(raw) {
|
|
417
|
+
if (typeof raw === "string")
|
|
418
|
+
return raw;
|
|
419
|
+
if (typeof raw === "boolean")
|
|
420
|
+
return raw;
|
|
421
|
+
if (typeof raw === "number" && Number.isFinite(raw))
|
|
422
|
+
return String(raw);
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
function appendOptionValues(raw, out, group) {
|
|
426
|
+
if (!Array.isArray(raw))
|
|
427
|
+
return;
|
|
428
|
+
for (const opt of raw) {
|
|
429
|
+
if (!opt || typeof opt !== "object")
|
|
430
|
+
continue;
|
|
431
|
+
const o = opt;
|
|
432
|
+
const value = coerceOptionValue(o.value) ?? coerceOptionValue(o.id);
|
|
433
|
+
if (value) {
|
|
434
|
+
const name = typeof o.name === "string" ? o.name : String(value);
|
|
435
|
+
out.push({
|
|
436
|
+
value,
|
|
437
|
+
name: group ? `${group} · ${name}` : name,
|
|
438
|
+
description: typeof o.description === "string" ? o.description : undefined
|
|
439
|
+
});
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
if (!Array.isArray(o.options))
|
|
443
|
+
continue;
|
|
444
|
+
const label = typeof o.group === "string" ? o.group : typeof o.name === "string" && o.name.trim() ? o.name : group;
|
|
445
|
+
appendOptionValues(o.options, out, label);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
function parseAcpConfigOptions(raw) {
|
|
449
|
+
if (!Array.isArray(raw))
|
|
450
|
+
return [];
|
|
451
|
+
const options = [];
|
|
452
|
+
for (const item of raw) {
|
|
453
|
+
if (!item || typeof item !== "object")
|
|
454
|
+
continue;
|
|
455
|
+
const row = item;
|
|
456
|
+
const configId = typeof row.configId === "string" ? row.configId : typeof row.id === "string" ? row.id : null;
|
|
457
|
+
if (!configId)
|
|
458
|
+
continue;
|
|
459
|
+
const name = typeof row.name === "string" ? row.name : configId;
|
|
460
|
+
const type = typeof row.type === "string" ? row.type : "select";
|
|
461
|
+
const values = [];
|
|
462
|
+
appendOptionValues(row.options, values);
|
|
463
|
+
options.push({
|
|
464
|
+
configId,
|
|
465
|
+
name,
|
|
466
|
+
description: typeof row.description === "string" ? row.description : undefined,
|
|
467
|
+
category: typeof row.category === "string" ? row.category : undefined,
|
|
468
|
+
type,
|
|
469
|
+
currentValue: coerceCurrentValue(row.currentValue),
|
|
470
|
+
options: values.length > 0 ? values : undefined
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
return options;
|
|
474
|
+
}
|
|
475
|
+
function findModelConfigOption(options) {
|
|
476
|
+
return options.find((o) => o.category === "model") ?? options.find((o) => o.configId === "model" || o.configId.includes("model"));
|
|
477
|
+
}
|
|
478
|
+
function coerceTopLevelModelEntry(raw) {
|
|
479
|
+
if (typeof raw === "string") {
|
|
480
|
+
const trimmed = raw.trim();
|
|
481
|
+
if (!trimmed)
|
|
482
|
+
return null;
|
|
483
|
+
return { value: trimmed, name: trimmed };
|
|
484
|
+
}
|
|
485
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
486
|
+
return null;
|
|
487
|
+
const row = raw;
|
|
488
|
+
const valueRaw = row.value ?? row.id;
|
|
489
|
+
const value = coerceOptionValue(valueRaw);
|
|
490
|
+
if (!value)
|
|
491
|
+
return null;
|
|
492
|
+
const name = typeof row.name === "string" && row.name.trim() ? row.name : value;
|
|
493
|
+
return { value, name };
|
|
494
|
+
}
|
|
495
|
+
function coerceTopLevelModelList(raw) {
|
|
496
|
+
if (!Array.isArray(raw))
|
|
497
|
+
return [];
|
|
498
|
+
const out = [];
|
|
499
|
+
for (const item of raw) {
|
|
500
|
+
const coerced = coerceTopLevelModelEntry(item);
|
|
501
|
+
if (coerced)
|
|
502
|
+
out.push(coerced);
|
|
503
|
+
}
|
|
504
|
+
return out;
|
|
505
|
+
}
|
|
506
|
+
function synthesizeModelOptionFromTopLevelModels(models, response) {
|
|
507
|
+
let list = [];
|
|
508
|
+
let currentValue;
|
|
509
|
+
if (Array.isArray(models)) {
|
|
510
|
+
list = coerceTopLevelModelList(models);
|
|
511
|
+
} else if (models && typeof models === "object" && !Array.isArray(models)) {
|
|
512
|
+
const row = models;
|
|
513
|
+
list = coerceTopLevelModelList(row.availableModels);
|
|
514
|
+
const currentRaw = row.currentModelId ?? response?.currentModelId;
|
|
515
|
+
if (typeof currentRaw === "string" && currentRaw.trim())
|
|
516
|
+
currentValue = currentRaw;
|
|
517
|
+
} else {
|
|
518
|
+
return null;
|
|
519
|
+
}
|
|
520
|
+
if (list.length === 0)
|
|
521
|
+
return null;
|
|
522
|
+
if (!currentValue && response && typeof response.currentModelId === "string") {
|
|
523
|
+
const trimmed = response.currentModelId.trim();
|
|
524
|
+
if (trimmed)
|
|
525
|
+
currentValue = trimmed;
|
|
526
|
+
}
|
|
527
|
+
return {
|
|
528
|
+
configId: "model",
|
|
529
|
+
name: "Model",
|
|
530
|
+
category: "model",
|
|
531
|
+
type: "select",
|
|
532
|
+
...currentValue ? { currentValue } : {},
|
|
533
|
+
options: list.map((item) => ({ value: item.value, name: item.name }))
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
function mergeTopLevelModelsIntoConfigOptions(configOptionsRaw, response) {
|
|
537
|
+
const parsed = parseAcpConfigOptions(configOptionsRaw);
|
|
538
|
+
if (findModelConfigOption(parsed))
|
|
539
|
+
return configOptionsRaw;
|
|
540
|
+
const models = response?.models;
|
|
541
|
+
if (models === undefined)
|
|
542
|
+
return configOptionsRaw;
|
|
543
|
+
const synthesized = synthesizeModelOptionFromTopLevelModels(models, response ?? undefined);
|
|
544
|
+
if (!synthesized)
|
|
545
|
+
return configOptionsRaw;
|
|
546
|
+
const base = Array.isArray(configOptionsRaw) ? [...configOptionsRaw] : [];
|
|
547
|
+
base.push({
|
|
548
|
+
configId: synthesized.configId,
|
|
549
|
+
name: synthesized.name,
|
|
550
|
+
category: synthesized.category,
|
|
551
|
+
type: synthesized.type,
|
|
552
|
+
...synthesized.currentValue !== undefined ? { currentValue: synthesized.currentValue } : {},
|
|
553
|
+
options: synthesized.options?.map((o) => ({ value: o.value, name: o.name }))
|
|
554
|
+
});
|
|
555
|
+
return base;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// src/client/session-open.ts
|
|
559
|
+
function isAuthenticationRequired(message) {
|
|
560
|
+
return !/\bmcp\b/i.test(message) && /authentication required|not authenticated|please (?:log|sign) in|需要认证|尚未认证/i.test(message);
|
|
561
|
+
}
|
|
562
|
+
function errorMessage(error) {
|
|
563
|
+
return error instanceof Error ? error.message : String(error);
|
|
564
|
+
}
|
|
565
|
+
function isTransientAcpTransportError(error) {
|
|
566
|
+
if (error instanceof import_sdk.RequestError) {
|
|
567
|
+
if (error.code === -32800 || error.code === -32601 || error.code === -32602)
|
|
568
|
+
return false;
|
|
569
|
+
let detail = "";
|
|
570
|
+
try {
|
|
571
|
+
detail = error.data === undefined ? "" : JSON.stringify(error.data);
|
|
572
|
+
} catch {
|
|
573
|
+
detail = String(error.data);
|
|
574
|
+
}
|
|
575
|
+
return /超时|timeout|timed out|temporar|busy|unavailable|closed|abort|econnreset|epipe/i.test(`${error.message} ${detail}`);
|
|
576
|
+
}
|
|
577
|
+
const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
578
|
+
return /ACP connection closed|connection closed|closed|abort|超时|timeout|timed out|econnreset|epipe|stdio|stream/i.test(message);
|
|
579
|
+
}
|
|
580
|
+
async function restoreOrCreateAcpSession(input) {
|
|
581
|
+
const resumeId = input.resumeSessionId?.trim() || null;
|
|
582
|
+
const restoreAttempts = [];
|
|
583
|
+
let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
|
|
584
|
+
let nativeSessionAccepted = false;
|
|
585
|
+
const sessionMeta = input.codeMode ? { ...input.sessionMeta ?? {}, toolsMode: "ptc" } : input.sessionMeta;
|
|
586
|
+
let recoveredToolOutputs;
|
|
587
|
+
const request = async (method, params) => {
|
|
588
|
+
const opened = await requestSessionWithResources(input.request, method, params, sessionMeta);
|
|
589
|
+
nativeSessionAccepted = opened.nativeSessionAccepted;
|
|
590
|
+
const meta = opened.result._meta;
|
|
591
|
+
const outputs = meta?.toolOutputRecovery?.outputs;
|
|
592
|
+
let total = 0;
|
|
593
|
+
recoveredToolOutputs = Array.isArray(outputs) ? outputs.slice(0, 20).flatMap((row) => {
|
|
594
|
+
if (!row || typeof row.toolCallId !== "string" || row.toolCallId.length > 120 || typeof row.text !== "string")
|
|
595
|
+
return [];
|
|
596
|
+
const bytes = Buffer.byteLength(row.text);
|
|
597
|
+
if (bytes > 128 * 1024 || total + bytes > 256 * 1024)
|
|
598
|
+
return [];
|
|
599
|
+
total += bytes;
|
|
600
|
+
return [{ toolCallId: row.toolCallId, text: row.text }];
|
|
601
|
+
}) : undefined;
|
|
602
|
+
return opened.result;
|
|
603
|
+
};
|
|
604
|
+
const delayMs = input.retryDelayMs ?? 250;
|
|
605
|
+
const log = input.log ?? ((level, message, data) => {
|
|
606
|
+
if (level === "info" && false)
|
|
607
|
+
;
|
|
608
|
+
const line = `[acp] ${message}`;
|
|
609
|
+
if (level === "warn")
|
|
610
|
+
console.warn(line, data ?? "");
|
|
611
|
+
else
|
|
612
|
+
console.info(line, data ?? "");
|
|
613
|
+
});
|
|
614
|
+
const tryRestoreMethod = async (method, rpcMethod) => {
|
|
615
|
+
const maxTries = 2;
|
|
616
|
+
let lastError = "";
|
|
617
|
+
for (let tryIndex = 1;tryIndex <= maxTries; tryIndex++) {
|
|
618
|
+
log("info", "session restore attempt", {
|
|
619
|
+
method: rpcMethod,
|
|
620
|
+
sessionId: resumeId,
|
|
621
|
+
try: tryIndex,
|
|
622
|
+
maxTries
|
|
623
|
+
});
|
|
624
|
+
try {
|
|
625
|
+
const result = await request(rpcMethod, {
|
|
626
|
+
sessionId: resumeId,
|
|
627
|
+
cwd: input.cwd,
|
|
628
|
+
mcpServers: input.mcpServers ?? []
|
|
629
|
+
});
|
|
630
|
+
restoreAttempts.push({ method, ok: true, tries: tryIndex });
|
|
631
|
+
log("info", "session restore ok", { method: rpcMethod, sessionId: resumeId });
|
|
632
|
+
return result;
|
|
633
|
+
} catch (error) {
|
|
634
|
+
lastError = errorMessage(error);
|
|
635
|
+
log("warn", "session restore failed", {
|
|
636
|
+
method: rpcMethod,
|
|
637
|
+
sessionId: resumeId,
|
|
638
|
+
try: tryIndex,
|
|
639
|
+
error: lastError
|
|
640
|
+
});
|
|
641
|
+
const canRetry = tryIndex < maxTries && isTransientAcpTransportError(error);
|
|
642
|
+
if (!canRetry) {
|
|
643
|
+
restoreAttempts.push({ method, ok: false, tries: tryIndex, error: lastError });
|
|
644
|
+
return null;
|
|
645
|
+
}
|
|
646
|
+
if (delayMs > 0)
|
|
647
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
restoreAttempts.push({ method, ok: false, tries: maxTries, error: lastError });
|
|
651
|
+
return null;
|
|
652
|
+
};
|
|
653
|
+
log("info", "openSession", {
|
|
654
|
+
resumeId,
|
|
655
|
+
resumeSupported: input.resumeSupported,
|
|
656
|
+
loadSupported: input.loadSupported
|
|
657
|
+
});
|
|
658
|
+
const requestSessionNew = async () => {
|
|
659
|
+
const baseParams = {
|
|
660
|
+
cwd: input.cwd,
|
|
661
|
+
mcpServers: input.mcpServers ?? []
|
|
662
|
+
};
|
|
663
|
+
try {
|
|
664
|
+
return await request("session/new", baseParams);
|
|
665
|
+
} catch (firstError) {
|
|
666
|
+
if (isTransientAcpTransportError(firstError))
|
|
667
|
+
throw firstError;
|
|
668
|
+
if ((input.mcpServers ?? []).length === 0)
|
|
669
|
+
throw firstError;
|
|
670
|
+
const preserve = input.preserveMcpOnRetry !== false;
|
|
671
|
+
log("warn", preserve ? "session/new failed, retry with mcpServers" : "session/new failed, retry without mcpServers", {
|
|
672
|
+
error: errorMessage(firstError)
|
|
673
|
+
});
|
|
674
|
+
try {
|
|
675
|
+
const result = await request("session/new", {
|
|
676
|
+
cwd: input.cwd,
|
|
677
|
+
mcpServers: preserve ? input.mcpServers ?? [] : []
|
|
678
|
+
});
|
|
679
|
+
mcpServersAccepted = preserve;
|
|
680
|
+
return result;
|
|
681
|
+
} catch {
|
|
682
|
+
throw firstError;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
const withModelsFallback = (result) => mergeTopLevelModelsIntoConfigOptions(result.configOptions, result);
|
|
687
|
+
if (resumeId && input.resumeSupported) {
|
|
688
|
+
const resumed = await tryRestoreMethod("resume", "session/resume");
|
|
689
|
+
if (resumed) {
|
|
690
|
+
const id = typeof resumed.sessionId === "string" ? resumed.sessionId : resumeId;
|
|
691
|
+
return {
|
|
692
|
+
sessionId: id,
|
|
693
|
+
configOptions: withModelsFallback(resumed),
|
|
694
|
+
restoreMethod: "resume",
|
|
695
|
+
sessionRestored: true,
|
|
696
|
+
recoveredToolOutputs,
|
|
697
|
+
mcpServersAccepted,
|
|
698
|
+
nativeSessionAccepted,
|
|
699
|
+
requestedSessionId: resumeId,
|
|
700
|
+
restoreAttempts
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
} else if (resumeId && !input.resumeSupported) {
|
|
704
|
+
log("info", "skip session/resume:Agent 未声明 resume 能力");
|
|
705
|
+
}
|
|
706
|
+
if (resumeId && input.loadSupported) {
|
|
707
|
+
input.onSuppressUpdates?.(true);
|
|
708
|
+
try {
|
|
709
|
+
const loaded = await tryRestoreMethod("load", "session/load");
|
|
710
|
+
if (loaded) {
|
|
711
|
+
const id = typeof loaded.sessionId === "string" ? loaded.sessionId : resumeId;
|
|
712
|
+
return {
|
|
713
|
+
sessionId: id,
|
|
714
|
+
configOptions: withModelsFallback(loaded),
|
|
715
|
+
restoreMethod: "load",
|
|
716
|
+
sessionRestored: true,
|
|
717
|
+
recoveredToolOutputs,
|
|
718
|
+
mcpServersAccepted,
|
|
719
|
+
nativeSessionAccepted,
|
|
720
|
+
requestedSessionId: resumeId,
|
|
721
|
+
restoreAttempts
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
} finally {
|
|
725
|
+
input.onSuppressUpdates?.(false);
|
|
726
|
+
}
|
|
727
|
+
} else if (resumeId && !input.loadSupported) {
|
|
728
|
+
log("info", "skip session/load:Agent 未声明 loadSession 能力");
|
|
729
|
+
}
|
|
730
|
+
log("info", "falling back to session/new", { resumeId, restoreAttempts });
|
|
731
|
+
const sessionResult = await requestSessionNew();
|
|
732
|
+
const newSessionId = typeof sessionResult.sessionId === "string" ? sessionResult.sessionId : null;
|
|
733
|
+
if (!newSessionId) {
|
|
734
|
+
throw new Error("session/new 未返回 sessionId");
|
|
735
|
+
}
|
|
736
|
+
return {
|
|
737
|
+
sessionId: newSessionId,
|
|
738
|
+
configOptions: withModelsFallback(sessionResult),
|
|
739
|
+
restoreMethod: "new",
|
|
740
|
+
sessionRestored: false,
|
|
741
|
+
mcpServersAccepted,
|
|
742
|
+
nativeSessionAccepted,
|
|
743
|
+
requestedSessionId: resumeId ?? undefined,
|
|
744
|
+
restoreAttempts
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
async function requestSessionWithResources(request, method, params, sessionMeta) {
|
|
748
|
+
if (!sessionMeta)
|
|
749
|
+
return { result: await request(method, params), nativeSessionAccepted: false };
|
|
750
|
+
try {
|
|
751
|
+
return { result: await request(method, { ...params, _meta: sessionMeta }), nativeSessionAccepted: true };
|
|
752
|
+
} catch (error) {
|
|
753
|
+
const rejected = error instanceof import_sdk.RequestError && error.code === -32602 || /native.*meta.*reject|unsupported.*(meta|systemPrompt)|unknown.*(meta|systemPrompt)/i.test(errorMessage(error));
|
|
754
|
+
if (!rejected || isTransientAcpTransportError(error))
|
|
755
|
+
throw error;
|
|
756
|
+
return { result: await request(method, params), nativeSessionAccepted: false };
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// src/client/mcp-session-recovery.ts
|
|
761
|
+
class AcpMcpRecoveryCancelledError extends Error {
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
class RecoveryInvariantError extends Error {
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
class AcpMcpSessionRecovery {
|
|
768
|
+
options;
|
|
769
|
+
sessions = new Map;
|
|
770
|
+
generation = 0;
|
|
771
|
+
suppressing = false;
|
|
772
|
+
active;
|
|
773
|
+
constructor(options) {
|
|
774
|
+
this.options = options;
|
|
775
|
+
}
|
|
776
|
+
get isRecovering() {
|
|
777
|
+
return Boolean(this.active);
|
|
778
|
+
}
|
|
779
|
+
register(input) {
|
|
780
|
+
if (this.active)
|
|
781
|
+
throw new Error("MCP recovery is in progress; wait before opening a session");
|
|
782
|
+
if (!input.sessionId.trim() || !input.mcpServers.length)
|
|
783
|
+
throw new Error("MCP recovery requires a session id and servers");
|
|
784
|
+
this.sessions.set(input.sessionId, {
|
|
785
|
+
...input,
|
|
786
|
+
mcpServers: structuredClone(input.mcpServers),
|
|
787
|
+
sessionMeta: input.sessionMeta ? structuredClone(input.sessionMeta) : undefined,
|
|
788
|
+
disconnects: input.monitor.disconnects
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
cancel(sessionId) {
|
|
792
|
+
if (sessionId === undefined || this.active?.sessionId === sessionId)
|
|
793
|
+
this.active?.controller.abort();
|
|
794
|
+
}
|
|
795
|
+
reset() {
|
|
796
|
+
++this.generation;
|
|
797
|
+
this.cancel();
|
|
798
|
+
this.active = undefined;
|
|
799
|
+
this.sessions.clear();
|
|
800
|
+
if (this.suppressing) {
|
|
801
|
+
this.suppressing = false;
|
|
802
|
+
this.options.onSuppressUpdates?.(false);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
ensureReady(sessionId) {
|
|
806
|
+
if (this.active) {
|
|
807
|
+
return this.active.sessionId === sessionId ? this.active.promise : Promise.reject(new Error("Another session is recovering MCP tools; retry shortly"));
|
|
808
|
+
}
|
|
809
|
+
const binding = this.sessions.get(sessionId);
|
|
810
|
+
if (!binding || binding.monitor.disconnects <= binding.disconnects)
|
|
811
|
+
return Promise.resolve();
|
|
812
|
+
const controller = new AbortController;
|
|
813
|
+
const generation = this.generation;
|
|
814
|
+
const promise = Promise.resolve().then(() => this.recover(binding, controller, generation));
|
|
815
|
+
const active = { sessionId, controller, promise };
|
|
816
|
+
this.active = active;
|
|
817
|
+
promise.finally(() => {
|
|
818
|
+
if (this.active === active)
|
|
819
|
+
this.active = undefined;
|
|
820
|
+
}).catch(() => {
|
|
821
|
+
return;
|
|
822
|
+
});
|
|
823
|
+
return promise;
|
|
824
|
+
}
|
|
825
|
+
emit(event) {
|
|
826
|
+
try {
|
|
827
|
+
this.options.onEvent?.(event);
|
|
828
|
+
} catch {}
|
|
829
|
+
}
|
|
830
|
+
async recover(binding, controller, generation) {
|
|
831
|
+
const { sessionId, monitor } = binding;
|
|
832
|
+
const valid = () => {
|
|
833
|
+
if (controller.signal.aborted || generation !== this.generation || !this.options.isConnected()) {
|
|
834
|
+
throw new AcpMcpRecoveryCancelledError("MCP recovery cancelled or ACP connection changed");
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
let suppressed = false;
|
|
838
|
+
try {
|
|
839
|
+
valid();
|
|
840
|
+
if (this.options.isBusy?.(sessionId))
|
|
841
|
+
throw new Error("Agent is processing a prompt; retry MCP recovery shortly");
|
|
842
|
+
const caps = this.options.getCapabilities();
|
|
843
|
+
const methods = [...caps.resume ? ["session/resume"] : [], ...caps.load ? ["session/load"] : []];
|
|
844
|
+
if (!methods.length)
|
|
845
|
+
throw new Error("MCP disconnected and the agent cannot restore this session; reconnect the agent");
|
|
846
|
+
this.emit({ type: "started", sessionId });
|
|
847
|
+
suppressed = true;
|
|
848
|
+
this.suppressing = true;
|
|
849
|
+
this.options.onSuppressUpdates?.(true);
|
|
850
|
+
for (const method of methods) {
|
|
851
|
+
valid();
|
|
852
|
+
const after = monitor.discoveries;
|
|
853
|
+
try {
|
|
854
|
+
const opened = await requestSessionWithResources((rpc, params) => this.boundedRequest(rpc, params, controller.signal), method, { sessionId, cwd: binding.cwd, mcpServers: structuredClone(binding.mcpServers) }, binding.sessionMeta ? structuredClone(binding.sessionMeta) : undefined);
|
|
855
|
+
valid();
|
|
856
|
+
if (typeof opened.result.sessionId === "string" && opened.result.sessionId !== sessionId) {
|
|
857
|
+
throw new RecoveryInvariantError("Agent restored a different session; reconnect the original session");
|
|
858
|
+
}
|
|
859
|
+
if (binding.sessionMeta?.toolsMode === "ptc" && !opened.nativeSessionAccepted) {
|
|
860
|
+
throw new RecoveryInvariantError("Agent rejected Code mode during recovery; reconnect the agent");
|
|
861
|
+
}
|
|
862
|
+
const timeoutMs = this.options.discoveryTimeoutMs ?? 1e4;
|
|
863
|
+
await this.bounded((signal) => monitor.waitForDiscovery(after, signal, timeoutMs), controller.signal, timeoutMs, "Timed out waiting for the agent to rediscover MCP tools");
|
|
864
|
+
valid();
|
|
865
|
+
if (!monitor.hasDiscoveredClient)
|
|
866
|
+
throw new Error("MCP transport closed again during recovery");
|
|
867
|
+
binding.disconnects = monitor.disconnects;
|
|
868
|
+
this.emit({ type: "discovered", sessionId, method });
|
|
869
|
+
return;
|
|
870
|
+
} catch (error) {
|
|
871
|
+
valid();
|
|
872
|
+
this.emit({ type: "failed", sessionId, method });
|
|
873
|
+
if (error instanceof RecoveryInvariantError)
|
|
874
|
+
throw error;
|
|
875
|
+
if (method === methods.at(-1)) {
|
|
876
|
+
throw new Error(`MCP recovery failed; reconnect the agent: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
} catch (error) {
|
|
881
|
+
if (error instanceof AcpMcpRecoveryCancelledError)
|
|
882
|
+
this.emit({ type: "cancelled", sessionId });
|
|
883
|
+
throw error;
|
|
884
|
+
} finally {
|
|
885
|
+
if (suppressed && generation === this.generation) {
|
|
886
|
+
this.suppressing = false;
|
|
887
|
+
this.options.onSuppressUpdates?.(false);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
boundedRequest(method, params, signal) {
|
|
892
|
+
return this.bounded((requestSignal) => this.options.request(method, params, requestSignal), signal, this.options.requestTimeoutMs ?? 120000, "ACP MCP recovery request timed out");
|
|
893
|
+
}
|
|
894
|
+
bounded(operation, signal, timeoutMs, message) {
|
|
895
|
+
return new Promise((resolve, reject) => {
|
|
896
|
+
const controller = new AbortController;
|
|
897
|
+
let settled = false;
|
|
898
|
+
const finish = (callback) => {
|
|
899
|
+
if (settled)
|
|
900
|
+
return;
|
|
901
|
+
settled = true;
|
|
902
|
+
clearTimeout(timer);
|
|
903
|
+
signal.removeEventListener("abort", abort);
|
|
904
|
+
callback();
|
|
905
|
+
};
|
|
906
|
+
const abort = () => finish(() => {
|
|
907
|
+
controller.abort();
|
|
908
|
+
reject(new AcpMcpRecoveryCancelledError("MCP recovery cancelled"));
|
|
909
|
+
});
|
|
910
|
+
const timer = setTimeout(() => finish(() => {
|
|
911
|
+
controller.abort();
|
|
912
|
+
reject(new Error(message));
|
|
913
|
+
}), timeoutMs);
|
|
914
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
915
|
+
if (signal.aborted) {
|
|
916
|
+
abort();
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
Promise.resolve().then(() => {
|
|
920
|
+
if (controller.signal.aborted)
|
|
921
|
+
throw new AcpMcpRecoveryCancelledError("MCP recovery cancelled");
|
|
922
|
+
return operation(controller.signal);
|
|
923
|
+
}).then((result) => finish(() => resolve(result)), (error) => finish(() => reject(error)));
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
393
928
|
// src/client/sdk-client.ts
|
|
394
929
|
var import_node_stream = require("node:stream");
|
|
395
|
-
var
|
|
930
|
+
var import_sdk2 = require("@agentclientprotocol/sdk");
|
|
396
931
|
var ACP_SDK_REQUEST_TIMEOUT_MS = 120000;
|
|
397
932
|
function createSdkStreamHandle(child) {
|
|
398
933
|
const stdoutBridge = new import_node_stream.PassThrough;
|
|
399
934
|
const stdinBridge = new import_node_stream.PassThrough;
|
|
400
|
-
stdoutBridge.on("error", () => {});
|
|
401
|
-
stdinBridge.on("error", () => {});
|
|
402
935
|
child.stdout.pipe(stdoutBridge);
|
|
403
936
|
stdinBridge.pipe(child.stdin, { end: false });
|
|
404
937
|
const output = import_node_stream.Writable.toWeb(stdinBridge);
|
|
405
938
|
const input = import_node_stream.Readable.toWeb(stdoutBridge);
|
|
406
|
-
const stream =
|
|
939
|
+
const stream = import_sdk2.ndJsonStream(output, input);
|
|
407
940
|
let disposed = false;
|
|
408
941
|
return {
|
|
409
942
|
stream,
|
|
@@ -426,11 +959,11 @@ function createSdkStreamHandle(child) {
|
|
|
426
959
|
}
|
|
427
960
|
};
|
|
428
961
|
}
|
|
429
|
-
function connectSdkClient(child, configure, runtimeId
|
|
962
|
+
function connectSdkClient(child, configure, runtimeId) {
|
|
430
963
|
if (runtimeId && true) {
|
|
431
964
|
console.info(`[acp:sdk] connect runtime=${runtimeId} pid=${child.pid ?? "?"}`);
|
|
432
965
|
}
|
|
433
|
-
const app =
|
|
966
|
+
const app = import_sdk2.client({ name: "inkdown" });
|
|
434
967
|
configure(app);
|
|
435
968
|
const streamHandle = createSdkStreamHandle(child);
|
|
436
969
|
const connection = app.connect(streamHandle.stream);
|
|
@@ -460,7 +993,7 @@ async function closeAcpSessions(agent, sessionIds, timeoutMs = 2000) {
|
|
|
460
993
|
const failed = [];
|
|
461
994
|
await Promise.all([...new Set(sessionIds)].map(async (sessionId) => {
|
|
462
995
|
try {
|
|
463
|
-
await sdkRequest(agent,
|
|
996
|
+
await sdkRequest(agent, "session/close", { sessionId }, timeoutMs);
|
|
464
997
|
} catch {
|
|
465
998
|
failed.push(sessionId);
|
|
466
999
|
}
|
|
@@ -793,6 +1326,35 @@ class AvailableCommandsCache {
|
|
|
793
1326
|
}
|
|
794
1327
|
}
|
|
795
1328
|
|
|
1329
|
+
// src/session/code-mode.ts
|
|
1330
|
+
function parseCodeModeModes(caps) {
|
|
1331
|
+
const meta = caps?._meta;
|
|
1332
|
+
if (!meta || typeof meta !== "object")
|
|
1333
|
+
return null;
|
|
1334
|
+
const toolsMode = meta.toolsMode;
|
|
1335
|
+
if (!toolsMode || typeof toolsMode !== "object")
|
|
1336
|
+
return null;
|
|
1337
|
+
const values = toolsMode.values;
|
|
1338
|
+
if (!Array.isArray(values))
|
|
1339
|
+
return null;
|
|
1340
|
+
const modes = values.filter((value) => typeof value === "string");
|
|
1341
|
+
return modes.length > 0 ? modes : null;
|
|
1342
|
+
}
|
|
1343
|
+
function supportsCodeMode(caps) {
|
|
1344
|
+
return parseCodeModeModes(caps)?.includes("ptc") === true;
|
|
1345
|
+
}
|
|
1346
|
+
function codeModeSessionMeta(mode, caps) {
|
|
1347
|
+
if (mode !== "on" || !supportsCodeMode(caps))
|
|
1348
|
+
return;
|
|
1349
|
+
return { toolsMode: "ptc" };
|
|
1350
|
+
}
|
|
1351
|
+
function mergeSessionMeta(appMeta, mode, caps) {
|
|
1352
|
+
const requested = codeModeSessionMeta(mode, caps);
|
|
1353
|
+
if (!requested)
|
|
1354
|
+
return appMeta;
|
|
1355
|
+
return { ...appMeta ?? {}, ...requested };
|
|
1356
|
+
}
|
|
1357
|
+
|
|
796
1358
|
// src/session/quota.ts
|
|
797
1359
|
function parseRateLimitsFromStatusText(text, runtimeId = "unknown") {
|
|
798
1360
|
if (!text || typeof text !== "string")
|
|
@@ -973,8 +1535,8 @@ function emptyAcpAuthPreflight() {
|
|
|
973
1535
|
function isCodexPreflightRuntime(runtimeId) {
|
|
974
1536
|
return !runtimeId || runtimeId === "codex-acp";
|
|
975
1537
|
}
|
|
976
|
-
function resolveCodexHome() {
|
|
977
|
-
const fromEnv =
|
|
1538
|
+
function resolveCodexHome(env = process.env) {
|
|
1539
|
+
const fromEnv = env.CODEX_HOME?.trim();
|
|
978
1540
|
if (fromEnv)
|
|
979
1541
|
return fromEnv;
|
|
980
1542
|
return import_node_path3.join(import_node_os2.homedir(), ".codex");
|
|
@@ -1198,12 +1760,112 @@ async function probeCodexQuota(options) {
|
|
|
1198
1760
|
updatedAt: Date.now()
|
|
1199
1761
|
};
|
|
1200
1762
|
}
|
|
1763
|
+
// src/runtimes/codex/codex-code-mode-home.ts
|
|
1764
|
+
var import_promises2 = require("node:fs/promises");
|
|
1765
|
+
var import_node_fs5 = require("node:fs");
|
|
1766
|
+
var import_node_os3 = require("node:os");
|
|
1767
|
+
var import_node_path5 = require("node:path");
|
|
1768
|
+
var APP_HOME_DIR = ".acp-client";
|
|
1769
|
+
var APP_CODEX_HOME_DIR = "codex-home";
|
|
1770
|
+
function resolveAppCodexHome(baseDir, env = process.env) {
|
|
1771
|
+
const explicit = env.ACP_CODEX_HOME?.trim();
|
|
1772
|
+
if (explicit)
|
|
1773
|
+
return explicit;
|
|
1774
|
+
const base = baseDir?.trim() || env.ACP_STUDIO_HOME?.trim();
|
|
1775
|
+
if (base)
|
|
1776
|
+
return import_node_path5.join(base, APP_CODEX_HOME_DIR);
|
|
1777
|
+
return import_node_path5.join(import_node_os3.homedir(), APP_HOME_DIR, APP_CODEX_HOME_DIR);
|
|
1778
|
+
}
|
|
1779
|
+
function withCodeModeEnabled(toml) {
|
|
1780
|
+
const eol = toml.includes(`\r
|
|
1781
|
+
`) ? `\r
|
|
1782
|
+
` : `
|
|
1783
|
+
`;
|
|
1784
|
+
const lines = toml.split(/\r?\n/);
|
|
1785
|
+
const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/;
|
|
1786
|
+
let start = -1;
|
|
1787
|
+
let end = lines.length;
|
|
1788
|
+
for (let i = 0;i < lines.length; i += 1) {
|
|
1789
|
+
const match = lines[i].match(header);
|
|
1790
|
+
if (!match)
|
|
1791
|
+
continue;
|
|
1792
|
+
if (start >= 0) {
|
|
1793
|
+
end = i;
|
|
1794
|
+
break;
|
|
1795
|
+
}
|
|
1796
|
+
if (match[1].trim() === "features")
|
|
1797
|
+
start = i;
|
|
1798
|
+
}
|
|
1799
|
+
if (start < 0) {
|
|
1800
|
+
const body = toml.replace(/\s+$/, "");
|
|
1801
|
+
return `${body}${body ? `${eol}${eol}` : ""}[features]${eol}code_mode = true${eol}`;
|
|
1802
|
+
}
|
|
1803
|
+
const key = /^(\s*)code_mode\s*=/;
|
|
1804
|
+
for (let i = start + 1;i < end; i += 1) {
|
|
1805
|
+
const match = lines[i].match(key);
|
|
1806
|
+
if (match) {
|
|
1807
|
+
lines[i] = `${match[1]}code_mode = true`;
|
|
1808
|
+
return lines.join(eol);
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
lines.splice(start + 1, 0, "code_mode = true");
|
|
1812
|
+
return lines.join(eol);
|
|
1813
|
+
}
|
|
1814
|
+
async function writeAtomic(path, content) {
|
|
1815
|
+
await import_promises2.mkdir(import_node_path5.dirname(path), { recursive: true });
|
|
1816
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
1817
|
+
await import_promises2.writeFile(temp, content, { encoding: "utf8", mode: 384 });
|
|
1818
|
+
await import_promises2.rename(temp, path);
|
|
1819
|
+
await import_promises2.chmod(path, 384).catch(() => {
|
|
1820
|
+
return;
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
async function provisionCodexCodeModeHome(options = {}) {
|
|
1824
|
+
const env = options.env ?? process.env;
|
|
1825
|
+
const home = options.home?.trim() || resolveAppCodexHome(undefined, env);
|
|
1826
|
+
const sourceHome = options.sourceHome?.trim() || resolveCodexHome(env);
|
|
1827
|
+
const warnings = [];
|
|
1828
|
+
await import_promises2.mkdir(home, { recursive: true });
|
|
1829
|
+
const sourceAuth = import_node_path5.join(sourceHome, "auth.json");
|
|
1830
|
+
const targetAuth = import_node_path5.join(home, "auth.json");
|
|
1831
|
+
let authCopied = false;
|
|
1832
|
+
if (import_node_fs5.existsSync(sourceAuth) && (options.force || !import_node_fs5.existsSync(targetAuth))) {
|
|
1833
|
+
await import_promises2.copyFile(sourceAuth, targetAuth);
|
|
1834
|
+
await import_promises2.chmod(targetAuth, 384).catch(() => {
|
|
1835
|
+
return;
|
|
1836
|
+
});
|
|
1837
|
+
authCopied = true;
|
|
1838
|
+
} else if (!import_node_fs5.existsSync(targetAuth)) {
|
|
1839
|
+
warnings.push(`no auth.json in ${sourceHome}; run "CODEX_HOME=${home} codex login" or copy it manually`);
|
|
1840
|
+
}
|
|
1841
|
+
const sourceConfig = import_node_path5.join(sourceHome, "config.toml");
|
|
1842
|
+
const targetConfig = import_node_path5.join(home, "config.toml");
|
|
1843
|
+
let configCopied = false;
|
|
1844
|
+
if (import_node_fs5.existsSync(sourceConfig) && (options.force || !import_node_fs5.existsSync(targetConfig))) {
|
|
1845
|
+
await import_promises2.copyFile(sourceConfig, targetConfig);
|
|
1846
|
+
configCopied = true;
|
|
1847
|
+
} else if (!import_node_fs5.existsSync(targetConfig) && !import_node_fs5.existsSync(sourceConfig)) {
|
|
1848
|
+
warnings.push(`no config.toml in ${sourceHome}; starting from an empty one`);
|
|
1849
|
+
}
|
|
1850
|
+
const current = import_node_fs5.existsSync(targetConfig) ? await import_promises2.readFile(targetConfig, "utf8") : "";
|
|
1851
|
+
const next = withCodeModeEnabled(current);
|
|
1852
|
+
if (next !== current)
|
|
1853
|
+
await writeAtomic(targetConfig, next);
|
|
1854
|
+
return {
|
|
1855
|
+
home,
|
|
1856
|
+
sourceHome,
|
|
1857
|
+
authCopied,
|
|
1858
|
+
configCopied,
|
|
1859
|
+
codeModeEnabled: true,
|
|
1860
|
+
warnings
|
|
1861
|
+
};
|
|
1862
|
+
}
|
|
1201
1863
|
|
|
1202
1864
|
// src/runtimes/codex/index.ts
|
|
1203
|
-
var
|
|
1204
|
-
var
|
|
1205
|
-
var
|
|
1206
|
-
var
|
|
1865
|
+
var import_promises4 = require("node:fs/promises");
|
|
1866
|
+
var import_node_path8 = require("node:path");
|
|
1867
|
+
var import_node_os5 = require("node:os");
|
|
1868
|
+
var import_node_fs7 = require("node:fs");
|
|
1207
1869
|
var import_node_crypto2 = require("node:crypto");
|
|
1208
1870
|
|
|
1209
1871
|
// src/resources/config-text.ts
|
|
@@ -1317,13 +1979,13 @@ function buildCustomProviderSpawnEnv(config, apiKey, codexHome) {
|
|
|
1317
1979
|
}
|
|
1318
1980
|
|
|
1319
1981
|
// src/runtimes/codex/codex-provider.ts
|
|
1320
|
-
var
|
|
1321
|
-
var
|
|
1322
|
-
var
|
|
1982
|
+
var import_promises3 = require("node:fs/promises");
|
|
1983
|
+
var import_node_fs6 = require("node:fs");
|
|
1984
|
+
var import_node_path7 = require("node:path");
|
|
1323
1985
|
|
|
1324
1986
|
// src/client/acp-paths.ts
|
|
1325
|
-
var
|
|
1326
|
-
var
|
|
1987
|
+
var import_node_os4 = require("node:os");
|
|
1988
|
+
var import_node_path6 = require("node:path");
|
|
1327
1989
|
function getDefaultAgentDataDir() {
|
|
1328
1990
|
if (process.env.INKDOWN_DATA_DIR) {
|
|
1329
1991
|
return process.env.INKDOWN_DATA_DIR;
|
|
@@ -1332,20 +1994,20 @@ function getDefaultAgentDataDir() {
|
|
|
1332
1994
|
return process.env.ACP_DATA_DIR;
|
|
1333
1995
|
}
|
|
1334
1996
|
if (process.platform === "win32") {
|
|
1335
|
-
return process.env.LOCALAPPDATA || process.env.APPDATA ||
|
|
1997
|
+
return process.env.LOCALAPPDATA || process.env.APPDATA || import_node_path6.join(import_node_os4.homedir(), "AppData", "Local", "inkdown");
|
|
1336
1998
|
}
|
|
1337
1999
|
if (process.platform === "darwin") {
|
|
1338
|
-
return
|
|
2000
|
+
return import_node_path6.join(import_node_os4.homedir(), "Library", "Application Support", "inkdown");
|
|
1339
2001
|
}
|
|
1340
|
-
return process.env.XDG_DATA_HOME ||
|
|
2002
|
+
return process.env.XDG_DATA_HOME || import_node_path6.join(import_node_os4.homedir(), ".local", "share", "inkdown");
|
|
1341
2003
|
}
|
|
1342
2004
|
|
|
1343
2005
|
// src/runtimes/codex/codex-provider.ts
|
|
1344
2006
|
function providerFilePath(dir) {
|
|
1345
|
-
return
|
|
2007
|
+
return import_node_path7.join(dir, "agent", "provider.json");
|
|
1346
2008
|
}
|
|
1347
2009
|
function providerHomePath(dir) {
|
|
1348
|
-
return
|
|
2010
|
+
return import_node_path7.join(dir, "agent", "codex-home");
|
|
1349
2011
|
}
|
|
1350
2012
|
function toStatus(stored) {
|
|
1351
2013
|
if (!stored)
|
|
@@ -1371,10 +2033,10 @@ function validate(payload) {
|
|
|
1371
2033
|
}
|
|
1372
2034
|
async function readStoredAcpProvider(dir = getDefaultAgentDataDir()) {
|
|
1373
2035
|
const file = providerFilePath(dir);
|
|
1374
|
-
if (!
|
|
2036
|
+
if (!import_node_fs6.existsSync(file))
|
|
1375
2037
|
return null;
|
|
1376
2038
|
try {
|
|
1377
|
-
const raw = JSON.parse(await
|
|
2039
|
+
const raw = JSON.parse(await import_promises3.readFile(file, "utf8"));
|
|
1378
2040
|
if (typeof raw.baseUrl !== "string" || typeof raw.model !== "string" || typeof raw.apiKey !== "string" || !raw.apiKey.trim()) {
|
|
1379
2041
|
return null;
|
|
1380
2042
|
}
|
|
@@ -1400,7 +2062,7 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
|
|
|
1400
2062
|
const apiKey = payload.apiKey.trim() || (await readStoredAcpProvider(dir))?.apiKey || "";
|
|
1401
2063
|
if (!apiKey)
|
|
1402
2064
|
return err({ code: "INVALID_ARGUMENT", message: "API Key 不能为空" });
|
|
1403
|
-
await
|
|
2065
|
+
await import_promises3.mkdir(import_node_path7.join(dir, "agent"), { recursive: true });
|
|
1404
2066
|
const stored = {
|
|
1405
2067
|
name: payload.name?.trim() || undefined,
|
|
1406
2068
|
baseUrl: payload.baseUrl.trim(),
|
|
@@ -1408,11 +2070,11 @@ async function saveAcpProvider(payload, dir = getDefaultAgentDataDir()) {
|
|
|
1408
2070
|
apiKey,
|
|
1409
2071
|
wireApi: payload.wireApi === "responses" ? "responses" : "chat"
|
|
1410
2072
|
};
|
|
1411
|
-
await
|
|
2073
|
+
await import_promises3.writeFile(file, JSON.stringify(stored, null, 2), "utf8");
|
|
1412
2074
|
return ok(toStatus(stored));
|
|
1413
2075
|
}
|
|
1414
2076
|
async function clearAcpProvider(dir = getDefaultAgentDataDir()) {
|
|
1415
|
-
await
|
|
2077
|
+
await import_promises3.rm(providerFilePath(dir), { force: true });
|
|
1416
2078
|
return ok(undefined);
|
|
1417
2079
|
}
|
|
1418
2080
|
function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
|
|
@@ -1422,15 +2084,15 @@ function getAcpProviderCodexHome(dir = getDefaultAgentDataDir()) {
|
|
|
1422
2084
|
// src/runtimes/codex/index.ts
|
|
1423
2085
|
async function provisionCustomProviderCodexHome(provider, codexHome) {
|
|
1424
2086
|
try {
|
|
1425
|
-
await
|
|
2087
|
+
await import_promises4.mkdir(codexHome, { recursive: true });
|
|
1426
2088
|
let existing = null;
|
|
1427
2089
|
try {
|
|
1428
|
-
existing = await
|
|
2090
|
+
existing = await import_promises4.readFile(import_node_path8.join(codexHome, "config.toml"), "utf8");
|
|
1429
2091
|
} catch (error) {
|
|
1430
2092
|
if (error.code !== "ENOENT")
|
|
1431
2093
|
throw error;
|
|
1432
2094
|
}
|
|
1433
|
-
await
|
|
2095
|
+
await import_promises4.writeFile(import_node_path8.join(codexHome, "config.toml"), mergeConfigTomlPreserving({
|
|
1434
2096
|
existingText: existing,
|
|
1435
2097
|
managedTopKeys: ["model", "model_provider"],
|
|
1436
2098
|
managedTables: [`model_providers.${INKDOWN_PROVIDER_ID}`],
|
|
@@ -1475,20 +2137,20 @@ var codexAdapter = {
|
|
|
1475
2137
|
return notApplied("invalid-resource-directory");
|
|
1476
2138
|
if (env.CODEX_PATH)
|
|
1477
2139
|
return notApplied("execution-not-verified");
|
|
1478
|
-
const codexHome = env.CODEX_HOME ||
|
|
2140
|
+
const codexHome = env.CODEX_HOME || import_node_path8.join(import_node_os5.homedir(), ".codex");
|
|
1479
2141
|
try {
|
|
1480
|
-
await
|
|
2142
|
+
await import_promises4.readFile(import_node_path8.join(codexHome, "config.toml"));
|
|
1481
2143
|
return notApplied("effective-config-not-verified");
|
|
1482
2144
|
} catch (error) {
|
|
1483
2145
|
if (error.code !== "ENOENT")
|
|
1484
2146
|
return notApplied("effective-config-not-verified");
|
|
1485
2147
|
}
|
|
1486
2148
|
for (let dir = workspaceRoot;dir; ) {
|
|
1487
|
-
if (
|
|
2149
|
+
if (import_node_fs7.existsSync(import_node_path8.join(dir, ".codex", "config.toml")))
|
|
1488
2150
|
return notApplied("effective-config-not-verified");
|
|
1489
|
-
if (
|
|
2151
|
+
if (import_node_fs7.existsSync(import_node_path8.join(dir, ".git")))
|
|
1490
2152
|
break;
|
|
1491
|
-
const parent =
|
|
2153
|
+
const parent = import_node_path8.dirname(dir);
|
|
1492
2154
|
if (parent === dir)
|
|
1493
2155
|
break;
|
|
1494
2156
|
dir = parent;
|
|
@@ -1534,13 +2196,13 @@ var codexAdapter = {
|
|
|
1534
2196
|
};
|
|
1535
2197
|
|
|
1536
2198
|
// src/resources/runtime-bindings.ts
|
|
1537
|
-
var
|
|
2199
|
+
var import_node_path9 = require("node:path");
|
|
1538
2200
|
var import_node_child_process2 = require("node:child_process");
|
|
1539
2201
|
var import_node_util = require("node:util");
|
|
1540
2202
|
var APP_RESOURCE_CAPABILITIES = {
|
|
1541
2203
|
"codex-acp": { entry: "CODEX_CONFIG", strategy: "native-overlay", configHome: "CODEX_HOME" },
|
|
1542
2204
|
opencode: { entry: "OPENCODE_CONFIG_CONTENT", strategy: "native-overlay", configHome: "OPENCODE_CONFIG_DIR" },
|
|
1543
|
-
"opencode-v2": { entry:
|
|
2205
|
+
"opencode-v2": { entry: null, strategy: "compatibility", configHome: null },
|
|
1544
2206
|
claude: { entry: "_meta.systemPrompt + _meta.claudeCode.options.plugins", strategy: "native-session", configHome: "CLAUDE_CONFIG_DIR" },
|
|
1545
2207
|
gemini: { entry: null, strategy: "compatibility", configHome: "GEMINI_CLI_HOME" },
|
|
1546
2208
|
copilot: { entry: null, strategy: "compatibility", configHome: "COPILOT_HOME", candidateEntry: "COPILOT_CUSTOM_INSTRUCTIONS_DIRS" },
|
|
@@ -1574,53 +2236,22 @@ function mergeOpenCodeAppConfig(raw, directory) {
|
|
|
1574
2236
|
throw new Error("invalid-opencode-skill-paths");
|
|
1575
2237
|
return JSON.stringify({
|
|
1576
2238
|
...config,
|
|
1577
|
-
instructions: [...new Set([...config.instructions ?? [],
|
|
1578
|
-
skills: { ...skills, paths: [...new Set([...skills.paths ?? [],
|
|
2239
|
+
instructions: [...new Set([...config.instructions ?? [], import_node_path9.join(directory, "AGENTS.md")])],
|
|
2240
|
+
skills: { ...skills, paths: [...new Set([...skills.paths ?? [], import_node_path9.join(directory, "skills")])] }
|
|
1579
2241
|
});
|
|
1580
2242
|
}
|
|
1581
|
-
function resolveOpenCodeQuestionMode(version) {
|
|
1582
|
-
const normalized = version.trim().replace(/^opencode\s+v?/i, "");
|
|
1583
|
-
return ["1.18.35", "2.0.6"].includes(normalized) ? "fallback" : "unverified";
|
|
1584
|
-
}
|
|
1585
|
-
function mergeOpenCodeQuestionConfig(raw) {
|
|
1586
|
-
const value = raw?.trim() ? JSON.parse(raw) : {};
|
|
1587
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
1588
|
-
throw new Error("invalid-opencode-config");
|
|
1589
|
-
const config = value;
|
|
1590
|
-
const permission = config.permission;
|
|
1591
|
-
if (permission !== undefined && (typeof permission !== "string" || !["allow", "ask", "deny"].includes(permission)) && (!permission || typeof permission !== "object" || Array.isArray(permission)))
|
|
1592
|
-
throw new Error("invalid-opencode-permission");
|
|
1593
|
-
const rules = typeof permission === "string" ? { "*": permission } : permission ?? {};
|
|
1594
|
-
return JSON.stringify({ ...config, permission: { ...rules, question: "deny" } });
|
|
1595
|
-
}
|
|
1596
2243
|
async function prepareOpenCodeResources(input) {
|
|
1597
2244
|
const prep = prepareCompatibilityResources(input.directory, "native-entry-not-verified");
|
|
1598
|
-
|
|
1599
|
-
if (!input.command)
|
|
2245
|
+
if (!input.command || !readAppRulesText(input.directory))
|
|
1600
2246
|
return prep;
|
|
1601
2247
|
try {
|
|
1602
2248
|
const { stdout } = await import_node_util.promisify(import_node_child_process2.execFile)(input.command, ["--version"], { env: input.env, timeout: 8000, windowsHide: true });
|
|
1603
|
-
|
|
1604
|
-
if (resolveOpenCodeQuestionMode(version) !== "fallback") {
|
|
1605
|
-
prep.report.openCodeQuestions.version = version;
|
|
2249
|
+
if (stdout.trim() !== "1.18.35")
|
|
1606
2250
|
return prep;
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
const hasRules = version === "1.18.35" && !!readAppRulesText(input.directory);
|
|
1610
|
-
if (hasRules)
|
|
1611
|
-
json = mergeOpenCodeAppConfig(json, input.directory);
|
|
1612
|
-
return { env: { OPENCODE_CONFIG_CONTENT: json }, report: {
|
|
1613
|
-
...prep.report,
|
|
1614
|
-
rulesPrepared: hasRules,
|
|
1615
|
-
reason: hasRules ? undefined : version === "2.0.6" ? "native-entry-not-verified" : "missing-app-rules",
|
|
1616
|
-
openCodeQuestions: { version, mode: "fallback", configuration: "prepared", reason: "acp-question-not-forwarded" }
|
|
1617
|
-
} };
|
|
2251
|
+
const json = mergeOpenCodeAppConfig(input.env?.OPENCODE_CONFIG_CONTENT, input.directory);
|
|
2252
|
+
return { env: { OPENCODE_CONFIG_CONTENT: json }, report: { ...prep.report, rulesPrepared: true, reason: undefined } };
|
|
1618
2253
|
} catch {
|
|
1619
|
-
return { ...prep, report: {
|
|
1620
|
-
...prep.report,
|
|
1621
|
-
reason: "native-config-prepare-failed",
|
|
1622
|
-
openCodeQuestions: { mode: "unverified", configuration: "unchanged", reason: "prepare-failed" }
|
|
1623
|
-
} };
|
|
2254
|
+
return { ...prep, report: { ...prep.report, reason: "native-config-prepare-failed" } };
|
|
1624
2255
|
}
|
|
1625
2256
|
}
|
|
1626
2257
|
function prepareClaudeResources(directory) {
|
|
@@ -1638,9 +2269,9 @@ function claudeResourceSessionMeta(directory) {
|
|
|
1638
2269
|
}
|
|
1639
2270
|
|
|
1640
2271
|
// src/runtimes/claude/quota.ts
|
|
1641
|
-
var
|
|
1642
|
-
var
|
|
1643
|
-
var
|
|
2272
|
+
var import_node_fs8 = require("node:fs");
|
|
2273
|
+
var import_node_os6 = require("node:os");
|
|
2274
|
+
var import_node_path10 = require("node:path");
|
|
1644
2275
|
var import_node_child_process3 = require("node:child_process");
|
|
1645
2276
|
var cachedClaudeAuth = null;
|
|
1646
2277
|
async function queryClaudeAuthStatus(timeoutMs = 1200) {
|
|
@@ -1667,15 +2298,15 @@ async function queryClaudeAuthStatus(timeoutMs = 1200) {
|
|
|
1667
2298
|
}
|
|
1668
2299
|
async function probeClaudeQuota(options) {
|
|
1669
2300
|
const claudeHome = resolveClaudeHome();
|
|
1670
|
-
const claudeJsonPath =
|
|
1671
|
-
const credsPath =
|
|
2301
|
+
const claudeJsonPath = import_node_path10.join(import_node_os6.homedir(), ".claude.json");
|
|
2302
|
+
const credsPath = import_node_path10.join(claudeHome, ".credentials.json");
|
|
1672
2303
|
let isLoggedIn = false;
|
|
1673
2304
|
let isBanned = false;
|
|
1674
2305
|
let accountEmail;
|
|
1675
2306
|
let plan = "Claude Free / Default";
|
|
1676
|
-
if (
|
|
2307
|
+
if (import_node_fs8.existsSync(claudeJsonPath)) {
|
|
1677
2308
|
try {
|
|
1678
|
-
const data = JSON.parse(
|
|
2309
|
+
const data = JSON.parse(import_node_fs8.readFileSync(claudeJsonPath, "utf8"));
|
|
1679
2310
|
if (data.oauthAccount) {
|
|
1680
2311
|
isLoggedIn = true;
|
|
1681
2312
|
accountEmail = data.oauthAccount.emailAddress;
|
|
@@ -1686,9 +2317,9 @@ async function probeClaudeQuota(options) {
|
|
|
1686
2317
|
}
|
|
1687
2318
|
} catch {}
|
|
1688
2319
|
}
|
|
1689
|
-
if (
|
|
2320
|
+
if (import_node_fs8.existsSync(credsPath)) {
|
|
1690
2321
|
try {
|
|
1691
|
-
const creds = JSON.parse(
|
|
2322
|
+
const creds = JSON.parse(import_node_fs8.readFileSync(credsPath, "utf8"));
|
|
1692
2323
|
if (creds.accessToken || creds.sessionKey)
|
|
1693
2324
|
isLoggedIn = true;
|
|
1694
2325
|
} catch {}
|
|
@@ -1740,19 +2371,19 @@ async function probeClaudeQuota(options) {
|
|
|
1740
2371
|
}
|
|
1741
2372
|
|
|
1742
2373
|
// src/runtimes/claude/index.ts
|
|
1743
|
-
var
|
|
1744
|
-
var
|
|
1745
|
-
var
|
|
2374
|
+
var import_node_fs9 = require("node:fs");
|
|
2375
|
+
var import_node_os7 = require("node:os");
|
|
2376
|
+
var import_node_path11 = require("node:path");
|
|
1746
2377
|
function resolveClaudeHome() {
|
|
1747
2378
|
const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
1748
2379
|
if (fromEnv)
|
|
1749
2380
|
return fromEnv;
|
|
1750
|
-
return
|
|
2381
|
+
return import_node_path11.join(import_node_os7.homedir(), ".claude");
|
|
1751
2382
|
}
|
|
1752
2383
|
function probeClaudeAuth() {
|
|
1753
2384
|
const claudeHome = resolveClaudeHome();
|
|
1754
|
-
const hasCodexHome =
|
|
1755
|
-
const hasAuthFile =
|
|
2385
|
+
const hasCodexHome = import_node_fs9.existsSync(claudeHome);
|
|
2386
|
+
const hasAuthFile = import_node_fs9.existsSync(import_node_path11.join(import_node_os7.homedir(), ".claude.json")) || import_node_fs9.existsSync(import_node_path11.join(claudeHome, ".credentials.json"));
|
|
1756
2387
|
const hasApiKeyEnv = Boolean(process.env.ANTHROPIC_API_KEY?.trim() || process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim());
|
|
1757
2388
|
return {
|
|
1758
2389
|
codexHome: claudeHome,
|
|
@@ -1774,16 +2405,16 @@ var claudeAdapter = {
|
|
|
1774
2405
|
};
|
|
1775
2406
|
|
|
1776
2407
|
// src/runtimes/gemini/index.ts
|
|
1777
|
-
var
|
|
1778
|
-
var
|
|
1779
|
-
var
|
|
2408
|
+
var import_node_fs10 = require("node:fs");
|
|
2409
|
+
var import_node_os8 = require("node:os");
|
|
2410
|
+
var import_node_path12 = require("node:path");
|
|
1780
2411
|
function resolveGeminiHome() {
|
|
1781
|
-
return
|
|
2412
|
+
return import_node_path12.join(import_node_os8.homedir(), ".gemini");
|
|
1782
2413
|
}
|
|
1783
2414
|
function probeGeminiAuth() {
|
|
1784
2415
|
const geminiHome = resolveGeminiHome();
|
|
1785
|
-
const hasCodexHome =
|
|
1786
|
-
const hasAuthFile =
|
|
2416
|
+
const hasCodexHome = import_node_fs10.existsSync(geminiHome);
|
|
2417
|
+
const hasAuthFile = import_node_fs10.existsSync(import_node_path12.join(geminiHome, "oauth_creds.json")) || Boolean(process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim());
|
|
1787
2418
|
const hasApiKeyEnv = Boolean(process.env.GEMINI_API_KEY?.trim() || process.env.GOOGLE_API_KEY?.trim());
|
|
1788
2419
|
return {
|
|
1789
2420
|
codexHome: geminiHome,
|
|
@@ -1802,18 +2433,18 @@ var geminiAdapter = {
|
|
|
1802
2433
|
};
|
|
1803
2434
|
|
|
1804
2435
|
// src/runtimes/copilot/index.ts
|
|
1805
|
-
var
|
|
1806
|
-
var
|
|
1807
|
-
var
|
|
2436
|
+
var import_node_fs11 = require("node:fs");
|
|
2437
|
+
var import_node_os9 = require("node:os");
|
|
2438
|
+
var import_node_path13 = require("node:path");
|
|
1808
2439
|
function resolveCopilotHome() {
|
|
1809
2440
|
const fromEnv = process.env.COPILOT_HOME?.trim();
|
|
1810
2441
|
if (fromEnv)
|
|
1811
2442
|
return fromEnv;
|
|
1812
|
-
return
|
|
2443
|
+
return import_node_path13.join(import_node_os9.homedir(), ".copilot");
|
|
1813
2444
|
}
|
|
1814
2445
|
function hasCopilotLogin(home) {
|
|
1815
2446
|
try {
|
|
1816
|
-
const raw =
|
|
2447
|
+
const raw = import_node_fs11.readFileSync(import_node_path13.join(home, "config.json"), "utf8");
|
|
1817
2448
|
const parsed = JSON.parse(raw);
|
|
1818
2449
|
return Array.isArray(parsed.loggedInUsers) && parsed.loggedInUsers.length > 0;
|
|
1819
2450
|
} catch {
|
|
@@ -1822,7 +2453,7 @@ function hasCopilotLogin(home) {
|
|
|
1822
2453
|
}
|
|
1823
2454
|
function probeCopilotAuth() {
|
|
1824
2455
|
const copilotHome = resolveCopilotHome();
|
|
1825
|
-
const hasCodexHome =
|
|
2456
|
+
const hasCodexHome = import_node_fs11.existsSync(copilotHome);
|
|
1826
2457
|
const hasAuthFile = hasCopilotLogin(copilotHome);
|
|
1827
2458
|
const hasApiKeyEnv = Boolean(process.env.COPILOT_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim());
|
|
1828
2459
|
return {
|
|
@@ -1842,14 +2473,14 @@ var copilotAdapter = {
|
|
|
1842
2473
|
};
|
|
1843
2474
|
|
|
1844
2475
|
// src/runtimes/opencode/quota.ts
|
|
1845
|
-
var
|
|
2476
|
+
var import_node_fs12 = require("node:fs");
|
|
1846
2477
|
var import_node_child_process4 = require("node:child_process");
|
|
1847
2478
|
var os = __toESM(require("node:os"), 1);
|
|
1848
2479
|
var path = __toESM(require("node:path"), 1);
|
|
1849
2480
|
function resolveOpencodeAuthPath() {
|
|
1850
2481
|
const candidates = resolveOpencodeAuthCandidates();
|
|
1851
2482
|
for (const c of candidates) {
|
|
1852
|
-
if (
|
|
2483
|
+
if (import_node_fs12.existsSync(c))
|
|
1853
2484
|
return c;
|
|
1854
2485
|
}
|
|
1855
2486
|
return candidates[0] ?? null;
|
|
@@ -1900,7 +2531,7 @@ function readLocalOpencodeCredentials() {
|
|
|
1900
2531
|
path.join(home, ".config", "opencode", "opencode.db")
|
|
1901
2532
|
].filter(Boolean);
|
|
1902
2533
|
for (const dbPath of dbPaths) {
|
|
1903
|
-
if (!
|
|
2534
|
+
if (!import_node_fs12.existsSync(dbPath))
|
|
1904
2535
|
continue;
|
|
1905
2536
|
try {
|
|
1906
2537
|
let rows = [];
|
|
@@ -1929,7 +2560,7 @@ function readLocalOpencodeCredentials() {
|
|
|
1929
2560
|
}
|
|
1930
2561
|
} catch {
|
|
1931
2562
|
try {
|
|
1932
|
-
const buf =
|
|
2563
|
+
const buf = import_node_fs12.readFileSync(dbPath, "utf8");
|
|
1933
2564
|
const emailMatch = buf.match(/"email"\s*:\s*"([^"]+)"/);
|
|
1934
2565
|
const tokenMatch = buf.match(/"access"\s*:\s*"(st_[a-zA-Z0-9_\\-]+)"/);
|
|
1935
2566
|
const orgMatch = buf.match(/"orgID"\s*:\s*"(wrk_[a-zA-Z0-9_\\-]+)"/);
|
|
@@ -2053,9 +2684,9 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
|
|
|
2053
2684
|
let accountEmail = dbCreds.email;
|
|
2054
2685
|
let accountName = dbCreds.name;
|
|
2055
2686
|
let plan = "OpenCode Community";
|
|
2056
|
-
if (authPath &&
|
|
2687
|
+
if (authPath && import_node_fs12.existsSync(authPath)) {
|
|
2057
2688
|
try {
|
|
2058
|
-
const data = JSON.parse(
|
|
2689
|
+
const data = JSON.parse(import_node_fs12.readFileSync(authPath, "utf8"));
|
|
2059
2690
|
if (data && typeof data === "object") {
|
|
2060
2691
|
const keys = Object.keys(data);
|
|
2061
2692
|
if (keys.length > 0) {
|
|
@@ -2115,16 +2746,16 @@ async function probeOpencodeQuota(runtimeId = "opencode") {
|
|
|
2115
2746
|
}
|
|
2116
2747
|
|
|
2117
2748
|
// src/runtimes/opencode/index.ts
|
|
2118
|
-
var
|
|
2119
|
-
var
|
|
2120
|
-
var
|
|
2749
|
+
var import_node_fs13 = require("node:fs");
|
|
2750
|
+
var import_node_os10 = require("node:os");
|
|
2751
|
+
var import_node_path14 = require("node:path");
|
|
2121
2752
|
function pickEnv(env, key) {
|
|
2122
2753
|
return env?.[key]?.trim() ?? "";
|
|
2123
2754
|
}
|
|
2124
2755
|
function resolveOpencodeAuthCandidates(overrides) {
|
|
2125
2756
|
const platform = overrides?.platform ?? process.platform;
|
|
2126
2757
|
const env = overrides?.env ?? process.env;
|
|
2127
|
-
const home = overrides?.home ??
|
|
2758
|
+
const home = overrides?.home ?? import_node_os10.homedir();
|
|
2128
2759
|
const seen = new Set;
|
|
2129
2760
|
const out = [];
|
|
2130
2761
|
const push = (p) => {
|
|
@@ -2135,27 +2766,27 @@ function resolveOpencodeAuthCandidates(overrides) {
|
|
|
2135
2766
|
};
|
|
2136
2767
|
const xdg = pickEnv(env, "XDG_DATA_HOME");
|
|
2137
2768
|
if (xdg)
|
|
2138
|
-
push(
|
|
2769
|
+
push(import_node_path14.join(xdg, "opencode", "auth.json"));
|
|
2139
2770
|
if (platform === "win32") {
|
|
2140
|
-
const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ?
|
|
2771
|
+
const localAppData = pickEnv(env, "LOCALAPPDATA") || (pickEnv(env, "USERPROFILE") ? import_node_path14.join(pickEnv(env, "USERPROFILE"), "AppData", "Local") : "");
|
|
2141
2772
|
if (localAppData)
|
|
2142
|
-
push(
|
|
2773
|
+
push(import_node_path14.join(localAppData, "opencode", "auth.json"));
|
|
2143
2774
|
const userProfile = pickEnv(env, "USERPROFILE") || home;
|
|
2144
2775
|
if (userProfile)
|
|
2145
|
-
push(
|
|
2776
|
+
push(import_node_path14.join(userProfile, ".local", "share", "opencode", "auth.json"));
|
|
2146
2777
|
} else if (home) {
|
|
2147
|
-
push(
|
|
2778
|
+
push(import_node_path14.join(home, ".local", "share", "opencode", "auth.json"));
|
|
2148
2779
|
}
|
|
2149
2780
|
return out;
|
|
2150
2781
|
}
|
|
2151
2782
|
function resolveOpencodeAuthFile() {
|
|
2152
|
-
return resolveOpencodeAuthCandidates()[0] ??
|
|
2783
|
+
return resolveOpencodeAuthCandidates()[0] ?? import_node_path14.join(import_node_os10.homedir(), ".local", "share", "opencode", "auth.json");
|
|
2153
2784
|
}
|
|
2154
2785
|
function isValidOpencodeAuthFile(authFile) {
|
|
2155
2786
|
try {
|
|
2156
|
-
if (!authFile || !
|
|
2787
|
+
if (!authFile || !import_node_fs13.existsSync(authFile))
|
|
2157
2788
|
return false;
|
|
2158
|
-
const raw =
|
|
2789
|
+
const raw = import_node_fs13.readFileSync(authFile, "utf8").trim();
|
|
2159
2790
|
if (!raw)
|
|
2160
2791
|
return false;
|
|
2161
2792
|
const parsed = JSON.parse(raw);
|
|
@@ -2173,7 +2804,7 @@ function probeOpencodeAuth(overrides) {
|
|
|
2173
2804
|
for (const candidate of candidates) {
|
|
2174
2805
|
let exists = false;
|
|
2175
2806
|
try {
|
|
2176
|
-
exists =
|
|
2807
|
+
exists = import_node_fs13.existsSync(candidate);
|
|
2177
2808
|
} catch {
|
|
2178
2809
|
exists = false;
|
|
2179
2810
|
}
|
|
@@ -2186,10 +2817,10 @@ function probeOpencodeAuth(overrides) {
|
|
|
2186
2817
|
validFile = candidate;
|
|
2187
2818
|
}
|
|
2188
2819
|
const authFile = validFile ?? firstExisting ?? candidates[0] ?? resolveOpencodeAuthFile();
|
|
2189
|
-
const authDir =
|
|
2820
|
+
const authDir = import_node_path14.dirname(authFile);
|
|
2190
2821
|
let hasCodexHome = false;
|
|
2191
2822
|
try {
|
|
2192
|
-
hasCodexHome =
|
|
2823
|
+
hasCodexHome = import_node_fs13.existsSync(authDir);
|
|
2193
2824
|
} catch {
|
|
2194
2825
|
hasCodexHome = false;
|
|
2195
2826
|
}
|
|
@@ -2216,7 +2847,7 @@ var opencodeAdapter = {
|
|
|
2216
2847
|
// src/runtimes/opencode-v2/index.ts
|
|
2217
2848
|
var opencodeV2Adapter = {
|
|
2218
2849
|
id: "opencode-v2",
|
|
2219
|
-
prepareAppResources:
|
|
2850
|
+
prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
|
|
2220
2851
|
probeAuth: () => probeOpencodeAuth(),
|
|
2221
2852
|
orderAuthMethods: (methods) => methods,
|
|
2222
2853
|
canSkipInteractiveAuth: () => false,
|
|
@@ -2248,27 +2879,27 @@ async function probeCursorQuota() {
|
|
|
2248
2879
|
|
|
2249
2880
|
// src/runtimes/cursor/index.ts
|
|
2250
2881
|
var import_node_child_process5 = require("node:child_process");
|
|
2251
|
-
var
|
|
2252
|
-
var
|
|
2253
|
-
var
|
|
2882
|
+
var import_node_fs14 = require("node:fs");
|
|
2883
|
+
var import_node_os11 = require("node:os");
|
|
2884
|
+
var import_node_path15 = require("node:path");
|
|
2254
2885
|
function cursorLocalAppData(env) {
|
|
2255
2886
|
const local = env.LOCALAPPDATA?.trim();
|
|
2256
2887
|
if (local)
|
|
2257
2888
|
return local;
|
|
2258
2889
|
const profile = env.USERPROFILE?.trim();
|
|
2259
|
-
return profile ?
|
|
2890
|
+
return profile ? import_node_path15.join(profile, "AppData", "Local") : "";
|
|
2260
2891
|
}
|
|
2261
2892
|
function isOnPath(command, env, platform) {
|
|
2262
2893
|
const pathValue = env.PATH ?? env.Path ?? "";
|
|
2263
2894
|
if (!pathValue.trim())
|
|
2264
2895
|
return false;
|
|
2265
|
-
const sep = platform === "win32" ? ";" :
|
|
2896
|
+
const sep = platform === "win32" ? ";" : import_node_path15.delimiter;
|
|
2266
2897
|
for (const dir of pathValue.split(sep)) {
|
|
2267
2898
|
const trimmed = dir.trim().replace(/^"|"$/g, "");
|
|
2268
2899
|
if (!trimmed)
|
|
2269
2900
|
continue;
|
|
2270
2901
|
try {
|
|
2271
|
-
if (
|
|
2902
|
+
if (import_node_fs14.existsSync(import_node_path15.join(trimmed, command)))
|
|
2272
2903
|
return true;
|
|
2273
2904
|
} catch {}
|
|
2274
2905
|
}
|
|
@@ -2277,24 +2908,24 @@ function isOnPath(command, env, platform) {
|
|
|
2277
2908
|
function resolveDirectCursorCommand(platform, env, home) {
|
|
2278
2909
|
if (platform === "win32") {
|
|
2279
2910
|
const localAppData = cursorLocalAppData(env);
|
|
2280
|
-
return localAppData ?
|
|
2911
|
+
return localAppData ? import_node_path15.join(localAppData, "cursor-agent", "agent.cmd") : "";
|
|
2281
2912
|
}
|
|
2282
|
-
return home ?
|
|
2913
|
+
return home ? import_node_path15.join(home, ".local", "bin", "agent") : "";
|
|
2283
2914
|
}
|
|
2284
2915
|
function resolveCursorCommand(overrides) {
|
|
2285
2916
|
const args = ["acp"];
|
|
2286
2917
|
const platform = overrides?.platform ?? process.platform;
|
|
2287
2918
|
const env = overrides?.env ?? process.env;
|
|
2288
|
-
const home = overrides?.home ??
|
|
2919
|
+
const home = overrides?.home ?? import_node_os11.homedir();
|
|
2289
2920
|
if (platform === "win32") {
|
|
2290
2921
|
const directCmd = resolveDirectCursorCommand(platform, env, home);
|
|
2291
|
-
if (directCmd &&
|
|
2922
|
+
if (directCmd && import_node_fs14.existsSync(directCmd)) {
|
|
2292
2923
|
return { command: directCmd, args };
|
|
2293
2924
|
}
|
|
2294
2925
|
return { command: "agent.cmd", args };
|
|
2295
2926
|
}
|
|
2296
2927
|
const directBin = resolveDirectCursorCommand(platform, env, home);
|
|
2297
|
-
if (directBin &&
|
|
2928
|
+
if (directBin && import_node_fs14.existsSync(directBin)) {
|
|
2298
2929
|
return { command: directBin, args };
|
|
2299
2930
|
}
|
|
2300
2931
|
return { command: "agent", args };
|
|
@@ -2303,11 +2934,11 @@ function resolveCursorSpawnCommand(overrides) {
|
|
|
2303
2934
|
const args = ["acp"];
|
|
2304
2935
|
const platform = overrides?.platform ?? process.platform;
|
|
2305
2936
|
const env = overrides?.env ?? process.env;
|
|
2306
|
-
const home = overrides?.home ??
|
|
2937
|
+
const home = overrides?.home ?? import_node_os11.homedir();
|
|
2307
2938
|
const binary = platform === "win32" ? "agent.cmd" : "agent";
|
|
2308
2939
|
const direct = resolveDirectCursorCommand(platform, env, home);
|
|
2309
2940
|
try {
|
|
2310
|
-
if (direct &&
|
|
2941
|
+
if (direct && import_node_fs14.existsSync(direct))
|
|
2311
2942
|
return { command: direct, args };
|
|
2312
2943
|
} catch {}
|
|
2313
2944
|
if (isOnPath(binary, env, platform))
|
|
@@ -2329,12 +2960,12 @@ function cursorRoamingAppData(env, home) {
|
|
|
2329
2960
|
if (roaming)
|
|
2330
2961
|
return roaming;
|
|
2331
2962
|
const profile = pickEnv2(env, "USERPROFILE") || home;
|
|
2332
|
-
return profile ?
|
|
2963
|
+
return profile ? import_node_path15.join(profile, "AppData", "Roaming") : "";
|
|
2333
2964
|
}
|
|
2334
2965
|
function resolveCursorAuthCandidates(overrides) {
|
|
2335
2966
|
const platform = overrides?.platform ?? process.platform;
|
|
2336
2967
|
const env = overrides?.env ?? process.env;
|
|
2337
|
-
const home = overrides?.home ??
|
|
2968
|
+
const home = overrides?.home ?? import_node_os11.homedir();
|
|
2338
2969
|
const seen = new Set;
|
|
2339
2970
|
const out = [];
|
|
2340
2971
|
const push = (p) => {
|
|
@@ -2345,16 +2976,16 @@ function resolveCursorAuthCandidates(overrides) {
|
|
|
2345
2976
|
};
|
|
2346
2977
|
const xdg = pickEnv2(env, "XDG_CONFIG_HOME");
|
|
2347
2978
|
if (xdg)
|
|
2348
|
-
push(
|
|
2979
|
+
push(import_node_path15.join(xdg, "cursor", "auth.json"));
|
|
2349
2980
|
if (platform === "win32") {
|
|
2350
2981
|
const profile = pickEnv2(env, "USERPROFILE") || home;
|
|
2351
2982
|
if (profile)
|
|
2352
|
-
push(
|
|
2983
|
+
push(import_node_path15.join(profile, ".config", "cursor", "auth.json"));
|
|
2353
2984
|
const roaming = cursorRoamingAppData(env, home);
|
|
2354
2985
|
if (roaming)
|
|
2355
|
-
push(
|
|
2986
|
+
push(import_node_path15.join(roaming, "Cursor", "User", "globalStorage", "storage.json"));
|
|
2356
2987
|
} else if (home) {
|
|
2357
|
-
push(
|
|
2988
|
+
push(import_node_path15.join(home, ".config", "cursor", "auth.json"));
|
|
2358
2989
|
}
|
|
2359
2990
|
return out;
|
|
2360
2991
|
}
|
|
@@ -2365,9 +2996,9 @@ function isValidCursorAuthFile(authFile) {
|
|
|
2365
2996
|
try {
|
|
2366
2997
|
if (!authFile || isStorageHintPath(authFile))
|
|
2367
2998
|
return false;
|
|
2368
|
-
if (!
|
|
2999
|
+
if (!import_node_fs14.existsSync(authFile))
|
|
2369
3000
|
return false;
|
|
2370
|
-
const raw =
|
|
3001
|
+
const raw = import_node_fs14.readFileSync(authFile, "utf8").trim();
|
|
2371
3002
|
if (!raw)
|
|
2372
3003
|
return false;
|
|
2373
3004
|
const parsed = JSON.parse(raw);
|
|
@@ -2385,9 +3016,9 @@ function isHintCursorStorageFile(authFile) {
|
|
|
2385
3016
|
try {
|
|
2386
3017
|
if (!authFile || !isStorageHintPath(authFile))
|
|
2387
3018
|
return false;
|
|
2388
|
-
if (!
|
|
3019
|
+
if (!import_node_fs14.existsSync(authFile))
|
|
2389
3020
|
return false;
|
|
2390
|
-
const raw =
|
|
3021
|
+
const raw = import_node_fs14.readFileSync(authFile, "utf8").trim();
|
|
2391
3022
|
if (!raw)
|
|
2392
3023
|
return false;
|
|
2393
3024
|
const parsed = JSON.parse(raw);
|
|
@@ -2403,7 +3034,7 @@ function isValidCursorCandidate(authFile) {
|
|
|
2403
3034
|
}
|
|
2404
3035
|
function probeCursorAuth(overrides) {
|
|
2405
3036
|
const env = overrides?.env ?? process.env;
|
|
2406
|
-
const home = overrides?.home ??
|
|
3037
|
+
const home = overrides?.home ?? import_node_os11.homedir();
|
|
2407
3038
|
const hasApiKeyEnv = Boolean(env.CURSOR_API_KEY?.trim() || env.CURSOR_AUTH_TOKEN?.trim());
|
|
2408
3039
|
const candidates = resolveCursorAuthCandidates(overrides);
|
|
2409
3040
|
let firstExisting = null;
|
|
@@ -2411,7 +3042,7 @@ function probeCursorAuth(overrides) {
|
|
|
2411
3042
|
for (const candidate of candidates) {
|
|
2412
3043
|
let exists = false;
|
|
2413
3044
|
try {
|
|
2414
|
-
exists =
|
|
3045
|
+
exists = import_node_fs14.existsSync(candidate);
|
|
2415
3046
|
} catch {
|
|
2416
3047
|
exists = false;
|
|
2417
3048
|
}
|
|
@@ -2423,12 +3054,12 @@ function probeCursorAuth(overrides) {
|
|
|
2423
3054
|
if (isValidCursorCandidate(candidate))
|
|
2424
3055
|
validFile = candidate;
|
|
2425
3056
|
}
|
|
2426
|
-
const fallback = home ?
|
|
3057
|
+
const fallback = home ? import_node_path15.join(home, ".config", "cursor", "auth.json") : "";
|
|
2427
3058
|
const authFile = validFile ?? firstExisting ?? candidates[0] ?? fallback;
|
|
2428
|
-
const authDir = authFile ?
|
|
3059
|
+
const authDir = authFile ? import_node_path15.dirname(authFile) : "";
|
|
2429
3060
|
let hasCodexHome = false;
|
|
2430
3061
|
try {
|
|
2431
|
-
hasCodexHome = authDir ?
|
|
3062
|
+
hasCodexHome = authDir ? import_node_fs14.existsSync(authDir) : false;
|
|
2432
3063
|
} catch {
|
|
2433
3064
|
hasCodexHome = false;
|
|
2434
3065
|
}
|
|
@@ -2508,22 +3139,319 @@ function getCursorCatalogIds(execFile, overrides) {
|
|
|
2508
3139
|
cachedCursorCatalogIds = null;
|
|
2509
3140
|
return null;
|
|
2510
3141
|
}
|
|
2511
|
-
cachedCursorCatalogIds = ids;
|
|
2512
|
-
return ids;
|
|
2513
|
-
} catch {
|
|
2514
|
-
cachedCursorCatalogIds = null;
|
|
2515
|
-
return null;
|
|
3142
|
+
cachedCursorCatalogIds = ids;
|
|
3143
|
+
return ids;
|
|
3144
|
+
} catch {
|
|
3145
|
+
cachedCursorCatalogIds = null;
|
|
3146
|
+
return null;
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
3149
|
+
|
|
3150
|
+
// src/runtimes/deepseek/index.ts
|
|
3151
|
+
var import_node_fs16 = require("node:fs");
|
|
3152
|
+
var import_node_os13 = require("node:os");
|
|
3153
|
+
var import_node_path17 = require("node:path");
|
|
3154
|
+
|
|
3155
|
+
// src/runtimes/deepseek/quota.ts
|
|
3156
|
+
var import_node_fs15 = require("node:fs");
|
|
3157
|
+
var import_node_os12 = require("node:os");
|
|
3158
|
+
var import_node_path16 = require("node:path");
|
|
3159
|
+
var DEFAULT_API_ORIGIN = "https://api.deepseek.com";
|
|
3160
|
+
var DEFAULT_PLATFORM_ORIGIN = "https://platform.deepseek.com";
|
|
3161
|
+
var BALANCE_PATH = "/user/balance";
|
|
3162
|
+
var SUMMARY_PATH = "/api/v0/users/get_user_summary";
|
|
3163
|
+
var PROFILE_PATH = "/auth-api/v0/users/current";
|
|
3164
|
+
var CACHE_TTL_MS = 30000;
|
|
3165
|
+
var TIMEOUT_MS = 1800;
|
|
3166
|
+
var cached = null;
|
|
3167
|
+
function isRecord(value) {
|
|
3168
|
+
return typeof value === "object" && value !== null;
|
|
3169
|
+
}
|
|
3170
|
+
function decimal(value) {
|
|
3171
|
+
if (typeof value === "number")
|
|
3172
|
+
return Number.isFinite(value) ? value : undefined;
|
|
3173
|
+
if (typeof value !== "string")
|
|
3174
|
+
return;
|
|
3175
|
+
const trimmed = value.trim();
|
|
3176
|
+
if (!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(trimmed))
|
|
3177
|
+
return;
|
|
3178
|
+
const parsed = Number(trimmed);
|
|
3179
|
+
return Number.isFinite(parsed) ? parsed : trimmed;
|
|
3180
|
+
}
|
|
3181
|
+
function fingerprint(value) {
|
|
3182
|
+
let hash = 2166136261;
|
|
3183
|
+
for (let i = 0;i < value.length; i += 1) {
|
|
3184
|
+
hash ^= value.charCodeAt(i);
|
|
3185
|
+
hash = Math.imul(hash, 16777619);
|
|
3186
|
+
}
|
|
3187
|
+
return (hash >>> 0).toString(16);
|
|
3188
|
+
}
|
|
3189
|
+
function upperCurrency(value) {
|
|
3190
|
+
return typeof value === "string" && value.trim() ? value.trim().toUpperCase() : undefined;
|
|
3191
|
+
}
|
|
3192
|
+
function unauthorizedQuota(message, now) {
|
|
3193
|
+
return {
|
|
3194
|
+
runtimeId: "deepseek",
|
|
3195
|
+
provider: "DeepSeek",
|
|
3196
|
+
status: "unauthorized",
|
|
3197
|
+
message,
|
|
3198
|
+
updatedAt: now
|
|
3199
|
+
};
|
|
3200
|
+
}
|
|
3201
|
+
function parseDeepseekBalance(payload, runtimeId = "deepseek") {
|
|
3202
|
+
if (!isRecord(payload))
|
|
3203
|
+
return null;
|
|
3204
|
+
const infos = Array.isArray(payload.balance_infos) ? payload.balance_infos.filter(isRecord) : [];
|
|
3205
|
+
if (infos.length === 0)
|
|
3206
|
+
return null;
|
|
3207
|
+
const pick = infos.find((info) => upperCurrency(info.currency) === "CNY") ?? infos[0];
|
|
3208
|
+
const balance = decimal(pick.total_balance);
|
|
3209
|
+
if (balance === undefined)
|
|
3210
|
+
return null;
|
|
3211
|
+
const currency = upperCurrency(pick.currency);
|
|
3212
|
+
const available = payload.is_available !== false && payload.is_available !== "false";
|
|
3213
|
+
return {
|
|
3214
|
+
runtimeId,
|
|
3215
|
+
provider: "DeepSeek",
|
|
3216
|
+
account: { plan: "按量计费 (Pay-as-you-go)", type: "apiKey" },
|
|
3217
|
+
credits: { balance, ...currency ? { currency } : {} },
|
|
3218
|
+
status: available ? "ok" : "exhausted",
|
|
3219
|
+
...available ? {} : { message: "DeepSeek 余额不可用 (is_available=false)" },
|
|
3220
|
+
updatedAt: Date.now()
|
|
3221
|
+
};
|
|
3222
|
+
}
|
|
3223
|
+
function businessData(payload) {
|
|
3224
|
+
if (!isRecord(payload))
|
|
3225
|
+
return;
|
|
3226
|
+
if (payload.code !== 0)
|
|
3227
|
+
return;
|
|
3228
|
+
const data = payload.data;
|
|
3229
|
+
if (!isRecord(data) || data.biz_code !== 0)
|
|
3230
|
+
return;
|
|
3231
|
+
return data.biz_data;
|
|
3232
|
+
}
|
|
3233
|
+
function parsePlatformWallet(value) {
|
|
3234
|
+
if (!isRecord(value))
|
|
3235
|
+
return;
|
|
3236
|
+
const wallets = Array.isArray(value.normal_wallets) ? value.normal_wallets.filter(isRecord) : [];
|
|
3237
|
+
const pick = wallets.find((wallet) => upperCurrency(wallet.currency) === "CNY") ?? wallets[0];
|
|
3238
|
+
if (!pick)
|
|
3239
|
+
return;
|
|
3240
|
+
const balance = decimal(pick.balance);
|
|
3241
|
+
if (balance === undefined)
|
|
3242
|
+
return;
|
|
3243
|
+
const currency = upperCurrency(pick.currency);
|
|
3244
|
+
return { balance, ...currency ? { currency } : {} };
|
|
3245
|
+
}
|
|
3246
|
+
function parsePlatformAccount(value) {
|
|
3247
|
+
if (!isRecord(value))
|
|
3248
|
+
return;
|
|
3249
|
+
const email = typeof value.email === "string" && value.email.trim() ? value.email.trim() : undefined;
|
|
3250
|
+
const identity = isRecord(value.id_profile) ? value.id_profile : undefined;
|
|
3251
|
+
const name = identity && typeof identity.name === "string" && identity.name.trim() ? identity.name.trim() : undefined;
|
|
3252
|
+
if (!email && !name)
|
|
3253
|
+
return;
|
|
3254
|
+
return { email, name, plan: "DeepSeek Account", type: "account" };
|
|
3255
|
+
}
|
|
3256
|
+
function parseDshCredentialGrants(text) {
|
|
3257
|
+
const grants = [];
|
|
3258
|
+
let inRecords = false;
|
|
3259
|
+
let current = null;
|
|
3260
|
+
const scalar = (raw) => raw.trim().replace(/^['"]|['"]$/g, "");
|
|
3261
|
+
for (const rawLine of text.split(/\r?\n/)) {
|
|
3262
|
+
if (/^records:\s*$/.test(rawLine)) {
|
|
3263
|
+
inRecords = true;
|
|
3264
|
+
continue;
|
|
3265
|
+
}
|
|
3266
|
+
if (!inRecords)
|
|
3267
|
+
continue;
|
|
3268
|
+
if (/^\S/.test(rawLine)) {
|
|
3269
|
+
inRecords = false;
|
|
3270
|
+
if (current?.token)
|
|
3271
|
+
grants.push(current);
|
|
3272
|
+
current = null;
|
|
3273
|
+
continue;
|
|
3274
|
+
}
|
|
3275
|
+
const recordStart = /^ {2}([^\s:][^:]*):\s*$/.exec(rawLine);
|
|
3276
|
+
if (recordStart) {
|
|
3277
|
+
if (current?.token)
|
|
3278
|
+
grants.push(current);
|
|
3279
|
+
current = { token: "" };
|
|
3280
|
+
continue;
|
|
3281
|
+
}
|
|
3282
|
+
if (!current)
|
|
3283
|
+
continue;
|
|
3284
|
+
const token = /^ {6}token:\s*(.+)$/.exec(rawLine);
|
|
3285
|
+
if (token) {
|
|
3286
|
+
current.token = scalar(token[1]);
|
|
3287
|
+
continue;
|
|
3288
|
+
}
|
|
3289
|
+
const issuer = /^ {6}issuer:\s*(.+)$/.exec(rawLine);
|
|
3290
|
+
if (issuer) {
|
|
3291
|
+
current.issuer = scalar(issuer[1]);
|
|
3292
|
+
}
|
|
3293
|
+
}
|
|
3294
|
+
if (current?.token)
|
|
3295
|
+
grants.push(current);
|
|
3296
|
+
return grants.filter((grant) => grant.token.length > 0);
|
|
3297
|
+
}
|
|
3298
|
+
function grantsFile(env, override) {
|
|
3299
|
+
if (override)
|
|
3300
|
+
return override;
|
|
3301
|
+
const home = env.DSH_HOME?.trim() || import_node_path16.join(import_node_os12.homedir(), ".dsh");
|
|
3302
|
+
return import_node_path16.join(home, ".credentials.yaml");
|
|
3303
|
+
}
|
|
3304
|
+
function pickPlatformGrant(grants, platformOrigin) {
|
|
3305
|
+
return grants.find((grant) => grant.issuer?.startsWith(platformOrigin));
|
|
3306
|
+
}
|
|
3307
|
+
function resolveOrigin(raw, fallback, allowLoopbackHttp) {
|
|
3308
|
+
try {
|
|
3309
|
+
const url = new URL(raw?.trim() || fallback);
|
|
3310
|
+
const loopback = ["127.0.0.1", "localhost", "::1", "[::1]"].includes(url.hostname);
|
|
3311
|
+
if (url.protocol !== "https:" && !(allowLoopbackHttp && url.protocol === "http:" && loopback)) {
|
|
3312
|
+
return null;
|
|
3313
|
+
}
|
|
3314
|
+
return url.origin;
|
|
3315
|
+
} catch {
|
|
3316
|
+
return null;
|
|
3317
|
+
}
|
|
3318
|
+
}
|
|
3319
|
+
async function platformGet(origin, path, token, doFetch, signal) {
|
|
3320
|
+
try {
|
|
3321
|
+
const res = await doFetch(`${origin}${path}`, {
|
|
3322
|
+
method: "GET",
|
|
3323
|
+
headers: { "x-dsh-auth-token": token, Accept: "application/json" },
|
|
3324
|
+
signal
|
|
3325
|
+
});
|
|
3326
|
+
if (res.status === 401 || res.status === 403)
|
|
3327
|
+
return { status: res.status, payload: null };
|
|
3328
|
+
if (!res.ok)
|
|
3329
|
+
return null;
|
|
3330
|
+
const payload = await res.json().catch(() => null);
|
|
3331
|
+
if (isRecord(payload) && payload.code === 40003)
|
|
3332
|
+
return { status: 401, payload: null };
|
|
3333
|
+
return { status: res.status, payload };
|
|
3334
|
+
} catch {
|
|
3335
|
+
return null;
|
|
3336
|
+
}
|
|
3337
|
+
}
|
|
3338
|
+
async function probePlatformAccount(grant, platformOrigin, doFetch, now) {
|
|
3339
|
+
const controller = new AbortController;
|
|
3340
|
+
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
3341
|
+
try {
|
|
3342
|
+
const [summary, profile] = await Promise.all([
|
|
3343
|
+
platformGet(platformOrigin, SUMMARY_PATH, grant.token, doFetch, controller.signal),
|
|
3344
|
+
platformGet(platformOrigin, PROFILE_PATH, grant.token, doFetch, controller.signal)
|
|
3345
|
+
]);
|
|
3346
|
+
if (!summary)
|
|
3347
|
+
return null;
|
|
3348
|
+
if (summary.status === 401) {
|
|
3349
|
+
return unauthorizedQuota("DeepSeek 账户登录已过期,请在 DSH 中重新登录", now());
|
|
3350
|
+
}
|
|
3351
|
+
const credits = parsePlatformWallet(businessData(summary.payload));
|
|
3352
|
+
if (!credits)
|
|
3353
|
+
return null;
|
|
3354
|
+
const account = profile ? parsePlatformAccount(businessData(profile.payload)) : undefined;
|
|
3355
|
+
return {
|
|
3356
|
+
runtimeId: "deepseek",
|
|
3357
|
+
provider: "DeepSeek",
|
|
3358
|
+
...account ? { account } : { account: { plan: "DeepSeek Account", type: "account" } },
|
|
3359
|
+
credits,
|
|
3360
|
+
status: "ok",
|
|
3361
|
+
updatedAt: now()
|
|
3362
|
+
};
|
|
3363
|
+
} finally {
|
|
3364
|
+
clearTimeout(timer);
|
|
3365
|
+
}
|
|
3366
|
+
}
|
|
3367
|
+
async function probeApiKeyBalance(key, apiOrigin, doFetch, now) {
|
|
3368
|
+
const controller = new AbortController;
|
|
3369
|
+
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
3370
|
+
try {
|
|
3371
|
+
const res = await doFetch(`${apiOrigin}${BALANCE_PATH}`, {
|
|
3372
|
+
method: "GET",
|
|
3373
|
+
headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
|
|
3374
|
+
signal: controller.signal
|
|
3375
|
+
});
|
|
3376
|
+
if (res.status === 401 || res.status === 403) {
|
|
3377
|
+
return unauthorizedQuota("DEEPSEEK_API_KEY 无效或已失效 (401/403)", now());
|
|
3378
|
+
}
|
|
3379
|
+
if (!res.ok)
|
|
3380
|
+
return null;
|
|
3381
|
+
const payload = await res.json().catch(() => null);
|
|
3382
|
+
return parseDeepseekBalance(payload);
|
|
3383
|
+
} catch {
|
|
3384
|
+
return null;
|
|
3385
|
+
} finally {
|
|
3386
|
+
clearTimeout(timer);
|
|
3387
|
+
}
|
|
3388
|
+
}
|
|
3389
|
+
async function probeDeepseekQuota(options = {}) {
|
|
3390
|
+
const env = options.env ?? process.env;
|
|
3391
|
+
const now = options.now ?? Date.now;
|
|
3392
|
+
const doFetch = options.fetchImpl ?? fetch;
|
|
3393
|
+
const platformOrigin = resolveOrigin(options.platformOrigin || env.DSH_PLATFORM_ORIGIN, DEFAULT_PLATFORM_ORIGIN, false);
|
|
3394
|
+
const apiOrigin = resolveOrigin(env.DEEPSEEK_BASE_URL, DEFAULT_API_ORIGIN, true);
|
|
3395
|
+
const key = env.DEEPSEEK_API_KEY?.trim();
|
|
3396
|
+
let grant;
|
|
3397
|
+
if (platformOrigin) {
|
|
3398
|
+
try {
|
|
3399
|
+
const file = grantsFile(env, options.credentialsFile);
|
|
3400
|
+
if (import_node_fs15.existsSync(file)) {
|
|
3401
|
+
grant = pickPlatformGrant(parseDshCredentialGrants(import_node_fs15.readFileSync(file, "utf8")), platformOrigin);
|
|
3402
|
+
}
|
|
3403
|
+
} catch {
|
|
3404
|
+
grant = undefined;
|
|
3405
|
+
}
|
|
3406
|
+
}
|
|
3407
|
+
const cacheKey = grant ? `platform:${fingerprint(grant.token)}` : key ? `api:${fingerprint(key)}` : null;
|
|
3408
|
+
if (cacheKey && cached && cached.key === cacheKey && now() - cached.at < CACHE_TTL_MS) {
|
|
3409
|
+
return cached.quota;
|
|
3410
|
+
}
|
|
3411
|
+
let expired = null;
|
|
3412
|
+
if (grant && platformOrigin) {
|
|
3413
|
+
const quota = await probePlatformAccount(grant, platformOrigin, doFetch, now);
|
|
3414
|
+
if (quota && quota.status !== "unauthorized") {
|
|
3415
|
+
if (cacheKey)
|
|
3416
|
+
cached = { key: cacheKey, at: now(), quota };
|
|
3417
|
+
return quota;
|
|
3418
|
+
}
|
|
3419
|
+
expired = quota;
|
|
3420
|
+
}
|
|
3421
|
+
if (key && apiOrigin) {
|
|
3422
|
+
const quota = await probeApiKeyBalance(key, apiOrigin, doFetch, now);
|
|
3423
|
+
if (quota) {
|
|
3424
|
+
if (cacheKey && quota.status !== "unauthorized")
|
|
3425
|
+
cached = { key: cacheKey, at: now(), quota };
|
|
3426
|
+
return quota;
|
|
3427
|
+
}
|
|
2516
3428
|
}
|
|
3429
|
+
return expired;
|
|
2517
3430
|
}
|
|
2518
3431
|
|
|
2519
3432
|
// src/runtimes/deepseek/index.ts
|
|
2520
3433
|
function buildDeepseekMissingKeyMessage() {
|
|
2521
|
-
return "未检测到 DEEPSEEK_API_KEY
|
|
3434
|
+
return "未检测到 DEEPSEEK_API_KEY,也未找到 DSH 本地登录(~/.dsh/.credentials.yaml):请先在终端导出该变量,或先完成 DeepSeek Harness 自身登录后再连接";
|
|
3435
|
+
}
|
|
3436
|
+
function resolveDeepseekHarnessHome(env) {
|
|
3437
|
+
const source = env ?? process.env;
|
|
3438
|
+
const configured = source.DSH_HOME?.trim();
|
|
3439
|
+
return configured || import_node_path17.join(import_node_os13.homedir(), ".dsh");
|
|
3440
|
+
}
|
|
3441
|
+
function hasDeepseekHarnessCredentials(env) {
|
|
3442
|
+
const file = import_node_path17.join(resolveDeepseekHarnessHome(env), ".credentials.yaml");
|
|
3443
|
+
try {
|
|
3444
|
+
return import_node_fs16.existsSync(file) && import_node_fs16.statSync(file).size > 0;
|
|
3445
|
+
} catch {
|
|
3446
|
+
return false;
|
|
3447
|
+
}
|
|
2522
3448
|
}
|
|
2523
3449
|
function resolveDeepseekSpawnBlocker(env) {
|
|
2524
3450
|
const source = env ?? process.env;
|
|
2525
3451
|
if (source.DEEPSEEK_API_KEY?.trim())
|
|
2526
3452
|
return null;
|
|
3453
|
+
if (hasDeepseekHarnessCredentials(source))
|
|
3454
|
+
return null;
|
|
2527
3455
|
return buildDeepseekMissingKeyMessage();
|
|
2528
3456
|
}
|
|
2529
3457
|
function resolveDeepseekPackage(env) {
|
|
@@ -2546,18 +3474,21 @@ function resolveDeepseekSpawnCommand(env) {
|
|
|
2546
3474
|
}
|
|
2547
3475
|
function probeDeepseekAuth() {
|
|
2548
3476
|
const hasApiKeyEnv = Boolean(process.env.DEEPSEEK_API_KEY?.trim());
|
|
3477
|
+
const harnessHome = resolveDeepseekHarnessHome();
|
|
3478
|
+
const hasAuthFile = hasDeepseekHarnessCredentials();
|
|
2549
3479
|
return {
|
|
2550
|
-
codexHome:
|
|
2551
|
-
hasCodexHome:
|
|
2552
|
-
hasAuthFile
|
|
3480
|
+
codexHome: harnessHome,
|
|
3481
|
+
hasCodexHome: import_node_fs16.existsSync(harnessHome),
|
|
3482
|
+
hasAuthFile,
|
|
2553
3483
|
hasApiKeyEnv,
|
|
2554
|
-
looksLoggedIn: hasApiKeyEnv
|
|
3484
|
+
looksLoggedIn: hasApiKeyEnv || hasAuthFile
|
|
2555
3485
|
};
|
|
2556
3486
|
}
|
|
2557
3487
|
var deepseekAdapter = {
|
|
2558
3488
|
id: "deepseek",
|
|
2559
3489
|
prepareAppResources: async ({ directory }) => prepareCompatibilityResources(directory, "native-config-entry-not-verified"),
|
|
2560
3490
|
probeAuth: () => probeDeepseekAuth(),
|
|
3491
|
+
probeQuota: () => probeDeepseekQuota(),
|
|
2561
3492
|
resolveSpawnCommand: () => resolveDeepseekSpawnCommand(),
|
|
2562
3493
|
resolveSpawnBlocker: () => resolveDeepseekSpawnBlocker(),
|
|
2563
3494
|
orderAuthMethods: (methods) => methods,
|
|
@@ -2565,13 +3496,13 @@ var deepseekAdapter = {
|
|
|
2565
3496
|
};
|
|
2566
3497
|
|
|
2567
3498
|
// src/runtimes/agy/quota.ts
|
|
2568
|
-
var
|
|
2569
|
-
var
|
|
3499
|
+
var import_node_fs17 = require("node:fs");
|
|
3500
|
+
var import_node_path18 = require("node:path");
|
|
2570
3501
|
var import_node_child_process6 = require("node:child_process");
|
|
2571
3502
|
var os2 = __toESM(require("node:os"), 1);
|
|
2572
3503
|
function resolveGeminiHome2() {
|
|
2573
3504
|
const home = process.env.USERPROFILE || process.env.HOME || "";
|
|
2574
|
-
return
|
|
3505
|
+
return import_node_path18.join(home, ".gemini");
|
|
2575
3506
|
}
|
|
2576
3507
|
function resolveAntigravityAccount() {
|
|
2577
3508
|
if (process.env.GOOGLE_ACCOUNT?.trim()) {
|
|
@@ -2584,14 +3515,14 @@ function resolveAntigravityAccount() {
|
|
|
2584
3515
|
}
|
|
2585
3516
|
const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
|
|
2586
3517
|
const candidates = [
|
|
2587
|
-
process.env.APPDATA ?
|
|
2588
|
-
|
|
2589
|
-
|
|
3518
|
+
process.env.APPDATA ? import_node_path18.join(process.env.APPDATA, "Antigravity", "app_storage.json") : null,
|
|
3519
|
+
import_node_path18.join(home, ".config", "Antigravity", "app_storage.json"),
|
|
3520
|
+
import_node_path18.join(home, "Library", "Application Support", "Antigravity", "app_storage.json")
|
|
2590
3521
|
].filter(Boolean);
|
|
2591
3522
|
for (const file of candidates) {
|
|
2592
3523
|
try {
|
|
2593
|
-
if (
|
|
2594
|
-
const raw =
|
|
3524
|
+
if (import_node_fs17.existsSync(file)) {
|
|
3525
|
+
const raw = import_node_fs17.readFileSync(file, "utf8");
|
|
2595
3526
|
const json = JSON.parse(raw);
|
|
2596
3527
|
const username = json["jetski.onboarding.lastLoginUsername"];
|
|
2597
3528
|
if (username && typeof username === "string" && username.trim()) {
|
|
@@ -2612,30 +3543,30 @@ function resolveAntigravityAccount() {
|
|
|
2612
3543
|
}
|
|
2613
3544
|
function resolveAntigravityLanguageServer() {
|
|
2614
3545
|
const home = process.env.USERPROFILE || process.env.HOME || os2.homedir() || "";
|
|
2615
|
-
const appData = process.env.APPDATA || (process.platform === "win32" ?
|
|
3546
|
+
const appData = process.env.APPDATA || (process.platform === "win32" ? import_node_path18.join(home, "AppData", "Roaming") : "");
|
|
2616
3547
|
const baseDirs = [
|
|
2617
|
-
appData ?
|
|
2618
|
-
appData ?
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
3548
|
+
appData ? import_node_path18.join(appData, "Antigravity IDE", "logs") : null,
|
|
3549
|
+
appData ? import_node_path18.join(appData, "Antigravity", "logs") : null,
|
|
3550
|
+
import_node_path18.join(home, ".config", "Antigravity IDE", "logs"),
|
|
3551
|
+
import_node_path18.join(home, ".config", "Antigravity", "logs"),
|
|
3552
|
+
import_node_path18.join(home, "Library", "Application Support", "Antigravity IDE", "logs"),
|
|
3553
|
+
import_node_path18.join(home, "Library", "Application Support", "Antigravity", "logs")
|
|
2623
3554
|
].filter(Boolean);
|
|
2624
3555
|
for (const base of baseDirs) {
|
|
2625
3556
|
try {
|
|
2626
|
-
if (!
|
|
3557
|
+
if (!import_node_fs17.existsSync(base))
|
|
2627
3558
|
continue;
|
|
2628
|
-
const sessionDirs =
|
|
3559
|
+
const sessionDirs = import_node_fs17.readdirSync(base).map((d) => {
|
|
2629
3560
|
try {
|
|
2630
|
-
return { name: d, time:
|
|
3561
|
+
return { name: d, time: import_node_fs17.statSync(import_node_path18.join(base, d)).mtimeMs };
|
|
2631
3562
|
} catch {
|
|
2632
3563
|
return null;
|
|
2633
3564
|
}
|
|
2634
3565
|
}).filter((d) => Boolean(d)).sort((a, b) => b.time - a.time);
|
|
2635
3566
|
for (const s of sessionDirs) {
|
|
2636
|
-
const logFile =
|
|
2637
|
-
if (
|
|
2638
|
-
const content =
|
|
3567
|
+
const logFile = import_node_path18.join(base, s.name, "ls-main.log");
|
|
3568
|
+
if (import_node_fs17.existsSync(logFile)) {
|
|
3569
|
+
const content = import_node_fs17.readFileSync(logFile, "utf8");
|
|
2639
3570
|
const csrfMatch = content.match(/--csrf_token\s+([a-f0-9\-]+)/);
|
|
2640
3571
|
const portMatch = content.match(/LS started on port\s+(\d+)/) || content.match(/--https_server_port\s+(\d+)/);
|
|
2641
3572
|
if (csrfMatch && portMatch) {
|
|
@@ -2792,7 +3723,7 @@ async function probeAgyQuota(options) {
|
|
|
2792
3723
|
} catch {}
|
|
2793
3724
|
}
|
|
2794
3725
|
const geminiHome = resolveGeminiHome2();
|
|
2795
|
-
const hasAgyDir =
|
|
3726
|
+
const hasAgyDir = import_node_fs17.existsSync(import_node_path18.join(geminiHome, "antigravity")) || import_node_fs17.existsSync(import_node_path18.join(geminiHome, "antigravity-cli"));
|
|
2796
3727
|
const hasApiKey = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
|
|
2797
3728
|
const isAvailable = hasAgyDir || hasApiKey || Boolean(acc.email || acc.name);
|
|
2798
3729
|
if (!isAvailable) {
|
|
@@ -3096,598 +4027,255 @@ function getLiveAcpProcess(runtimeId, query = {}) {
|
|
|
3096
4027
|
function tryReuseLiveAcpProcess(runtimeId, query = {}) {
|
|
3097
4028
|
const hit = getLiveAcpProcess(runtimeId, query);
|
|
3098
4029
|
if (hit)
|
|
3099
|
-
return { status: "hit", handle: hit };
|
|
3100
|
-
if (query.expectedTag === undefined)
|
|
3101
|
-
return { status: "miss" };
|
|
3102
|
-
const stale = getLiveAcpProcess(runtimeId, { scopeKey: query.scopeKey, executionContext: query.executionContext });
|
|
3103
|
-
if (!stale)
|
|
3104
|
-
return { status: "miss" };
|
|
3105
|
-
if (query.isBusy?.(stale))
|
|
3106
|
-
return { status: "busy", handle: stale };
|
|
3107
|
-
stale.kill();
|
|
3108
|
-
return { status: "miss" };
|
|
3109
|
-
}
|
|
3110
|
-
|
|
3111
|
-
// src/client/client-handlers.ts
|
|
3112
|
-
var import_sdk2 = require("@agentclientprotocol/sdk");
|
|
3113
|
-
|
|
3114
|
-
// src/client/acp-fs.ts
|
|
3115
|
-
var import_promises4 = require("node:fs/promises");
|
|
3116
|
-
var import_node_path16 = require("node:path");
|
|
3117
|
-
var import_promises5 = require("node:fs/promises");
|
|
3118
|
-
var MAX_READ_BYTES = 2 * 1024 * 1024;
|
|
3119
|
-
var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
|
|
3120
|
-
function isBinaryDocumentPath(filePath) {
|
|
3121
|
-
return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path16.extname(filePath).toLowerCase());
|
|
3122
|
-
}
|
|
3123
|
-
function assertPathInsideWorkspace(filePath, workspaceRoot) {
|
|
3124
|
-
const root = import_node_path16.resolve(workspaceRoot);
|
|
3125
|
-
const target = import_node_path16.resolve(filePath);
|
|
3126
|
-
const rootWithSep = root.endsWith(import_node_path16.sep) ? root : root + import_node_path16.sep;
|
|
3127
|
-
if (target !== root && !target.startsWith(rootWithSep)) {
|
|
3128
|
-
throw new Error(`路径不在工作区内: ${filePath}`);
|
|
3129
|
-
}
|
|
3130
|
-
return target;
|
|
3131
|
-
}
|
|
3132
|
-
async function acpReadTextFile(params) {
|
|
3133
|
-
if (isBinaryDocumentPath(params.path)) {
|
|
3134
|
-
throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
|
|
3135
|
-
}
|
|
3136
|
-
const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
|
|
3137
|
-
await import_promises4.access(abs);
|
|
3138
|
-
let content = await import_promises4.readFile(abs, "utf-8");
|
|
3139
|
-
if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
|
|
3140
|
-
content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
|
|
3141
|
-
content += `
|
|
3142
|
-
|
|
3143
|
-
…[截断:文件过大]…`;
|
|
3144
|
-
}
|
|
3145
|
-
if (typeof params.line === "number" && params.line > 0) {
|
|
3146
|
-
const lines = content.split(`
|
|
3147
|
-
`);
|
|
3148
|
-
const start = params.line - 1;
|
|
3149
|
-
const limit = typeof params.limit === "number" && params.limit > 0 ? params.limit : lines.length;
|
|
3150
|
-
content = lines.slice(start, start + limit).join(`
|
|
3151
|
-
`);
|
|
3152
|
-
}
|
|
3153
|
-
return { content };
|
|
3154
|
-
}
|
|
3155
|
-
async function acpWriteTextFile(params) {
|
|
3156
|
-
const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
|
|
3157
|
-
await import_promises5.mkdir(import_node_path16.dirname(abs), { recursive: true });
|
|
3158
|
-
await import_promises4.writeFile(abs, params.content, "utf-8");
|
|
3159
|
-
return {};
|
|
3160
|
-
}
|
|
3161
|
-
|
|
3162
|
-
// src/client/client-handlers.ts
|
|
3163
|
-
function toInvalidParams(message) {
|
|
3164
|
-
return import_sdk2.RequestError.invalidParams(undefined, message);
|
|
3165
|
-
}
|
|
3166
|
-
function toServerError(error, fallback) {
|
|
3167
|
-
return new import_sdk2.RequestError(-32000, error instanceof Error ? error.message : fallback);
|
|
3168
|
-
}
|
|
3169
|
-
function registerAcpClientHandlers(app, deps) {
|
|
3170
|
-
app.onRequest(import_sdk2.methods.client.session.requestPermission, async (ctx) => {
|
|
3171
|
-
const params = ctx.params;
|
|
3172
|
-
const toolCall = params.toolCall;
|
|
3173
|
-
const toolHint = toolCall && typeof toolCall === "object" ? {
|
|
3174
|
-
id: typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : undefined,
|
|
3175
|
-
title: typeof toolCall.title === "string" ? toolCall.title : undefined,
|
|
3176
|
-
kind: typeof toolCall.kind === "string" ? toolCall.kind : undefined
|
|
3177
|
-
} : undefined;
|
|
3178
|
-
console.info("[acp] ← Agent request", {
|
|
3179
|
-
requestId: ctx.requestId,
|
|
3180
|
-
method: "session/request_permission",
|
|
3181
|
-
toolCall: toolHint,
|
|
3182
|
-
optionCount: Array.isArray(params.options) ? params.options.length : undefined
|
|
3183
|
-
});
|
|
3184
|
-
try {
|
|
3185
|
-
const outcome = await deps.onPermission({
|
|
3186
|
-
sessionId: typeof params.sessionId === "string" ? params.sessionId : undefined,
|
|
3187
|
-
params
|
|
3188
|
-
});
|
|
3189
|
-
return { outcome };
|
|
3190
|
-
} catch (error) {
|
|
3191
|
-
console.error("[acp] request_permission 失败", error);
|
|
3192
|
-
return { outcome: { outcome: "cancelled" } };
|
|
3193
|
-
}
|
|
3194
|
-
});
|
|
3195
|
-
app.onRequest(import_sdk2.methods.client.fs.readTextFile, async (ctx) => {
|
|
3196
|
-
const workspaceRoot = deps.getWorkspaceRoot();
|
|
3197
|
-
const filePath = ctx.params.path;
|
|
3198
|
-
if (!workspaceRoot || !filePath) {
|
|
3199
|
-
throw toInvalidParams("fs/read_text_file 需要 path 与已连接工作区");
|
|
3200
|
-
}
|
|
3201
|
-
const virtualResource = parseInkdownVirtualPath(filePath, workspaceRoot);
|
|
3202
|
-
if (virtualResource) {
|
|
3203
|
-
try {
|
|
3204
|
-
const content = await deps.readSnapshot(virtualResource);
|
|
3205
|
-
console.info("[acp] fs/read_text_file 虚拟快照 ok", {
|
|
3206
|
-
resource: virtualResource,
|
|
3207
|
-
chars: content.length
|
|
3208
|
-
});
|
|
3209
|
-
return { content };
|
|
3210
|
-
} catch (error) {
|
|
3211
|
-
throw toServerError(error, "读取 Inkdown 快照失败");
|
|
3212
|
-
}
|
|
3213
|
-
}
|
|
3214
|
-
if (isInkdownVirtualDirPath(filePath, workspaceRoot)) {
|
|
3215
|
-
throw toInvalidParams(`Inkdown 虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
|
|
3216
|
-
}
|
|
3217
|
-
try {
|
|
3218
|
-
const result = await acpReadTextFile({
|
|
3219
|
-
path: filePath,
|
|
3220
|
-
workspaceRoot,
|
|
3221
|
-
line: ctx.params.line ?? undefined,
|
|
3222
|
-
limit: ctx.params.limit ?? undefined
|
|
3223
|
-
});
|
|
3224
|
-
console.info("[acp] fs/read_text_file ok", { path: filePath });
|
|
3225
|
-
return result;
|
|
3226
|
-
} catch (error) {
|
|
3227
|
-
throw toServerError(error, "读取文件失败");
|
|
3228
|
-
}
|
|
3229
|
-
});
|
|
3230
|
-
app.onRequest(import_sdk2.methods.client.fs.writeTextFile, async (ctx) => {
|
|
3231
|
-
const workspaceRoot = deps.getWorkspaceRoot();
|
|
3232
|
-
const filePath = ctx.params.path;
|
|
3233
|
-
const content = ctx.params.content;
|
|
3234
|
-
if (!workspaceRoot || !filePath || typeof content !== "string") {
|
|
3235
|
-
throw toInvalidParams("fs/write_text_file 需要 path、content 与已连接工作区");
|
|
3236
|
-
}
|
|
3237
|
-
try {
|
|
3238
|
-
console.info("[acp] fs/write_text_file(无内嵌审批,依赖 Agent 是否先 request_permission)", {
|
|
3239
|
-
path: filePath,
|
|
3240
|
-
bytes: content.length
|
|
3241
|
-
});
|
|
3242
|
-
return await acpWriteTextFile({ path: filePath, content, workspaceRoot });
|
|
3243
|
-
} catch (error) {
|
|
3244
|
-
throw toServerError(error, "写入文件失败");
|
|
3245
|
-
}
|
|
3246
|
-
});
|
|
3247
|
-
app.onRequest(import_sdk2.methods.client.terminal.create, async (ctx) => {
|
|
3248
|
-
const workspaceRoot = deps.getWorkspaceRoot();
|
|
3249
|
-
const sessionId = ctx.params.sessionId;
|
|
3250
|
-
const command = ctx.params.command;
|
|
3251
|
-
if (!workspaceRoot || !sessionId || !command) {
|
|
3252
|
-
throw toInvalidParams("terminal/create 需要 sessionId、command 与已连接工作区");
|
|
3253
|
-
}
|
|
3254
|
-
try {
|
|
3255
|
-
return deps.terminals.create({
|
|
3256
|
-
sessionId,
|
|
3257
|
-
command,
|
|
3258
|
-
args: ctx.params.args ?? undefined,
|
|
3259
|
-
env: ctx.params.env ?? undefined,
|
|
3260
|
-
cwd: ctx.params.cwd ?? undefined,
|
|
3261
|
-
outputByteLimit: ctx.params.outputByteLimit ?? undefined,
|
|
3262
|
-
workspaceRoot
|
|
3263
|
-
});
|
|
3264
|
-
} catch (error) {
|
|
3265
|
-
throw toServerError(error, "创建终端失败");
|
|
3266
|
-
}
|
|
3267
|
-
});
|
|
3268
|
-
app.onRequest(import_sdk2.methods.client.terminal.output, async (ctx) => {
|
|
3269
|
-
const terminalId = ctx.params.terminalId;
|
|
3270
|
-
if (!terminalId) {
|
|
3271
|
-
throw toInvalidParams("terminal/output 需要 terminalId");
|
|
3272
|
-
}
|
|
3273
|
-
try {
|
|
3274
|
-
return deps.terminals.getOutput(terminalId);
|
|
3275
|
-
} catch (error) {
|
|
3276
|
-
throw toServerError(error, "读取终端输出失败");
|
|
3277
|
-
}
|
|
3278
|
-
});
|
|
3279
|
-
app.onRequest(import_sdk2.methods.client.terminal.waitForExit, async (ctx) => {
|
|
3280
|
-
const terminalId = ctx.params.terminalId;
|
|
3281
|
-
if (!terminalId) {
|
|
3282
|
-
throw toInvalidParams("terminal/wait_for_exit 需要 terminalId");
|
|
3283
|
-
}
|
|
3284
|
-
try {
|
|
3285
|
-
return await deps.terminals.waitForExit(terminalId);
|
|
3286
|
-
} catch (error) {
|
|
3287
|
-
throw toServerError(error, "等待终端退出失败");
|
|
3288
|
-
}
|
|
3289
|
-
});
|
|
3290
|
-
app.onRequest(import_sdk2.methods.client.terminal.kill, async (ctx) => {
|
|
3291
|
-
const terminalId = ctx.params.terminalId;
|
|
3292
|
-
if (!terminalId) {
|
|
3293
|
-
throw toInvalidParams("terminal/kill 需要 terminalId");
|
|
3294
|
-
}
|
|
3295
|
-
try {
|
|
3296
|
-
return deps.terminals.kill(terminalId);
|
|
3297
|
-
} catch (error) {
|
|
3298
|
-
throw toServerError(error, "终止终端失败");
|
|
3299
|
-
}
|
|
3300
|
-
});
|
|
3301
|
-
app.onRequest(import_sdk2.methods.client.terminal.release, async (ctx) => {
|
|
3302
|
-
const terminalId = ctx.params.terminalId;
|
|
3303
|
-
if (!terminalId) {
|
|
3304
|
-
throw toInvalidParams("terminal/release 需要 terminalId");
|
|
3305
|
-
}
|
|
3306
|
-
try {
|
|
3307
|
-
return deps.terminals.release(terminalId);
|
|
3308
|
-
} catch (error) {
|
|
3309
|
-
throw toServerError(error, "释放终端失败");
|
|
3310
|
-
}
|
|
3311
|
-
});
|
|
3312
|
-
app.onNotification(import_sdk2.methods.client.session.update, async (ctx) => {
|
|
3313
|
-
deps.onSessionUpdate({
|
|
3314
|
-
sessionId: ctx.params.sessionId,
|
|
3315
|
-
update: ctx.params.update
|
|
3316
|
-
});
|
|
3317
|
-
});
|
|
3318
|
-
}
|
|
3319
|
-
function permissionOptionId(option) {
|
|
3320
|
-
if (typeof option.optionId === "string")
|
|
3321
|
-
return option.optionId;
|
|
3322
|
-
if (typeof option.id === "string")
|
|
3323
|
-
return option.id;
|
|
3324
|
-
return null;
|
|
3325
|
-
}
|
|
3326
|
-
function pickAllowOptionId(params) {
|
|
3327
|
-
const options = params.options;
|
|
3328
|
-
if (!Array.isArray(options))
|
|
3329
|
-
return null;
|
|
3330
|
-
for (const item of options) {
|
|
3331
|
-
if (!item || typeof item !== "object")
|
|
3332
|
-
continue;
|
|
3333
|
-
const option = item;
|
|
3334
|
-
const id = permissionOptionId(option);
|
|
3335
|
-
const kind = typeof option.kind === "string" ? option.kind : "";
|
|
3336
|
-
if (id && (kind.includes("allow") || kind === "allow_once" || kind === "allow_always")) {
|
|
3337
|
-
return id;
|
|
3338
|
-
}
|
|
3339
|
-
}
|
|
3340
|
-
for (const item of options) {
|
|
3341
|
-
if (!item || typeof item !== "object")
|
|
3342
|
-
continue;
|
|
3343
|
-
const id = permissionOptionId(item);
|
|
3344
|
-
if (id)
|
|
3345
|
-
return id;
|
|
3346
|
-
}
|
|
3347
|
-
return null;
|
|
4030
|
+
return { status: "hit", handle: hit };
|
|
4031
|
+
if (query.expectedTag === undefined)
|
|
4032
|
+
return { status: "miss" };
|
|
4033
|
+
const stale = getLiveAcpProcess(runtimeId, { scopeKey: query.scopeKey, executionContext: query.executionContext });
|
|
4034
|
+
if (!stale)
|
|
4035
|
+
return { status: "miss" };
|
|
4036
|
+
if (query.isBusy?.(stale))
|
|
4037
|
+
return { status: "busy", handle: stale };
|
|
4038
|
+
stale.kill();
|
|
4039
|
+
return { status: "miss" };
|
|
3348
4040
|
}
|
|
3349
4041
|
|
|
3350
|
-
// src/client/
|
|
4042
|
+
// src/client/client-handlers.ts
|
|
3351
4043
|
var import_sdk3 = require("@agentclientprotocol/sdk");
|
|
3352
4044
|
|
|
3353
|
-
// src/
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
return null;
|
|
3362
|
-
}
|
|
3363
|
-
function coerceCurrentValue(raw) {
|
|
3364
|
-
if (typeof raw === "string")
|
|
3365
|
-
return raw;
|
|
3366
|
-
if (typeof raw === "boolean")
|
|
3367
|
-
return raw;
|
|
3368
|
-
if (typeof raw === "number" && Number.isFinite(raw))
|
|
3369
|
-
return String(raw);
|
|
3370
|
-
return;
|
|
3371
|
-
}
|
|
3372
|
-
function parseAcpConfigOptions(raw) {
|
|
3373
|
-
if (!Array.isArray(raw))
|
|
3374
|
-
return [];
|
|
3375
|
-
const options = [];
|
|
3376
|
-
for (const item of raw) {
|
|
3377
|
-
if (!item || typeof item !== "object")
|
|
3378
|
-
continue;
|
|
3379
|
-
const row = item;
|
|
3380
|
-
const configId = typeof row.configId === "string" ? row.configId : typeof row.id === "string" ? row.id : null;
|
|
3381
|
-
if (!configId)
|
|
3382
|
-
continue;
|
|
3383
|
-
const name = typeof row.name === "string" ? row.name : configId;
|
|
3384
|
-
const type = typeof row.type === "string" ? row.type : "select";
|
|
3385
|
-
const values = [];
|
|
3386
|
-
if (Array.isArray(row.options)) {
|
|
3387
|
-
for (const opt of row.options) {
|
|
3388
|
-
if (!opt || typeof opt !== "object")
|
|
3389
|
-
continue;
|
|
3390
|
-
const o = opt;
|
|
3391
|
-
const value = coerceOptionValue(o.value) ?? coerceOptionValue(o.id);
|
|
3392
|
-
if (!value)
|
|
3393
|
-
continue;
|
|
3394
|
-
values.push({
|
|
3395
|
-
value,
|
|
3396
|
-
name: typeof o.name === "string" ? o.name : String(value),
|
|
3397
|
-
description: typeof o.description === "string" ? o.description : undefined
|
|
3398
|
-
});
|
|
3399
|
-
}
|
|
3400
|
-
}
|
|
3401
|
-
options.push({
|
|
3402
|
-
configId,
|
|
3403
|
-
name,
|
|
3404
|
-
description: typeof row.description === "string" ? row.description : undefined,
|
|
3405
|
-
category: typeof row.category === "string" ? row.category : undefined,
|
|
3406
|
-
type,
|
|
3407
|
-
currentValue: coerceCurrentValue(row.currentValue),
|
|
3408
|
-
options: values.length > 0 ? values : undefined
|
|
3409
|
-
});
|
|
3410
|
-
}
|
|
3411
|
-
return options;
|
|
3412
|
-
}
|
|
3413
|
-
function findModelConfigOption(options) {
|
|
3414
|
-
return options.find((o) => o.category === "model") ?? options.find((o) => o.configId === "model" || o.configId.includes("model"));
|
|
4045
|
+
// src/client/acp-fs.ts
|
|
4046
|
+
var import_promises5 = require("node:fs/promises");
|
|
4047
|
+
var import_node_path19 = require("node:path");
|
|
4048
|
+
var import_promises6 = require("node:fs/promises");
|
|
4049
|
+
var MAX_READ_BYTES = 2 * 1024 * 1024;
|
|
4050
|
+
var BINARY_DOCUMENT_EXTENSIONS = new Set([".epub", ".mobi", ".azw", ".azw3", ".pdf"]);
|
|
4051
|
+
function isBinaryDocumentPath(filePath) {
|
|
4052
|
+
return BINARY_DOCUMENT_EXTENSIONS.has(import_node_path19.extname(filePath).toLowerCase());
|
|
3415
4053
|
}
|
|
3416
|
-
function
|
|
3417
|
-
|
|
3418
|
-
|
|
3419
|
-
|
|
3420
|
-
|
|
3421
|
-
|
|
4054
|
+
function assertPathInsideWorkspace(filePath, workspaceRoot) {
|
|
4055
|
+
const root = import_node_path19.resolve(workspaceRoot);
|
|
4056
|
+
const target = import_node_path19.resolve(filePath);
|
|
4057
|
+
const rootWithSep = root.endsWith(import_node_path19.sep) ? root : root + import_node_path19.sep;
|
|
4058
|
+
if (target !== root && !target.startsWith(rootWithSep)) {
|
|
4059
|
+
throw new Error(`路径不在工作区内: ${filePath}`);
|
|
3422
4060
|
}
|
|
3423
|
-
|
|
3424
|
-
return null;
|
|
3425
|
-
const row = raw;
|
|
3426
|
-
const valueRaw = row.value ?? row.id;
|
|
3427
|
-
const value = coerceOptionValue(valueRaw);
|
|
3428
|
-
if (!value)
|
|
3429
|
-
return null;
|
|
3430
|
-
const name = typeof row.name === "string" && row.name.trim() ? row.name : value;
|
|
3431
|
-
return { value, name };
|
|
4061
|
+
return target;
|
|
3432
4062
|
}
|
|
3433
|
-
function
|
|
3434
|
-
if (
|
|
3435
|
-
|
|
3436
|
-
const out = [];
|
|
3437
|
-
for (const item of raw) {
|
|
3438
|
-
const coerced = coerceTopLevelModelEntry(item);
|
|
3439
|
-
if (coerced)
|
|
3440
|
-
out.push(coerced);
|
|
4063
|
+
async function acpReadTextFile(params) {
|
|
4064
|
+
if (isBinaryDocumentPath(params.path)) {
|
|
4065
|
+
throw new Error(`Inkdown 拒绝按文本读取电子书/PDF:${params.path}。` + "该格式已由客户端解析,请改为向用户索取所需的章节、目录或视口文本。");
|
|
3441
4066
|
}
|
|
3442
|
-
|
|
3443
|
-
|
|
3444
|
-
|
|
3445
|
-
|
|
3446
|
-
|
|
3447
|
-
|
|
3448
|
-
|
|
3449
|
-
|
|
3450
|
-
const row = models;
|
|
3451
|
-
list = coerceTopLevelModelList(row.availableModels);
|
|
3452
|
-
const currentRaw = row.currentModelId ?? response?.currentModelId;
|
|
3453
|
-
if (typeof currentRaw === "string" && currentRaw.trim())
|
|
3454
|
-
currentValue = currentRaw;
|
|
3455
|
-
} else {
|
|
3456
|
-
return null;
|
|
4067
|
+
const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
|
|
4068
|
+
await import_promises5.access(abs);
|
|
4069
|
+
let content = await import_promises5.readFile(abs, "utf-8");
|
|
4070
|
+
if (Buffer.byteLength(content, "utf-8") > MAX_READ_BYTES) {
|
|
4071
|
+
content = content.slice(0, Math.floor(MAX_READ_BYTES / 2));
|
|
4072
|
+
content += `
|
|
4073
|
+
|
|
4074
|
+
…[截断:文件过大]…`;
|
|
3457
4075
|
}
|
|
3458
|
-
if (
|
|
3459
|
-
|
|
3460
|
-
|
|
3461
|
-
const
|
|
3462
|
-
|
|
3463
|
-
|
|
4076
|
+
if (typeof params.line === "number" && params.line > 0) {
|
|
4077
|
+
const lines = content.split(`
|
|
4078
|
+
`);
|
|
4079
|
+
const start = params.line - 1;
|
|
4080
|
+
const limit = typeof params.limit === "number" && params.limit > 0 ? params.limit : lines.length;
|
|
4081
|
+
content = lines.slice(start, start + limit).join(`
|
|
4082
|
+
`);
|
|
3464
4083
|
}
|
|
3465
|
-
return {
|
|
3466
|
-
configId: "model",
|
|
3467
|
-
name: "Model",
|
|
3468
|
-
category: "model",
|
|
3469
|
-
type: "select",
|
|
3470
|
-
...currentValue ? { currentValue } : {},
|
|
3471
|
-
options: list.map((item) => ({ value: item.value, name: item.name }))
|
|
3472
|
-
};
|
|
4084
|
+
return { content };
|
|
3473
4085
|
}
|
|
3474
|
-
function
|
|
3475
|
-
const
|
|
3476
|
-
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
if (models === undefined)
|
|
3480
|
-
return configOptionsRaw;
|
|
3481
|
-
const synthesized = synthesizeModelOptionFromTopLevelModels(models, response ?? undefined);
|
|
3482
|
-
if (!synthesized)
|
|
3483
|
-
return configOptionsRaw;
|
|
3484
|
-
const base = Array.isArray(configOptionsRaw) ? [...configOptionsRaw] : [];
|
|
3485
|
-
base.push({
|
|
3486
|
-
configId: synthesized.configId,
|
|
3487
|
-
name: synthesized.name,
|
|
3488
|
-
category: synthesized.category,
|
|
3489
|
-
type: synthesized.type,
|
|
3490
|
-
...synthesized.currentValue !== undefined ? { currentValue: synthesized.currentValue } : {},
|
|
3491
|
-
options: synthesized.options?.map((o) => ({ value: o.value, name: o.name }))
|
|
3492
|
-
});
|
|
3493
|
-
return base;
|
|
4086
|
+
async function acpWriteTextFile(params) {
|
|
4087
|
+
const abs = assertPathInsideWorkspace(params.path, params.workspaceRoot);
|
|
4088
|
+
await import_promises6.mkdir(import_node_path19.dirname(abs), { recursive: true });
|
|
4089
|
+
await import_promises5.writeFile(abs, params.content, "utf-8");
|
|
4090
|
+
return {};
|
|
3494
4091
|
}
|
|
3495
4092
|
|
|
3496
|
-
// src/client/
|
|
3497
|
-
function
|
|
3498
|
-
return
|
|
4093
|
+
// src/client/client-handlers.ts
|
|
4094
|
+
function toInvalidParams(message) {
|
|
4095
|
+
return import_sdk3.RequestError.invalidParams(undefined, message);
|
|
3499
4096
|
}
|
|
3500
|
-
function
|
|
3501
|
-
return error instanceof Error ? error.message :
|
|
4097
|
+
function toServerError(error, fallback) {
|
|
4098
|
+
return new import_sdk3.RequestError(-32000, error instanceof Error ? error.message : fallback);
|
|
3502
4099
|
}
|
|
3503
|
-
function
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
|
|
4100
|
+
function registerAcpClientHandlers(app, deps) {
|
|
4101
|
+
app.onRequest(import_sdk3.methods.client.session.requestPermission, async (ctx) => {
|
|
4102
|
+
const params = ctx.params;
|
|
4103
|
+
const toolCall = params.toolCall;
|
|
4104
|
+
const toolHint = toolCall && typeof toolCall === "object" ? {
|
|
4105
|
+
id: typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : undefined,
|
|
4106
|
+
title: typeof toolCall.title === "string" ? toolCall.title : undefined,
|
|
4107
|
+
kind: typeof toolCall.kind === "string" ? toolCall.kind : undefined
|
|
4108
|
+
} : undefined;
|
|
4109
|
+
console.info("[acp] ← Agent request", {
|
|
4110
|
+
requestId: ctx.requestId,
|
|
4111
|
+
method: "session/request_permission",
|
|
4112
|
+
toolCall: toolHint,
|
|
4113
|
+
optionCount: Array.isArray(params.options) ? params.options.length : undefined
|
|
4114
|
+
});
|
|
3508
4115
|
try {
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
4116
|
+
const outcome = await deps.onPermission({
|
|
4117
|
+
sessionId: typeof params.sessionId === "string" ? params.sessionId : undefined,
|
|
4118
|
+
params
|
|
4119
|
+
});
|
|
4120
|
+
return { outcome };
|
|
4121
|
+
} catch (error) {
|
|
4122
|
+
console.error("[acp] request_permission 失败", error);
|
|
4123
|
+
return { outcome: { outcome: "cancelled" } };
|
|
3512
4124
|
}
|
|
3513
|
-
return /超时|timeout|timed out|temporar|busy|unavailable|closed|abort|econnreset|epipe/i.test(`${error.message} ${detail}`);
|
|
3514
|
-
}
|
|
3515
|
-
const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
3516
|
-
return /ACP connection closed|connection closed|closed|abort|超时|timeout|timed out|econnreset|epipe|stdio|stream/i.test(message);
|
|
3517
|
-
}
|
|
3518
|
-
async function restoreOrCreateAcpSession(input) {
|
|
3519
|
-
let mcpServersAccepted = (input.mcpServers ?? []).length > 0;
|
|
3520
|
-
let nativeSessionAccepted = false;
|
|
3521
|
-
let recoveredToolOutputs;
|
|
3522
|
-
const request = async (method, params) => {
|
|
3523
|
-
const opened = await requestSessionWithResources(input.request, method, params, input.sessionMeta);
|
|
3524
|
-
nativeSessionAccepted = opened.nativeSessionAccepted;
|
|
3525
|
-
const meta = opened.result._meta;
|
|
3526
|
-
const outputs = meta?.toolOutputRecovery?.outputs;
|
|
3527
|
-
let total = 0;
|
|
3528
|
-
recoveredToolOutputs = Array.isArray(outputs) ? outputs.slice(0, 20).filter((row) => {
|
|
3529
|
-
if (!row || typeof row.toolCallId !== "string" || row.toolCallId.length > 120 || typeof row.text !== "string")
|
|
3530
|
-
return false;
|
|
3531
|
-
const bytes = Buffer.byteLength(row.text);
|
|
3532
|
-
if (bytes > 128 * 1024 || total + bytes > 256 * 1024)
|
|
3533
|
-
return false;
|
|
3534
|
-
total += bytes;
|
|
3535
|
-
return true;
|
|
3536
|
-
}) : undefined;
|
|
3537
|
-
return opened.result;
|
|
3538
|
-
};
|
|
3539
|
-
const resumeId = input.resumeSessionId?.trim() || null;
|
|
3540
|
-
const restoreAttempts = [];
|
|
3541
|
-
const delayMs = input.retryDelayMs ?? 250;
|
|
3542
|
-
const outputLog = input.log ?? ((level, message, data) => {
|
|
3543
|
-
if (level === "info" && false)
|
|
3544
|
-
;
|
|
3545
|
-
const line = `[acp] ${message}`;
|
|
3546
|
-
if (level === "warn")
|
|
3547
|
-
console.warn(line, data ?? "");
|
|
3548
|
-
else
|
|
3549
|
-
console.info(line, data ?? "");
|
|
3550
4125
|
});
|
|
3551
|
-
|
|
3552
|
-
|
|
3553
|
-
const
|
|
3554
|
-
|
|
3555
|
-
|
|
3556
|
-
|
|
3557
|
-
|
|
3558
|
-
|
|
3559
|
-
try: tryIndex,
|
|
3560
|
-
maxTries
|
|
3561
|
-
});
|
|
4126
|
+
app.onRequest(import_sdk3.methods.client.fs.readTextFile, async (ctx) => {
|
|
4127
|
+
const workspaceRoot = deps.getWorkspaceRoot();
|
|
4128
|
+
const filePath = ctx.params.path;
|
|
4129
|
+
if (!workspaceRoot || !filePath) {
|
|
4130
|
+
throw toInvalidParams("fs/read_text_file 需要 path 与已连接工作区");
|
|
4131
|
+
}
|
|
4132
|
+
const virtualResource = parseInkdownVirtualPath(filePath, workspaceRoot);
|
|
4133
|
+
if (virtualResource) {
|
|
3562
4134
|
try {
|
|
3563
|
-
const
|
|
3564
|
-
|
|
3565
|
-
|
|
3566
|
-
|
|
4135
|
+
const content = await deps.readSnapshot(virtualResource);
|
|
4136
|
+
console.info("[acp] fs/read_text_file 虚拟快照 ok", {
|
|
4137
|
+
resource: virtualResource,
|
|
4138
|
+
chars: content.length
|
|
3567
4139
|
});
|
|
3568
|
-
|
|
3569
|
-
log("info", "session restore ok", { method: rpcMethod, sessionId: resumeId });
|
|
3570
|
-
return result;
|
|
4140
|
+
return { content };
|
|
3571
4141
|
} catch (error) {
|
|
3572
|
-
|
|
3573
|
-
log("warn", "session restore failed", {
|
|
3574
|
-
method: rpcMethod,
|
|
3575
|
-
sessionId: resumeId,
|
|
3576
|
-
try: tryIndex,
|
|
3577
|
-
error: lastError
|
|
3578
|
-
});
|
|
3579
|
-
const canRetry = tryIndex < maxTries && isTransientAcpTransportError(error);
|
|
3580
|
-
if (!canRetry) {
|
|
3581
|
-
restoreAttempts.push({ method, ok: false, tries: tryIndex, error: lastError });
|
|
3582
|
-
return null;
|
|
3583
|
-
}
|
|
3584
|
-
if (delayMs > 0)
|
|
3585
|
-
await new Promise((r) => setTimeout(r, delayMs));
|
|
4142
|
+
throw toServerError(error, "读取 Inkdown 快照失败");
|
|
3586
4143
|
}
|
|
3587
4144
|
}
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
4145
|
+
if (isInkdownVirtualDirPath(filePath, workspaceRoot)) {
|
|
4146
|
+
throw toInvalidParams(`Inkdown 虚拟目录下可读:${INKDOWN_VIRTUAL_RESOURCES.join("、")}`);
|
|
4147
|
+
}
|
|
4148
|
+
try {
|
|
4149
|
+
const result = await acpReadTextFile({
|
|
4150
|
+
path: filePath,
|
|
4151
|
+
workspaceRoot,
|
|
4152
|
+
line: ctx.params.line ?? undefined,
|
|
4153
|
+
limit: ctx.params.limit ?? undefined
|
|
4154
|
+
});
|
|
4155
|
+
console.info("[acp] fs/read_text_file ok", { path: filePath });
|
|
4156
|
+
return result;
|
|
4157
|
+
} catch (error) {
|
|
4158
|
+
throw toServerError(error, "读取文件失败");
|
|
4159
|
+
}
|
|
3595
4160
|
});
|
|
3596
|
-
|
|
3597
|
-
const
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
|
|
4161
|
+
app.onRequest(import_sdk3.methods.client.fs.writeTextFile, async (ctx) => {
|
|
4162
|
+
const workspaceRoot = deps.getWorkspaceRoot();
|
|
4163
|
+
const filePath = ctx.params.path;
|
|
4164
|
+
const content = ctx.params.content;
|
|
4165
|
+
if (!workspaceRoot || !filePath || typeof content !== "string") {
|
|
4166
|
+
throw toInvalidParams("fs/write_text_file 需要 path、content 与已连接工作区");
|
|
4167
|
+
}
|
|
3601
4168
|
try {
|
|
3602
|
-
|
|
3603
|
-
|
|
3604
|
-
|
|
3605
|
-
throw firstError;
|
|
3606
|
-
log("warn", input.preserveMcpOnRetry ? "session/new failed, retry with mcpServers" : "session/new failed, retry without mcpServers", {
|
|
3607
|
-
error: errorMessage(firstError)
|
|
4169
|
+
console.info("[acp] fs/write_text_file(无内嵌审批,依赖 Agent 是否先 request_permission)", {
|
|
4170
|
+
path: filePath,
|
|
4171
|
+
bytes: content.length
|
|
3608
4172
|
});
|
|
3609
|
-
|
|
3610
|
-
|
|
3611
|
-
|
|
3612
|
-
mcpServersAccepted = retryServers.length > 0;
|
|
3613
|
-
return result;
|
|
3614
|
-
} catch {
|
|
3615
|
-
throw firstError;
|
|
3616
|
-
}
|
|
4173
|
+
return await acpWriteTextFile({ path: filePath, content, workspaceRoot });
|
|
4174
|
+
} catch (error) {
|
|
4175
|
+
throw toServerError(error, "写入文件失败");
|
|
3617
4176
|
}
|
|
3618
|
-
};
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
const
|
|
3622
|
-
|
|
3623
|
-
|
|
3624
|
-
|
|
3625
|
-
sessionId: id,
|
|
3626
|
-
mcpServersAccepted,
|
|
3627
|
-
recoveredToolOutputs,
|
|
3628
|
-
nativeSessionAccepted,
|
|
3629
|
-
configOptions: withModelsFallback(resumed),
|
|
3630
|
-
restoreMethod: "resume",
|
|
3631
|
-
sessionRestored: true,
|
|
3632
|
-
requestedSessionId: resumeId,
|
|
3633
|
-
restoreAttempts
|
|
3634
|
-
};
|
|
4177
|
+
});
|
|
4178
|
+
app.onRequest(import_sdk3.methods.client.terminal.create, async (ctx) => {
|
|
4179
|
+
const workspaceRoot = deps.getWorkspaceRoot();
|
|
4180
|
+
const sessionId = ctx.params.sessionId;
|
|
4181
|
+
const command = ctx.params.command;
|
|
4182
|
+
if (!workspaceRoot || !sessionId || !command) {
|
|
4183
|
+
throw toInvalidParams("terminal/create 需要 sessionId、command 与已连接工作区");
|
|
3635
4184
|
}
|
|
3636
|
-
} else if (resumeId && !input.resumeSupported) {
|
|
3637
|
-
log("info", "skip session/resume:Agent 未声明 resume 能力");
|
|
3638
|
-
}
|
|
3639
|
-
if (resumeId && input.loadSupported) {
|
|
3640
|
-
input.onSuppressUpdates?.(true);
|
|
3641
4185
|
try {
|
|
3642
|
-
|
|
3643
|
-
|
|
3644
|
-
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
3650
|
-
|
|
3651
|
-
|
|
3652
|
-
|
|
3653
|
-
requestedSessionId: resumeId,
|
|
3654
|
-
restoreAttempts
|
|
3655
|
-
};
|
|
3656
|
-
}
|
|
3657
|
-
} finally {
|
|
3658
|
-
input.onSuppressUpdates?.(false);
|
|
4186
|
+
return deps.terminals.create({
|
|
4187
|
+
sessionId,
|
|
4188
|
+
command,
|
|
4189
|
+
args: ctx.params.args ?? undefined,
|
|
4190
|
+
env: ctx.params.env ?? undefined,
|
|
4191
|
+
cwd: ctx.params.cwd ?? undefined,
|
|
4192
|
+
outputByteLimit: ctx.params.outputByteLimit ?? undefined,
|
|
4193
|
+
workspaceRoot
|
|
4194
|
+
});
|
|
4195
|
+
} catch (error) {
|
|
4196
|
+
throw toServerError(error, "创建终端失败");
|
|
3659
4197
|
}
|
|
3660
|
-
}
|
|
3661
|
-
|
|
3662
|
-
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
|
|
3666
|
-
|
|
3667
|
-
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
4198
|
+
});
|
|
4199
|
+
app.onRequest(import_sdk3.methods.client.terminal.output, async (ctx) => {
|
|
4200
|
+
const terminalId = ctx.params.terminalId;
|
|
4201
|
+
if (!terminalId) {
|
|
4202
|
+
throw toInvalidParams("terminal/output 需要 terminalId");
|
|
4203
|
+
}
|
|
4204
|
+
try {
|
|
4205
|
+
return deps.terminals.getOutput(terminalId);
|
|
4206
|
+
} catch (error) {
|
|
4207
|
+
throw toServerError(error, "读取终端输出失败");
|
|
4208
|
+
}
|
|
4209
|
+
});
|
|
4210
|
+
app.onRequest(import_sdk3.methods.client.terminal.waitForExit, async (ctx) => {
|
|
4211
|
+
const terminalId = ctx.params.terminalId;
|
|
4212
|
+
if (!terminalId) {
|
|
4213
|
+
throw toInvalidParams("terminal/wait_for_exit 需要 terminalId");
|
|
4214
|
+
}
|
|
4215
|
+
try {
|
|
4216
|
+
return await deps.terminals.waitForExit(terminalId);
|
|
4217
|
+
} catch (error) {
|
|
4218
|
+
throw toServerError(error, "等待终端退出失败");
|
|
4219
|
+
}
|
|
4220
|
+
});
|
|
4221
|
+
app.onRequest(import_sdk3.methods.client.terminal.kill, async (ctx) => {
|
|
4222
|
+
const terminalId = ctx.params.terminalId;
|
|
4223
|
+
if (!terminalId) {
|
|
4224
|
+
throw toInvalidParams("terminal/kill 需要 terminalId");
|
|
4225
|
+
}
|
|
4226
|
+
try {
|
|
4227
|
+
return deps.terminals.kill(terminalId);
|
|
4228
|
+
} catch (error) {
|
|
4229
|
+
throw toServerError(error, "终止终端失败");
|
|
4230
|
+
}
|
|
4231
|
+
});
|
|
4232
|
+
app.onRequest(import_sdk3.methods.client.terminal.release, async (ctx) => {
|
|
4233
|
+
const terminalId = ctx.params.terminalId;
|
|
4234
|
+
if (!terminalId) {
|
|
4235
|
+
throw toInvalidParams("terminal/release 需要 terminalId");
|
|
4236
|
+
}
|
|
4237
|
+
try {
|
|
4238
|
+
return deps.terminals.release(terminalId);
|
|
4239
|
+
} catch (error) {
|
|
4240
|
+
throw toServerError(error, "释放终端失败");
|
|
4241
|
+
}
|
|
4242
|
+
});
|
|
4243
|
+
app.onNotification(import_sdk3.methods.client.session.update, async (ctx) => {
|
|
4244
|
+
deps.onSessionUpdate({
|
|
4245
|
+
sessionId: ctx.params.sessionId,
|
|
4246
|
+
update: ctx.params.update
|
|
4247
|
+
});
|
|
4248
|
+
});
|
|
3679
4249
|
}
|
|
3680
|
-
|
|
3681
|
-
if (
|
|
3682
|
-
return
|
|
3683
|
-
|
|
3684
|
-
return
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
4250
|
+
function permissionOptionId(option) {
|
|
4251
|
+
if (typeof option.optionId === "string")
|
|
4252
|
+
return option.optionId;
|
|
4253
|
+
if (typeof option.id === "string")
|
|
4254
|
+
return option.id;
|
|
4255
|
+
return null;
|
|
4256
|
+
}
|
|
4257
|
+
function pickAllowOptionId(params) {
|
|
4258
|
+
const options = params.options;
|
|
4259
|
+
if (!Array.isArray(options))
|
|
4260
|
+
return null;
|
|
4261
|
+
for (const item of options) {
|
|
4262
|
+
if (!item || typeof item !== "object")
|
|
4263
|
+
continue;
|
|
4264
|
+
const option = item;
|
|
4265
|
+
const id = permissionOptionId(option);
|
|
4266
|
+
const kind = typeof option.kind === "string" ? option.kind : "";
|
|
4267
|
+
if (id && (kind.includes("allow") || kind === "allow_once" || kind === "allow_always")) {
|
|
4268
|
+
return id;
|
|
4269
|
+
}
|
|
4270
|
+
}
|
|
4271
|
+
for (const item of options) {
|
|
4272
|
+
if (!item || typeof item !== "object")
|
|
4273
|
+
continue;
|
|
4274
|
+
const id = permissionOptionId(item);
|
|
4275
|
+
if (id)
|
|
4276
|
+
return id;
|
|
3690
4277
|
}
|
|
4278
|
+
return null;
|
|
3691
4279
|
}
|
|
3692
4280
|
|
|
3693
4281
|
// src/client/acp-terminal.ts
|
|
@@ -3875,9 +4463,9 @@ class AcpTerminalManager {
|
|
|
3875
4463
|
}
|
|
3876
4464
|
|
|
3877
4465
|
// src/client/acp-proxy-service.ts
|
|
3878
|
-
var
|
|
3879
|
-
var
|
|
3880
|
-
var
|
|
4466
|
+
var import_promises7 = require("node:fs/promises");
|
|
4467
|
+
var import_node_fs18 = require("node:fs");
|
|
4468
|
+
var import_node_path20 = require("node:path");
|
|
3881
4469
|
var DEFAULT_ACP_PROXY_SETTINGS = {
|
|
3882
4470
|
enabled: false,
|
|
3883
4471
|
host: "127.0.0.1",
|
|
@@ -3886,7 +4474,7 @@ var DEFAULT_ACP_PROXY_SETTINGS = {
|
|
|
3886
4474
|
var PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
|
|
3887
4475
|
var LOWERCASE_PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "no_proxy"];
|
|
3888
4476
|
function proxyFilePath(dir) {
|
|
3889
|
-
return
|
|
4477
|
+
return import_node_path20.join(dir, "agent", "proxy.json");
|
|
3890
4478
|
}
|
|
3891
4479
|
function validate2(settings) {
|
|
3892
4480
|
if (!settings.host.trim())
|
|
@@ -3898,10 +4486,10 @@ function validate2(settings) {
|
|
|
3898
4486
|
}
|
|
3899
4487
|
async function readAcpProxySettings(dir = getDefaultAgentDataDir()) {
|
|
3900
4488
|
const file = proxyFilePath(dir);
|
|
3901
|
-
if (!
|
|
4489
|
+
if (!import_node_fs18.existsSync(file))
|
|
3902
4490
|
return { ...DEFAULT_ACP_PROXY_SETTINGS };
|
|
3903
4491
|
try {
|
|
3904
|
-
const raw = JSON.parse(await
|
|
4492
|
+
const raw = JSON.parse(await import_promises7.readFile(file, "utf8"));
|
|
3905
4493
|
return {
|
|
3906
4494
|
enabled: raw.enabled === true,
|
|
3907
4495
|
host: typeof raw.host === "string" && raw.host.trim() ? raw.host : DEFAULT_ACP_PROXY_SETTINGS.host,
|
|
@@ -3920,8 +4508,8 @@ async function saveAcpProxySettings(payload, dir = getDefaultAgentDataDir()) {
|
|
|
3920
4508
|
host: payload.host.trim() || DEFAULT_ACP_PROXY_SETTINGS.host,
|
|
3921
4509
|
port: payload.port
|
|
3922
4510
|
};
|
|
3923
|
-
await
|
|
3924
|
-
await
|
|
4511
|
+
await import_promises7.mkdir(import_node_path20.join(dir, "agent"), { recursive: true });
|
|
4512
|
+
await import_promises7.writeFile(proxyFilePath(dir), JSON.stringify(stored, null, 2), "utf8");
|
|
3925
4513
|
return ok(stored);
|
|
3926
4514
|
}
|
|
3927
4515
|
function buildAcpProxySpawnEnv(settings) {
|
|
@@ -3976,9 +4564,9 @@ function compatDeliveryKey(sessionId, generation, digest) {
|
|
|
3976
4564
|
}
|
|
3977
4565
|
|
|
3978
4566
|
// src/mcp/app-skills-mcp.ts
|
|
3979
|
-
var
|
|
4567
|
+
var import_node_path21 = require("node:path");
|
|
3980
4568
|
var import_node_url = require("node:url");
|
|
3981
|
-
var
|
|
4569
|
+
var import_node_fs19 = require("node:fs");
|
|
3982
4570
|
var APP_SKILLS_MCP_SERVER_NAME = "app-skills";
|
|
3983
4571
|
var APP_SKILLS_TOOLS = [
|
|
3984
4572
|
{
|
|
@@ -4014,11 +4602,11 @@ function buildAppSkillsMcpServer(directory, opts) {
|
|
|
4014
4602
|
function resolveAppSkillsRunnerPath(fromFile) {
|
|
4015
4603
|
const base = fromFile ?? import_node_url.fileURLToPath("file:///home/runner/work/acp-client/acp-client/src/mcp/app-skills-mcp.ts");
|
|
4016
4604
|
const candidates = [
|
|
4017
|
-
|
|
4018
|
-
|
|
4605
|
+
import_node_path21.join(import_node_path21.dirname(base), "app-skills-mcp-serve.cjs"),
|
|
4606
|
+
import_node_path21.join(import_node_path21.dirname(base), "app-skills-mcp-serve.ts")
|
|
4019
4607
|
];
|
|
4020
4608
|
for (const candidate of candidates) {
|
|
4021
|
-
if (
|
|
4609
|
+
if (import_node_fs19.existsSync(candidate))
|
|
4022
4610
|
return candidate;
|
|
4023
4611
|
}
|
|
4024
4612
|
throw new Error(`技能 MCP 入口缺失(dist 未构建?): ${candidates[0]}`);
|
|
@@ -4109,12 +4697,17 @@ class AcpSessionHandle {
|
|
|
4109
4697
|
get availableCommands() {
|
|
4110
4698
|
return this.client.getAvailableCommands(this.sessionId);
|
|
4111
4699
|
}
|
|
4700
|
+
cancel() {
|
|
4701
|
+
return this.client.cancelSession(this.sessionId);
|
|
4702
|
+
}
|
|
4112
4703
|
async setConfigOption(configId, value) {
|
|
4113
4704
|
return this.client.setSessionConfigOption(this.sessionId, configId, value);
|
|
4114
4705
|
}
|
|
4115
4706
|
}
|
|
4116
4707
|
|
|
4117
4708
|
class AcpClient {
|
|
4709
|
+
mcpRecovery;
|
|
4710
|
+
suppressRecoveryUpdates = false;
|
|
4118
4711
|
status = "disconnected";
|
|
4119
4712
|
commandsCache = new AvailableCommandsCache;
|
|
4120
4713
|
quotaCache = new QuotaCache;
|
|
@@ -4163,6 +4756,23 @@ class AcpClient {
|
|
|
4163
4756
|
this.resourcesDir = options.resources?.directory ?? null;
|
|
4164
4757
|
this.attachSkillsMcp = options.resources?.attachSkillsMcp !== false;
|
|
4165
4758
|
this.callbacks = options.callbacks ?? {};
|
|
4759
|
+
this.mcpRecovery = new AcpMcpSessionRecovery({
|
|
4760
|
+
request: (method, params, signal) => {
|
|
4761
|
+
if (!this.sdkConnection?.agent)
|
|
4762
|
+
throw new AcpMcpRecoveryCancelledError("ACP connection closed");
|
|
4763
|
+
return this.sdkConnection.agent.request(method, params, { cancellationSignal: signal });
|
|
4764
|
+
},
|
|
4765
|
+
getCapabilities: () => ({
|
|
4766
|
+
resume: Boolean(this.initResponse && parseResumeSessionSupported(this.initResponse.agentCapabilities)),
|
|
4767
|
+
load: Boolean(this.initResponse && parseLoadSessionSupported(this.initResponse.agentCapabilities))
|
|
4768
|
+
}),
|
|
4769
|
+
isConnected: () => this.isConnected,
|
|
4770
|
+
isBusy: (sessionId) => [...this.inflightPrompts].some((id) => id !== sessionId),
|
|
4771
|
+
onSuppressUpdates: (suppress) => {
|
|
4772
|
+
this.suppressRecoveryUpdates = suppress;
|
|
4773
|
+
},
|
|
4774
|
+
onEvent: (event) => this.callbacks.onLog?.("info", "mcp.recovery." + event.type, { sessionId: event.sessionId, method: event.method })
|
|
4775
|
+
});
|
|
4166
4776
|
const runtimeId = typeof options.runtime === "string" ? options.runtime : options.runtime?.id ?? DEFAULT_ACP_RUNTIME_ID;
|
|
4167
4777
|
this.adapter = getAcpRuntimeAdapter(runtimeId);
|
|
4168
4778
|
if (typeof options.runtime === "object" && options.runtime !== null) {
|
|
@@ -4195,6 +4805,7 @@ class AcpClient {
|
|
|
4195
4805
|
if (this.currentStatus === "connecting")
|
|
4196
4806
|
return err({ code: "ACP_PROTOCOL_ERROR", message: "Agent 正在连接" });
|
|
4197
4807
|
this.connectionGen += 1;
|
|
4808
|
+
this.mcpRecovery.reset();
|
|
4198
4809
|
const connectGen = this.connectionGen;
|
|
4199
4810
|
try {
|
|
4200
4811
|
this.setStatus("connecting");
|
|
@@ -4231,13 +4842,6 @@ class AcpClient {
|
|
|
4231
4842
|
}
|
|
4232
4843
|
this.sessionConfig = profile;
|
|
4233
4844
|
resourceEnv = this.sessionConfig.env;
|
|
4234
|
-
const interactions = ["opencode", "opencode-v2"].includes(this.runtimeInfo.id) && this.adapter.prepareAppResources ? await this.adapter.prepareAppResources({
|
|
4235
|
-
directory: this.resourcesDir,
|
|
4236
|
-
command: effectiveRuntime.command,
|
|
4237
|
-
workspaceRoot: this.workspaceRoot,
|
|
4238
|
-
env: { ...process.env, ...spawnEnv.env, ...resourceEnv }
|
|
4239
|
-
}) : undefined;
|
|
4240
|
-
Object.assign(resourceEnv, interactions?.env);
|
|
4241
4845
|
const load = readAppResourcesDir(this.resourcesDir);
|
|
4242
4846
|
this.resourcePrep = { profileTag: null, report: {
|
|
4243
4847
|
rulesApplied: false,
|
|
@@ -4246,7 +4850,6 @@ class AcpClient {
|
|
|
4246
4850
|
rulesChars: load.rules?.chars ?? 0,
|
|
4247
4851
|
profileDigest: digestAppResources(load),
|
|
4248
4852
|
skillsFound: load.skills.map((s) => s.name),
|
|
4249
|
-
openCodeQuestions: interactions?.report.openCodeQuestions,
|
|
4250
4853
|
configurationScope: "session",
|
|
4251
4854
|
configurationDirectory: this.sessionConfig.directory,
|
|
4252
4855
|
configurationRulesFile: this.sessionConfig.rulesFile,
|
|
@@ -4357,7 +4960,8 @@ class AcpClient {
|
|
|
4357
4960
|
onSessionUpdate: (params) => {
|
|
4358
4961
|
this.commandsCache.observe(params);
|
|
4359
4962
|
this.quotaCache.observe(params, this.runtimeInfo.id);
|
|
4360
|
-
this.
|
|
4963
|
+
if (!this.suppressRecoveryUpdates)
|
|
4964
|
+
this.callbacks.onSessionUpdate?.(params);
|
|
4361
4965
|
}
|
|
4362
4966
|
};
|
|
4363
4967
|
const { app, connection, streamHandle } = connectSdkClient(processHandle.child, (clientApp) => {
|
|
@@ -4434,7 +5038,10 @@ class AcpClient {
|
|
|
4434
5038
|
return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
|
|
4435
5039
|
}
|
|
4436
5040
|
const agent = this.sdkConnection.agent;
|
|
5041
|
+
const generation = this.connectionGen;
|
|
4437
5042
|
const init = this.initResponse;
|
|
5043
|
+
if (this.mcpRecovery.isRecovering)
|
|
5044
|
+
return err({ code: "ACP_PROTOCOL_ERROR", message: "Wait for MCP recovery before opening another session" });
|
|
4438
5045
|
const resumeSupported = Boolean(init && parseResumeSessionSupported(init.agentCapabilities));
|
|
4439
5046
|
const loadSupported = Boolean(init && parseLoadSessionSupported(init.agentCapabilities));
|
|
4440
5047
|
try {
|
|
@@ -4461,6 +5068,7 @@ class AcpClient {
|
|
|
4461
5068
|
});
|
|
4462
5069
|
}
|
|
4463
5070
|
}
|
|
5071
|
+
const sessionMeta = mergeSessionMeta((!this.sessionConfig || this.runtimeInfo.id === "agy") && this.resourcesDir && this.resourcePrep?.report.bridgeSupported ? this.adapter.appResourceSessionMeta?.(this.resourcesDir) : undefined, options?.codeMode, this.initResponse?.agentCapabilities ?? undefined);
|
|
4464
5072
|
const openResult = await restoreOrCreateAcpSession({
|
|
4465
5073
|
request: async (method, params) => {
|
|
4466
5074
|
return sdkRequest(agent, method, params);
|
|
@@ -4470,13 +5078,24 @@ class AcpClient {
|
|
|
4470
5078
|
resumeSupported,
|
|
4471
5079
|
loadSupported,
|
|
4472
5080
|
mcpServers,
|
|
4473
|
-
sessionMeta
|
|
5081
|
+
sessionMeta,
|
|
5082
|
+
preserveMcpOnRetry: true,
|
|
4474
5083
|
log: (level, msg, meta) => {
|
|
4475
5084
|
this.callbacks.onLog?.(level, msg, meta);
|
|
4476
5085
|
}
|
|
4477
5086
|
});
|
|
5087
|
+
if (generation !== this.connectionGen || !this.isConnected)
|
|
5088
|
+
return err({ code: "CANCELLED", message: "Connection changed while opening session" });
|
|
4478
5089
|
if (!openResult.mcpServersAccepted)
|
|
4479
5090
|
skillsExposed = "none";
|
|
5091
|
+
if (options?.mcpHealth && mcpServers.length)
|
|
5092
|
+
this.mcpRecovery.register({
|
|
5093
|
+
sessionId: openResult.sessionId,
|
|
5094
|
+
cwd: this.workspaceRoot,
|
|
5095
|
+
mcpServers,
|
|
5096
|
+
sessionMeta: openResult.nativeSessionAccepted ? sessionMeta : undefined,
|
|
5097
|
+
monitor: options.mcpHealth
|
|
5098
|
+
});
|
|
4480
5099
|
this.sessionLedger.set(openResult.sessionId, {
|
|
4481
5100
|
restoreMethod: openResult.restoreMethod,
|
|
4482
5101
|
gen: this.connectionGen,
|
|
@@ -4500,8 +5119,17 @@ class AcpClient {
|
|
|
4500
5119
|
if (!this.sdkConnection?.agent) {
|
|
4501
5120
|
return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
|
|
4502
5121
|
}
|
|
5122
|
+
if (!this.isConnected)
|
|
5123
|
+
return err({ code: "ACP_NOT_CONNECTED", message: "Agent is not connected" });
|
|
5124
|
+
if (this.inflightPrompts.has(sessionId))
|
|
5125
|
+
return err({ code: "ACP_PROTOCOL_ERROR", message: "Session already has an in-flight prompt" });
|
|
5126
|
+
const generation = this.connectionGen;
|
|
5127
|
+
const agent = this.sdkConnection.agent;
|
|
4503
5128
|
this.inflightPrompts.add(sessionId);
|
|
4504
5129
|
try {
|
|
5130
|
+
await this.mcpRecovery.ensureReady(sessionId);
|
|
5131
|
+
if (generation !== this.connectionGen || !this.isConnected)
|
|
5132
|
+
throw new AcpMcpRecoveryCancelledError("ACP connection changed");
|
|
4505
5133
|
const prompt = [{ type: "text", text: promptText }];
|
|
4506
5134
|
for (const image of options?.images ?? []) {
|
|
4507
5135
|
if (!image?.data || !image?.mimeType)
|
|
@@ -4510,16 +5138,17 @@ class AcpClient {
|
|
|
4510
5138
|
}
|
|
4511
5139
|
const compat = this.buildCompatPrepend(sessionId);
|
|
4512
5140
|
const blocks = compat ? [{ type: "text", text: compat }, ...prompt] : prompt;
|
|
4513
|
-
const response = await sdkRequest(
|
|
5141
|
+
const response = await sdkRequest(agent, import_sdk4.methods.agent.session.prompt, {
|
|
4514
5142
|
sessionId,
|
|
4515
5143
|
prompt: blocks
|
|
4516
5144
|
}, options?.timeoutMs);
|
|
4517
5145
|
return ok(response);
|
|
4518
5146
|
} catch (e) {
|
|
4519
5147
|
const message = e instanceof Error ? e.message : String(e);
|
|
4520
|
-
return err({ code: "ACP_PROTOCOL_ERROR", message });
|
|
5148
|
+
return err({ code: e instanceof AcpMcpRecoveryCancelledError ? "CANCELLED" : "ACP_PROTOCOL_ERROR", message });
|
|
4521
5149
|
} finally {
|
|
4522
|
-
this.
|
|
5150
|
+
if (generation === this.connectionGen)
|
|
5151
|
+
this.inflightPrompts.delete(sessionId);
|
|
4523
5152
|
}
|
|
4524
5153
|
}
|
|
4525
5154
|
buildCompatPrepend(sessionId) {
|
|
@@ -4554,6 +5183,17 @@ class AcpClient {
|
|
|
4554
5183
|
this.compatSentKeys.add(key);
|
|
4555
5184
|
return text;
|
|
4556
5185
|
}
|
|
5186
|
+
async cancelSession(sessionId) {
|
|
5187
|
+
this.mcpRecovery.cancel(sessionId);
|
|
5188
|
+
if (!this.sdkConnection?.agent)
|
|
5189
|
+
return err({ code: "ACP_NOT_CONNECTED", message: "Agent is not connected" });
|
|
5190
|
+
try {
|
|
5191
|
+
await this.sdkConnection.agent.notify(import_sdk4.methods.agent.session.cancel, { sessionId });
|
|
5192
|
+
return ok(undefined);
|
|
5193
|
+
} catch (error) {
|
|
5194
|
+
return err({ code: "ACP_PROTOCOL_ERROR", message: error instanceof Error ? error.message : String(error) });
|
|
5195
|
+
}
|
|
5196
|
+
}
|
|
4557
5197
|
async setSessionConfigOption(sessionId, configId, value) {
|
|
4558
5198
|
if (!this.sdkConnection?.agent) {
|
|
4559
5199
|
return err({ code: "ACP_NOT_CONNECTED", message: "尚未连接到 Agent 服务端" });
|
|
@@ -4571,6 +5211,9 @@ class AcpClient {
|
|
|
4571
5211
|
}
|
|
4572
5212
|
}
|
|
4573
5213
|
async disconnect(reason) {
|
|
5214
|
+
++this.connectionGen;
|
|
5215
|
+
this.mcpRecovery.reset();
|
|
5216
|
+
this.inflightPrompts.clear();
|
|
4574
5217
|
this.setStatus("disconnected", reason);
|
|
4575
5218
|
this.resourcePrep = null;
|
|
4576
5219
|
const capabilities = this.initResponse?.agentCapabilities?.sessionCapabilities;
|
|
@@ -5525,3 +6168,61 @@ async function handleInkdownMcpRpc(message, context, tools = INKDOWN_MCP_TOOLS,
|
|
|
5525
6168
|
return rpcError(message.id, -32601, `未实现的方法: ${method}`);
|
|
5526
6169
|
}
|
|
5527
6170
|
}
|
|
6171
|
+
// src/mcp/connection-health.ts
|
|
6172
|
+
class McpConnectionHealth {
|
|
6173
|
+
clients = new Set;
|
|
6174
|
+
listeners = new Set;
|
|
6175
|
+
discoveryCount = 0;
|
|
6176
|
+
disconnectCount = 0;
|
|
6177
|
+
get discoveries() {
|
|
6178
|
+
return this.discoveryCount;
|
|
6179
|
+
}
|
|
6180
|
+
get disconnects() {
|
|
6181
|
+
return this.disconnectCount;
|
|
6182
|
+
}
|
|
6183
|
+
get hasDiscoveredClient() {
|
|
6184
|
+
return this.clients.size > 0;
|
|
6185
|
+
}
|
|
6186
|
+
discovered(client) {
|
|
6187
|
+
this.clients.add(client);
|
|
6188
|
+
++this.discoveryCount;
|
|
6189
|
+
for (const listener of this.listeners)
|
|
6190
|
+
listener();
|
|
6191
|
+
}
|
|
6192
|
+
closed(client) {
|
|
6193
|
+
if (this.clients.delete(client))
|
|
6194
|
+
++this.disconnectCount;
|
|
6195
|
+
}
|
|
6196
|
+
needsRecovery(since) {
|
|
6197
|
+
return this.disconnectCount > since;
|
|
6198
|
+
}
|
|
6199
|
+
waitForDiscovery(after, signal, timeoutMs = 1e4) {
|
|
6200
|
+
return new Promise((resolve, reject) => {
|
|
6201
|
+
const cleanup = () => {
|
|
6202
|
+
clearTimeout(timer);
|
|
6203
|
+
this.listeners.delete(check);
|
|
6204
|
+
signal.removeEventListener("abort", abort);
|
|
6205
|
+
};
|
|
6206
|
+
const abort = () => {
|
|
6207
|
+
cleanup();
|
|
6208
|
+
reject(new Error("MCP discovery cancelled"));
|
|
6209
|
+
};
|
|
6210
|
+
const check = () => {
|
|
6211
|
+
if (this.discoveries <= after || !this.hasDiscoveredClient)
|
|
6212
|
+
return;
|
|
6213
|
+
cleanup();
|
|
6214
|
+
resolve();
|
|
6215
|
+
};
|
|
6216
|
+
const timer = setTimeout(() => {
|
|
6217
|
+
cleanup();
|
|
6218
|
+
reject(new Error("Timed out waiting for the agent to rediscover MCP tools; reconnect the agent"));
|
|
6219
|
+
}, timeoutMs);
|
|
6220
|
+
this.listeners.add(check);
|
|
6221
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
6222
|
+
if (signal.aborted)
|
|
6223
|
+
abort();
|
|
6224
|
+
else
|
|
6225
|
+
check();
|
|
6226
|
+
});
|
|
6227
|
+
}
|
|
6228
|
+
}
|