@bubx/cli 0.0.0-stage → 0.1.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/README.md +53 -2
- package/dist/bot-server.js +2197 -0
- package/dist/main.js +2135 -0
- package/package.json +45 -4
package/dist/main.js
ADDED
|
@@ -0,0 +1,2135 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __esm = (fn, res, err) => function __init() {
|
|
5
|
+
if (err) throw err[0];
|
|
6
|
+
try {
|
|
7
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
8
|
+
} catch (e) {
|
|
9
|
+
throw err = [e], e;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
var __export = (target, all) => {
|
|
13
|
+
for (var name in all)
|
|
14
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// ../../packages/agent-adapters/agy/dist/local.js
|
|
18
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
19
|
+
import { promisify as promisify2 } from "node:util";
|
|
20
|
+
function agyEnvironment() {
|
|
21
|
+
return Object.fromEntries(environmentKeys2.map((key) => [key, process.env[key]]));
|
|
22
|
+
}
|
|
23
|
+
function catalogError(error, cancelled2, timedOut) {
|
|
24
|
+
if (cancelled2)
|
|
25
|
+
return new Error("Antigravity model lookup was cancelled.");
|
|
26
|
+
if (timedOut)
|
|
27
|
+
return new Error("Antigravity model lookup timed out.");
|
|
28
|
+
const failure = error;
|
|
29
|
+
if (failure.code === "ENOENT")
|
|
30
|
+
return new Error("agy was not found on PATH.");
|
|
31
|
+
if (/authentication required|not authenticated|not logged in|sign.?in required/i.test(`${failure.stderr ?? ""}
|
|
32
|
+
${failure.stdout ?? ""}`)) {
|
|
33
|
+
return new Error("Antigravity is not logged in. Run agy and sign in first.");
|
|
34
|
+
}
|
|
35
|
+
return new Error("Could not read the local Antigravity model catalog.");
|
|
36
|
+
}
|
|
37
|
+
async function agyLoginStatus(cwd, signal) {
|
|
38
|
+
try {
|
|
39
|
+
await listAgyModels(cwd, signal);
|
|
40
|
+
return "signed-in";
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error instanceof Error && error.message === "agy was not found on PATH.")
|
|
43
|
+
return "not-installed";
|
|
44
|
+
if (error instanceof Error && error.message.startsWith("Antigravity is not logged in."))
|
|
45
|
+
return "signed-out";
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function listAgyModels(cwd, signal) {
|
|
50
|
+
const timeout = AbortSignal.timeout(timeoutMs2);
|
|
51
|
+
const deadline = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
52
|
+
const options = {
|
|
53
|
+
cwd,
|
|
54
|
+
env: agyEnvironment(),
|
|
55
|
+
signal: deadline,
|
|
56
|
+
maxBuffer: 1048576
|
|
57
|
+
};
|
|
58
|
+
try {
|
|
59
|
+
const { stdout } = await run2("agy", ["models"], options);
|
|
60
|
+
const current = await run2("agy", ["--print", "/model", "--output-format", "json"], options);
|
|
61
|
+
const selection = JSON.parse(current.stdout);
|
|
62
|
+
const selectedModel = selection.command?.data?.id;
|
|
63
|
+
const models = stdout.split("\n").filter((line) => line.trim()).map((line) => {
|
|
64
|
+
const separator = line.indexOf(" ");
|
|
65
|
+
if (separator < 1 || !line.slice(separator + 1).trim())
|
|
66
|
+
throw new Error("Antigravity returned an invalid model catalog.");
|
|
67
|
+
const id = line.slice(0, separator);
|
|
68
|
+
return {
|
|
69
|
+
id,
|
|
70
|
+
displayName: line.slice(separator + 1).trim(),
|
|
71
|
+
isDefault: id === selectedModel,
|
|
72
|
+
// Native slugs include reasoning variants; do not invent extra effort options.
|
|
73
|
+
defaultReasoningEffort: "default",
|
|
74
|
+
supportedReasoningEfforts: ["default"]
|
|
75
|
+
};
|
|
76
|
+
});
|
|
77
|
+
if (!models.length)
|
|
78
|
+
throw new Error("The local Antigravity account returned no models.");
|
|
79
|
+
return models;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error instanceof Error && (error.message === "Antigravity returned an invalid model catalog." || error.message === "The local Antigravity account returned no models."))
|
|
82
|
+
throw error;
|
|
83
|
+
throw catalogError(error, signal?.aborted ?? false, timeout.aborted);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
var run2, timeoutMs2, environmentKeys2, supportedAgyPermissions;
|
|
87
|
+
var init_local = __esm({
|
|
88
|
+
"../../packages/agent-adapters/agy/dist/local.js"() {
|
|
89
|
+
"use strict";
|
|
90
|
+
run2 = promisify2(execFile2);
|
|
91
|
+
timeoutMs2 = 3e4;
|
|
92
|
+
environmentKeys2 = [
|
|
93
|
+
"HOME",
|
|
94
|
+
"PATH",
|
|
95
|
+
"USER",
|
|
96
|
+
"TMPDIR",
|
|
97
|
+
"XDG_CONFIG_HOME",
|
|
98
|
+
"XDG_DATA_HOME",
|
|
99
|
+
"LANG",
|
|
100
|
+
"HTTPS_PROXY",
|
|
101
|
+
"HTTP_PROXY",
|
|
102
|
+
"ALL_PROXY",
|
|
103
|
+
"NO_PROXY",
|
|
104
|
+
"https_proxy",
|
|
105
|
+
"http_proxy",
|
|
106
|
+
"all_proxy",
|
|
107
|
+
"no_proxy",
|
|
108
|
+
"SSL_CERT_FILE",
|
|
109
|
+
"SSL_CERT_DIR"
|
|
110
|
+
];
|
|
111
|
+
supportedAgyPermissions = ["read-only", "full-access"];
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
// ../../packages/agent-adapters/agy/dist/text.js
|
|
116
|
+
var init_text = __esm({
|
|
117
|
+
"../../packages/agent-adapters/agy/dist/text.js"() {
|
|
118
|
+
"use strict";
|
|
119
|
+
init_local();
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// ../../packages/agent-adapters/agy/dist/index.js
|
|
124
|
+
var agyDescriptor;
|
|
125
|
+
var init_dist = __esm({
|
|
126
|
+
"../../packages/agent-adapters/agy/dist/index.js"() {
|
|
127
|
+
"use strict";
|
|
128
|
+
init_local();
|
|
129
|
+
init_text();
|
|
130
|
+
agyDescriptor = {
|
|
131
|
+
id: "agy",
|
|
132
|
+
name: "Antigravity",
|
|
133
|
+
integrationStatus: "ready",
|
|
134
|
+
capabilities: {
|
|
135
|
+
textStreaming: "unsupported",
|
|
136
|
+
toolEvents: "unsupported",
|
|
137
|
+
approvals: "unsupported",
|
|
138
|
+
cancellation: process.platform === "win32" ? "unverified" : "supported",
|
|
139
|
+
sessionResume: "unsupported"
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
// src/start-prompts.ts
|
|
146
|
+
var start_prompts_exports = {};
|
|
147
|
+
__export(start_prompts_exports, {
|
|
148
|
+
displayBotState: () => displayBotState,
|
|
149
|
+
displayWorkspace: () => displayWorkspace,
|
|
150
|
+
promptBotStart: () => promptBotStart,
|
|
151
|
+
selectBot: () => selectBot
|
|
152
|
+
});
|
|
153
|
+
import { realpathSync as realpathSync2, statSync as statSync2 } from "node:fs";
|
|
154
|
+
import { homedir as homedir2 } from "node:os";
|
|
155
|
+
import { join as join3, resolve as resolve2 } from "node:path";
|
|
156
|
+
import { stripVTControlCharacters } from "node:util";
|
|
157
|
+
import {
|
|
158
|
+
autocomplete,
|
|
159
|
+
cancel,
|
|
160
|
+
isCancel,
|
|
161
|
+
log,
|
|
162
|
+
note,
|
|
163
|
+
select,
|
|
164
|
+
text
|
|
165
|
+
} from "@clack/prompts";
|
|
166
|
+
function terminalLabel(value) {
|
|
167
|
+
return stripVTControlCharacters(value).replace(new RegExp("\\p{Cc}", "gu"), " ");
|
|
168
|
+
}
|
|
169
|
+
function displayWorkspace(path) {
|
|
170
|
+
if (!path) return "\u2014";
|
|
171
|
+
const home = homedir2();
|
|
172
|
+
if (path === home) return "~";
|
|
173
|
+
return terminalLabel(
|
|
174
|
+
path.startsWith(home + "/") ? "~" + path.slice(home.length) : path
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
function displayBotState(state) {
|
|
178
|
+
return Object.hasOwn(botStates, state) ? botStates[state] : terminalLabel(state);
|
|
179
|
+
}
|
|
180
|
+
function requireTerminal(command) {
|
|
181
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
182
|
+
throw new Error("\u8BF7\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u4E2D\u8FD0\u884C " + command + "\u3002");
|
|
183
|
+
}
|
|
184
|
+
async function selectBot(rows, purpose) {
|
|
185
|
+
if (rows.length === 0) return purpose === "start" ? "new" : void 0;
|
|
186
|
+
const command = purpose === "stop" ? "bubai stop" : "bubai bot " + purpose;
|
|
187
|
+
requireTerminal(command);
|
|
188
|
+
const entries = rows.map((row) => ({
|
|
189
|
+
value: row,
|
|
190
|
+
label: [
|
|
191
|
+
terminalLabel(row.name),
|
|
192
|
+
purpose === "start" ? row.adapter === "codex" || row.adapter === "agy" ? adapterNames[row.adapter] : row.adapter ?? "\u2014" : "",
|
|
193
|
+
displayWorkspace(row.workspace),
|
|
194
|
+
displayBotState(row.state)
|
|
195
|
+
].filter(Boolean).join(" ")
|
|
196
|
+
}));
|
|
197
|
+
const selection = await select({
|
|
198
|
+
message: selectionMessages[purpose],
|
|
199
|
+
options: [
|
|
200
|
+
...entries.map(
|
|
201
|
+
(entry) => entries.filter(({ label }) => label === entry.label).length > 1 ? { ...entry, label: entry.label + " " + entry.value.id } : entry
|
|
202
|
+
),
|
|
203
|
+
...purpose === "start" ? [{ value: "new", label: "\u65B0\u5EFA Bot" }] : [],
|
|
204
|
+
{ value: "quit", label: "\u9000\u51FA" }
|
|
205
|
+
]
|
|
206
|
+
});
|
|
207
|
+
if (isCancel(selection) || selection === "quit") {
|
|
208
|
+
cancel("\u5DF2\u53D6\u6D88\u3002");
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
return selection;
|
|
212
|
+
}
|
|
213
|
+
function workspacePath(value, cwd) {
|
|
214
|
+
if (!value) throw new Error("\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u76EE\u5F55\u3002");
|
|
215
|
+
const path = value === "~" ? homedir2() : value.startsWith("~/") ? join3(homedir2(), value.slice(2)) : resolve2(cwd, value);
|
|
216
|
+
try {
|
|
217
|
+
const directory2 = realpathSync2(path);
|
|
218
|
+
if (statSync2(directory2).isDirectory()) return directory2;
|
|
219
|
+
} catch {
|
|
220
|
+
}
|
|
221
|
+
throw new Error("\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u5B58\u5728\u4E14\u53EF\u8BBF\u95EE\u7684\u76EE\u5F55\u3002");
|
|
222
|
+
}
|
|
223
|
+
async function askWorkspace(initialValue, cwd) {
|
|
224
|
+
const value = await text({
|
|
225
|
+
message: "\u8F93\u5165\u5DE5\u4F5C\u533A\u76EE\u5F55",
|
|
226
|
+
initialValue,
|
|
227
|
+
validate(input) {
|
|
228
|
+
try {
|
|
229
|
+
workspacePath(input ?? "", cwd);
|
|
230
|
+
} catch (error) {
|
|
231
|
+
return errorMessage(error);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
if (isCancel(value)) return value;
|
|
236
|
+
return workspacePath(value, cwd);
|
|
237
|
+
}
|
|
238
|
+
function errorMessage(error) {
|
|
239
|
+
return error instanceof Error ? error.message : String(error);
|
|
240
|
+
}
|
|
241
|
+
function cancelled() {
|
|
242
|
+
cancel("\u5DF2\u53D6\u6D88\u542F\u52A8\u3002");
|
|
243
|
+
return void 0;
|
|
244
|
+
}
|
|
245
|
+
function adapterPrompt(initialValue = "codex") {
|
|
246
|
+
return select({
|
|
247
|
+
message: "\u9009\u62E9 Adapter",
|
|
248
|
+
initialValue,
|
|
249
|
+
options: [
|
|
250
|
+
{ value: "codex", label: "Codex" },
|
|
251
|
+
{ value: "agy", label: "agy\uFF08Antigravity\uFF09" }
|
|
252
|
+
]
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
function allowedPermissions(adapter) {
|
|
256
|
+
return adapter === "agy" ? supportedAgyPermissions : ["read-only", "workspace-write", "full-access"];
|
|
257
|
+
}
|
|
258
|
+
function effortLabel(value) {
|
|
259
|
+
return value === "default" ? "\u6A21\u578B\u9ED8\u8BA4" : value;
|
|
260
|
+
}
|
|
261
|
+
function showSummary(draft, models) {
|
|
262
|
+
const currentModel = models.find((model) => model.id === draft.model);
|
|
263
|
+
const modelSuffix = currentModel?.isDefault ? "\uFF08\u63A8\u8350\uFF09" : "";
|
|
264
|
+
const effortSuffix = draft.reasoningEffort !== "default" && currentModel?.defaultReasoningEffort === draft.reasoningEffort ? "\uFF08\u6A21\u578B\u9ED8\u8BA4\uFF09" : "";
|
|
265
|
+
note(
|
|
266
|
+
[
|
|
267
|
+
"Bot " + terminalLabel(draft.name),
|
|
268
|
+
`\u5DE5\u4F5C\u533A ${terminalLabel(draft.workspace)}`,
|
|
269
|
+
`Adapter ${adapterNames[draft.adapter]}`,
|
|
270
|
+
`\u6A21\u578B ${draft.model}${modelSuffix}`,
|
|
271
|
+
`\u63A8\u7406\u5F3A\u5EA6 ${effortLabel(draft.reasoningEffort)}${effortSuffix}`,
|
|
272
|
+
`\u6743\u9650 ${permissions[draft.permission].label}`,
|
|
273
|
+
...draft.permission === "full-access" ? [
|
|
274
|
+
`${adapterNames[draft.adapter]} \u81EA\u52A8\u6279\u51C6\u5DE5\u5177\u8C03\u7528\uFF0C\u6587\u4EF6\u8BBF\u95EE\u53EF\u8D85\u51FA\u5DE5\u4F5C\u533A\u3002`
|
|
275
|
+
] : []
|
|
276
|
+
].join("\n"),
|
|
277
|
+
"Bot \u914D\u7F6E"
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
async function promptBotStart({
|
|
281
|
+
cwd,
|
|
282
|
+
name: existingName,
|
|
283
|
+
saved,
|
|
284
|
+
loadModels
|
|
285
|
+
}) {
|
|
286
|
+
requireTerminal("bubai bot start");
|
|
287
|
+
let name;
|
|
288
|
+
let workspace;
|
|
289
|
+
if (existingName === void 0) {
|
|
290
|
+
const input = await text({
|
|
291
|
+
message: "\u8F93\u5165 Bot \u540D\u79F0",
|
|
292
|
+
placeholder: "\u4F8B\u5982 \u524D\u7AEF Bot",
|
|
293
|
+
validate(value) {
|
|
294
|
+
const trimmed = value?.trim() ?? "";
|
|
295
|
+
if (!trimmed || trimmed.length > 100 || new RegExp("\\p{Cc}", "u").test(trimmed))
|
|
296
|
+
return "\u8BF7\u8F93\u5165 1 \u5230 100 \u4E2A\u5B57\u7B26\u7684 Bot \u540D\u79F0\u3002";
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
if (isCancel(input)) return cancelled();
|
|
300
|
+
name = input.trim();
|
|
301
|
+
const selected = await askWorkspace(cwd, cwd);
|
|
302
|
+
if (isCancel(selected)) return cancelled();
|
|
303
|
+
workspace = selected;
|
|
304
|
+
} else {
|
|
305
|
+
name = existingName;
|
|
306
|
+
try {
|
|
307
|
+
workspace = workspacePath(saved?.workspace ?? cwd, cwd);
|
|
308
|
+
} catch (error) {
|
|
309
|
+
log.warn(errorMessage(error));
|
|
310
|
+
const selected = await askWorkspace(saved?.workspace ?? cwd, cwd);
|
|
311
|
+
if (isCancel(selected)) return cancelled();
|
|
312
|
+
workspace = selected;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
const initialAdapter = saved?.adapter ?? await adapterPrompt();
|
|
316
|
+
if (isCancel(initialAdapter)) return cancelled();
|
|
317
|
+
let adapter = initialAdapter;
|
|
318
|
+
let models;
|
|
319
|
+
let recommended;
|
|
320
|
+
for (; ; ) {
|
|
321
|
+
try {
|
|
322
|
+
models = await loadModels(adapter, workspace);
|
|
323
|
+
const model = models.find((model2) => model2.isDefault) ?? models[0];
|
|
324
|
+
if (!model)
|
|
325
|
+
throw new Error(`\u672C\u673A ${adapterNames[adapter]} \u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B\u3002`);
|
|
326
|
+
recommended = model;
|
|
327
|
+
break;
|
|
328
|
+
} catch (error) {
|
|
329
|
+
log.error(errorMessage(error));
|
|
330
|
+
const selected = await adapterPrompt(adapter);
|
|
331
|
+
if (isCancel(selected)) return cancelled();
|
|
332
|
+
adapter = selected;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const draft = saved?.adapter === adapter ? { ...saved, name, workspace } : {
|
|
336
|
+
name,
|
|
337
|
+
workspace,
|
|
338
|
+
adapter,
|
|
339
|
+
model: recommended.id,
|
|
340
|
+
reasoningEffort: recommended.defaultReasoningEffort,
|
|
341
|
+
permission: "read-only"
|
|
342
|
+
};
|
|
343
|
+
for (; ; ) {
|
|
344
|
+
showSummary(draft, models);
|
|
345
|
+
const action = await select({
|
|
346
|
+
message: "\u7528\u4EE5\u4E0A\u914D\u7F6E\u542F\u52A8 Bot\uFF1F",
|
|
347
|
+
options: [
|
|
348
|
+
{ value: "start", label: "\u542F\u52A8" },
|
|
349
|
+
{ value: "edit", label: "\u4FEE\u6539\u914D\u7F6E" },
|
|
350
|
+
{ value: "quit", label: "\u9000\u51FA" }
|
|
351
|
+
]
|
|
352
|
+
});
|
|
353
|
+
if (isCancel(action) || action === "quit") return cancelled();
|
|
354
|
+
const currentModel = models.find((model) => model.id === draft.model);
|
|
355
|
+
if (action === "start") {
|
|
356
|
+
try {
|
|
357
|
+
if (!currentModel?.supportedReasoningEfforts.includes(
|
|
358
|
+
draft.reasoningEffort
|
|
359
|
+
) || !allowedPermissions(draft.adapter).includes(draft.permission)) {
|
|
360
|
+
throw new Error("\u5F53\u524D\u6A21\u578B\u3001\u63A8\u7406\u5F3A\u5EA6\u6216\u6743\u9650\u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u4FEE\u6539\u914D\u7F6E\u3002");
|
|
361
|
+
}
|
|
362
|
+
draft.workspace = workspacePath(draft.workspace, cwd);
|
|
363
|
+
return draft;
|
|
364
|
+
} catch (error) {
|
|
365
|
+
log.error(errorMessage(error));
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const field = await select({
|
|
370
|
+
message: "\u4FEE\u6539\u54EA\u4E00\u9879\uFF1F",
|
|
371
|
+
options: [
|
|
372
|
+
{
|
|
373
|
+
value: "workspace",
|
|
374
|
+
label: "\u5DE5\u4F5C\u533A",
|
|
375
|
+
hint: terminalLabel(draft.workspace)
|
|
376
|
+
},
|
|
377
|
+
{
|
|
378
|
+
value: "adapter",
|
|
379
|
+
label: "Adapter",
|
|
380
|
+
hint: adapterNames[draft.adapter]
|
|
381
|
+
},
|
|
382
|
+
{ value: "model", label: "\u6A21\u578B", hint: draft.model },
|
|
383
|
+
{
|
|
384
|
+
value: "effort",
|
|
385
|
+
label: "\u63A8\u7406\u5F3A\u5EA6",
|
|
386
|
+
hint: effortLabel(draft.reasoningEffort)
|
|
387
|
+
},
|
|
388
|
+
{
|
|
389
|
+
value: "permission",
|
|
390
|
+
label: "\u6743\u9650",
|
|
391
|
+
hint: permissions[draft.permission].label
|
|
392
|
+
},
|
|
393
|
+
{ value: "back", label: "\u8FD4\u56DE\u542F\u52A8\u786E\u8BA4" }
|
|
394
|
+
]
|
|
395
|
+
});
|
|
396
|
+
if (isCancel(field)) return cancelled();
|
|
397
|
+
switch (field) {
|
|
398
|
+
case "workspace": {
|
|
399
|
+
const selected = await askWorkspace(draft.workspace, cwd);
|
|
400
|
+
if (isCancel(selected)) return cancelled();
|
|
401
|
+
if (selected === draft.workspace) break;
|
|
402
|
+
try {
|
|
403
|
+
const nextModels = await loadModels(draft.adapter, selected);
|
|
404
|
+
if (!nextModels.length)
|
|
405
|
+
throw new Error(
|
|
406
|
+
`\u8BE5\u5DE5\u4F5C\u533A\u7684 ${adapterNames[draft.adapter]} \u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B\u3002`
|
|
407
|
+
);
|
|
408
|
+
models = nextModels;
|
|
409
|
+
draft.workspace = selected;
|
|
410
|
+
} catch (error) {
|
|
411
|
+
log.error(errorMessage(error));
|
|
412
|
+
}
|
|
413
|
+
break;
|
|
414
|
+
}
|
|
415
|
+
case "adapter": {
|
|
416
|
+
const selected = await adapterPrompt(draft.adapter);
|
|
417
|
+
if (isCancel(selected)) return cancelled();
|
|
418
|
+
if (selected === draft.adapter) break;
|
|
419
|
+
try {
|
|
420
|
+
const nextModels = await loadModels(selected, draft.workspace);
|
|
421
|
+
const nextModel = nextModels.find((model) => model.isDefault) ?? nextModels[0];
|
|
422
|
+
if (!nextModel)
|
|
423
|
+
throw new Error(`\u672C\u673A ${adapterNames[selected]} \u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B\u3002`);
|
|
424
|
+
models = nextModels;
|
|
425
|
+
draft.adapter = selected;
|
|
426
|
+
draft.model = nextModel.id;
|
|
427
|
+
draft.reasoningEffort = nextModel.defaultReasoningEffort;
|
|
428
|
+
if (!allowedPermissions(selected).includes(draft.permission))
|
|
429
|
+
draft.permission = "read-only";
|
|
430
|
+
} catch (error) {
|
|
431
|
+
log.error(errorMessage(error));
|
|
432
|
+
}
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
case "model": {
|
|
436
|
+
const model = await autocomplete({
|
|
437
|
+
message: "\u9009\u62E9\u6A21\u578B",
|
|
438
|
+
options: [
|
|
439
|
+
...models.map((value) => ({
|
|
440
|
+
value,
|
|
441
|
+
label: value.id,
|
|
442
|
+
...value.isDefault ? { hint: "\u63A8\u8350" } : {}
|
|
443
|
+
})),
|
|
444
|
+
{ value: "back", label: "\u8FD4\u56DE" }
|
|
445
|
+
],
|
|
446
|
+
...currentModel ? { initialValue: currentModel } : {}
|
|
447
|
+
});
|
|
448
|
+
if (isCancel(model)) return cancelled();
|
|
449
|
+
if (model === "back") break;
|
|
450
|
+
draft.model = model.id;
|
|
451
|
+
if (!model.supportedReasoningEfforts.includes(draft.reasoningEffort)) {
|
|
452
|
+
draft.reasoningEffort = model.defaultReasoningEffort;
|
|
453
|
+
}
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
case "effort": {
|
|
457
|
+
if (!currentModel) {
|
|
458
|
+
log.warn("\u8BF7\u5148\u9009\u62E9\u53EF\u7528\u6A21\u578B\u3002");
|
|
459
|
+
break;
|
|
460
|
+
}
|
|
461
|
+
const effort = await select({
|
|
462
|
+
message: `\u9009\u62E9\u63A8\u7406\u5F3A\u5EA6 \xB7 ${currentModel.id}`,
|
|
463
|
+
initialValue: currentModel.supportedReasoningEfforts.includes(
|
|
464
|
+
draft.reasoningEffort
|
|
465
|
+
) ? draft.reasoningEffort : currentModel.defaultReasoningEffort,
|
|
466
|
+
options: [
|
|
467
|
+
...currentModel.supportedReasoningEfforts.map((value) => ({
|
|
468
|
+
value,
|
|
469
|
+
label: effortLabel(value),
|
|
470
|
+
...value === currentModel.defaultReasoningEffort ? { hint: "\u6A21\u578B\u9ED8\u8BA4" } : {}
|
|
471
|
+
})),
|
|
472
|
+
{ value: "back", label: "\u8FD4\u56DE" }
|
|
473
|
+
]
|
|
474
|
+
});
|
|
475
|
+
if (isCancel(effort)) return cancelled();
|
|
476
|
+
if (effort !== "back") draft.reasoningEffort = effort;
|
|
477
|
+
break;
|
|
478
|
+
}
|
|
479
|
+
case "permission": {
|
|
480
|
+
const permission = await select({
|
|
481
|
+
message: "\u9009\u62E9\u6743\u9650",
|
|
482
|
+
initialValue: draft.permission,
|
|
483
|
+
options: [
|
|
484
|
+
...allowedPermissions(draft.adapter).map((value) => ({
|
|
485
|
+
value,
|
|
486
|
+
...permissions[value]
|
|
487
|
+
})),
|
|
488
|
+
{ value: "back", label: "\u8FD4\u56DE" }
|
|
489
|
+
]
|
|
490
|
+
});
|
|
491
|
+
if (isCancel(permission)) return cancelled();
|
|
492
|
+
if (permission !== "back") draft.permission = permission;
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
var adapterNames, selectionMessages, botStates, permissions;
|
|
499
|
+
var init_start_prompts = __esm({
|
|
500
|
+
"src/start-prompts.ts"() {
|
|
501
|
+
"use strict";
|
|
502
|
+
init_dist();
|
|
503
|
+
adapterNames = { codex: "Codex", agy: "agy" };
|
|
504
|
+
selectionMessages = {
|
|
505
|
+
start: "\u9009\u62E9 Bot",
|
|
506
|
+
stop: "\u9009\u62E9\u8981\u505C\u6B62\u7684 Bot"
|
|
507
|
+
};
|
|
508
|
+
botStates = {
|
|
509
|
+
STOPPED: "\u5DF2\u505C\u6B62",
|
|
510
|
+
ONLINE: "\u5DF2\u5728\u7EBF",
|
|
511
|
+
CONNECTING: "\u8FDE\u63A5\u4E2D",
|
|
512
|
+
OFFLINE: "\u79BB\u7EBF",
|
|
513
|
+
UNAVAILABLE: "\u72B6\u6001\u4E0D\u53EF\u7528",
|
|
514
|
+
DRAINING: "\u505C\u6B62\u4E2D"
|
|
515
|
+
};
|
|
516
|
+
permissions = {
|
|
517
|
+
"read-only": { label: "\u53EA\u8BFB", hint: "\u8BFB\u53D6\u548C\u5206\u6790\u6587\u4EF6" },
|
|
518
|
+
"workspace-write": {
|
|
519
|
+
label: "\u5DE5\u4F5C\u533A\u53EF\u5199",
|
|
520
|
+
hint: "\u4FEE\u6539\u6388\u6743\u5DE5\u4F5C\u533A\uFF0C\u8FD0\u884C\u83B7\u51C6\u7684\u547D\u4EE4"
|
|
521
|
+
},
|
|
522
|
+
"full-access": {
|
|
523
|
+
label: "\u5B8C\u5168\u8BBF\u95EE",
|
|
524
|
+
hint: "\u6309\u672C\u673A\u8D26\u53F7\u6743\u9650\u8BBF\u95EE\u6587\u4EF6\u3001\u6267\u884C\u547D\u4EE4\u548C\u4F7F\u7528\u7F51\u7EDC"
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
});
|
|
529
|
+
|
|
530
|
+
// src/main.ts
|
|
531
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
532
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
533
|
+
import { hostname } from "node:os";
|
|
534
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
535
|
+
|
|
536
|
+
// ../../packages/agent-adapters/codex/dist/local.js
|
|
537
|
+
import { execFile, spawn } from "node:child_process";
|
|
538
|
+
import { createInterface } from "node:readline";
|
|
539
|
+
import { promisify } from "node:util";
|
|
540
|
+
var run = promisify(execFile);
|
|
541
|
+
var timeoutMs = 15e3;
|
|
542
|
+
var environmentKeys = [
|
|
543
|
+
"HOME",
|
|
544
|
+
"PATH",
|
|
545
|
+
"USER",
|
|
546
|
+
"TMPDIR",
|
|
547
|
+
"CODEX_HOME",
|
|
548
|
+
"XDG_CONFIG_HOME",
|
|
549
|
+
"XDG_DATA_HOME",
|
|
550
|
+
"LANG",
|
|
551
|
+
"HTTPS_PROXY",
|
|
552
|
+
"HTTP_PROXY",
|
|
553
|
+
"ALL_PROXY",
|
|
554
|
+
"NO_PROXY",
|
|
555
|
+
"https_proxy",
|
|
556
|
+
"http_proxy",
|
|
557
|
+
"all_proxy",
|
|
558
|
+
"no_proxy",
|
|
559
|
+
"SSL_CERT_FILE",
|
|
560
|
+
"SSL_CERT_DIR"
|
|
561
|
+
];
|
|
562
|
+
function codexEnvironment() {
|
|
563
|
+
return Object.fromEntries(environmentKeys.map((key) => [key, process.env[key]]));
|
|
564
|
+
}
|
|
565
|
+
async function codexLoginStatus(cwd, signal = AbortSignal.timeout(timeoutMs)) {
|
|
566
|
+
try {
|
|
567
|
+
await run("codex", ["login", "status"], {
|
|
568
|
+
cwd,
|
|
569
|
+
env: codexEnvironment(),
|
|
570
|
+
signal
|
|
571
|
+
});
|
|
572
|
+
return "signed-in";
|
|
573
|
+
} catch (error) {
|
|
574
|
+
if (signal.aborted)
|
|
575
|
+
throw error;
|
|
576
|
+
const code = error.code;
|
|
577
|
+
if (code === "ENOENT")
|
|
578
|
+
return "not-installed";
|
|
579
|
+
if (code === 1)
|
|
580
|
+
return "signed-out";
|
|
581
|
+
throw new Error("Could not check the local Codex login status.", {
|
|
582
|
+
cause: error
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
function parseModel(value) {
|
|
587
|
+
const model = value;
|
|
588
|
+
if (!model || typeof model.model !== "string" || typeof model.displayName !== "string" || typeof model.isDefault !== "boolean" || typeof model.defaultReasoningEffort !== "string" || !Array.isArray(model.supportedReasoningEfforts)) {
|
|
589
|
+
throw new Error("Codex returned an invalid model catalog.");
|
|
590
|
+
}
|
|
591
|
+
const supportedReasoningEfforts = model.supportedReasoningEfforts.map((entry) => {
|
|
592
|
+
if (typeof entry?.reasoningEffort !== "string")
|
|
593
|
+
throw new Error("Codex returned an invalid model catalog.");
|
|
594
|
+
return entry.reasoningEffort;
|
|
595
|
+
});
|
|
596
|
+
return {
|
|
597
|
+
id: model.model,
|
|
598
|
+
displayName: model.displayName,
|
|
599
|
+
isDefault: model.isDefault,
|
|
600
|
+
defaultReasoningEffort: model.defaultReasoningEffort,
|
|
601
|
+
supportedReasoningEfforts
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
async function listCodexModels(cwd, signal) {
|
|
605
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
606
|
+
const deadline = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
607
|
+
const options = { cwd, env: codexEnvironment(), signal: deadline };
|
|
608
|
+
const requestError = () => new Error(signal?.aborted ? "Codex model lookup was cancelled." : timeout.aborted ? "Codex model lookup timed out." : "Could not read the local Codex model catalog.");
|
|
609
|
+
const login2 = await codexLoginStatus(cwd, deadline).catch((error) => {
|
|
610
|
+
if (deadline.aborted)
|
|
611
|
+
throw requestError();
|
|
612
|
+
throw error;
|
|
613
|
+
});
|
|
614
|
+
if (login2 === "not-installed")
|
|
615
|
+
throw new Error("Codex was not found on PATH.");
|
|
616
|
+
if (login2 === "signed-out")
|
|
617
|
+
throw new Error("Codex is not logged in. Run codex login and try again.");
|
|
618
|
+
return new Promise((resolve3, reject) => {
|
|
619
|
+
const child = spawn("codex", ["app-server", "--listen", "stdio://", "-c", 'model_provider="openai"'], { ...options, stdio: ["pipe", "pipe", "ignore"], killSignal: "SIGKILL" });
|
|
620
|
+
const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
621
|
+
const models = [];
|
|
622
|
+
let requestId = 0;
|
|
623
|
+
function cleanup() {
|
|
624
|
+
lines.close();
|
|
625
|
+
child.stdin.destroy();
|
|
626
|
+
child.kill();
|
|
627
|
+
}
|
|
628
|
+
function fail(error) {
|
|
629
|
+
cleanup();
|
|
630
|
+
reject(error);
|
|
631
|
+
}
|
|
632
|
+
function send(message) {
|
|
633
|
+
child.stdin.write(JSON.stringify(message) + "\n");
|
|
634
|
+
}
|
|
635
|
+
function requestPage(cursor) {
|
|
636
|
+
send({
|
|
637
|
+
id: ++requestId,
|
|
638
|
+
method: "model/list",
|
|
639
|
+
params: { limit: 100, includeHidden: false, cursor }
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
child.on("error", () => fail(requestError()));
|
|
643
|
+
child.stdin.on("error", () => fail(requestError()));
|
|
644
|
+
lines.on("error", () => fail(requestError()));
|
|
645
|
+
child.once("close", () => reject(requestError()));
|
|
646
|
+
lines.on("line", (line) => {
|
|
647
|
+
try {
|
|
648
|
+
const message = JSON.parse(line);
|
|
649
|
+
if (message?.id !== requestId)
|
|
650
|
+
return;
|
|
651
|
+
if (message.error || !message.result)
|
|
652
|
+
throw requestError();
|
|
653
|
+
if (requestId === 0) {
|
|
654
|
+
send({ method: "initialized" });
|
|
655
|
+
requestPage();
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const { data, nextCursor } = message.result;
|
|
659
|
+
if (!Array.isArray(data))
|
|
660
|
+
throw new Error("Codex returned an invalid model catalog.");
|
|
661
|
+
models.push(...data.map(parseModel));
|
|
662
|
+
if (typeof nextCursor === "string" && nextCursor) {
|
|
663
|
+
requestPage(nextCursor);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
if (!models.length)
|
|
667
|
+
throw new Error("The local Codex account returned no models.");
|
|
668
|
+
resolve3(models);
|
|
669
|
+
cleanup();
|
|
670
|
+
} catch (error) {
|
|
671
|
+
fail(error instanceof Error ? error : requestError());
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
send({
|
|
675
|
+
id: requestId,
|
|
676
|
+
method: "initialize",
|
|
677
|
+
params: { clientInfo: { name: "bubai", version: "0.0.0" } }
|
|
678
|
+
});
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// ../../packages/agent-adapters/codex/dist/index.js
|
|
683
|
+
var codexDescriptor = {
|
|
684
|
+
id: "codex",
|
|
685
|
+
name: "Codex",
|
|
686
|
+
integrationStatus: "planned",
|
|
687
|
+
capabilities: {
|
|
688
|
+
textStreaming: "unverified",
|
|
689
|
+
toolEvents: "unverified",
|
|
690
|
+
approvals: "unverified",
|
|
691
|
+
cancellation: "unverified",
|
|
692
|
+
sessionResume: "unverified"
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
|
|
696
|
+
// ../../packages/agent-adapters/claude/dist/index.js
|
|
697
|
+
var claudeDescriptor = {
|
|
698
|
+
id: "claude",
|
|
699
|
+
name: "Claude",
|
|
700
|
+
integrationStatus: "planned",
|
|
701
|
+
capabilities: {
|
|
702
|
+
textStreaming: "unverified",
|
|
703
|
+
toolEvents: "unverified",
|
|
704
|
+
approvals: "unverified",
|
|
705
|
+
cancellation: "unverified",
|
|
706
|
+
sessionResume: "unverified"
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
|
|
710
|
+
// src/main.ts
|
|
711
|
+
init_dist();
|
|
712
|
+
|
|
713
|
+
// ../../packages/api-client/dist/index.js
|
|
714
|
+
function createApiClient(baseURL) {
|
|
715
|
+
const base = new URL(baseURL);
|
|
716
|
+
if (!["http:", "https:"].includes(base.protocol)) {
|
|
717
|
+
throw new Error("API URL must use HTTP or HTTPS");
|
|
718
|
+
}
|
|
719
|
+
return {
|
|
720
|
+
async health(signal) {
|
|
721
|
+
const response = await fetch(new URL("/health", base), {
|
|
722
|
+
signal: signal ?? AbortSignal.timeout(3e3)
|
|
723
|
+
});
|
|
724
|
+
if (!response.ok) {
|
|
725
|
+
throw new Error(`API health request failed: HTTP ${response.status}`);
|
|
726
|
+
}
|
|
727
|
+
const body = await response.json();
|
|
728
|
+
if (typeof body !== "object" || body === null || !("status" in body) || body.status !== "ok" || !("service" in body) || body.service !== "api") {
|
|
729
|
+
throw new Error("Invalid API health response");
|
|
730
|
+
}
|
|
731
|
+
return { status: "ok", service: "api" };
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// src/main.ts
|
|
737
|
+
import { Command } from "commander";
|
|
738
|
+
import qr from "qrcode-terminal";
|
|
739
|
+
|
|
740
|
+
// package.json
|
|
741
|
+
var package_default = {
|
|
742
|
+
name: "@bubx/cli",
|
|
743
|
+
version: "0.1.0",
|
|
744
|
+
description: "Bubai Bot CLI",
|
|
745
|
+
type: "module",
|
|
746
|
+
bin: {
|
|
747
|
+
bubai: "./dist/main.js"
|
|
748
|
+
},
|
|
749
|
+
files: [
|
|
750
|
+
"dist/main.js",
|
|
751
|
+
"dist/bot-server.js"
|
|
752
|
+
],
|
|
753
|
+
engines: {
|
|
754
|
+
node: "^22.23.0 || >=24.0.0"
|
|
755
|
+
},
|
|
756
|
+
publishConfig: {
|
|
757
|
+
access: "public",
|
|
758
|
+
registry: "https://registry.npmjs.org/"
|
|
759
|
+
},
|
|
760
|
+
scripts: {
|
|
761
|
+
dev: "tsx src/main.ts",
|
|
762
|
+
build: "tsc -p tsconfig.json",
|
|
763
|
+
prepack: "turbo run build --filter=@bubx/cli && esbuild main=src/main.ts bot-server=../bot-server/src/main.ts --bundle --platform=node --format=esm --target=node22 --external:@clack/prompts --external:capnweb --external:commander --external:qrcode-terminal --external:zod --outdir=dist",
|
|
764
|
+
typecheck: "tsc --noEmit"
|
|
765
|
+
},
|
|
766
|
+
dependencies: {
|
|
767
|
+
"@clack/prompts": "1.9.0",
|
|
768
|
+
capnweb: "0.13.1",
|
|
769
|
+
commander: "15.1.0",
|
|
770
|
+
"qrcode-terminal": "0.12.0",
|
|
771
|
+
zod: "4.6.7"
|
|
772
|
+
},
|
|
773
|
+
devDependencies: {
|
|
774
|
+
"@bubai/agent-agy": "workspace:*",
|
|
775
|
+
"@bubai/agent-claude": "workspace:*",
|
|
776
|
+
"@bubai/agent-codex": "workspace:*",
|
|
777
|
+
"@bubai/api-client": "workspace:*",
|
|
778
|
+
"@bubai/bot-server": "workspace:*",
|
|
779
|
+
"@bubai/relay-sdk": "workspace:*",
|
|
780
|
+
"@bubai/shared-config": "workspace:*",
|
|
781
|
+
"@types/node": "catalog:",
|
|
782
|
+
"@types/qrcode-terminal": "0.12.2",
|
|
783
|
+
esbuild: "0.28.2",
|
|
784
|
+
tsx: "catalog:",
|
|
785
|
+
typescript: "catalog:"
|
|
786
|
+
}
|
|
787
|
+
};
|
|
788
|
+
|
|
789
|
+
// src/api.ts
|
|
790
|
+
var ApiError = class extends Error {
|
|
791
|
+
constructor(status, code, retryAfterSeconds) {
|
|
792
|
+
super(`API request failed: ${code} (HTTP ${status})`);
|
|
793
|
+
this.status = status;
|
|
794
|
+
this.code = code;
|
|
795
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
796
|
+
}
|
|
797
|
+
status;
|
|
798
|
+
code;
|
|
799
|
+
retryAfterSeconds;
|
|
800
|
+
};
|
|
801
|
+
function hasErrorCode(value) {
|
|
802
|
+
return typeof value === "object" && value !== null && "code" in value && typeof value.code === "string" && /^[A-Z][A-Z0-9_]*$/.test(value.code);
|
|
803
|
+
}
|
|
804
|
+
function isLoopback(url) {
|
|
805
|
+
return ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
806
|
+
}
|
|
807
|
+
function apiOrigin(input) {
|
|
808
|
+
const url = new URL(input);
|
|
809
|
+
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
|
|
810
|
+
throw new Error("API URL must be an HTTP or HTTPS origin.");
|
|
811
|
+
}
|
|
812
|
+
if (url.protocol === "http:" && !isLoopback(url)) {
|
|
813
|
+
throw new Error("A remote API URL must use HTTPS.");
|
|
814
|
+
}
|
|
815
|
+
return url.origin;
|
|
816
|
+
}
|
|
817
|
+
function parseApprovalLink(input, api) {
|
|
818
|
+
const url = URL.parse(input);
|
|
819
|
+
if (!url || url.pathname !== "/cli/approve" && url.pathname !== "/console/cli/approve" || url.href !== `${url.origin}${url.pathname}${url.hash}`)
|
|
820
|
+
return;
|
|
821
|
+
if (url.protocol === "https:") return url;
|
|
822
|
+
if (url.protocol === "http:" && isLoopback(url) && isLoopback(new URL(api))) {
|
|
823
|
+
return url;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
function createControlClient(origin, credential) {
|
|
827
|
+
async function request(method, path, body, signal, deviceId) {
|
|
828
|
+
const timeout = AbortSignal.timeout(1e4);
|
|
829
|
+
let response;
|
|
830
|
+
try {
|
|
831
|
+
response = await fetch(new URL(path, origin), {
|
|
832
|
+
method,
|
|
833
|
+
headers: {
|
|
834
|
+
accept: "application/json",
|
|
835
|
+
...body === void 0 ? {} : { "content-type": "application/json" },
|
|
836
|
+
...credential ? { authorization: `Bearer ${credential}` } : {},
|
|
837
|
+
...deviceId ? { "x-bubai-device-id": deviceId } : {}
|
|
838
|
+
},
|
|
839
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
840
|
+
redirect: "error",
|
|
841
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout
|
|
842
|
+
});
|
|
843
|
+
} catch (cause) {
|
|
844
|
+
if (signal?.aborted) throw cause;
|
|
845
|
+
throw new Error("Could not reach the API.", { cause });
|
|
846
|
+
}
|
|
847
|
+
if (!response.ok) {
|
|
848
|
+
const error = await response.json().catch(() => void 0);
|
|
849
|
+
const retryAfter = response.headers.get("retry-after");
|
|
850
|
+
const retrySeconds = retryAfter === null ? NaN : Number(retryAfter);
|
|
851
|
+
throw new ApiError(
|
|
852
|
+
response.status,
|
|
853
|
+
hasErrorCode(error) ? error.code : "REQUEST_FAILED",
|
|
854
|
+
Number.isFinite(retrySeconds) && retrySeconds >= 0 ? retrySeconds : void 0
|
|
855
|
+
);
|
|
856
|
+
}
|
|
857
|
+
return await response.json();
|
|
858
|
+
}
|
|
859
|
+
return {
|
|
860
|
+
startLogin(registrationId, deviceName, signal) {
|
|
861
|
+
return request(
|
|
862
|
+
"POST",
|
|
863
|
+
"/api/cli/logins",
|
|
864
|
+
{ registrationId, deviceName },
|
|
865
|
+
signal
|
|
866
|
+
);
|
|
867
|
+
},
|
|
868
|
+
pollLogin(loginId, deviceCode, signal) {
|
|
869
|
+
return request(
|
|
870
|
+
"POST",
|
|
871
|
+
"/api/cli/logins/poll",
|
|
872
|
+
{ loginId, deviceCode },
|
|
873
|
+
signal
|
|
874
|
+
);
|
|
875
|
+
},
|
|
876
|
+
registerBot(body) {
|
|
877
|
+
return request("POST", "/api/v2/bots", body);
|
|
878
|
+
},
|
|
879
|
+
issueBotCredential(botId, signal) {
|
|
880
|
+
return request(
|
|
881
|
+
"POST",
|
|
882
|
+
`/api/v2/bots/${encodeURIComponent(botId)}/credential`,
|
|
883
|
+
void 0,
|
|
884
|
+
signal
|
|
885
|
+
);
|
|
886
|
+
},
|
|
887
|
+
prepareLocalRoute(botId, expectedRouteRevision) {
|
|
888
|
+
return request(
|
|
889
|
+
"PUT",
|
|
890
|
+
`/api/v2/bots/${encodeURIComponent(botId)}/relay-route`,
|
|
891
|
+
{ protocolVersion: 2, serverTransport: "PEER", expectedRouteRevision }
|
|
892
|
+
);
|
|
893
|
+
},
|
|
894
|
+
issueUserTicket(botId, deviceId, signal) {
|
|
895
|
+
return request(
|
|
896
|
+
"POST",
|
|
897
|
+
"/api/v2/relay/tickets",
|
|
898
|
+
{ botId, deviceId },
|
|
899
|
+
signal,
|
|
900
|
+
deviceId
|
|
901
|
+
);
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
// src/bot-client.ts
|
|
907
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
908
|
+
|
|
909
|
+
// ../../packages/relay-sdk/dist/client-v2/index.js
|
|
910
|
+
import { newWebSocketRpcSession } from "capnweb";
|
|
911
|
+
import { z } from "zod";
|
|
912
|
+
var __addDisposableResource = function(env, value, async) {
|
|
913
|
+
if (value !== null && value !== void 0) {
|
|
914
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
915
|
+
var dispose, inner;
|
|
916
|
+
if (async) {
|
|
917
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
918
|
+
dispose = value[Symbol.asyncDispose];
|
|
919
|
+
}
|
|
920
|
+
if (dispose === void 0) {
|
|
921
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
922
|
+
dispose = value[Symbol.dispose];
|
|
923
|
+
if (async) inner = dispose;
|
|
924
|
+
}
|
|
925
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
926
|
+
if (inner) dispose = function() {
|
|
927
|
+
try {
|
|
928
|
+
inner.call(this);
|
|
929
|
+
} catch (e) {
|
|
930
|
+
return Promise.reject(e);
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
env.stack.push({ value, dispose, async });
|
|
934
|
+
} else if (async) {
|
|
935
|
+
env.stack.push({ async: true });
|
|
936
|
+
}
|
|
937
|
+
return value;
|
|
938
|
+
};
|
|
939
|
+
var __disposeResources = /* @__PURE__ */ (function(SuppressedError2) {
|
|
940
|
+
return function(env) {
|
|
941
|
+
function fail(e) {
|
|
942
|
+
env.error = env.hasError ? new SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e;
|
|
943
|
+
env.hasError = true;
|
|
944
|
+
}
|
|
945
|
+
var r, s = 0;
|
|
946
|
+
function next() {
|
|
947
|
+
while (r = env.stack.pop()) {
|
|
948
|
+
try {
|
|
949
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
950
|
+
if (r.dispose) {
|
|
951
|
+
var result = r.dispose.call(r.value);
|
|
952
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
|
|
953
|
+
fail(e);
|
|
954
|
+
return next();
|
|
955
|
+
});
|
|
956
|
+
} else s |= 1;
|
|
957
|
+
} catch (e) {
|
|
958
|
+
fail(e);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
962
|
+
if (env.hasError) throw env.error;
|
|
963
|
+
}
|
|
964
|
+
return next();
|
|
965
|
+
};
|
|
966
|
+
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
|
|
967
|
+
var e = new Error(message);
|
|
968
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
969
|
+
});
|
|
970
|
+
var botEvent = z.strictObject({
|
|
971
|
+
event: z.string().min(1).max(128),
|
|
972
|
+
payload: z.json(),
|
|
973
|
+
requestId: z.string().min(1).max(128).optional(),
|
|
974
|
+
sessionId: z.string().min(1).max(128).optional(),
|
|
975
|
+
seq: z.int().nonnegative().optional()
|
|
976
|
+
});
|
|
977
|
+
var botResult = z.discriminatedUnion("ok", [
|
|
978
|
+
z.strictObject({ ok: z.literal(true), value: z.json() }),
|
|
979
|
+
z.strictObject({
|
|
980
|
+
ok: z.literal(false),
|
|
981
|
+
error: z.strictObject({ code: z.string(), message: z.string() })
|
|
982
|
+
})
|
|
983
|
+
]);
|
|
984
|
+
var RelayAdmissionError = class extends Error {
|
|
985
|
+
code;
|
|
986
|
+
constructor(code) {
|
|
987
|
+
super(`Relay admission failed: ${code}`);
|
|
988
|
+
this.code = code;
|
|
989
|
+
this.name = "RelayAdmissionError";
|
|
990
|
+
}
|
|
991
|
+
};
|
|
992
|
+
async function connectRelayRpcClient(options) {
|
|
993
|
+
const { relayUrl, ticket, expiresAt, signal, onEvent } = options;
|
|
994
|
+
if (signal.aborted)
|
|
995
|
+
throw signal.reason;
|
|
996
|
+
const url = new URL(relayUrl);
|
|
997
|
+
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
998
|
+
if (url.protocol !== "wss:" && (url.protocol !== "ws:" || !local) || url.username || url.password || url.search || url.hash || !(Date.parse(expiresAt) > Date.now())) {
|
|
999
|
+
throw new Error("\u8FDE\u63A5\u51ED\u8BC1\u4E0D\u53EF\u7528\u3002");
|
|
1000
|
+
}
|
|
1001
|
+
const root = newWebSocketRpcSession(url.href);
|
|
1002
|
+
let disconnected = false;
|
|
1003
|
+
let resolveDisconnected;
|
|
1004
|
+
const whenDisconnected = new Promise((resolve3) => {
|
|
1005
|
+
resolveDisconnected = resolve3;
|
|
1006
|
+
});
|
|
1007
|
+
function close() {
|
|
1008
|
+
if (disconnected)
|
|
1009
|
+
return;
|
|
1010
|
+
disconnected = true;
|
|
1011
|
+
signal.removeEventListener("abort", close);
|
|
1012
|
+
try {
|
|
1013
|
+
root[Symbol.dispose]();
|
|
1014
|
+
} finally {
|
|
1015
|
+
resolveDisconnected();
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
root.onRpcBroken(close);
|
|
1019
|
+
signal.addEventListener("abort", close, { once: true });
|
|
1020
|
+
const deadline = setTimeout(close, 7e3);
|
|
1021
|
+
try {
|
|
1022
|
+
const connection = await root.connect(ticket);
|
|
1023
|
+
if (connection.kind === "error") {
|
|
1024
|
+
throw new RelayAdmissionError(connection.code);
|
|
1025
|
+
}
|
|
1026
|
+
if (connection.kind !== "session") {
|
|
1027
|
+
throw new RelayAdmissionError("ACCESS_DENIED");
|
|
1028
|
+
}
|
|
1029
|
+
const receive = (event) => {
|
|
1030
|
+
if (!botEvent.safeParse(event).success) {
|
|
1031
|
+
close();
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
return onEvent(event);
|
|
1035
|
+
};
|
|
1036
|
+
return {
|
|
1037
|
+
close,
|
|
1038
|
+
disconnected: whenDisconnected,
|
|
1039
|
+
async call(request) {
|
|
1040
|
+
const env_1 = { stack: [], error: void 0, hasError: false };
|
|
1041
|
+
try {
|
|
1042
|
+
const result = __addDisposableResource(env_1, await connection.session.call(request, receive), false);
|
|
1043
|
+
return botResult.parse(result);
|
|
1044
|
+
} catch (e_1) {
|
|
1045
|
+
env_1.error = e_1;
|
|
1046
|
+
env_1.hasError = true;
|
|
1047
|
+
} finally {
|
|
1048
|
+
__disposeResources(env_1);
|
|
1049
|
+
}
|
|
1050
|
+
},
|
|
1051
|
+
async watchPresence(onChange) {
|
|
1052
|
+
let notified = false;
|
|
1053
|
+
const watchDeadline = setTimeout(close, 7e3);
|
|
1054
|
+
try {
|
|
1055
|
+
const initial = await connection.presence.watch((state) => {
|
|
1056
|
+
notified = true;
|
|
1057
|
+
onChange(state);
|
|
1058
|
+
});
|
|
1059
|
+
if (!notified)
|
|
1060
|
+
onChange(initial.state);
|
|
1061
|
+
} finally {
|
|
1062
|
+
clearTimeout(watchDeadline);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
};
|
|
1066
|
+
} catch (error) {
|
|
1067
|
+
close();
|
|
1068
|
+
throw error;
|
|
1069
|
+
} finally {
|
|
1070
|
+
clearTimeout(deadline);
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// src/bot-client.ts
|
|
1075
|
+
import { z as z2 } from "zod";
|
|
1076
|
+
|
|
1077
|
+
// src/credentials.ts
|
|
1078
|
+
import { spawnSync } from "node:child_process";
|
|
1079
|
+
var service = "dev.bubai.cli";
|
|
1080
|
+
function isSecret(value) {
|
|
1081
|
+
return /^[A-Za-z0-9_-]{32,512}$/.test(value);
|
|
1082
|
+
}
|
|
1083
|
+
function storeError() {
|
|
1084
|
+
return new Error(
|
|
1085
|
+
"Bubai could not access the OS credential store. Unlock Keychain or start Secret Service, then retry."
|
|
1086
|
+
);
|
|
1087
|
+
}
|
|
1088
|
+
function credentialStore(profileId) {
|
|
1089
|
+
if (!/^[a-f0-9-]{36}$/.test(profileId)) {
|
|
1090
|
+
throw new Error("The CLI profile ID is invalid.");
|
|
1091
|
+
}
|
|
1092
|
+
function read(name) {
|
|
1093
|
+
const account = `${profileId}:${name}`;
|
|
1094
|
+
const result = process.platform === "darwin" ? spawnSync(
|
|
1095
|
+
"/usr/bin/security",
|
|
1096
|
+
["find-generic-password", "-s", service, "-a", account, "-w"],
|
|
1097
|
+
{ encoding: "utf8", timeout: 5e3 }
|
|
1098
|
+
) : spawnSync(
|
|
1099
|
+
"secret-tool",
|
|
1100
|
+
["lookup", "service", service, "account", account],
|
|
1101
|
+
{
|
|
1102
|
+
encoding: "utf8",
|
|
1103
|
+
timeout: 5e3
|
|
1104
|
+
}
|
|
1105
|
+
);
|
|
1106
|
+
if (result.error) throw storeError();
|
|
1107
|
+
if (result.status !== 0) return void 0;
|
|
1108
|
+
const value = result.stdout.trim();
|
|
1109
|
+
if (!isSecret(value)) throw storeError();
|
|
1110
|
+
return value;
|
|
1111
|
+
}
|
|
1112
|
+
return {
|
|
1113
|
+
read,
|
|
1114
|
+
write(name, secret) {
|
|
1115
|
+
if (!isSecret(secret))
|
|
1116
|
+
throw new Error("The credential format is invalid.");
|
|
1117
|
+
const account = `${profileId}:${name}`;
|
|
1118
|
+
const result = process.platform === "darwin" ? spawnSync("/usr/bin/security", ["-i"], {
|
|
1119
|
+
input: `add-generic-password -U -s ${service} -a ${account} -w ${secret}
|
|
1120
|
+
`,
|
|
1121
|
+
timeout: 5e3,
|
|
1122
|
+
stdio: ["pipe", "ignore", "ignore"]
|
|
1123
|
+
}) : spawnSync(
|
|
1124
|
+
"secret-tool",
|
|
1125
|
+
[
|
|
1126
|
+
"store",
|
|
1127
|
+
"--label=Bubai CLI",
|
|
1128
|
+
"service",
|
|
1129
|
+
service,
|
|
1130
|
+
"account",
|
|
1131
|
+
account
|
|
1132
|
+
],
|
|
1133
|
+
{
|
|
1134
|
+
input: secret,
|
|
1135
|
+
timeout: 5e3,
|
|
1136
|
+
stdio: ["pipe", "ignore", "ignore"]
|
|
1137
|
+
}
|
|
1138
|
+
);
|
|
1139
|
+
if (result.error || result.status !== 0 || read(name) !== secret) {
|
|
1140
|
+
throw storeError();
|
|
1141
|
+
}
|
|
1142
|
+
},
|
|
1143
|
+
remove(name) {
|
|
1144
|
+
const account = `${profileId}:${name}`;
|
|
1145
|
+
if (process.platform === "darwin") {
|
|
1146
|
+
spawnSync(
|
|
1147
|
+
"/usr/bin/security",
|
|
1148
|
+
["delete-generic-password", "-s", service, "-a", account],
|
|
1149
|
+
{
|
|
1150
|
+
stdio: "ignore",
|
|
1151
|
+
timeout: 5e3
|
|
1152
|
+
}
|
|
1153
|
+
);
|
|
1154
|
+
} else {
|
|
1155
|
+
spawnSync(
|
|
1156
|
+
"secret-tool",
|
|
1157
|
+
["clear", "service", service, "account", account],
|
|
1158
|
+
{
|
|
1159
|
+
stdio: "ignore",
|
|
1160
|
+
timeout: 5e3
|
|
1161
|
+
}
|
|
1162
|
+
);
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
// src/profile.ts
|
|
1169
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
1170
|
+
import {
|
|
1171
|
+
existsSync,
|
|
1172
|
+
lstatSync,
|
|
1173
|
+
mkdtempSync,
|
|
1174
|
+
mkdirSync,
|
|
1175
|
+
readdirSync,
|
|
1176
|
+
realpathSync,
|
|
1177
|
+
renameSync,
|
|
1178
|
+
rmSync,
|
|
1179
|
+
statSync
|
|
1180
|
+
} from "node:fs";
|
|
1181
|
+
import { homedir } from "node:os";
|
|
1182
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
1183
|
+
import { DatabaseSync } from "node:sqlite";
|
|
1184
|
+
var botDirectoryName = /^[a-f0-9]{8}$/;
|
|
1185
|
+
function stateDirectory() {
|
|
1186
|
+
if (process.env.BUBAI_HOME) return resolve(process.env.BUBAI_HOME);
|
|
1187
|
+
if (process.platform === "darwin") {
|
|
1188
|
+
return join(homedir(), "Library", "Application Support", "Bubai");
|
|
1189
|
+
}
|
|
1190
|
+
return join(
|
|
1191
|
+
process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"),
|
|
1192
|
+
"bubai"
|
|
1193
|
+
);
|
|
1194
|
+
}
|
|
1195
|
+
function verifyPrivateDirectory(directory2) {
|
|
1196
|
+
const stats = lstatSync(directory2);
|
|
1197
|
+
if (!stats.isDirectory() || stats.uid !== process.getuid?.() || (stats.mode & 63) !== 0) {
|
|
1198
|
+
throw new Error(
|
|
1199
|
+
"Bubai state must be in a private directory owned by the current user."
|
|
1200
|
+
);
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
function openProfileDatabase(directory2) {
|
|
1204
|
+
const db = new DatabaseSync(join(directory2, "profile.sqlite"));
|
|
1205
|
+
db.exec(`
|
|
1206
|
+
PRAGMA busy_timeout = 3000;
|
|
1207
|
+
CREATE TABLE IF NOT EXISTS profile (
|
|
1208
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
1209
|
+
content TEXT NOT NULL
|
|
1210
|
+
)
|
|
1211
|
+
`);
|
|
1212
|
+
return db;
|
|
1213
|
+
}
|
|
1214
|
+
function readProfile(directory2) {
|
|
1215
|
+
if (!existsSync(directory2)) return void 0;
|
|
1216
|
+
verifyPrivateDirectory(directory2);
|
|
1217
|
+
const path = join(directory2, "profile.sqlite");
|
|
1218
|
+
if (!existsSync(path)) return void 0;
|
|
1219
|
+
const db = new DatabaseSync(path, { readOnly: true, timeout: 3e3 });
|
|
1220
|
+
try {
|
|
1221
|
+
const table = db.prepare(
|
|
1222
|
+
"SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'profile'"
|
|
1223
|
+
).get();
|
|
1224
|
+
if (!table) return void 0;
|
|
1225
|
+
const row = db.prepare("SELECT content FROM profile WHERE id = 1").get();
|
|
1226
|
+
return row ? JSON.parse(String(row.content)) : void 0;
|
|
1227
|
+
} finally {
|
|
1228
|
+
db.close();
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
function requireProfile(directory2) {
|
|
1232
|
+
const profile = readProfile(directory2);
|
|
1233
|
+
if (!profile) throw new Error("Run bubai init first.");
|
|
1234
|
+
return profile;
|
|
1235
|
+
}
|
|
1236
|
+
function deviceDirectory(directory2, profile) {
|
|
1237
|
+
return profile.sharedDevice ? dirname(dirname(directory2)) : directory2;
|
|
1238
|
+
}
|
|
1239
|
+
function listBotProfiles(root) {
|
|
1240
|
+
const rootProfile = readProfile(root);
|
|
1241
|
+
const profiles = rootProfile && !rootProfile.deviceOnly ? [{ directory: root, profile: rootProfile }] : [];
|
|
1242
|
+
const botsDirectory = join(root, "bots");
|
|
1243
|
+
if (!existsSync(botsDirectory)) return profiles;
|
|
1244
|
+
verifyPrivateDirectory(botsDirectory);
|
|
1245
|
+
const entries = readdirSync(botsDirectory, { withFileTypes: true });
|
|
1246
|
+
entries.sort((left, right) => left.name.localeCompare(right.name));
|
|
1247
|
+
for (const entry of entries) {
|
|
1248
|
+
if (!entry.isDirectory() || !botDirectoryName.test(entry.name)) continue;
|
|
1249
|
+
const directory2 = join(botsDirectory, entry.name);
|
|
1250
|
+
const profile = requireProfile(directory2);
|
|
1251
|
+
if (!profile.sharedDevice)
|
|
1252
|
+
throw new Error("The Bot profile is missing its device association.");
|
|
1253
|
+
profiles.push({ directory: directory2, profile });
|
|
1254
|
+
}
|
|
1255
|
+
return profiles;
|
|
1256
|
+
}
|
|
1257
|
+
function writeProfile(directory2, profile) {
|
|
1258
|
+
verifyPrivateDirectory(directory2);
|
|
1259
|
+
const db = openProfileDatabase(directory2);
|
|
1260
|
+
try {
|
|
1261
|
+
db.prepare("UPDATE profile SET content = ? WHERE id = 1").run(
|
|
1262
|
+
JSON.stringify(profile)
|
|
1263
|
+
);
|
|
1264
|
+
} finally {
|
|
1265
|
+
db.close();
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
function workspaceAt(workspacePath2) {
|
|
1269
|
+
const path = realpathSync(workspacePath2);
|
|
1270
|
+
if (!statSync(path).isDirectory()) {
|
|
1271
|
+
throw new Error("The workspace must be a directory.");
|
|
1272
|
+
}
|
|
1273
|
+
return {
|
|
1274
|
+
id: randomUUID(),
|
|
1275
|
+
path,
|
|
1276
|
+
label: basename(path).replace(/[\\\r\n]/g, " ").trim().slice(0, 100) || "Workspace"
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
function initializeDirectory(directory2) {
|
|
1280
|
+
if (process.platform !== "darwin" && process.platform !== "linux") {
|
|
1281
|
+
throw new Error("This CLI currently supports macOS and Linux.");
|
|
1282
|
+
}
|
|
1283
|
+
mkdirSync(directory2, { recursive: true, mode: 448 });
|
|
1284
|
+
verifyPrivateDirectory(directory2);
|
|
1285
|
+
}
|
|
1286
|
+
function newProfile(apiOrigin2, name, workspace) {
|
|
1287
|
+
return {
|
|
1288
|
+
id: randomUUID(),
|
|
1289
|
+
apiOrigin: apiOrigin2,
|
|
1290
|
+
name,
|
|
1291
|
+
deviceRegistrationId: randomUUID(),
|
|
1292
|
+
botRegistrationId: randomUUID(),
|
|
1293
|
+
ownerPermissions: {
|
|
1294
|
+
agentIds: [],
|
|
1295
|
+
workspaceIds: workspace ? [workspace.id] : [],
|
|
1296
|
+
toolIds: [],
|
|
1297
|
+
canApprove: false
|
|
1298
|
+
},
|
|
1299
|
+
...workspace ? { workspace } : {}
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
function insertProfile(directory2, profile) {
|
|
1303
|
+
const db = openProfileDatabase(directory2);
|
|
1304
|
+
try {
|
|
1305
|
+
const inserted = db.prepare("INSERT OR IGNORE INTO profile (id, content) VALUES (1, ?)").run(JSON.stringify(profile));
|
|
1306
|
+
const row = db.prepare("SELECT content FROM profile WHERE id = 1").get();
|
|
1307
|
+
return {
|
|
1308
|
+
profile: JSON.parse(String(row?.content)),
|
|
1309
|
+
initialized: inserted.changes > 0
|
|
1310
|
+
};
|
|
1311
|
+
} finally {
|
|
1312
|
+
db.close();
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
function initialize(directory2, apiOrigin2, name, workspacePath2) {
|
|
1316
|
+
initializeDirectory(directory2);
|
|
1317
|
+
const workspace = workspacePath2 ? workspaceAt(workspacePath2) : void 0;
|
|
1318
|
+
const candidate = newProfile(apiOrigin2, name, workspace);
|
|
1319
|
+
const initial = insertProfile(directory2, candidate);
|
|
1320
|
+
if (!initial.profile.deviceOnly) return initial;
|
|
1321
|
+
const unlock = lockProfile(directory2);
|
|
1322
|
+
try {
|
|
1323
|
+
const current = requireProfile(directory2);
|
|
1324
|
+
if (!current.deviceOnly) return { profile: current, initialized: false };
|
|
1325
|
+
const profile = {
|
|
1326
|
+
...current,
|
|
1327
|
+
name,
|
|
1328
|
+
ownerPermissions: candidate.ownerPermissions,
|
|
1329
|
+
...workspace ? { workspace } : {}
|
|
1330
|
+
};
|
|
1331
|
+
delete profile.deviceOnly;
|
|
1332
|
+
writeProfile(directory2, profile);
|
|
1333
|
+
return { profile, initialized: true };
|
|
1334
|
+
} finally {
|
|
1335
|
+
unlock();
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
function createBotProfile(root, origin, name, workspacePath2, execution, orgId) {
|
|
1339
|
+
const workspace = workspaceAt(workspacePath2);
|
|
1340
|
+
initializeDirectory(root);
|
|
1341
|
+
const { profile: device } = insertProfile(root, {
|
|
1342
|
+
...newProfile(origin, "Bubai"),
|
|
1343
|
+
deviceOnly: true
|
|
1344
|
+
});
|
|
1345
|
+
const botsDirectory = join(root, "bots");
|
|
1346
|
+
initializeDirectory(botsDirectory);
|
|
1347
|
+
const directory2 = join(botsDirectory, randomBytes(4).toString("hex"));
|
|
1348
|
+
const profile = {
|
|
1349
|
+
...newProfile(device.apiOrigin, name, workspace),
|
|
1350
|
+
deviceRegistrationId: device.deviceRegistrationId,
|
|
1351
|
+
sharedDevice: true,
|
|
1352
|
+
execution,
|
|
1353
|
+
...orgId ? { orgId } : {}
|
|
1354
|
+
};
|
|
1355
|
+
const staging = mkdtempSync(join(botsDirectory, ".new-"));
|
|
1356
|
+
try {
|
|
1357
|
+
insertProfile(staging, profile);
|
|
1358
|
+
renameSync(staging, directory2);
|
|
1359
|
+
} finally {
|
|
1360
|
+
rmSync(staging, { recursive: true, force: true });
|
|
1361
|
+
}
|
|
1362
|
+
return { directory: directory2, profile };
|
|
1363
|
+
}
|
|
1364
|
+
function saveBotStart(directory2, origin, workspacePath2, execution) {
|
|
1365
|
+
if (!readProfile(directory2))
|
|
1366
|
+
initialize(directory2, origin, "Bubai", workspacePath2);
|
|
1367
|
+
const unlock = lockProfile(directory2);
|
|
1368
|
+
try {
|
|
1369
|
+
const profile = requireProfile(directory2);
|
|
1370
|
+
const selected = workspaceAt(workspacePath2);
|
|
1371
|
+
const workspace = profile.workspace?.path === selected.path ? profile.workspace : selected;
|
|
1372
|
+
const updated = { ...profile, workspace, execution };
|
|
1373
|
+
writeProfile(directory2, updated);
|
|
1374
|
+
return updated;
|
|
1375
|
+
} finally {
|
|
1376
|
+
unlock();
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
function lockProfile(directory2) {
|
|
1380
|
+
verifyPrivateDirectory(directory2);
|
|
1381
|
+
const db = new DatabaseSync(join(directory2, "daemon-lock.sqlite"));
|
|
1382
|
+
try {
|
|
1383
|
+
db.exec("BEGIN EXCLUSIVE");
|
|
1384
|
+
} catch (error) {
|
|
1385
|
+
db.close();
|
|
1386
|
+
if (error instanceof Error && "errcode" in error && error.errcode === 5) {
|
|
1387
|
+
throw new Error(
|
|
1388
|
+
"A daemon or login is already active for this CLI profile.",
|
|
1389
|
+
{ cause: error }
|
|
1390
|
+
);
|
|
1391
|
+
}
|
|
1392
|
+
throw error;
|
|
1393
|
+
}
|
|
1394
|
+
return () => db.close();
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
// src/bot-client.ts
|
|
1398
|
+
async function callBot(directory2, botId, method, input, {
|
|
1399
|
+
requestId = randomUUID2(),
|
|
1400
|
+
watch = false
|
|
1401
|
+
}) {
|
|
1402
|
+
const profile = requireProfile(directory2);
|
|
1403
|
+
const credential = credentialStore(profile.id).read("device");
|
|
1404
|
+
const device = profile.device;
|
|
1405
|
+
if (!credential || !device || device.revokedAt)
|
|
1406
|
+
throw new Error("Run bubai login first.");
|
|
1407
|
+
const payload = z2.json().parse(JSON.parse(input));
|
|
1408
|
+
const sessionId = payload && typeof payload === "object" && "sessionId" in payload && typeof payload.sessionId === "string" ? payload.sessionId : void 0;
|
|
1409
|
+
const controller = new AbortController();
|
|
1410
|
+
const stop = () => controller.abort();
|
|
1411
|
+
process.once("SIGINT", stop);
|
|
1412
|
+
process.once("SIGTERM", stop);
|
|
1413
|
+
const timeout = watch ? void 0 : setTimeout(stop, 3e4);
|
|
1414
|
+
try {
|
|
1415
|
+
const api = createControlClient(profile.apiOrigin, credential);
|
|
1416
|
+
const ticket = await api.issueUserTicket(
|
|
1417
|
+
botId,
|
|
1418
|
+
device.id,
|
|
1419
|
+
controller.signal
|
|
1420
|
+
);
|
|
1421
|
+
const client = await connectRelayRpcClient({
|
|
1422
|
+
...ticket,
|
|
1423
|
+
signal: controller.signal,
|
|
1424
|
+
onEvent: (event) => console.log(JSON.stringify(event))
|
|
1425
|
+
});
|
|
1426
|
+
try {
|
|
1427
|
+
const result = await client.call({
|
|
1428
|
+
method,
|
|
1429
|
+
payload,
|
|
1430
|
+
requestId,
|
|
1431
|
+
...sessionId ? { sessionId } : {}
|
|
1432
|
+
});
|
|
1433
|
+
console.log(JSON.stringify({ requestId, ...result }));
|
|
1434
|
+
if (!result.ok) process.exitCode = 1;
|
|
1435
|
+
else if (watch) await client.disconnected;
|
|
1436
|
+
} catch (cause) {
|
|
1437
|
+
throw new Error(
|
|
1438
|
+
`Bot Server call was interrupted. Request ID ${requestId}`,
|
|
1439
|
+
{ cause }
|
|
1440
|
+
);
|
|
1441
|
+
} finally {
|
|
1442
|
+
client.close();
|
|
1443
|
+
}
|
|
1444
|
+
} finally {
|
|
1445
|
+
clearTimeout(timeout);
|
|
1446
|
+
process.off("SIGINT", stop);
|
|
1447
|
+
process.off("SIGTERM", stop);
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
// src/launcher.ts
|
|
1452
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1453
|
+
import { createHash } from "node:crypto";
|
|
1454
|
+
import { fileURLToPath } from "node:url";
|
|
1455
|
+
function executionFingerprint(profile) {
|
|
1456
|
+
return createHash("sha256").update(
|
|
1457
|
+
JSON.stringify([
|
|
1458
|
+
profile.id,
|
|
1459
|
+
profile.workspace,
|
|
1460
|
+
profile.execution,
|
|
1461
|
+
profile.orgId
|
|
1462
|
+
])
|
|
1463
|
+
).digest("hex");
|
|
1464
|
+
}
|
|
1465
|
+
async function configure(directory2, expectedExecution, rotate = false) {
|
|
1466
|
+
const release = lockProfile(directory2);
|
|
1467
|
+
try {
|
|
1468
|
+
const profile = requireProfile(directory2);
|
|
1469
|
+
if (profile.deviceOnly)
|
|
1470
|
+
throw new Error("\u8BF7\u5148\u8FD0\u884C bubai bot start \u65B0\u5EFA Bot\u3002");
|
|
1471
|
+
if (expectedExecution && executionFingerprint(profile) !== expectedExecution)
|
|
1472
|
+
throw new Error(
|
|
1473
|
+
"The Bot configuration changed. Run bubai bot start to confirm it again."
|
|
1474
|
+
);
|
|
1475
|
+
const account = requireProfile(deviceDirectory(directory2, profile));
|
|
1476
|
+
const credential = credentialStore(account.id).read("device");
|
|
1477
|
+
if (!credential || account.device?.revokedAt)
|
|
1478
|
+
throw new Error("Run bubai login first.");
|
|
1479
|
+
const api = createControlClient(profile.apiOrigin, credential);
|
|
1480
|
+
const bot = await api.registerBot({
|
|
1481
|
+
registrationId: profile.botRegistrationId,
|
|
1482
|
+
name: profile.name,
|
|
1483
|
+
ownerPermissions: profile.ownerPermissions,
|
|
1484
|
+
...profile.orgId ? { orgId: profile.orgId } : {}
|
|
1485
|
+
});
|
|
1486
|
+
if (!bot.id || !bot.ownerId || profile.botId && profile.botId !== bot.id || profile.ownerId && profile.ownerId !== bot.ownerId)
|
|
1487
|
+
throw new Error("The API returned an unexpected Bot registration.");
|
|
1488
|
+
if (bot.serverTransport === "CLOUDFLARE_DO")
|
|
1489
|
+
throw new Error(
|
|
1490
|
+
"\u6B64 Bot \u5DF2\u90E8\u7F72\u5230 Cloudflare\uFF0C\u4E0D\u80FD\u4ECE\u672C\u673A\u542F\u52A8 Bot Server\u3002"
|
|
1491
|
+
);
|
|
1492
|
+
if (bot.serverTransport !== "PEER" || !Number.isSafeInteger(bot.routeRevision))
|
|
1493
|
+
throw new Error("The API returned an invalid Bot Server route.");
|
|
1494
|
+
await api.prepareLocalRoute(bot.id, bot.routeRevision);
|
|
1495
|
+
const credentials = credentialStore(profile.id);
|
|
1496
|
+
const existing = credentials.read("bot-server");
|
|
1497
|
+
let expiresAt = profile.botServerCredentialExpiresAt;
|
|
1498
|
+
let key = existing;
|
|
1499
|
+
if (rotate || !key || !expiresAt || Date.parse(expiresAt) <= Date.now()) {
|
|
1500
|
+
const issued = await api.issueBotCredential(bot.id);
|
|
1501
|
+
key = issued.key;
|
|
1502
|
+
expiresAt = issued.expiresAt;
|
|
1503
|
+
credentials.write("bot-server", key);
|
|
1504
|
+
}
|
|
1505
|
+
writeProfile(directory2, {
|
|
1506
|
+
...profile,
|
|
1507
|
+
botId: bot.id,
|
|
1508
|
+
ownerId: bot.ownerId,
|
|
1509
|
+
botServerCredentialExpiresAt: expiresAt
|
|
1510
|
+
});
|
|
1511
|
+
return {
|
|
1512
|
+
apiOrigin: profile.apiOrigin,
|
|
1513
|
+
botId: bot.id,
|
|
1514
|
+
ownerId: bot.ownerId,
|
|
1515
|
+
key,
|
|
1516
|
+
directory: directory2,
|
|
1517
|
+
ownerPermissions: profile.ownerPermissions,
|
|
1518
|
+
...profile.workspace ? { workspace: profile.workspace } : {},
|
|
1519
|
+
...profile.execution ? { execution: profile.execution } : {},
|
|
1520
|
+
requireOnline: true
|
|
1521
|
+
};
|
|
1522
|
+
} finally {
|
|
1523
|
+
release();
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
var StartupError = class extends Error {
|
|
1527
|
+
constructor(message, authFailed) {
|
|
1528
|
+
super(message);
|
|
1529
|
+
this.authFailed = authFailed;
|
|
1530
|
+
}
|
|
1531
|
+
authFailed;
|
|
1532
|
+
};
|
|
1533
|
+
function botServerEntrypoint() {
|
|
1534
|
+
try {
|
|
1535
|
+
return import.meta.resolve("@bubai/bot-server/entry");
|
|
1536
|
+
} catch {
|
|
1537
|
+
return new URL("./bot-server.js", import.meta.url);
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
async function spawnServer(config, foreground, onReady) {
|
|
1541
|
+
const child = spawn2(
|
|
1542
|
+
process.execPath,
|
|
1543
|
+
[...process.execArgv, fileURLToPath(botServerEntrypoint())],
|
|
1544
|
+
{
|
|
1545
|
+
detached: !foreground,
|
|
1546
|
+
stdio: [
|
|
1547
|
+
"ignore",
|
|
1548
|
+
foreground ? "inherit" : "ignore",
|
|
1549
|
+
foreground ? "inherit" : "ignore",
|
|
1550
|
+
"ipc"
|
|
1551
|
+
]
|
|
1552
|
+
}
|
|
1553
|
+
);
|
|
1554
|
+
let abortStartup;
|
|
1555
|
+
const cancel2 = () => {
|
|
1556
|
+
abortStartup?.();
|
|
1557
|
+
child.kill("SIGTERM");
|
|
1558
|
+
};
|
|
1559
|
+
process.once("SIGINT", cancel2);
|
|
1560
|
+
process.once("SIGTERM", cancel2);
|
|
1561
|
+
const exited = new Promise(
|
|
1562
|
+
(resolve3) => child.once("exit", resolve3)
|
|
1563
|
+
);
|
|
1564
|
+
try {
|
|
1565
|
+
const message = await new Promise((resolve3, reject) => {
|
|
1566
|
+
const deadline = setTimeout(
|
|
1567
|
+
() => finish(() => reject(new Error("Bot Server did not start in time."))),
|
|
1568
|
+
6e4
|
|
1569
|
+
);
|
|
1570
|
+
function finish(done) {
|
|
1571
|
+
clearTimeout(deadline);
|
|
1572
|
+
abortStartup = void 0;
|
|
1573
|
+
done();
|
|
1574
|
+
}
|
|
1575
|
+
abortStartup = () => finish(() => reject(new Error("\u542F\u52A8\u5DF2\u53D6\u6D88\u3002")));
|
|
1576
|
+
child.once("error", (error) => finish(() => reject(error)));
|
|
1577
|
+
child.once(
|
|
1578
|
+
"exit",
|
|
1579
|
+
() => finish(() => reject(new Error("Bot Server exited during startup.")))
|
|
1580
|
+
);
|
|
1581
|
+
child.once("message", (message2) => finish(() => resolve3(message2)));
|
|
1582
|
+
child.send(config, (error) => {
|
|
1583
|
+
if (error) finish(() => reject(error));
|
|
1584
|
+
});
|
|
1585
|
+
});
|
|
1586
|
+
if (typeof message !== "object" || message === null || !("ok" in message)) {
|
|
1587
|
+
throw new Error("Bot Server sent an invalid startup response.");
|
|
1588
|
+
}
|
|
1589
|
+
if (message.ok !== true || !("value" in message)) {
|
|
1590
|
+
throw new StartupError(
|
|
1591
|
+
"error" in message && typeof message.error === "string" ? message.error : "Bot Server could not start.",
|
|
1592
|
+
"status" in message && message.status === 401 && "code" in message && message.code === "UNAUTHENTICATED"
|
|
1593
|
+
);
|
|
1594
|
+
}
|
|
1595
|
+
const status = message.value;
|
|
1596
|
+
onReady(status);
|
|
1597
|
+
if (foreground) {
|
|
1598
|
+
const code = await exited;
|
|
1599
|
+
if (code) throw new Error(`Bot Server exited with status ${code}.`);
|
|
1600
|
+
} else {
|
|
1601
|
+
child.unref();
|
|
1602
|
+
}
|
|
1603
|
+
return status;
|
|
1604
|
+
} catch (error) {
|
|
1605
|
+
child.kill("SIGTERM");
|
|
1606
|
+
throw error;
|
|
1607
|
+
} finally {
|
|
1608
|
+
process.off("SIGINT", cancel2);
|
|
1609
|
+
process.off("SIGTERM", cancel2);
|
|
1610
|
+
if (child.connected) child.disconnect();
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
async function startBotServer(directory2, {
|
|
1614
|
+
expectedExecution,
|
|
1615
|
+
foreground = false,
|
|
1616
|
+
onReady = () => {
|
|
1617
|
+
}
|
|
1618
|
+
} = {}) {
|
|
1619
|
+
const config = await configure(directory2, expectedExecution);
|
|
1620
|
+
try {
|
|
1621
|
+
return await spawnServer(config, foreground, onReady);
|
|
1622
|
+
} catch (error) {
|
|
1623
|
+
if (!(error instanceof StartupError) || !error.authFailed) throw error;
|
|
1624
|
+
return spawnServer(
|
|
1625
|
+
await configure(directory2, expectedExecution, true),
|
|
1626
|
+
foreground,
|
|
1627
|
+
onReady
|
|
1628
|
+
);
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
|
|
1632
|
+
// ../bot-server/dist/ipc.js
|
|
1633
|
+
import { createHmac, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
|
|
1634
|
+
import { chmodSync, existsSync as existsSync2, lstatSync as lstatSync2, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
1635
|
+
import { createConnection, createServer } from "node:net";
|
|
1636
|
+
import { join as join2 } from "node:path";
|
|
1637
|
+
var frameLimit = 4096;
|
|
1638
|
+
function verifyPrivateDirectory2(directory2) {
|
|
1639
|
+
const stats = lstatSync2(directory2);
|
|
1640
|
+
if (!stats.isDirectory() || stats.uid !== process.getuid?.() || (stats.mode & 63) !== 0)
|
|
1641
|
+
throw new Error("Bot Server state must be in a private directory owned by the current user.");
|
|
1642
|
+
}
|
|
1643
|
+
function credentialPath(directory2) {
|
|
1644
|
+
return join2(directory2, "bot-server-ipc.secret");
|
|
1645
|
+
}
|
|
1646
|
+
function socketPath(directory2) {
|
|
1647
|
+
const path = join2(directory2, "daemon.sock");
|
|
1648
|
+
if (Buffer.byteLength(path) > 100) {
|
|
1649
|
+
throw new Error("The Bubai state directory is too long for the daemon socket.");
|
|
1650
|
+
}
|
|
1651
|
+
return path;
|
|
1652
|
+
}
|
|
1653
|
+
function verifiedEndpoint(directory2, path) {
|
|
1654
|
+
verifyPrivateDirectory2(directory2);
|
|
1655
|
+
const stats = lstatSync2(path);
|
|
1656
|
+
if (!stats.isSocket() || stats.uid !== process.getuid?.() || (stats.mode & 63) !== 0) {
|
|
1657
|
+
throw new Error("The Bubai daemon socket has invalid ownership or permissions.");
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
function proof(secret, nonce, method) {
|
|
1661
|
+
return createHmac("sha256", secret).update(nonce).update(":").update(method).digest("hex");
|
|
1662
|
+
}
|
|
1663
|
+
function frame(socket) {
|
|
1664
|
+
return new Promise((resolve3, reject) => {
|
|
1665
|
+
let body = "";
|
|
1666
|
+
function cleanup() {
|
|
1667
|
+
socket.off("data", onData);
|
|
1668
|
+
socket.off("end", onEnd);
|
|
1669
|
+
socket.off("error", onError);
|
|
1670
|
+
socket.off("timeout", onTimeout);
|
|
1671
|
+
}
|
|
1672
|
+
function fail(error) {
|
|
1673
|
+
cleanup();
|
|
1674
|
+
reject(error);
|
|
1675
|
+
}
|
|
1676
|
+
function onEnd() {
|
|
1677
|
+
fail(new Error("The daemon connection ended early."));
|
|
1678
|
+
}
|
|
1679
|
+
function onError(error) {
|
|
1680
|
+
fail(error);
|
|
1681
|
+
}
|
|
1682
|
+
function onTimeout() {
|
|
1683
|
+
fail(new Error("The daemon did not respond in time."));
|
|
1684
|
+
}
|
|
1685
|
+
function onData(chunk) {
|
|
1686
|
+
body += chunk;
|
|
1687
|
+
if (Buffer.byteLength(body) > frameLimit) {
|
|
1688
|
+
fail(new Error("The daemon IPC frame exceeds its limit."));
|
|
1689
|
+
} else if (body.endsWith("\n")) {
|
|
1690
|
+
cleanup();
|
|
1691
|
+
try {
|
|
1692
|
+
resolve3(JSON.parse(body));
|
|
1693
|
+
} catch {
|
|
1694
|
+
reject(new Error("The daemon IPC frame is invalid."));
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
socket.on("data", onData);
|
|
1699
|
+
socket.once("end", onEnd);
|
|
1700
|
+
socket.once("error", onError);
|
|
1701
|
+
socket.once("timeout", onTimeout);
|
|
1702
|
+
});
|
|
1703
|
+
}
|
|
1704
|
+
function record(value) {
|
|
1705
|
+
return typeof value === "object" && value !== null;
|
|
1706
|
+
}
|
|
1707
|
+
function isDaemonUnavailable(error) {
|
|
1708
|
+
return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ECONNREFUSED");
|
|
1709
|
+
}
|
|
1710
|
+
async function callDaemon(directory2, method, legacySecret) {
|
|
1711
|
+
const path = socketPath(directory2);
|
|
1712
|
+
verifiedEndpoint(directory2, path);
|
|
1713
|
+
const key = credentialPath(directory2);
|
|
1714
|
+
let secret;
|
|
1715
|
+
if (existsSync2(key)) {
|
|
1716
|
+
const stats = lstatSync2(key);
|
|
1717
|
+
if (!stats.isFile() || stats.uid !== process.getuid?.() || (stats.mode & 63) !== 0)
|
|
1718
|
+
throw new Error("The Bot Server IPC credential has invalid ownership or permissions.");
|
|
1719
|
+
secret = readFileSync(key, "utf8");
|
|
1720
|
+
} else {
|
|
1721
|
+
secret = legacySecret?.();
|
|
1722
|
+
}
|
|
1723
|
+
if (!secret)
|
|
1724
|
+
throw new Error("The daemon IPC credential could not be read.");
|
|
1725
|
+
const socket = createConnection(path).setEncoding("utf8").setTimeout(15e3);
|
|
1726
|
+
socket.on("error", () => {
|
|
1727
|
+
});
|
|
1728
|
+
try {
|
|
1729
|
+
const hello = await frame(socket);
|
|
1730
|
+
if (!record(hello) || typeof hello.nonce !== "string" || !/^[a-f0-9]{64}$/.test(hello.nonce)) {
|
|
1731
|
+
throw new Error("The daemon returned an invalid authentication challenge.");
|
|
1732
|
+
}
|
|
1733
|
+
const response = frame(socket);
|
|
1734
|
+
socket.write(JSON.stringify({ method, proof: proof(secret, hello.nonce, method) }) + "\n");
|
|
1735
|
+
const result = await response;
|
|
1736
|
+
if (!record(result) || result.ok !== true) {
|
|
1737
|
+
throw new Error(record(result) && typeof result.error === "string" ? result.error : "The daemon command failed.");
|
|
1738
|
+
}
|
|
1739
|
+
return result.value;
|
|
1740
|
+
} finally {
|
|
1741
|
+
socket.destroy();
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
// src/main.ts
|
|
1746
|
+
var defaultApi = "http://127.0.0.1:3000";
|
|
1747
|
+
var directory = stateDirectory();
|
|
1748
|
+
function print(value) {
|
|
1749
|
+
console.log(JSON.stringify(value, null, 2));
|
|
1750
|
+
}
|
|
1751
|
+
function printQrLink(url, expiresAt) {
|
|
1752
|
+
qr.generate(url, { small: true });
|
|
1753
|
+
console.log(url);
|
|
1754
|
+
console.log(`Expires at ${expiresAt}`);
|
|
1755
|
+
}
|
|
1756
|
+
function openBrowser(url) {
|
|
1757
|
+
const browser = spawn3(
|
|
1758
|
+
process.platform === "darwin" ? "open" : "xdg-open",
|
|
1759
|
+
[url],
|
|
1760
|
+
{
|
|
1761
|
+
stdio: "ignore",
|
|
1762
|
+
detached: true
|
|
1763
|
+
}
|
|
1764
|
+
);
|
|
1765
|
+
browser.on("error", () => {
|
|
1766
|
+
});
|
|
1767
|
+
browser.unref();
|
|
1768
|
+
}
|
|
1769
|
+
async function daemonStatus(bot) {
|
|
1770
|
+
try {
|
|
1771
|
+
return await callDaemon(
|
|
1772
|
+
bot.directory,
|
|
1773
|
+
"status",
|
|
1774
|
+
() => credentialStore(bot.profile.id).read("ipc")
|
|
1775
|
+
);
|
|
1776
|
+
} catch (error) {
|
|
1777
|
+
if (!isDaemonUnavailable(error)) throw error;
|
|
1778
|
+
return void 0;
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
async function login(options) {
|
|
1782
|
+
const deviceName = options.deviceName.trim();
|
|
1783
|
+
if (!deviceName || deviceName.length > 100) {
|
|
1784
|
+
throw new Error("Device name must contain between 1 and 100 characters.");
|
|
1785
|
+
}
|
|
1786
|
+
requireProfile(directory);
|
|
1787
|
+
const unlock = lockProfile(directory);
|
|
1788
|
+
const abort = new AbortController();
|
|
1789
|
+
const cancel2 = () => abort.abort();
|
|
1790
|
+
process.once("SIGINT", cancel2);
|
|
1791
|
+
process.once("SIGTERM", cancel2);
|
|
1792
|
+
try {
|
|
1793
|
+
const profile = requireProfile(directory);
|
|
1794
|
+
if (options.reuseDevice && hasDeviceCredential(profile)) return;
|
|
1795
|
+
const api = createControlClient(profile.apiOrigin);
|
|
1796
|
+
const challenge = await api.startLogin(
|
|
1797
|
+
profile.deviceRegistrationId,
|
|
1798
|
+
deviceName,
|
|
1799
|
+
abort.signal
|
|
1800
|
+
);
|
|
1801
|
+
const verification = parseApprovalLink(
|
|
1802
|
+
challenge.verificationUri,
|
|
1803
|
+
profile.apiOrigin
|
|
1804
|
+
);
|
|
1805
|
+
const expiry = Date.parse(challenge.expiresAt);
|
|
1806
|
+
let interval = challenge.pollIntervalSeconds;
|
|
1807
|
+
if (!verification || verification.hash || !/^[A-Z2-9]{10}$/.test(challenge.userCode) || !Number.isFinite(expiry) || !Number.isFinite(interval) || interval < 1) {
|
|
1808
|
+
throw new Error("The API returned an invalid login challenge.");
|
|
1809
|
+
}
|
|
1810
|
+
if (options.showQr) {
|
|
1811
|
+
verification.searchParams.set("userCode", challenge.userCode);
|
|
1812
|
+
console.log("\u626B\u7801\u6216\u70B9\u51FB\u94FE\u63A5\u6279\u51C6\u8FD9\u53F0\u7535\u8111");
|
|
1813
|
+
printQrLink(verification.href, challenge.expiresAt);
|
|
1814
|
+
console.log(`\u7528\u6237\u7801 ${challenge.userCode}`);
|
|
1815
|
+
console.log("\u7B49\u5F85\u8BBE\u5907\u6279\u51C6\u2026");
|
|
1816
|
+
} else {
|
|
1817
|
+
console.log(`Verification URL: ${verification.href}`);
|
|
1818
|
+
console.log(`User code: ${challenge.userCode}`);
|
|
1819
|
+
if (options.open) openBrowser(verification.href);
|
|
1820
|
+
}
|
|
1821
|
+
while (Date.now() < expiry) {
|
|
1822
|
+
await delay(Math.min(expiry - Date.now(), interval * 1e3), void 0, {
|
|
1823
|
+
signal: abort.signal
|
|
1824
|
+
});
|
|
1825
|
+
if (Date.now() >= expiry) break;
|
|
1826
|
+
try {
|
|
1827
|
+
const result = await api.pollLogin(
|
|
1828
|
+
challenge.loginId,
|
|
1829
|
+
challenge.deviceCode,
|
|
1830
|
+
abort.signal
|
|
1831
|
+
);
|
|
1832
|
+
if (result.status === "PENDING") {
|
|
1833
|
+
if (!Number.isFinite(result.pollIntervalSeconds) || result.pollIntervalSeconds < 1) {
|
|
1834
|
+
throw new Error("The API returned an invalid polling interval.");
|
|
1835
|
+
}
|
|
1836
|
+
interval = result.pollIntervalSeconds;
|
|
1837
|
+
continue;
|
|
1838
|
+
}
|
|
1839
|
+
if (result.status !== "APPROVED" || !result.device.id || result.device.kind !== "CLI" || Boolean(result.device.revokedAt) || profile.device && profile.device.id !== result.device.id || !Number.isFinite(Date.parse(result.credentialExpiresAt))) {
|
|
1840
|
+
throw new Error(
|
|
1841
|
+
"The API returned an unexpected device login result."
|
|
1842
|
+
);
|
|
1843
|
+
}
|
|
1844
|
+
credentialStore(profile.id).write("device", result.credential);
|
|
1845
|
+
writeProfile(directory, {
|
|
1846
|
+
...profile,
|
|
1847
|
+
device: result.device,
|
|
1848
|
+
credentialExpiresAt: result.credentialExpiresAt
|
|
1849
|
+
});
|
|
1850
|
+
if (options.showQr) console.log("\u2713 \u8BBE\u5907\u5DF2\u6279\u51C6");
|
|
1851
|
+
else {
|
|
1852
|
+
print({
|
|
1853
|
+
status: "APPROVED",
|
|
1854
|
+
deviceId: result.device.id,
|
|
1855
|
+
credentialExpiresAt: result.credentialExpiresAt
|
|
1856
|
+
});
|
|
1857
|
+
}
|
|
1858
|
+
return;
|
|
1859
|
+
} catch (error) {
|
|
1860
|
+
if (!(error instanceof ApiError) || error.status !== 429) throw error;
|
|
1861
|
+
interval = Math.max(interval, error.retryAfterSeconds ?? interval * 2);
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
throw new Error("The device login challenge expired.");
|
|
1865
|
+
} catch (error) {
|
|
1866
|
+
if (abort.signal.aborted) {
|
|
1867
|
+
throw new Error("Device login cancelled.", { cause: error });
|
|
1868
|
+
}
|
|
1869
|
+
throw error;
|
|
1870
|
+
} finally {
|
|
1871
|
+
process.off("SIGINT", cancel2);
|
|
1872
|
+
process.off("SIGTERM", cancel2);
|
|
1873
|
+
unlock();
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
function hasDeviceCredential(profile) {
|
|
1877
|
+
return Boolean(
|
|
1878
|
+
profile?.device && !profile.device.revokedAt && profile.credentialExpiresAt && Date.parse(profile.credentialExpiresAt) > Date.now() && credentialStore(profile.id).read("device")
|
|
1879
|
+
);
|
|
1880
|
+
}
|
|
1881
|
+
async function localBots() {
|
|
1882
|
+
return Promise.all(
|
|
1883
|
+
listBotProfiles(directory).map(async (bot) => {
|
|
1884
|
+
try {
|
|
1885
|
+
return { ...bot, status: await daemonStatus(bot) };
|
|
1886
|
+
} catch (error) {
|
|
1887
|
+
return {
|
|
1888
|
+
...bot,
|
|
1889
|
+
status: void 0,
|
|
1890
|
+
statusError: error instanceof Error ? error.message : String(error)
|
|
1891
|
+
};
|
|
1892
|
+
}
|
|
1893
|
+
})
|
|
1894
|
+
);
|
|
1895
|
+
}
|
|
1896
|
+
function botRow({ profile, status, statusError }) {
|
|
1897
|
+
const adapter = profile.execution?.adapter ?? status?.adapter;
|
|
1898
|
+
return {
|
|
1899
|
+
id: profile.id,
|
|
1900
|
+
name: profile.name,
|
|
1901
|
+
...profile.workspace ? { workspace: profile.workspace.path } : {},
|
|
1902
|
+
...adapter ? { adapter } : {},
|
|
1903
|
+
state: status?.state ?? (statusError ? "UNAVAILABLE" : "STOPPED")
|
|
1904
|
+
};
|
|
1905
|
+
}
|
|
1906
|
+
function findBot(bots, id) {
|
|
1907
|
+
const bot = bots.find(
|
|
1908
|
+
({ profile }) => profile.id === id || profile.botId === id
|
|
1909
|
+
);
|
|
1910
|
+
if (!bot)
|
|
1911
|
+
throw new Error(`\u627E\u4E0D\u5230 Bot ${id}\u3002\u8BF7\u7528 bubai status --json \u67E5\u770B ID\u3002`);
|
|
1912
|
+
return bot;
|
|
1913
|
+
}
|
|
1914
|
+
async function chooseRunningBot(id) {
|
|
1915
|
+
if (id !== void 0) {
|
|
1916
|
+
const bot = findBot(listBotProfiles(directory), id);
|
|
1917
|
+
return { ...bot, status: await daemonStatus(bot) };
|
|
1918
|
+
}
|
|
1919
|
+
const bots = await localBots();
|
|
1920
|
+
const candidates = bots.filter(({ status }) => status !== void 0);
|
|
1921
|
+
if (candidates.length === 1) return candidates[0];
|
|
1922
|
+
if (!candidates.length) {
|
|
1923
|
+
console.log("\u6CA1\u6709\u8FD0\u884C\u4E2D\u7684 Bot\u3002");
|
|
1924
|
+
return;
|
|
1925
|
+
}
|
|
1926
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
1927
|
+
throw new Error("\u6709\u591A\u4E2A\u53EF\u9009 Bot\uFF0C\u8BF7\u4F7F\u7528 --bot \u6307\u5B9A ID\u3002");
|
|
1928
|
+
const { selectBot: selectBot2 } = await Promise.resolve().then(() => (init_start_prompts(), start_prompts_exports));
|
|
1929
|
+
const selected = await selectBot2(candidates.map(botRow), "stop");
|
|
1930
|
+
if (selected && selected !== "new") return findBot(candidates, selected.id);
|
|
1931
|
+
}
|
|
1932
|
+
async function startBot({ org }) {
|
|
1933
|
+
const { selectBot: selectBot2, promptBotStart: promptBotStart2, displayBotState: displayBotState2 } = await Promise.resolve().then(() => (init_start_prompts(), start_prompts_exports));
|
|
1934
|
+
const bots = await localBots();
|
|
1935
|
+
const selected = await selectBot2(bots.map(botRow), "start");
|
|
1936
|
+
if (!selected) return;
|
|
1937
|
+
const existing = selected === "new" ? void 0 : findBot(bots, selected.id);
|
|
1938
|
+
if (existing && org !== void 0 && org !== existing.profile.orgId)
|
|
1939
|
+
throw new Error("--org \u7528\u4E8E\u65B0\u5EFA Bot\u3002\u5DF2\u6709 Bot \u6CBF\u7528\u6CE8\u518C\u65F6\u7684\u7EC4\u7EC7\u3002");
|
|
1940
|
+
if (existing?.statusError)
|
|
1941
|
+
throw new Error(
|
|
1942
|
+
`\u65E0\u6CD5\u67E5\u8BE2\u300C${existing.profile.name}\u300D\u7684\u72B6\u6001\u3002 ${existing.statusError}`
|
|
1943
|
+
);
|
|
1944
|
+
if (existing?.status) {
|
|
1945
|
+
console.log(
|
|
1946
|
+
`${existing.profile.name} ${displayBotState2(existing.status.state)}`
|
|
1947
|
+
);
|
|
1948
|
+
return;
|
|
1949
|
+
}
|
|
1950
|
+
const saved = existing?.profile;
|
|
1951
|
+
const selection = await promptBotStart2({
|
|
1952
|
+
cwd: saved?.workspace?.path ?? process.cwd(),
|
|
1953
|
+
loadModels: (adapter, cwd) => adapter === "agy" ? listAgyModels(cwd) : listCodexModels(cwd),
|
|
1954
|
+
...saved ? { name: saved.name } : {},
|
|
1955
|
+
...saved?.workspace && saved.execution ? { saved: { workspace: saved.workspace.path, ...saved.execution } } : {}
|
|
1956
|
+
});
|
|
1957
|
+
if (!selection) return;
|
|
1958
|
+
const { name, workspace, ...execution } = selection;
|
|
1959
|
+
const origin = readProfile(directory)?.apiOrigin ?? apiOrigin(process.env.BUBAI_API_URL ?? defaultApi);
|
|
1960
|
+
const bot = existing ? {
|
|
1961
|
+
directory: existing.directory,
|
|
1962
|
+
profile: saveBotStart(existing.directory, origin, workspace, execution)
|
|
1963
|
+
} : createBotProfile(directory, origin, name, workspace, execution, org);
|
|
1964
|
+
if (!hasDeviceCredential(readProfile(directory))) {
|
|
1965
|
+
await login({
|
|
1966
|
+
open: false,
|
|
1967
|
+
deviceName: hostname(),
|
|
1968
|
+
showQr: true,
|
|
1969
|
+
reuseDevice: true
|
|
1970
|
+
});
|
|
1971
|
+
}
|
|
1972
|
+
console.log("\u6B63\u5728\u8FDE\u63A5 Relay\u2026");
|
|
1973
|
+
await startBotServer(bot.directory, {
|
|
1974
|
+
expectedExecution: executionFingerprint(bot.profile)
|
|
1975
|
+
});
|
|
1976
|
+
console.log(`\u2713 ${name} \u5DF2\u5728\u7EBF`);
|
|
1977
|
+
console.log("\u4F7F\u7528\u540C\u4E00\u8D26\u53F7\u5728\u5BA2\u6237\u7AEF\u7684 Bot \u5217\u8868\u4E2D\u6253\u5F00\u3002");
|
|
1978
|
+
}
|
|
1979
|
+
var program = new Command().name("bubai").description("Bubai Bot CLI").version(package_default.version);
|
|
1980
|
+
var botCommands = program.command("bot").description("Manage local Bots");
|
|
1981
|
+
botCommands.command("start").description("Select or create a Bot, then start it").option("--org <id>", "Organization ID for a new Bot").action(startBot);
|
|
1982
|
+
botCommands.command("call <bot-id> <method> [payload]").description("Call a Bot Server as the signed-in user").option("--request-id <id>", "Use this request ID for result recovery").option("--watch", "Read events until the connection closes").action(
|
|
1983
|
+
(botId, method, payload = "{}", options) => callBot(directory, botId, method, payload, options)
|
|
1984
|
+
);
|
|
1985
|
+
program.command("agents").description("List Adapters and local readiness").option("--json", "Print JSON").action(async ({ json }) => {
|
|
1986
|
+
const [localStatus, agyStatus] = await Promise.all([
|
|
1987
|
+
codexLoginStatus(process.cwd()).catch(() => "unknown"),
|
|
1988
|
+
agyLoginStatus(process.cwd()).catch(() => "unknown")
|
|
1989
|
+
]);
|
|
1990
|
+
if (json) {
|
|
1991
|
+
print([
|
|
1992
|
+
{ ...codexDescriptor, localStatus },
|
|
1993
|
+
{ ...agyDescriptor, localStatus: agyStatus },
|
|
1994
|
+
claudeDescriptor
|
|
1995
|
+
]);
|
|
1996
|
+
return;
|
|
1997
|
+
}
|
|
1998
|
+
const labels = {
|
|
1999
|
+
"signed-in": "\u53EF\u7528 \xB7 \u672C\u673A\u5DF2\u767B\u5F55",
|
|
2000
|
+
"signed-out": "\u5F85\u767B\u5F55 \xB7 \u8FD0\u884C codex login",
|
|
2001
|
+
"not-installed": "\u672A\u5B89\u88C5",
|
|
2002
|
+
unknown: "\u65E0\u6CD5\u68C0\u67E5\u672C\u673A\u767B\u5F55\u72B6\u6001"
|
|
2003
|
+
};
|
|
2004
|
+
console.log(`Codex ${labels[localStatus]}`);
|
|
2005
|
+
console.log(
|
|
2006
|
+
`agy ${agyStatus === "signed-out" ? "\u5F85\u767B\u5F55 \xB7 \u5728 agy \u4E2D\u767B\u5F55" : labels[agyStatus]}`
|
|
2007
|
+
);
|
|
2008
|
+
console.log("Claude \u5F85\u63A5\u5165");
|
|
2009
|
+
});
|
|
2010
|
+
program.command("init").description("Initialize a local Bot profile").option("--api <url>", "API origin", process.env.BUBAI_API_URL ?? defaultApi).option("--name <name>", "Bot name", "Bubai").option("--workspace <path>", "Explicitly provision a local workspace").action((options) => {
|
|
2011
|
+
const name = options.name.trim();
|
|
2012
|
+
if (!name || name.length > 100) {
|
|
2013
|
+
throw new Error("Bot name must contain between 1 and 100 characters.");
|
|
2014
|
+
}
|
|
2015
|
+
const { profile, initialized } = initialize(
|
|
2016
|
+
directory,
|
|
2017
|
+
apiOrigin(options.api),
|
|
2018
|
+
name,
|
|
2019
|
+
options.workspace
|
|
2020
|
+
);
|
|
2021
|
+
print({
|
|
2022
|
+
status: initialized ? "INITIALIZED" : "ALREADY_INITIALIZED",
|
|
2023
|
+
name: profile.name,
|
|
2024
|
+
api: profile.apiOrigin
|
|
2025
|
+
});
|
|
2026
|
+
});
|
|
2027
|
+
program.command("login").description("Log this device in with browser approval").option("--no-open", "Print the approval URL without opening a browser").option("--device-name <name>", "Name shown on the approval page", hostname()).action(login);
|
|
2028
|
+
function advancedBot(id) {
|
|
2029
|
+
const bots = listBotProfiles(directory);
|
|
2030
|
+
if (id !== void 0) return findBot(bots, id);
|
|
2031
|
+
const legacy = bots.find((bot) => bot.directory === directory);
|
|
2032
|
+
if (legacy) return legacy;
|
|
2033
|
+
if (bots.length === 1) return bots[0];
|
|
2034
|
+
if (!bots.length) throw new Error("\u8BF7\u5148\u8FD0\u884C bubai bot start \u65B0\u5EFA Bot\u3002");
|
|
2035
|
+
throw new Error("\u6709\u591A\u4E2A Bot\uFF0C\u8BF7\u4F7F\u7528 --bot \u6307\u5B9A ID\u3002");
|
|
2036
|
+
}
|
|
2037
|
+
program.command("start").description("Start a local Bot Server for advanced use").option("--foreground", "Run Bot Server in the current terminal").option("--bot <id>", "Select the Bot by ID").action(
|
|
2038
|
+
async ({ foreground, bot: id }) => {
|
|
2039
|
+
const bot = advancedBot(id);
|
|
2040
|
+
const running = await daemonStatus(bot);
|
|
2041
|
+
if (running) {
|
|
2042
|
+
print(running);
|
|
2043
|
+
return;
|
|
2044
|
+
}
|
|
2045
|
+
await startBotServer(bot.directory, {
|
|
2046
|
+
...foreground ? { foreground } : {},
|
|
2047
|
+
onReady: print
|
|
2048
|
+
});
|
|
2049
|
+
}
|
|
2050
|
+
);
|
|
2051
|
+
program.command("stop").description("Stop one local Bot").option("--bot <id>", "Select the Bot by ID").action(async ({ bot: id }) => {
|
|
2052
|
+
const bot = await chooseRunningBot(id);
|
|
2053
|
+
if (!bot) return;
|
|
2054
|
+
const { name } = bot.profile;
|
|
2055
|
+
if (bot.status) {
|
|
2056
|
+
console.log(`\u6B63\u5728\u505C\u6B62\u300C${name}\u300D\u2026`);
|
|
2057
|
+
try {
|
|
2058
|
+
await callDaemon(
|
|
2059
|
+
bot.directory,
|
|
2060
|
+
"stop",
|
|
2061
|
+
() => credentialStore(bot.profile.id).read("ipc")
|
|
2062
|
+
);
|
|
2063
|
+
const path = socketPath(bot.directory);
|
|
2064
|
+
const deadline = Date.now() + 5e3;
|
|
2065
|
+
while (existsSync3(path)) {
|
|
2066
|
+
if (Date.now() >= deadline)
|
|
2067
|
+
throw new Error(`\u300C${name}\u300D\u4ECD\u5728\u505C\u6B62\u4E2D\u3002`);
|
|
2068
|
+
await delay(100);
|
|
2069
|
+
}
|
|
2070
|
+
} catch (error) {
|
|
2071
|
+
if (!isDaemonUnavailable(error)) throw error;
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
console.log(`\u2713 ${name} \u5DF2\u505C\u6B62`);
|
|
2075
|
+
});
|
|
2076
|
+
program.command("status").description("List all local Bots").option("--json", "Print JSON with Bot IDs").option("--api <url>", "Check API health at the given origin").action(async ({ json, api }) => {
|
|
2077
|
+
const profiles = await localBots();
|
|
2078
|
+
const deviceId = readProfile(directory)?.device?.id;
|
|
2079
|
+
const bots = profiles.map((bot) => ({
|
|
2080
|
+
...bot.status,
|
|
2081
|
+
...botRow(bot),
|
|
2082
|
+
botId: bot.status?.botId ?? bot.profile.botId,
|
|
2083
|
+
deviceId,
|
|
2084
|
+
localReady: bot.status?.localReady ?? false,
|
|
2085
|
+
...bot.statusError ? { error: bot.statusError } : {}
|
|
2086
|
+
}));
|
|
2087
|
+
if (api) {
|
|
2088
|
+
const health = await createApiClient(api).health();
|
|
2089
|
+
print({ bots, api: health });
|
|
2090
|
+
return;
|
|
2091
|
+
}
|
|
2092
|
+
if (json) {
|
|
2093
|
+
print({ bots });
|
|
2094
|
+
return;
|
|
2095
|
+
}
|
|
2096
|
+
if (!bots.length) {
|
|
2097
|
+
console.log("\u672C\u673A\u6682\u65E0 Bot\u3002\u8FD0\u884C bubai bot start \u65B0\u5EFA\u3002");
|
|
2098
|
+
return;
|
|
2099
|
+
}
|
|
2100
|
+
const { displayBotState: displayBotState2, displayWorkspace: displayWorkspace2 } = await Promise.resolve().then(() => (init_start_prompts(), start_prompts_exports));
|
|
2101
|
+
console.table(
|
|
2102
|
+
bots.map((bot) => ({
|
|
2103
|
+
Bot: bot.name,
|
|
2104
|
+
Adapter: bot.adapter === "codex" ? "Codex" : bot.adapter === "agy" ? "agy" : "\u2014",
|
|
2105
|
+
\u5DE5\u4F5C\u533A: displayWorkspace2(bot.workspace),
|
|
2106
|
+
\u72B6\u6001: displayBotState2(bot.state)
|
|
2107
|
+
}))
|
|
2108
|
+
);
|
|
2109
|
+
});
|
|
2110
|
+
program.command("devices").description("Show the shared authorization of this CLI device").option("--json", "Print JSON").action(({ json }) => {
|
|
2111
|
+
const profile = readProfile(directory);
|
|
2112
|
+
const device = profile?.device;
|
|
2113
|
+
if (json) {
|
|
2114
|
+
print({
|
|
2115
|
+
device: device ?? null,
|
|
2116
|
+
credentialExpiresAt: profile?.credentialExpiresAt
|
|
2117
|
+
});
|
|
2118
|
+
return;
|
|
2119
|
+
}
|
|
2120
|
+
if (!device) {
|
|
2121
|
+
console.log("\u672C\u673A CLI \u8BBE\u5907\u5C1A\u672A\u6279\u51C6\u3002");
|
|
2122
|
+
return;
|
|
2123
|
+
}
|
|
2124
|
+
const state = device.revokedAt ? "\u5DF2\u64A4\u9500" : hasDeviceCredential(profile) ? "\u5DF2\u6279\u51C6" : "\u5F85\u91CD\u65B0\u6279\u51C6";
|
|
2125
|
+
console.log(`\u8BBE\u5907 ${device.name}`);
|
|
2126
|
+
console.log("\u7C7B\u578B CLI");
|
|
2127
|
+
console.log(`\u72B6\u6001 ${state}`);
|
|
2128
|
+
console.log(`\u51ED\u8BC1\u5230\u671F ${profile?.credentialExpiresAt ?? "\u2014"}`);
|
|
2129
|
+
});
|
|
2130
|
+
try {
|
|
2131
|
+
await program.parseAsync();
|
|
2132
|
+
} catch (error) {
|
|
2133
|
+
console.error(error instanceof Error ? error.message : "CLI command failed");
|
|
2134
|
+
process.exitCode = 1;
|
|
2135
|
+
}
|