larkin 0.4.29 → 0.5.0
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/CHANGELOG.md +11 -0
- package/README.md +5 -9
- package/artifacts/release/THIRD_PARTY_NOTICES.txt +751 -4425
- package/dist/app/agent-cli.mjs +14 -2
- package/dist/app/agent-config.mjs +26 -86
- package/dist/app/binary-entry.mjs +0 -20
- package/dist/app/cli.mjs +6 -22
- package/dist/app/internal-command.cjs +0 -2
- package/dist/app/internal-command.mjs +0 -2
- package/dist/app/runtime-model-directory.mjs +2 -16
- package/dist/app/runtime-process.mjs +0 -1
- package/dist/app/setup.mjs +52 -57
- package/dist/dashboard/dashboard-config-controller.mjs +43 -109
- package/dist/dashboard/dashboard-view-model.mjs +4 -7
- package/dist/dashboard/web/assets/dashboard.css +1 -1
- package/dist/dashboard/web/assets/dashboard.js +15 -15
- package/dist/feishu/host-shell.cjs +1 -2
- package/dist/feishu/host-shell.mjs +1 -2
- package/dist/platform/config.cjs +168 -133
- package/dist/platform/config.mjs +168 -133
- package/dist/runtime/pi-artifact-provenance.mjs +3 -3
- package/dist/runtime/pi-bash-timeout-extension.mjs +4 -5
- package/dist/runtime/pi-compaction-recovery.cjs +9 -11
- package/dist/runtime/pi-compaction-recovery.mjs +8 -10
- package/dist/runtime/pi-extension-api.mjs +1 -0
- package/dist/runtime/pi-model-catalog.cjs +7 -8
- package/dist/runtime/pi-model-catalog.mjs +7 -8
- package/dist/runtime/pi-subagent-injection.mjs +17 -4
- package/dist/runtime/runtime-adapters.mjs +26 -43
- package/dist/runtime/runtime-host.cjs +21 -43
- package/dist/runtime/runtime-host.mjs +22 -44
- package/dist/runtime/runtime-model-catalog.cjs +1 -1
- package/dist/runtime/runtime-model-catalog.mjs +1 -1
- package/dist/runtime/runtime-readiness.cjs +42 -99
- package/dist/runtime/runtime-readiness.mjs +40 -98
- package/dist/runtime/user-runtime.cjs +7 -24
- package/dist/runtime/user-runtime.mjs +7 -23
- package/dist/setup/bot-register.mjs +15 -123
- package/dist/setup/setup-agent-choice.mjs +48 -74
- package/dist/setup/setup-bind.mjs +51 -151
- package/dist/setup/setup-binding.mjs +6 -9
- package/package.json +3 -2
- package/dist/app/pi-auth-cli.mjs +0 -277
- package/dist/platform/process-boundary-trace.cjs +0 -108
- package/dist/runtime/builtin-pi-assets.cjs +0 -117
- package/dist/runtime/builtin-pi-assets.mjs +0 -105
- package/dist/runtime/pi-artifact-provenance.cjs +0 -147
- package/dist/runtime/pi-distribution-label.cjs +0 -6
- package/dist/runtime/pi-distribution-label.mjs +0 -3
- package/dist/runtime/pi-inline-extensions.mjs +0 -78
- package/dist/runtime/pi-official-auth.cjs +0 -594
- package/dist/runtime/pi-official-auth.mjs +0 -544
- package/dist/runtime/pi-profile-migration.cjs +0 -764
- package/dist/runtime/pi-profile-migration.mjs +0 -719
- package/dist/runtime/pi-provider-config.cjs +0 -354
- package/dist/runtime/pi-provider-config.mjs +0 -334
- package/dist/runtime/pi-provider-login.mjs +0 -240
|
@@ -12,10 +12,7 @@ import { createAgentStateStore } from "../agent/agent-state-store.mjs";
|
|
|
12
12
|
import { hydrateRuntimeAgent, syncAgentProfile, syncAgentProfileAsync } from "../app/runtime-agent-config.mjs";
|
|
13
13
|
import { managedLarkCliEnv } from "../app/agent-lark-cli-workspace.mjs";
|
|
14
14
|
import { resolveOfficialLarkCli } from "../app/official-lark-cli.mjs";
|
|
15
|
-
import { collectSetupAgentChoice,
|
|
16
|
-
import { probeNativeRuntimeReadiness } from "../runtime/runtime-readiness.mjs";
|
|
17
|
-
import { configureBuiltinPiProviderModel, stageBuiltinPiProvider, validatePiBaseUrl, validateBuiltinPiProviderSelection, listProviderModels, PI_PROVIDER_PRESETS } from "../runtime/pi-provider-config.mjs";
|
|
18
|
-
import { beginBuiltinPiCredentialTransaction, createOfficialPiCredentialRuntime, createOfficialPiAuthInteraction, createOfficialPiModelRuntime, createOfficialPiLogoutRuntime, createOfficialPiRegistryRuntime, listOfficialPiAuthProviders, logoutOfficialPiProvider, officialPiAuthStatus, runOfficialPiLogin, verifyOfficialPiProviderTurn, } from "../runtime/pi-official-auth.mjs";
|
|
15
|
+
import { collectSetupAgentChoice, missingRuntimeInstallMessage, terminalSetupQuestioner } from "./setup-agent-choice.mjs";
|
|
19
16
|
import { documentCommentSubscriptionCapability, markDocumentCommentSubscriptionVerified, } from "../platform/callback-capability.mjs";
|
|
20
17
|
import { openPlatformHost, parseLarkinTenant, registerAppAccountsHost, } from "../feishu/platform-hosts.mjs";
|
|
21
18
|
import { authorizationUrlFailureMessage, presentAuthorizationUrl } from "./setup-authorization-url.mjs";
|
|
@@ -35,7 +32,6 @@ const resolveOfficialCli = testFixture?.resolveOfficialLarkCli ?? resolveOfficia
|
|
|
35
32
|
const wait = testFixture?.wait ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
|
|
36
33
|
const CFG_DIR = larkinConfig.resolveConfigDir(process.env);
|
|
37
34
|
let temporaryAgentChoiceFile = null;
|
|
38
|
-
let pendingPiAuthTransaction = null;
|
|
39
35
|
let pendingBindChild = null;
|
|
40
36
|
let pendingChildSettled = null;
|
|
41
37
|
let settlePendingChild = null;
|
|
@@ -54,7 +50,6 @@ function trackPendingChild(child) {
|
|
|
54
50
|
pendingChildSettled = null;
|
|
55
51
|
}
|
|
56
52
|
process.on("exit", () => {
|
|
57
|
-
pendingPiAuthTransaction?.rollback();
|
|
58
53
|
if (!temporaryAgentChoiceFile)
|
|
59
54
|
return;
|
|
60
55
|
try {
|
|
@@ -70,8 +65,6 @@ for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
|
70
65
|
const settling = pendingChildSettled;
|
|
71
66
|
shutdownController.abort(new Error(`setup interrupted by ${signal}`));
|
|
72
67
|
void (settling ?? Promise.resolve()).finally(() => {
|
|
73
|
-
pendingPiAuthTransaction?.rollback();
|
|
74
|
-
pendingPiAuthTransaction = null;
|
|
75
68
|
process.exit(signal === "SIGINT" ? 130 : 143);
|
|
76
69
|
});
|
|
77
70
|
});
|
|
@@ -99,8 +92,6 @@ const CHILD_MAX_OUTPUT_BYTES = Number.isFinite(testChildMaxOutput) && testChildM
|
|
|
99
92
|
function officialCliForProfile(env) {
|
|
100
93
|
if (resolvedSetupOfficialCli)
|
|
101
94
|
return resolvedSetupOfficialCli;
|
|
102
|
-
if (pendingPiAuthTransaction)
|
|
103
|
-
throw new Error("official lark-cli must be resolved before the Pi credential transaction starts");
|
|
104
95
|
resolvedSetupOfficialCli = resolveOfficialCli({ env });
|
|
105
96
|
return resolvedSetupOfficialCli;
|
|
106
97
|
}
|
|
@@ -304,7 +295,7 @@ function openBrowser(url) {
|
|
|
304
295
|
}
|
|
305
296
|
}
|
|
306
297
|
async function runBindProcess(command, args) {
|
|
307
|
-
if (testFixture?.spawnSync
|
|
298
|
+
if (testFixture?.spawnSync) {
|
|
308
299
|
return spawnSync(command, [...args], { env: process.env, stdio: "inherit" }).status;
|
|
309
300
|
}
|
|
310
301
|
return await new Promise((resolve, reject) => {
|
|
@@ -336,7 +327,7 @@ async function runBindProcess(command, args) {
|
|
|
336
327
|
}).finally(() => { trackPendingChild(null); });
|
|
337
328
|
}
|
|
338
329
|
async function runBoundedCliProcess(command, args, env, label) {
|
|
339
|
-
if (testFixture?.spawnSync &&
|
|
330
|
+
if (testFixture?.spawnSync && process.env.LARKIN_TEST_ASYNC_IDENTITY !== "1") {
|
|
340
331
|
const result = spawnSync(command, [...args], { encoding: "utf8", env });
|
|
341
332
|
return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
|
|
342
333
|
}
|
|
@@ -643,128 +634,30 @@ Lark 必须用 --tenant lark:授权二维码是官方 /page/cli(begin 仍走
|
|
|
643
634
|
: commentSubscription === "none" || !priorSubscription
|
|
644
635
|
? { mode: "none", status: "safe-default", source: "setup-default", updatedAt: requestedAt }
|
|
645
636
|
: priorSubscription;
|
|
637
|
+
if (flag("--provider") || flag("--api-key") || flag("--base-url") || flag("--pi-distribution")) {
|
|
638
|
+
die("setup 不再接受 --provider/--api-key/--base-url;请安装并登录外部 pi、codex 或 claude");
|
|
639
|
+
}
|
|
646
640
|
const injectedAgentChoice = testFixture?.collectSetupAgentChoice;
|
|
647
641
|
if (!flag("--runtime") && (!testFixture || injectedAgentChoice || process.env.LARKIN_TEST_ENABLE_AGENT_CHOICE === "1")) {
|
|
648
642
|
const existing = larkinConfig.loadConfig(process.env).config.agents[id];
|
|
649
|
-
// The official resolver performs a synchronous login-shell probe. Resolve it
|
|
650
|
-
// exactly once before the credential heartbeat lock becomes active.
|
|
651
643
|
resolvedSetupOfficialCli = resolveOfficialCli({ env: process.env });
|
|
652
644
|
const questioner = injectedAgentChoice ? { ask: async () => "", secret: async () => "" } : terminalSetupQuestioner();
|
|
653
|
-
// One setup-owned transaction starts before status/logout and remains active
|
|
654
|
-
// through selection, login, bind, readiness, and the final setup commit.
|
|
655
|
-
pendingPiAuthTransaction = beginBuiltinPiCredentialTransaction(CFG_DIR, id);
|
|
656
|
-
const authServices = {
|
|
657
|
-
providers: async () => listOfficialPiAuthProviders(await createOfficialPiRegistryRuntime()),
|
|
658
|
-
status: async () => officialPiAuthStatus(await createOfficialPiCredentialRuntime(CFG_DIR, id)),
|
|
659
|
-
logout: async (providerId) => logoutOfficialPiProvider(await createOfficialPiLogoutRuntime(CFG_DIR, id), providerId),
|
|
660
|
-
report: (message) => say(message),
|
|
661
|
-
};
|
|
662
645
|
try {
|
|
663
|
-
const requested = injectedAgentChoice
|
|
664
|
-
? await injectedAgentChoice()
|
|
665
|
-
: await collectSetupAgentChoice(questioner, existing, authServices);
|
|
666
646
|
const choice = injectedAgentChoice
|
|
667
|
-
?
|
|
668
|
-
: await
|
|
669
|
-
runtime: "pi", agentId: id, cwd: path.join(CFG_DIR, "agents", id),
|
|
670
|
-
env: { ...process.env, LARKIN_CONFIG_DIR: CFG_DIR, LARKIN_PI_DISTRIBUTION: "external" },
|
|
671
|
-
}), (message) => say(`! ${message}`), authServices);
|
|
647
|
+
? await injectedAgentChoice()
|
|
648
|
+
: await collectSetupAgentChoice(questioner, existing);
|
|
672
649
|
if (choice) {
|
|
673
|
-
|
|
674
|
-
if (
|
|
675
|
-
|
|
676
|
-
const official = choice.preset === "official" ? choice : null;
|
|
677
|
-
const configured = official ? null : configureBuiltinPiProviderModel(CFG_DIR, id, choice);
|
|
678
|
-
const providerId = official?.providerId || configured.provider;
|
|
679
|
-
const authType = official?.authType || "api_key";
|
|
680
|
-
let piRuntime;
|
|
681
|
-
try {
|
|
682
|
-
say(`正在通过捆绑官方 Pi 登录 ${providerId}(${authType})…`);
|
|
683
|
-
piRuntime = await createOfficialPiModelRuntime(CFG_DIR, id);
|
|
684
|
-
await runOfficialPiLogin(piRuntime, providerId, authType, createOfficialPiAuthInteraction({ questioner, report: (message) => say(message), openUrl: openBrowser }));
|
|
685
|
-
}
|
|
686
|
-
catch {
|
|
687
|
-
pendingPiAuthTransaction.rollback();
|
|
688
|
-
pendingPiAuthTransaction = null;
|
|
689
|
-
throw new Error(`官方 Pi ${providerId} 登录失败或已取消;credential/config 未修改`);
|
|
690
|
-
}
|
|
691
|
-
if (process.env.LARKIN_TEST_SKIP_BUILTIN_PI_PROVIDER_TURN !== "1") {
|
|
692
|
-
say("正在验证内置 Pi provider(受控单轮,不发送飞书(Lark)消息)…");
|
|
693
|
-
try {
|
|
694
|
-
await verifyOfficialPiProviderTurn(piRuntime, choice.model);
|
|
695
|
-
}
|
|
696
|
-
catch {
|
|
697
|
-
pendingPiAuthTransaction.rollback();
|
|
698
|
-
pendingPiAuthTransaction = null;
|
|
699
|
-
throw new Error(`官方 Pi ${providerId} readiness 失败;credential/config 未修改`);
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
serializedChoice = { ...choice, authCompleted: true, readinessCompleted: true };
|
|
704
|
-
}
|
|
650
|
+
const missing = missingRuntimeInstallMessage(choice.runtime, process.env);
|
|
651
|
+
if (missing)
|
|
652
|
+
die(missing);
|
|
705
653
|
temporaryAgentChoiceFile = path.join(CFG_DIR, `.setup-agent-choice-${process.pid}-${Date.now()}.json`);
|
|
706
|
-
fs.writeFileSync(temporaryAgentChoiceFile, `${JSON.stringify(
|
|
654
|
+
fs.writeFileSync(temporaryAgentChoiceFile, `${JSON.stringify({ runtime: choice.runtime })}\n`, { mode: 0o600, flag: "wx" });
|
|
707
655
|
}
|
|
708
656
|
}
|
|
709
657
|
finally {
|
|
710
658
|
questioner.close?.();
|
|
711
659
|
}
|
|
712
660
|
}
|
|
713
|
-
// ── 非交互参数化内置 Pi(builtin-pi 是默认 runtime 类型)──
|
|
714
|
-
// --pi-distribution builtin:需 --provider <id> + --api-key <key>(或 --base-url 自定义端点)。
|
|
715
|
-
const piDistributionFlag = flag("--pi-distribution");
|
|
716
|
-
const setupProvider = flag("--provider");
|
|
717
|
-
const setupApiKey = flag("--api-key");
|
|
718
|
-
const setupBaseUrl = flag("--base-url");
|
|
719
|
-
const setupModel = flag("--model");
|
|
720
|
-
if (piDistributionFlag === "builtin") {
|
|
721
|
-
if (!setupProvider && !setupBaseUrl) {
|
|
722
|
-
throw new Error(`builtin-pi 需要 --provider <id>(${PI_PROVIDER_PRESETS.map((p) => p.id).join("|")}|custom)或 --base-url;或改用 --runtime pi 使用已有 pi 环境`);
|
|
723
|
-
}
|
|
724
|
-
if (!setupApiKey)
|
|
725
|
-
throw new Error("builtin-pi 需要 --api-key;或改用 --runtime pi 使用已有 pi 登录");
|
|
726
|
-
// 自定义网关(--base-url)走 custom 预设:pi 会把 baseUrl 作为 provider 端点写入配置,
|
|
727
|
-
// 而不是用预设厂商目录(否则会打到预设默认地址,如 api.openai.com)。
|
|
728
|
-
const presetId = setupBaseUrl ? "custom" : (setupProvider ?? "custom");
|
|
729
|
-
if (presetId === "custom" && !setupModel)
|
|
730
|
-
throw new Error("custom base-url 需要 --model <模型名>");
|
|
731
|
-
const presetDef = PI_PROVIDER_PRESETS.find((p) => p.id === presetId);
|
|
732
|
-
if (!presetDef && !setupBaseUrl)
|
|
733
|
-
throw new Error(`未知 provider \`${presetId}\`;可选:${PI_PROVIDER_PRESETS.map((p) => p.id).join(" | ")} | custom`);
|
|
734
|
-
const raw = {
|
|
735
|
-
distribution: "builtin",
|
|
736
|
-
preset: presetId,
|
|
737
|
-
model: setupModel ?? presetDef?.defaultModel ?? "",
|
|
738
|
-
// 显式 --base-url 优先于预设默认值(自定义网关场景,如 opencode)。
|
|
739
|
-
...(setupBaseUrl ? { baseUrl: validatePiBaseUrl(setupBaseUrl) } : presetDef ? { baseUrl: presetDef.baseUrl } : {}),
|
|
740
|
-
};
|
|
741
|
-
if (setupModel && raw.baseUrl) {
|
|
742
|
-
// Owner 决策:模型名必须来自 provider 的权威可用列表,输错即报错,不做运行时猜测。
|
|
743
|
-
// 网络超时/不可达时不阻塞 setup(null),运行时对账会严格兜底。
|
|
744
|
-
const availableIds = await listProviderModels(raw.baseUrl, setupApiKey);
|
|
745
|
-
if (availableIds !== null) {
|
|
746
|
-
const matched = availableIds.some((id) => id === setupModel || id.endsWith(`/${setupModel}`));
|
|
747
|
-
if (!matched) {
|
|
748
|
-
const preview = availableIds.slice(0, 12).join(", ") + (availableIds.length > 12 ? ", …" : "");
|
|
749
|
-
throw new Error(`未知模型 ${setupModel};provider 可用模型:[${preview || "无"}]`);
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
else {
|
|
753
|
-
say("[setup] 网络暂不可达,跳过 /models 预校验;运行时将对模型严格对账");
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
stageBuiltinPiProvider(CFG_DIR, id, { ...raw, apiKey: setupApiKey });
|
|
757
|
-
// 选择文件写入解析后的全称模型(custom 预设为 larkin-custom/<model>):
|
|
758
|
-
// pi 运行时按 provider 前缀解析凭证,裸模型名会回落到默认 provider(deepseek)
|
|
759
|
-
// 导致「No API key found for deepseek」。
|
|
760
|
-
const validated = validateBuiltinPiProviderSelection({ ...raw, apiKey: setupApiKey });
|
|
761
|
-
temporaryAgentChoiceFile = path.join(CFG_DIR, `.setup-agent-choice-${process.pid}-${Date.now()}.json`);
|
|
762
|
-
fs.writeFileSync(temporaryAgentChoiceFile, `${JSON.stringify({ ...raw, runtime: "pi", model: validated.model, authCompleted: true, readinessCompleted: true })}\n`, { mode: 0o600, flag: "wx" });
|
|
763
|
-
say(`[setup 2/5] ✓ 内置 Pi provider 已配置(${presetId}${setupBaseUrl ? " / custom" : ""})`);
|
|
764
|
-
}
|
|
765
|
-
else if (piDistributionFlag === "external" && (setupProvider || setupApiKey || setupBaseUrl)) {
|
|
766
|
-
throw new Error("pi 使用已有 pi 环境与登录,不接受 --provider/--api-key/--base-url");
|
|
767
|
-
}
|
|
768
661
|
const stagedBotFile = path.join(botsDir, `.${id}.${process.pid}.tmp`);
|
|
769
662
|
try {
|
|
770
663
|
fs.writeFileSync(stagedBotFile, `${JSON.stringify({
|
|
@@ -811,13 +704,14 @@ Lark 必须用 --tenant lark:授权二维码是官方 /page/cli(begin 仍走
|
|
|
811
704
|
const runtime = flag("--runtime");
|
|
812
705
|
if (runtime)
|
|
813
706
|
bindArgs.push("--runtime", runtime);
|
|
707
|
+
const model = flag("--model");
|
|
708
|
+
if (model)
|
|
709
|
+
bindArgs.push("--model", model);
|
|
814
710
|
if (temporaryAgentChoiceFile)
|
|
815
711
|
bindArgs.push("--selection-file", temporaryAgentChoiceFile);
|
|
816
712
|
const bindSpec = internalCommandSpec("setup-bind", bindArgs, process.env);
|
|
817
713
|
const bindStatus = await runBindProcess(bindSpec.command, bindSpec.args);
|
|
818
714
|
if (bindStatus !== 0) {
|
|
819
|
-
pendingPiAuthTransaction?.rollback();
|
|
820
|
-
pendingPiAuthTransaction = null;
|
|
821
715
|
die("新 bot 凭证已发布但 Agent 绑定失败;权威凭证状态已保留,请重跑 larkin setup 并在网页中重新选择机器人");
|
|
822
716
|
}
|
|
823
717
|
try {
|
|
@@ -943,8 +837,6 @@ Lark 必须用 --tenant lark:授权二维码是官方 /page/cli(begin 仍走
|
|
|
943
837
|
die("Agent 绑定与新 bot 凭证已保留,但 setup 结果写入失败;请重跑 larkin setup 并在网页中重新选择机器人");
|
|
944
838
|
}
|
|
945
839
|
}
|
|
946
|
-
pendingPiAuthTransaction?.commit();
|
|
947
|
-
pendingPiAuthTransaction = null;
|
|
948
840
|
}
|
|
949
841
|
if (path.resolve(process.argv[1] || "") === path.resolve(fileURLToPath(import.meta.url))) {
|
|
950
842
|
main().catch((error) => { if (!requestedShutdown)
|
|
@@ -1,92 +1,66 @@
|
|
|
1
1
|
import { createInterface } from "node:readline/promises";
|
|
2
2
|
import { stdin, stdout } from "node:process";
|
|
3
|
-
import { toUserRuntime } from "../runtime/user-runtime.mjs";
|
|
4
|
-
import {
|
|
3
|
+
import { RUNTIME_OPTIONS, toUserRuntime } from "../runtime/user-runtime.mjs";
|
|
4
|
+
import { resolveRuntimeExecutable, runtimeInstallNextAction } from "../runtime/runtime-readiness.mjs";
|
|
5
|
+
function runtimeCommand(runtime, env) {
|
|
6
|
+
if (runtime === "pi")
|
|
7
|
+
return env.LARKIN_PI_COMMAND || "pi";
|
|
8
|
+
if (runtime === "codex")
|
|
9
|
+
return env.LARKIN_CODEX_COMMAND || "codex";
|
|
10
|
+
return env.LARKIN_CLAUDE_COMMAND || "claude";
|
|
11
|
+
}
|
|
12
|
+
export function listRuntimeInstallStatuses(env = process.env) {
|
|
13
|
+
return RUNTIME_OPTIONS.map((runtime) => {
|
|
14
|
+
if (resolveRuntimeExecutable(runtimeCommand(runtime, env), env))
|
|
15
|
+
return { runtime, installed: true };
|
|
16
|
+
return {
|
|
17
|
+
runtime,
|
|
18
|
+
installed: false,
|
|
19
|
+
reason: `${runtime} is not installed`,
|
|
20
|
+
nextAction: runtimeInstallNextAction(runtime),
|
|
21
|
+
};
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
export function missingRuntimeInstallMessage(runtime, env = process.env) {
|
|
25
|
+
if (runtime !== "pi" && runtime !== "codex" && runtime !== "claude")
|
|
26
|
+
return null;
|
|
27
|
+
const status = listRuntimeInstallStatuses(env).find((entry) => entry.runtime === runtime);
|
|
28
|
+
if (!status || status.installed)
|
|
29
|
+
return null;
|
|
30
|
+
return `${status.reason};${status.nextAction}`;
|
|
31
|
+
}
|
|
32
|
+
const RUNTIME_LABELS = {
|
|
33
|
+
pi: "pi(本机官方 pi CLI)",
|
|
34
|
+
codex: "Codex",
|
|
35
|
+
claude: "Claude Code",
|
|
36
|
+
};
|
|
5
37
|
function number(value, fallback, max) {
|
|
6
38
|
const parsed = value.trim() ? Number(value.trim()) : fallback;
|
|
7
39
|
if (!Number.isInteger(parsed) || parsed < 1 || parsed > max)
|
|
8
40
|
throw new Error(`请选择 1-${max}`);
|
|
9
41
|
return parsed;
|
|
10
42
|
}
|
|
11
|
-
|
|
12
|
-
const lines =
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const status = await services.status();
|
|
18
|
-
if (status.length === 0)
|
|
19
|
-
services.report("尚无已配置的官方 Pi credential");
|
|
20
|
-
else
|
|
21
|
-
status.forEach((entry, index) => services.report(` ${index + 1}. ${entry.providerName} (${entry.providerId}) — ${entry.credentialType}/${entry.source}${entry.stored ? ",已存储" : ",ambient"}`));
|
|
22
|
-
const answer = (await questioner.ask("输入要 logout 的序号;直接回车返回:")).trim();
|
|
23
|
-
if (answer) {
|
|
24
|
-
const selected = number(answer, 0, status.length);
|
|
25
|
-
await services.logout(status[selected - 1].providerId);
|
|
26
|
-
services.report(`已退出 ${status[selected - 1].providerName};未修改其他 provider`);
|
|
27
|
-
}
|
|
28
|
-
return collectBuiltinPiChoice(questioner, services);
|
|
29
|
-
}
|
|
30
|
-
if (providerChoice === 6) {
|
|
31
|
-
if (!services)
|
|
32
|
-
throw new Error("当前 setup 上下文无法读取官方 Pi auth registry");
|
|
33
|
-
const providers = await services.providers();
|
|
34
|
-
const methods = providers.flatMap((provider) => provider.methods.map((method) => ({ provider, method })));
|
|
35
|
-
if (methods.length === 0)
|
|
36
|
-
throw new Error("捆绑官方 Pi auth registry 没有可交互登录方式");
|
|
37
|
-
const methodLines = methods.map(({ provider, method }, index) => ` ${index + 1}. ${provider.name} — ${method.name} [${method.type}]`).join("\n");
|
|
38
|
-
const methodChoice = number(await questioner.ask(`选择官方 Pi 登录方式:\n${methodLines}\n> `), 1, methods.length);
|
|
39
|
-
const selected = methods[methodChoice - 1];
|
|
40
|
-
const defaultModel = selected.provider.models[0] || "";
|
|
41
|
-
const model = (await questioner.ask(`模型 ID${defaultModel ? `(默认 ${defaultModel})` : "(provider/model)"}:`)).trim() || defaultModel;
|
|
42
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[A-Za-z0-9][A-Za-z0-9._:@+\/-]{0,255}$/.test(model))
|
|
43
|
-
throw new Error("模型 ID 必须是安全的 provider/model");
|
|
44
|
-
if (!model.startsWith(`${selected.provider.id}/`))
|
|
45
|
-
throw new Error(`模型 ID 必须属于 ${selected.provider.id}`);
|
|
46
|
-
return { runtime: "pi", distribution: "builtin", preset: "official", providerId: selected.provider.id,
|
|
47
|
-
authType: selected.method.type, model };
|
|
48
|
-
}
|
|
49
|
-
const preset = providerChoice === 5 ? "custom" : PI_PROVIDER_PRESETS[providerChoice - 1].id;
|
|
50
|
-
const selected = preset === "custom" ? null : PI_PROVIDER_PRESETS.find((candidate) => candidate.id === preset);
|
|
51
|
-
const baseUrl = preset === "custom" ? await questioner.ask("Base URL(https;localhost 可用 http):") : selected.baseUrl;
|
|
52
|
-
const model = (await questioner.ask(`模型 ID${selected ? `(默认 ${selected.defaultModel})` : ""}:`)).trim() || selected?.defaultModel || "";
|
|
53
|
-
const validated = resolveBuiltinPiProviderSetupSelection({ distribution: "builtin", preset, model, ...(baseUrl ? { baseUrl } : {}) });
|
|
54
|
-
return { runtime: "pi", distribution: "builtin", preset, model: validated.model, ...(preset === "custom" ? { baseUrl: validated.baseUrl } : {}) };
|
|
43
|
+
function formatRuntimeMenu(statuses) {
|
|
44
|
+
const lines = statuses.map((status, index) => {
|
|
45
|
+
const mark = status.installed ? "installed" : "not installed";
|
|
46
|
+
return ` ${index + 1}. ${RUNTIME_LABELS[status.runtime]} [${mark}]`;
|
|
47
|
+
});
|
|
48
|
+
return `选择 Agent:\n${lines.join("\n")}\n> `;
|
|
55
49
|
}
|
|
56
|
-
export async function collectSetupAgentChoice(questioner, prior,
|
|
50
|
+
export async function collectSetupAgentChoice(questioner, prior, statuses = listRuntimeInstallStatuses()) {
|
|
57
51
|
if (prior) {
|
|
58
|
-
const keep = (await questioner.ask(`已有 Agent:${toUserRuntime(prior.runtime
|
|
52
|
+
const keep = (await questioner.ask(`已有 Agent:${toUserRuntime(prior.runtime)}/${prior.model}。直接回车保留;输入 c 才修改:`)).trim().toLowerCase();
|
|
59
53
|
if (!keep)
|
|
60
54
|
return null;
|
|
61
55
|
if (keep !== "c")
|
|
62
56
|
throw new Error("请输入 c 修改,或直接回车保留现有配置");
|
|
63
57
|
}
|
|
64
|
-
const runtimeChoice = number(await questioner.ask(
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
return { runtime: "claude" };
|
|
69
|
-
if (runtimeChoice === 2)
|
|
70
|
-
return { runtime: "pi", distribution: "external" };
|
|
71
|
-
return collectBuiltinPiChoice(questioner, services);
|
|
72
|
-
}
|
|
73
|
-
export async function recoverUnavailableExternalPi(initial, questioner, probe, report = () => { }, services) {
|
|
74
|
-
let choice = initial;
|
|
75
|
-
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
|
76
|
-
if (choice?.runtime !== "pi" || choice.distribution !== "external")
|
|
77
|
-
return choice;
|
|
78
|
-
const readiness = await probe();
|
|
79
|
-
if (readiness.state === "ready")
|
|
80
|
-
return choice;
|
|
81
|
-
report(`外置 Pi ${readiness.state}:${readiness.reason || "prerequisite unavailable"};${readiness.nextAction || "可切换到 builtin-pi"}`);
|
|
82
|
-
const action = number(await questioner.ask("外置 Pi 当前不可用:\n 1. 切换到 builtin-pi(推荐)\n 2. 重新选择 Agent\n 3. 取消 setup(保留原配置)\n> "), 1, 3);
|
|
83
|
-
if (action === 1)
|
|
84
|
-
return collectBuiltinPiChoice(questioner, services);
|
|
85
|
-
if (action === 3)
|
|
86
|
-
throw new Error("setup 已取消;未修改 Agent/config");
|
|
87
|
-
choice = await collectSetupAgentChoice(questioner, undefined, services);
|
|
58
|
+
const runtimeChoice = number(await questioner.ask(formatRuntimeMenu(statuses)), 1, statuses.length);
|
|
59
|
+
const selected = statuses[runtimeChoice - 1];
|
|
60
|
+
if (!selected.installed) {
|
|
61
|
+
throw new Error(`${selected.reason};${selected.nextAction}`);
|
|
88
62
|
}
|
|
89
|
-
|
|
63
|
+
return { runtime: selected.runtime };
|
|
90
64
|
}
|
|
91
65
|
export function terminalSetupQuestioner() {
|
|
92
66
|
let rl = null;
|
|
@@ -150,7 +124,7 @@ export function terminalSetupQuestioner() {
|
|
|
150
124
|
const onData = (chunk) => {
|
|
151
125
|
for (const byte of chunk) {
|
|
152
126
|
if (byte === 3)
|
|
153
|
-
return finish(new Error("setup
|
|
127
|
+
return finish(new Error("setup 已取消;未保存输入"));
|
|
154
128
|
if (byte === 10 || byte === 13)
|
|
155
129
|
return finish();
|
|
156
130
|
if (byte === 8 || byte === 127) {
|