@guandata/decidex 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 +198 -0
- package/package.json +24 -0
- package/src/cli.js +1162 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,1162 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { access, chmod, link, lstat, mkdir, readFile, realpath, rename, unlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
8
|
+
import { parseArgs } from "node:util";
|
|
9
|
+
|
|
10
|
+
const COOKIE_NAME = "decidex_session";
|
|
11
|
+
const DEFAULT_CONFIG_PATH = join(homedir(), ".config", "decidex", "config.json");
|
|
12
|
+
|
|
13
|
+
const HELP = `decidex - Decidex command line client
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
decidex auth login --base-url URL [--timeout SECONDS]
|
|
17
|
+
decidex auth import --base-url URL # read decidex_session or Cookie header from stdin
|
|
18
|
+
decidex auth status
|
|
19
|
+
decidex auth logout
|
|
20
|
+
decidex context show
|
|
21
|
+
decidex org use ID
|
|
22
|
+
|
|
23
|
+
decidex agent list
|
|
24
|
+
decidex agent get ID
|
|
25
|
+
decidex agent apply FILE # create; update when FILE contains id
|
|
26
|
+
decidex agent export ID FILE
|
|
27
|
+
decidex agent import FILE # Personal Agent Transfer Bundle
|
|
28
|
+
decidex agent publish ID (--email EMAIL | --user-id ID)
|
|
29
|
+
decidex agent unpublish ID --user-id ID
|
|
30
|
+
decidex agent file list ID
|
|
31
|
+
decidex agent file add ID FILE...
|
|
32
|
+
decidex agent file delete ID FILE_ID
|
|
33
|
+
decidex agent file download ID FILE_ID FILE
|
|
34
|
+
decidex agent models ID
|
|
35
|
+
decidex agent run ID (--message TEXT | --input FILE) [--wait] [--follow] [--output FILE] [--timeout SECONDS]
|
|
36
|
+
|
|
37
|
+
decidex session list [--status all|running|completed] [--query TEXT]
|
|
38
|
+
decidex session view SESSION_ID
|
|
39
|
+
decidex session send SESSION_ID (--message TEXT | --input FILE) [--wait] [--follow]
|
|
40
|
+
decidex session stop SESSION_ID
|
|
41
|
+
decidex session artifacts list SESSION_ID
|
|
42
|
+
decidex session artifacts download SESSION_ID --all --dir DIR [--overwrite]
|
|
43
|
+
decidex run diagnose RUN_ID [--session-id ID] [--agent-id ID] --json
|
|
44
|
+
|
|
45
|
+
decidex skill list
|
|
46
|
+
decidex skill upload FILE
|
|
47
|
+
decidex skill update ID FILE
|
|
48
|
+
decidex skill download ID FILE
|
|
49
|
+
decidex skill delete ID
|
|
50
|
+
|
|
51
|
+
decidex eval cases list AGENT_ID
|
|
52
|
+
decidex eval cases export AGENT_ID FILE
|
|
53
|
+
decidex eval cases plan AGENT_ID FILE [--prune]
|
|
54
|
+
decidex eval cases apply AGENT_ID FILE [--prune]
|
|
55
|
+
decidex eval run AGENT_ID FILE [--cases all] [--wait] [--output FILE] [--timeout SECONDS]
|
|
56
|
+
decidex eval stop AGENT_ID RUN_ID
|
|
57
|
+
|
|
58
|
+
decidex ontology list
|
|
59
|
+
decidex ontology get ID
|
|
60
|
+
decidex ontology export ID FILE [--version-id ID]
|
|
61
|
+
decidex ontology plan FILE [--network-id ID] [--name NAME]
|
|
62
|
+
decidex ontology apply FILE [--network-id ID] [--name NAME]
|
|
63
|
+
|
|
64
|
+
decidex api METHOD PATH [--data FILE] [--output FILE]
|
|
65
|
+
decidex version --json
|
|
66
|
+
|
|
67
|
+
Environment:
|
|
68
|
+
DECIDEX_BASE_URL, DECIDEX_SESSION, DECIDEX_CONFIG, DECIDEX_CHROME_PATH,
|
|
69
|
+
DECIDEX_ALLOW_INSECURE_HTTP=1
|
|
70
|
+
`;
|
|
71
|
+
|
|
72
|
+
const HELP_BY_COMMAND = {
|
|
73
|
+
auth: `Usage:
|
|
74
|
+
decidex auth login --base-url URL [--timeout SECONDS]
|
|
75
|
+
decidex auth import --base-url URL
|
|
76
|
+
decidex auth status
|
|
77
|
+
decidex auth logout`,
|
|
78
|
+
agent: `Usage:
|
|
79
|
+
decidex agent list|get|apply|export|import ...
|
|
80
|
+
decidex agent file list|add|delete|download ...
|
|
81
|
+
decidex agent models AGENT_ID
|
|
82
|
+
decidex agent run AGENT_ID (--message TEXT | --input FILE) [--wait] [--follow] [--output FILE]`,
|
|
83
|
+
"agent run": `Usage:
|
|
84
|
+
decidex agent run AGENT_ID (--message TEXT | --input FILE) [--wait] [--follow] [--output FILE] [--timeout SECONDS]
|
|
85
|
+
|
|
86
|
+
With --wait, emits a stable JSON result containing sessionId, runId, status,
|
|
87
|
+
error, answer, artifacts, startedAt, finishedAt, and durationMs. --follow writes progress
|
|
88
|
+
to stderr, so stdout or --output remains machine-readable.`,
|
|
89
|
+
session: `Usage:
|
|
90
|
+
decidex session list [--status all|running|completed] [--query TEXT]
|
|
91
|
+
decidex session view SESSION_ID
|
|
92
|
+
decidex session send SESSION_ID (--message TEXT | --input FILE) [--wait] [--follow]
|
|
93
|
+
decidex session stop SESSION_ID
|
|
94
|
+
decidex session artifacts ...
|
|
95
|
+
|
|
96
|
+
With --wait, the message must start immediately; a busy session returns a conflict instead
|
|
97
|
+
of queuing an untrackable run. Without --wait, the result can be kind=direct or kind=queued.`,
|
|
98
|
+
"session artifacts": `Usage:
|
|
99
|
+
decidex session artifacts list SESSION_ID
|
|
100
|
+
decidex session artifacts download SESSION_ID --all --dir DIR [--overwrite]`,
|
|
101
|
+
"run diagnose": `Usage:
|
|
102
|
+
decidex run diagnose RUN_ID [--session-id ID] [--agent-id ID] --json
|
|
103
|
+
|
|
104
|
+
Without explicit IDs, the CLI uses a matching recent local Run context.
|
|
105
|
+
Runtime Pod termination details require backend support.`,
|
|
106
|
+
skill: `Usage:
|
|
107
|
+
decidex skill list
|
|
108
|
+
decidex skill upload FILE
|
|
109
|
+
decidex skill update ID FILE
|
|
110
|
+
decidex skill download ID FILE
|
|
111
|
+
decidex skill delete ID`,
|
|
112
|
+
eval: `Usage:
|
|
113
|
+
decidex eval cases list|export|plan|apply ...
|
|
114
|
+
decidex eval run AGENT_ID FILE [--cases all] [--wait] [--output FILE]
|
|
115
|
+
decidex eval stop AGENT_ID RUN_ID`,
|
|
116
|
+
"eval cases": `Usage:
|
|
117
|
+
decidex eval cases list AGENT_ID
|
|
118
|
+
decidex eval cases export AGENT_ID FILE
|
|
119
|
+
decidex eval cases plan AGENT_ID FILE [--prune]
|
|
120
|
+
decidex eval cases apply AGENT_ID FILE [--prune]`,
|
|
121
|
+
ontology: `Usage:
|
|
122
|
+
decidex ontology list|get|export|plan|apply ...`,
|
|
123
|
+
api: `Usage:
|
|
124
|
+
decidex api METHOD PATH [--data FILE] [--output FILE]`,
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
function commandArgs(args, options = {}) {
|
|
128
|
+
return parseArgs({
|
|
129
|
+
args,
|
|
130
|
+
allowPositionals: true,
|
|
131
|
+
options: {
|
|
132
|
+
"base-url": { type: "string" },
|
|
133
|
+
json: { type: "boolean", default: false },
|
|
134
|
+
...options,
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function normalizeBaseUrl(value) {
|
|
140
|
+
let url;
|
|
141
|
+
try {
|
|
142
|
+
url = new URL(value);
|
|
143
|
+
} catch {
|
|
144
|
+
throw new Error("base URL 必须是根路径 HTTP(S) 地址,例如 https://decidex.example.com");
|
|
145
|
+
}
|
|
146
|
+
if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
|
147
|
+
throw new Error("base URL 必须是根路径 HTTP(S) 地址,例如 https://decidex.example.com");
|
|
148
|
+
}
|
|
149
|
+
const localHosts = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
150
|
+
if (url.protocol === "http:" && !localHosts.has(url.hostname) && process.env.DECIDEX_ALLOW_INSECURE_HTTP !== "1") {
|
|
151
|
+
throw new Error("拒绝通过 HTTP 传输登录态;如目标确为可信内网,设置 DECIDEX_ALLOW_INSECURE_HTTP=1");
|
|
152
|
+
}
|
|
153
|
+
return url.origin;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function configPath() {
|
|
157
|
+
return process.env.DECIDEX_CONFIG || DEFAULT_CONFIG_PATH;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function readConfig() {
|
|
161
|
+
try {
|
|
162
|
+
return JSON.parse(await readFile(configPath(), "utf8"));
|
|
163
|
+
} catch (error) {
|
|
164
|
+
if (error?.code === "ENOENT") return {};
|
|
165
|
+
throw new Error(`配置文件读取失败:${error.message}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function saveConfig(update) {
|
|
170
|
+
const file = configPath();
|
|
171
|
+
const value = { ...(await readConfig()), ...update };
|
|
172
|
+
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
173
|
+
const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
174
|
+
try {
|
|
175
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
176
|
+
await chmod(temporary, 0o600);
|
|
177
|
+
await rename(temporary, file);
|
|
178
|
+
} finally {
|
|
179
|
+
await unlink(temporary).catch((error) => {
|
|
180
|
+
if (error?.code !== "ENOENT") throw error;
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function auth(values = {}) {
|
|
186
|
+
const stored = await readConfig();
|
|
187
|
+
const optionBaseUrl = values["base-url"];
|
|
188
|
+
const environmentBaseUrl = process.env.DECIDEX_BASE_URL;
|
|
189
|
+
const environmentSession = process.env.DECIDEX_SESSION;
|
|
190
|
+
if (environmentSession && !(environmentBaseUrl || optionBaseUrl)) {
|
|
191
|
+
throw new Error("DECIDEX_BASE_URL 与 DECIDEX_SESSION 必须成对设置");
|
|
192
|
+
}
|
|
193
|
+
const baseUrl = optionBaseUrl || environmentBaseUrl || stored.baseUrl;
|
|
194
|
+
const session = environmentSession || stored.session;
|
|
195
|
+
if (!baseUrl) throw new Error("缺少 Decidex 地址;先运行 decidex auth login --base-url URL");
|
|
196
|
+
if (!session) throw new Error("缺少登录态;先运行 decidex auth login 或 auth import");
|
|
197
|
+
const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
|
|
198
|
+
if ((optionBaseUrl || environmentBaseUrl) && !environmentSession && stored.session && (!stored.baseUrl || normalizedBaseUrl !== normalizeBaseUrl(stored.baseUrl))) {
|
|
199
|
+
throw new Error("拒绝把已保存的登录态发送到其他 Decidex 地址;请重新 login/import,或成对设置环境变量");
|
|
200
|
+
}
|
|
201
|
+
return { baseUrl: normalizedBaseUrl, session, organizationId: stored.organizationId ?? null };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function request(path, { method = "GET", body, deadline, headers: extraHeaders, output, returnBytes = false, values } = {}) {
|
|
205
|
+
const credentials = await auth(values);
|
|
206
|
+
const url = new URL(path, `${credentials.baseUrl}/`);
|
|
207
|
+
if (url.origin !== credentials.baseUrl) throw new Error("API path 不能指向其他主机");
|
|
208
|
+
const headers = {
|
|
209
|
+
...extraHeaders,
|
|
210
|
+
accept: "application/json",
|
|
211
|
+
cookie: `${COOKIE_NAME}=${credentials.session}`,
|
|
212
|
+
};
|
|
213
|
+
let requestBody;
|
|
214
|
+
if (body instanceof FormData) {
|
|
215
|
+
requestBody = body;
|
|
216
|
+
} else if (body instanceof Uint8Array) {
|
|
217
|
+
requestBody = body;
|
|
218
|
+
headers["content-type"] = "application/octet-stream";
|
|
219
|
+
} else if (body !== undefined) {
|
|
220
|
+
requestBody = JSON.stringify(body);
|
|
221
|
+
headers["content-type"] = "application/json";
|
|
222
|
+
}
|
|
223
|
+
const remaining = deadline ? deadline - Date.now() : null;
|
|
224
|
+
if (remaining !== null && remaining <= 0) throw new Error("等待运行完成超时");
|
|
225
|
+
let response;
|
|
226
|
+
try {
|
|
227
|
+
response = await fetch(url, {
|
|
228
|
+
method,
|
|
229
|
+
headers,
|
|
230
|
+
body: requestBody,
|
|
231
|
+
redirect: "manual",
|
|
232
|
+
signal: remaining === null ? undefined : AbortSignal.timeout(remaining),
|
|
233
|
+
});
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (error?.name === "TimeoutError" || error?.name === "AbortError") throw new Error("等待运行完成超时");
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
239
|
+
const contentType = response.headers.get("content-type") || "";
|
|
240
|
+
const text = new TextDecoder().decode(bytes);
|
|
241
|
+
let payload = text;
|
|
242
|
+
if (contentType.includes("json")) {
|
|
243
|
+
try {
|
|
244
|
+
payload = JSON.parse(text);
|
|
245
|
+
} catch {
|
|
246
|
+
// Keep the server text when a proxy labels malformed JSON as JSON.
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (!response.ok) {
|
|
250
|
+
const detail = payload && typeof payload === "object" ? payload.error || JSON.stringify(payload) : payload;
|
|
251
|
+
const error = new Error(`Decidex ${response.status}: ${detail || response.statusText}`);
|
|
252
|
+
error.httpStatus = response.status;
|
|
253
|
+
error.code = payload && typeof payload === "object" ? payload.code : undefined;
|
|
254
|
+
error.requestId = payload && typeof payload === "object" ? payload.requestId : undefined;
|
|
255
|
+
throw error;
|
|
256
|
+
}
|
|
257
|
+
if (returnBytes) return bytes;
|
|
258
|
+
if (output) {
|
|
259
|
+
await writeFile(resolve(output), bytes);
|
|
260
|
+
return { output: resolve(output), bytes: bytes.byteLength };
|
|
261
|
+
}
|
|
262
|
+
return payload === "" ? { ok: true } : payload;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function emit(value, output) {
|
|
266
|
+
if (output) {
|
|
267
|
+
const file = resolve(output);
|
|
268
|
+
await writeFile(file, `${JSON.stringify(value, null, 2)}\n`);
|
|
269
|
+
print({ output: file });
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
print(value);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function print(value) {
|
|
276
|
+
process.stdout.write(`${typeof value === "string" ? value : JSON.stringify(value, null, 2)}\n`);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function readJsonFile(file) {
|
|
280
|
+
const source = file === "-" ? await readStdin("JSON") : await readFile(resolve(file), "utf8");
|
|
281
|
+
try {
|
|
282
|
+
return JSON.parse(source);
|
|
283
|
+
} catch (error) {
|
|
284
|
+
throw new Error(`${file === "-" ? "stdin" : file} 不是合法 JSON:${error.message}`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async function readMessage(values) {
|
|
289
|
+
if (Boolean(values.message) === Boolean(values.input)) throw new Error("必须且只能指定 --message TEXT 或 --input FILE;--input - 表示 stdin");
|
|
290
|
+
const message = values.message ?? (values.input === "-" ? await readStdin("消息") : await readFile(resolve(values.input), "utf8"));
|
|
291
|
+
if (!message.trim()) throw new Error("消息不能为空");
|
|
292
|
+
return message;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function uploadForm(files, field = "file") {
|
|
296
|
+
const form = new FormData();
|
|
297
|
+
for (const file of files) {
|
|
298
|
+
const path = resolve(file);
|
|
299
|
+
form.append(field, new Blob([await readFile(path)]), basename(path));
|
|
300
|
+
}
|
|
301
|
+
return form;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function positiveSeconds(value, name = "timeout") {
|
|
305
|
+
const seconds = Number(value);
|
|
306
|
+
if (!Number.isFinite(seconds) || seconds <= 0) throw new Error(`${name} 必须是正数秒`);
|
|
307
|
+
return seconds;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function poll(fetchValue, isTerminal, timeoutSeconds, onValue) {
|
|
311
|
+
const deadline = Date.now() + timeoutSeconds * 1000;
|
|
312
|
+
while (Date.now() < deadline) {
|
|
313
|
+
const value = await fetchValue(deadline);
|
|
314
|
+
await onValue?.(value);
|
|
315
|
+
if (isTerminal(value)) return value;
|
|
316
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 2_000));
|
|
317
|
+
}
|
|
318
|
+
throw new Error(`等待运行完成超时(${timeoutSeconds} 秒)`);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function runPath(agentId, sessionId, runId) {
|
|
322
|
+
return `/api/personal-agents/${encodeURIComponent(agentId)}/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}`;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function sessionPath(agentId, sessionId) {
|
|
326
|
+
return `/api/personal-agents/${encodeURIComponent(agentId)}/sessions/${encodeURIComponent(sessionId)}`;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function rememberRun(agentId, sessionId, runId, values) {
|
|
330
|
+
const config = await readConfig();
|
|
331
|
+
const credentials = await auth(values);
|
|
332
|
+
const recentRuns = [
|
|
333
|
+
{ agentId, sessionId, runId, baseUrl: credentials.baseUrl, organizationId: credentials.organizationId },
|
|
334
|
+
...(config.recentRuns ?? []).filter((item) => item.runId !== runId),
|
|
335
|
+
].slice(0, 50);
|
|
336
|
+
await saveConfig({ recentRuns });
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async function rememberRunBestEffort(agentId, sessionId, runId, values) {
|
|
340
|
+
await rememberRun(agentId, sessionId, runId, values).catch((error) => {
|
|
341
|
+
process.stderr.write(`[decidex] warning: Run 已启动,但本地历史保存失败:${error.message}\n`);
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function turnForRun(view, runId) {
|
|
346
|
+
return (view.messages ?? []).find((message) => message.turn?.id === runId)?.turn ?? null;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function artifactsForRun(view, runId) {
|
|
350
|
+
return (turnForRun(view, runId)?.outputs ?? []).map((item) =>
|
|
351
|
+
item.kind === "FILE"
|
|
352
|
+
? { name: item.name, path: item.relativePath, sizeBytes: item.sizeBytes }
|
|
353
|
+
: { name: item.appSlug, path: item.rootDir, entryPath: item.entryRelativePath, fileCount: item.fileCount },
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function answerForRun(view, runId) {
|
|
358
|
+
return (view.messages ?? []).find((message) => message.turn?.id === runId && message.role === "ASSISTANT")?.content ?? null;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function elapsedMs(startedAt, finishedAt) {
|
|
362
|
+
if (!startedAt || !finishedAt) return null;
|
|
363
|
+
const value = Date.parse(finishedAt) - Date.parse(startedAt);
|
|
364
|
+
return Number.isFinite(value) && value >= 0 ? value : null;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function finalRunResult(sessionId, runId, statusResult, view) {
|
|
368
|
+
const run = statusResult.run;
|
|
369
|
+
return {
|
|
370
|
+
schemaVersion: 1,
|
|
371
|
+
sessionId,
|
|
372
|
+
runId,
|
|
373
|
+
status: run.status,
|
|
374
|
+
error: run.error ?? null,
|
|
375
|
+
answer: answerForRun(view, runId),
|
|
376
|
+
artifacts: artifactsForRun(view, runId),
|
|
377
|
+
startedAt: run.startedAt ?? null,
|
|
378
|
+
finishedAt: run.finishedAt ?? null,
|
|
379
|
+
durationMs: elapsedMs(run.startedAt, run.finishedAt),
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function followProgress(view, runId, seen) {
|
|
384
|
+
const message = (view.messages ?? []).find((candidate) => candidate.turn?.id === runId);
|
|
385
|
+
for (const item of message?.timelineItems ?? []) {
|
|
386
|
+
if (seen.has(item.id)) continue;
|
|
387
|
+
seen.add(item.id);
|
|
388
|
+
const text = item.type === "event" ? `${item.event.status}: ${item.event.title}` : item.content.replace(/\s+/g, " ").trim();
|
|
389
|
+
if (text) process.stderr.write(`[decidex] ${text.slice(0, 240)}\n`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function waitForRun(agentId, sessionId, runId, values) {
|
|
394
|
+
process.stderr.write(`[decidex] started session=${sessionId} run=${runId}\n`);
|
|
395
|
+
let lastStatus;
|
|
396
|
+
let lastHeartbeatAt = 0;
|
|
397
|
+
let runDeadline;
|
|
398
|
+
const seen = new Set();
|
|
399
|
+
try {
|
|
400
|
+
const finished = await poll(
|
|
401
|
+
(deadline) => {
|
|
402
|
+
runDeadline = deadline;
|
|
403
|
+
return request(runPath(agentId, sessionId, runId), { deadline, values });
|
|
404
|
+
},
|
|
405
|
+
(result) => ["SUCCEEDED", "CANCELED", "FAILED"].includes(result.run.status),
|
|
406
|
+
positiveSeconds(values.timeout),
|
|
407
|
+
values.follow
|
|
408
|
+
? async (result) => {
|
|
409
|
+
if (result.run.status !== lastStatus || Date.now() - lastHeartbeatAt >= 10_000) {
|
|
410
|
+
process.stderr.write(`[decidex] run ${result.run.status}\n`);
|
|
411
|
+
lastStatus = result.run.status;
|
|
412
|
+
lastHeartbeatAt = Date.now();
|
|
413
|
+
}
|
|
414
|
+
followProgress(await request(`${sessionPath(agentId, sessionId)}/view`, { deadline: runDeadline, values }), runId, seen);
|
|
415
|
+
}
|
|
416
|
+
: undefined,
|
|
417
|
+
);
|
|
418
|
+
const view = await request(`${sessionPath(agentId, sessionId)}/view`, { deadline: runDeadline, values });
|
|
419
|
+
return finalRunResult(sessionId, runId, finished, view);
|
|
420
|
+
} catch (error) {
|
|
421
|
+
error.message = `${error.message}; sessionId=${sessionId}; runId=${runId}; 可运行 decidex run diagnose ${runId} --session-id ${sessionId}`;
|
|
422
|
+
throw error;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async function resolveSession(sessionId, values) {
|
|
427
|
+
const result = await request(`/api/agent-sessions?sessionId=${encodeURIComponent(sessionId)}`, { values });
|
|
428
|
+
const session = (result.sessions ?? []).find((item) => item.id === sessionId);
|
|
429
|
+
if (!session?.agentId) throw new Error(`会话不存在或无权访问:${sessionId}`);
|
|
430
|
+
return session;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async function listSessionArtifacts(agentId, sessionId, values) {
|
|
434
|
+
const result = await request(`${sessionPath(agentId, sessionId)}/files?force=1`, { values });
|
|
435
|
+
return (result.files ?? []).filter((file) => file.relativePath?.startsWith("artifacts/"));
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function safeDestination(root, artifactPath) {
|
|
439
|
+
const destination = resolve(root, artifactPath.replace(/^artifacts\//, ""));
|
|
440
|
+
const child = relative(root, destination);
|
|
441
|
+
if (!child || child.startsWith("..") || isAbsolute(child)) throw new Error(`非法产物路径:${artifactPath}`);
|
|
442
|
+
return destination;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
async function assertSafeArtifactTarget(root, destination, overwrite) {
|
|
446
|
+
let current = root;
|
|
447
|
+
for (const part of relative(root, dirname(destination)).split(sep).filter((item) => item && item !== ".")) {
|
|
448
|
+
current = join(current, part);
|
|
449
|
+
const stat = await lstat(current).catch((error) => {
|
|
450
|
+
if (error?.code === "ENOENT") return null;
|
|
451
|
+
throw error;
|
|
452
|
+
});
|
|
453
|
+
if (stat?.isSymbolicLink()) throw new Error(`拒绝写入符号链接目录:${current}`);
|
|
454
|
+
}
|
|
455
|
+
const stat = await lstat(destination).catch((error) => {
|
|
456
|
+
if (error?.code === "ENOENT") return null;
|
|
457
|
+
throw error;
|
|
458
|
+
});
|
|
459
|
+
if (stat?.isSymbolicLink()) throw new Error(`拒绝覆盖符号链接:${destination}`);
|
|
460
|
+
if (stat && !overwrite) throw new Error(`文件已存在:${destination};确认覆盖请加 --overwrite`);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function writeArtifact(root, destination, bytes, overwrite) {
|
|
464
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
465
|
+
await assertSafeArtifactTarget(root, destination, overwrite);
|
|
466
|
+
const temporary = join(dirname(destination), `.${basename(destination)}.${randomUUID()}.tmp`);
|
|
467
|
+
try {
|
|
468
|
+
await writeFile(temporary, bytes, { flag: "wx" });
|
|
469
|
+
if (overwrite) await rename(temporary, destination);
|
|
470
|
+
else {
|
|
471
|
+
await link(temporary, destination);
|
|
472
|
+
await unlink(temporary);
|
|
473
|
+
}
|
|
474
|
+
} finally {
|
|
475
|
+
await unlink(temporary).catch((error) => {
|
|
476
|
+
if (error?.code !== "ENOENT") throw error;
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
async function readStdin(label = "内容") {
|
|
482
|
+
if (process.stdin.isTTY) throw new Error(`请通过 stdin 传入${label}`);
|
|
483
|
+
const chunks = [];
|
|
484
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
485
|
+
return Buffer.concat(chunks).toString("utf8").trim();
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function sessionFromText(text) {
|
|
489
|
+
const match = text.match(new RegExp(`(?:^|[;\\s])${COOKIE_NAME}=([^;\\s]+)`));
|
|
490
|
+
const token = match?.[1] || text.trim();
|
|
491
|
+
if (!/^[A-Za-z0-9_-]{20,}$/.test(token)) throw new Error("未找到合法的 decidex_session");
|
|
492
|
+
return token;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async function chromeBinary() {
|
|
496
|
+
const candidates = [
|
|
497
|
+
process.env.DECIDEX_CHROME_PATH,
|
|
498
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
499
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
500
|
+
"/usr/bin/google-chrome",
|
|
501
|
+
"/usr/bin/chromium",
|
|
502
|
+
].filter(Boolean);
|
|
503
|
+
for (const candidate of candidates) {
|
|
504
|
+
try {
|
|
505
|
+
await access(candidate);
|
|
506
|
+
return candidate;
|
|
507
|
+
} catch {
|
|
508
|
+
// Try the next installed browser.
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
throw new Error("未找到 Chrome;可通过 DECIDEX_CHROME_PATH 指定路径");
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
async function waitForFile(file, timeoutMs = 10_000) {
|
|
515
|
+
const deadline = Date.now() + timeoutMs;
|
|
516
|
+
while (Date.now() < deadline) {
|
|
517
|
+
try {
|
|
518
|
+
return await readFile(file, "utf8");
|
|
519
|
+
} catch (error) {
|
|
520
|
+
if (error?.code !== "ENOENT") throw error;
|
|
521
|
+
}
|
|
522
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 100));
|
|
523
|
+
}
|
|
524
|
+
throw new Error("Chrome DevTools 启动超时");
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
async function cdpClient(url) {
|
|
528
|
+
const socket = new WebSocket(url);
|
|
529
|
+
await new Promise((resolveOpen, reject) => {
|
|
530
|
+
socket.addEventListener("open", resolveOpen, { once: true });
|
|
531
|
+
socket.addEventListener("error", () => reject(new Error("无法连接 Chrome DevTools")), { once: true });
|
|
532
|
+
});
|
|
533
|
+
let nextId = 0;
|
|
534
|
+
const pending = new Map();
|
|
535
|
+
socket.addEventListener("message", (event) => {
|
|
536
|
+
const message = JSON.parse(event.data);
|
|
537
|
+
const waiter = pending.get(message.id);
|
|
538
|
+
if (!waiter) return;
|
|
539
|
+
pending.delete(message.id);
|
|
540
|
+
clearTimeout(waiter.timer);
|
|
541
|
+
if (message.error) waiter.reject(new Error(message.error.message));
|
|
542
|
+
else waiter.resolve(message.result);
|
|
543
|
+
});
|
|
544
|
+
socket.addEventListener("close", () => {
|
|
545
|
+
for (const waiter of pending.values()) {
|
|
546
|
+
clearTimeout(waiter.timer);
|
|
547
|
+
waiter.reject(new Error("Chrome DevTools 已断开"));
|
|
548
|
+
}
|
|
549
|
+
pending.clear();
|
|
550
|
+
});
|
|
551
|
+
return {
|
|
552
|
+
send(method, params = {}) {
|
|
553
|
+
const id = ++nextId;
|
|
554
|
+
socket.send(JSON.stringify({ id, method, params }));
|
|
555
|
+
return new Promise((resolveSend, reject) => {
|
|
556
|
+
const timer = setTimeout(() => {
|
|
557
|
+
pending.delete(id);
|
|
558
|
+
reject(new Error(`Chrome DevTools 命令超时:${method}`));
|
|
559
|
+
}, 10_000);
|
|
560
|
+
pending.set(id, { resolve: resolveSend, reject, timer });
|
|
561
|
+
});
|
|
562
|
+
},
|
|
563
|
+
close() {
|
|
564
|
+
socket.close();
|
|
565
|
+
},
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function cookieMatchesHost(cookie, host) {
|
|
570
|
+
const domain = cookie.domain.replace(/^\./, "");
|
|
571
|
+
return cookie.name === COOKIE_NAME && (host === domain || host.endsWith(`.${domain}`));
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
async function browserLogin(baseUrl, timeoutSeconds) {
|
|
575
|
+
const profile = join(dirname(configPath()), "chrome-profile");
|
|
576
|
+
await mkdir(profile, { recursive: true, mode: 0o700 });
|
|
577
|
+
await unlink(join(profile, "DevToolsActivePort")).catch((error) => {
|
|
578
|
+
if (error?.code !== "ENOENT") throw error;
|
|
579
|
+
});
|
|
580
|
+
const child = spawn(
|
|
581
|
+
await chromeBinary(),
|
|
582
|
+
[
|
|
583
|
+
`--user-data-dir=${profile}`,
|
|
584
|
+
"--remote-debugging-port=0",
|
|
585
|
+
"--no-first-run",
|
|
586
|
+
"--no-default-browser-check",
|
|
587
|
+
`${baseUrl}/login`,
|
|
588
|
+
],
|
|
589
|
+
{ stdio: "ignore" },
|
|
590
|
+
);
|
|
591
|
+
let client;
|
|
592
|
+
try {
|
|
593
|
+
const [port, browserPath] = (await waitForFile(join(profile, "DevToolsActivePort"))).trim().split("\n");
|
|
594
|
+
client = await cdpClient(`ws://127.0.0.1:${port}${browserPath}`);
|
|
595
|
+
const deadline = Date.now() + timeoutSeconds * 1000;
|
|
596
|
+
const host = new URL(baseUrl).hostname;
|
|
597
|
+
while (Date.now() < deadline) {
|
|
598
|
+
const { cookies } = await client.send("Storage.getCookies");
|
|
599
|
+
const cookie = cookies.find((candidate) => cookieMatchesHost(candidate, host));
|
|
600
|
+
if (cookie?.value) return cookie.value;
|
|
601
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 500));
|
|
602
|
+
}
|
|
603
|
+
throw new Error(`等待浏览器登录超时(${timeoutSeconds} 秒)`);
|
|
604
|
+
} finally {
|
|
605
|
+
if (client) {
|
|
606
|
+
const closed = await client.send("Browser.close").then(
|
|
607
|
+
() => true,
|
|
608
|
+
() => false,
|
|
609
|
+
);
|
|
610
|
+
client.close();
|
|
611
|
+
if (!closed) child.kill();
|
|
612
|
+
} else {
|
|
613
|
+
child.kill();
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
async function authCommand(action, args) {
|
|
619
|
+
if (action === "login") {
|
|
620
|
+
const { values } = commandArgs(args, { timeout: { type: "string", default: "300" } });
|
|
621
|
+
const baseUrl = normalizeBaseUrl(values["base-url"] || process.env.DECIDEX_BASE_URL || "");
|
|
622
|
+
const timeout = positiveSeconds(values.timeout);
|
|
623
|
+
process.stderr.write("请在打开的 Chrome 窗口完成 Decidex 登录…\n");
|
|
624
|
+
const session = await browserLogin(baseUrl, timeout);
|
|
625
|
+
await saveConfig({ baseUrl, session, organizationId: null, recentRuns: [] });
|
|
626
|
+
const result = await request("/api/personal-agents", { values: { "base-url": baseUrl } });
|
|
627
|
+
print({ authenticated: true, baseUrl, agentCount: result.agents?.length ?? null });
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
if (action === "import") {
|
|
631
|
+
const { values } = commandArgs(args);
|
|
632
|
+
const baseUrl = normalizeBaseUrl(values["base-url"] || process.env.DECIDEX_BASE_URL || "");
|
|
633
|
+
const session = sessionFromText(await readStdin(" decidex_session 或完整 Cookie header"));
|
|
634
|
+
await saveConfig({ baseUrl, session, organizationId: null, recentRuns: [] });
|
|
635
|
+
print({ ok: true, baseUrl });
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
if (action === "status") {
|
|
639
|
+
const { values } = commandArgs(args);
|
|
640
|
+
const credentials = await auth(values);
|
|
641
|
+
const result = await request("/api/personal-agents", { values });
|
|
642
|
+
print({
|
|
643
|
+
authenticated: true,
|
|
644
|
+
baseUrl: credentials.baseUrl,
|
|
645
|
+
organizationId: credentials.organizationId,
|
|
646
|
+
organizationIdVerified: false,
|
|
647
|
+
agentCount: result.agents?.length ?? null,
|
|
648
|
+
});
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
if (action === "logout") {
|
|
652
|
+
const { values } = commandArgs(args);
|
|
653
|
+
const stored = await readConfig();
|
|
654
|
+
let remoteError = null;
|
|
655
|
+
if (stored.session || process.env.DECIDEX_SESSION) {
|
|
656
|
+
await request("/api/auth/logout", { method: "POST", values }).catch((error) => {
|
|
657
|
+
remoteError = error.message;
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
await saveConfig({ session: null, organizationId: null, recentRuns: [] });
|
|
661
|
+
print({ ok: true, localCleared: true, remoteLogout: remoteError ? "failed" : "succeeded", remoteError, environmentSessionStillActive: Boolean(process.env.DECIDEX_SESSION) });
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
throw new Error(`未知 auth 命令:${action || "(空)"}`);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
async function contextCommand(action) {
|
|
668
|
+
if (action !== "show") throw new Error(`未知 context 命令:${action || "(空)"}`);
|
|
669
|
+
const stored = await readConfig();
|
|
670
|
+
print({
|
|
671
|
+
baseUrl: process.env.DECIDEX_BASE_URL || stored.baseUrl || null,
|
|
672
|
+
organizationId: stored.organizationId ?? null,
|
|
673
|
+
organizationIdVerified: false,
|
|
674
|
+
sessionSource: process.env.DECIDEX_SESSION ? "environment" : stored.session ? "config" : null,
|
|
675
|
+
configPath: configPath(),
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
async function orgCommand(action, args) {
|
|
680
|
+
if (action !== "use") throw new Error(`未知 org 命令:${action || "(空)"}`);
|
|
681
|
+
const { values, positionals } = commandArgs(args);
|
|
682
|
+
const result = await request("/api/auth/active-organization", {
|
|
683
|
+
method: "PATCH",
|
|
684
|
+
body: { organizationId: required(positionals[0], "ID") },
|
|
685
|
+
values,
|
|
686
|
+
});
|
|
687
|
+
await saveConfig({ organizationId: result.activeOrganization?.id ?? positionals[0] });
|
|
688
|
+
print(result);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
async function agentCommand(action, args) {
|
|
692
|
+
const { values, positionals } = commandArgs(args, {
|
|
693
|
+
email: { type: "string" },
|
|
694
|
+
"user-id": { type: "string" },
|
|
695
|
+
input: { type: "string" },
|
|
696
|
+
message: { type: "string" },
|
|
697
|
+
output: { type: "string" },
|
|
698
|
+
timeout: { type: "string", default: "600" },
|
|
699
|
+
follow: { type: "boolean", default: false },
|
|
700
|
+
wait: { type: "boolean", default: false },
|
|
701
|
+
});
|
|
702
|
+
if (action === "list") return print(await request("/api/personal-agents", { values }));
|
|
703
|
+
if (action === "models") {
|
|
704
|
+
const agentId = encodeURIComponent(required(positionals[0], "AGENT_ID"));
|
|
705
|
+
const result = await request(`/api/personal-agents/${agentId}/sessions`, { values });
|
|
706
|
+
return print({ schemaVersion: 1, modelCatalog: result.modelCatalog });
|
|
707
|
+
}
|
|
708
|
+
if (action === "get") return print(await request(`/api/personal-agents/${encodeURIComponent(required(positionals[0], "ID"))}`, { values }));
|
|
709
|
+
if (action === "apply") {
|
|
710
|
+
expectPositionals(positionals, 1, "agent apply FILE");
|
|
711
|
+
const spec = await readJsonFile(required(positionals[0], "FILE"));
|
|
712
|
+
const id = spec.id;
|
|
713
|
+
const body = { ...spec };
|
|
714
|
+
delete body.id;
|
|
715
|
+
return print(
|
|
716
|
+
await request(id ? `/api/personal-agents/${encodeURIComponent(id)}` : "/api/personal-agents", {
|
|
717
|
+
method: id ? "PUT" : "POST",
|
|
718
|
+
body,
|
|
719
|
+
values,
|
|
720
|
+
}),
|
|
721
|
+
);
|
|
722
|
+
}
|
|
723
|
+
if (action === "export") {
|
|
724
|
+
expectPositionals(positionals, 2, "agent export ID FILE");
|
|
725
|
+
const id = required(positionals[0], "ID");
|
|
726
|
+
return print(await request(`/api/personal-agents/${encodeURIComponent(id)}/export`, { output: required(positionals[1], "FILE"), values }));
|
|
727
|
+
}
|
|
728
|
+
if (action === "import") {
|
|
729
|
+
expectPositionals(positionals, 1, "agent import FILE");
|
|
730
|
+
const bytes = await readFile(resolve(required(positionals[0], "FILE")));
|
|
731
|
+
return print(await request("/api/personal-agents/import", { method: "POST", body: bytes, values }));
|
|
732
|
+
}
|
|
733
|
+
if (action === "publish") {
|
|
734
|
+
expectPositionals(positionals, 1, "agent publish ID");
|
|
735
|
+
if (Boolean(values.email) === Boolean(values["user-id"])) throw new Error("publish 必须且只能指定 --email 或 --user-id");
|
|
736
|
+
const body = values.email ? { email: values.email } : values["user-id"] ? { userId: values["user-id"] } : null;
|
|
737
|
+
return print(await request(`/api/personal-agents/${encodeURIComponent(required(positionals[0], "ID"))}/publications`, { method: "POST", body, values }));
|
|
738
|
+
}
|
|
739
|
+
if (action === "unpublish") {
|
|
740
|
+
expectPositionals(positionals, 1, "agent unpublish ID");
|
|
741
|
+
if (!values["user-id"]) throw new Error("unpublish 需要 --user-id");
|
|
742
|
+
return print(await request(`/api/personal-agents/${encodeURIComponent(required(positionals[0], "ID"))}/publications`, { method: "DELETE", body: { userId: values["user-id"] }, values }));
|
|
743
|
+
}
|
|
744
|
+
if (action === "file") {
|
|
745
|
+
const [fileAction, agentId, ...files] = positionals;
|
|
746
|
+
const id = encodeURIComponent(required(agentId, "AGENT_ID"));
|
|
747
|
+
const path = `/api/personal-agents/${id}/files`;
|
|
748
|
+
if (fileAction === "list") {
|
|
749
|
+
expectPositionals(files, 0, "agent file list AGENT_ID");
|
|
750
|
+
return print(await request(path, { values }));
|
|
751
|
+
}
|
|
752
|
+
if (fileAction === "add") {
|
|
753
|
+
if (files.length === 0) throw new Error("file add 至少需要一个 FILE");
|
|
754
|
+
return print(await request(path, { method: "POST", body: await uploadForm(files, "files"), values }));
|
|
755
|
+
}
|
|
756
|
+
if (fileAction === "delete") {
|
|
757
|
+
expectPositionals(files, 1, "agent file delete AGENT_ID FILE_ID");
|
|
758
|
+
const fileId = required(files[0], "FILE_ID");
|
|
759
|
+
return print(await request(`${path}?fileId=${encodeURIComponent(fileId)}`, { method: "DELETE", values }));
|
|
760
|
+
}
|
|
761
|
+
if (fileAction === "download") {
|
|
762
|
+
expectPositionals(files, 2, "agent file download AGENT_ID FILE_ID FILE");
|
|
763
|
+
const fileId = encodeURIComponent(required(files[0], "FILE_ID"));
|
|
764
|
+
return print(await request(`${path}/${fileId}/content?download=1`, { output: required(files[1], "FILE"), values }));
|
|
765
|
+
}
|
|
766
|
+
throw new Error(`未知 agent file 命令:${fileAction || "(空)"}`);
|
|
767
|
+
}
|
|
768
|
+
if (action === "run") {
|
|
769
|
+
expectPositionals(positionals, 1, "agent run AGENT_ID");
|
|
770
|
+
if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
|
|
771
|
+
const agentId = required(positionals[0], "AGENT_ID");
|
|
772
|
+
const message = await readMessage(values);
|
|
773
|
+
const started = await request(`/api/personal-agents/${encodeURIComponent(agentId)}/sessions/start`, {
|
|
774
|
+
method: "POST",
|
|
775
|
+
body: { message },
|
|
776
|
+
values,
|
|
777
|
+
});
|
|
778
|
+
await rememberRunBestEffort(agentId, started.session.id, started.runId, values);
|
|
779
|
+
if (!values.wait) return emit(started, values.output);
|
|
780
|
+
const sessionId = started.session.id;
|
|
781
|
+
const runId = started.runId;
|
|
782
|
+
const result = await waitForRun(agentId, sessionId, runId, values);
|
|
783
|
+
await emit(result, values.output);
|
|
784
|
+
if (result.status !== "SUCCEEDED") process.exitCode = 1;
|
|
785
|
+
return;
|
|
786
|
+
}
|
|
787
|
+
throw new Error(`未知 agent 命令:${action || "(空)"}`);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
async function sessionCommand(action, args) {
|
|
791
|
+
const { values, positionals } = commandArgs(args, {
|
|
792
|
+
all: { type: "boolean", default: false },
|
|
793
|
+
dir: { type: "string" },
|
|
794
|
+
follow: { type: "boolean", default: false },
|
|
795
|
+
input: { type: "string" },
|
|
796
|
+
message: { type: "string" },
|
|
797
|
+
output: { type: "string" },
|
|
798
|
+
overwrite: { type: "boolean", default: false },
|
|
799
|
+
query: { type: "string" },
|
|
800
|
+
status: { type: "string", default: "all" },
|
|
801
|
+
timeout: { type: "string", default: "600" },
|
|
802
|
+
wait: { type: "boolean", default: false },
|
|
803
|
+
});
|
|
804
|
+
if (action === "list") {
|
|
805
|
+
expectPositionals(positionals, 0, "session list");
|
|
806
|
+
if (!new Set(["all", "running", "completed"]).has(values.status)) throw new Error("--status 只支持 all、running、completed");
|
|
807
|
+
const query = new URLSearchParams({ status: values.status });
|
|
808
|
+
if (values.query) query.set("q", values.query);
|
|
809
|
+
return print(await request(`/api/agent-sessions?${query}`, { values }));
|
|
810
|
+
}
|
|
811
|
+
if (action !== "artifacts") {
|
|
812
|
+
expectPositionals(positionals, 1, `session ${action || "COMMAND"} SESSION_ID`);
|
|
813
|
+
const sessionId = required(positionals[0], "SESSION_ID");
|
|
814
|
+
const session = await resolveSession(sessionId, values);
|
|
815
|
+
if (action === "view") return print(await request(`${sessionPath(session.agentId, sessionId)}/view`, { values }));
|
|
816
|
+
if (action === "stop") return print(await request(`${sessionPath(session.agentId, sessionId)}/stop`, { method: "POST", values }));
|
|
817
|
+
if (action === "send") {
|
|
818
|
+
if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
|
|
819
|
+
const started = await request(`${sessionPath(session.agentId, sessionId)}/chat`, {
|
|
820
|
+
method: "POST",
|
|
821
|
+
body: { message: await readMessage(values) },
|
|
822
|
+
headers: values.wait ? { "x-decidex-queue-if-running": "false" } : undefined,
|
|
823
|
+
values,
|
|
824
|
+
});
|
|
825
|
+
if (started.kind === "queued") return emit(started, values.output);
|
|
826
|
+
if (started.kind !== "direct" || !started.runId) throw new Error("Decidex 返回了无法识别的会话运行结果");
|
|
827
|
+
await rememberRunBestEffort(session.agentId, sessionId, started.runId, values);
|
|
828
|
+
if (!values.wait) return emit(started, values.output);
|
|
829
|
+
const result = await waitForRun(session.agentId, sessionId, started.runId, values);
|
|
830
|
+
await emit(result, values.output);
|
|
831
|
+
if (result.status !== "SUCCEEDED") process.exitCode = 1;
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
throw new Error(`未知 session 命令:${action || "(空)"}`);
|
|
835
|
+
}
|
|
836
|
+
const [artifactAction, sessionIdValue] = positionals;
|
|
837
|
+
expectPositionals(positionals, 2, `session artifacts ${artifactAction || "COMMAND"} SESSION_ID`);
|
|
838
|
+
const sessionId = required(sessionIdValue, "SESSION_ID");
|
|
839
|
+
const session = await resolveSession(sessionId, values);
|
|
840
|
+
const artifacts = await listSessionArtifacts(session.agentId, sessionId, values);
|
|
841
|
+
if (artifactAction === "list") {
|
|
842
|
+
return print({ schemaVersion: 1, sessionId, agentId: session.agentId, artifacts });
|
|
843
|
+
}
|
|
844
|
+
if (artifactAction === "download") {
|
|
845
|
+
if (!values.all) throw new Error("artifacts download 需要 --all");
|
|
846
|
+
const directory = resolve(required(values.dir, "--dir DIR"));
|
|
847
|
+
await mkdir(directory, { recursive: true });
|
|
848
|
+
const root = await realpath(directory);
|
|
849
|
+
const targets = artifacts.map((artifact) => ({ artifact, destination: safeDestination(root, artifact.relativePath) }));
|
|
850
|
+
for (const { destination } of targets) await assertSafeArtifactTarget(root, destination, values.overwrite);
|
|
851
|
+
const downloaded = [];
|
|
852
|
+
for (const { artifact, destination } of targets) {
|
|
853
|
+
const bytes = await request(`${sessionPath(session.agentId, sessionId)}/files/content?path=${encodeURIComponent(artifact.relativePath)}&download=1`, {
|
|
854
|
+
returnBytes: true,
|
|
855
|
+
values,
|
|
856
|
+
});
|
|
857
|
+
await writeArtifact(root, destination, bytes, values.overwrite);
|
|
858
|
+
downloaded.push({ name: artifact.name, path: destination, sizeBytes: artifact.sizeBytes });
|
|
859
|
+
}
|
|
860
|
+
return print({ schemaVersion: 1, sessionId, directory, downloaded });
|
|
861
|
+
}
|
|
862
|
+
throw new Error(`未知 session artifacts 命令:${artifactAction || "(空)"}`);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
async function runCommand(action, args) {
|
|
866
|
+
if (action !== "diagnose") throw new Error(`未知 run 命令:${action || "(空)"}`);
|
|
867
|
+
const { values, positionals } = commandArgs(args, {
|
|
868
|
+
"agent-id": { type: "string" },
|
|
869
|
+
"session-id": { type: "string" },
|
|
870
|
+
});
|
|
871
|
+
const runId = required(positionals[0], "RUN_ID");
|
|
872
|
+
expectPositionals(positionals, 1, "run diagnose RUN_ID");
|
|
873
|
+
let context;
|
|
874
|
+
if (values["session-id"]) {
|
|
875
|
+
const session = values["agent-id"] ? { agentId: values["agent-id"] } : await resolveSession(values["session-id"], values);
|
|
876
|
+
context = { agentId: session.agentId, sessionId: values["session-id"], runId };
|
|
877
|
+
} else {
|
|
878
|
+
if (values["agent-id"]) throw new Error("--agent-id 必须和 --session-id 一起使用");
|
|
879
|
+
context = (await readConfig()).recentRuns?.find((item) => item.runId === runId);
|
|
880
|
+
if (!context) throw new Error(`本地没有 Run 上下文:${runId};请提供 --session-id,必要时再提供 --agent-id`);
|
|
881
|
+
const credentials = await auth(values);
|
|
882
|
+
if (context.baseUrl && context.baseUrl !== credentials.baseUrl) throw new Error("Run 属于其他 Decidex 地址;请切换认证上下文");
|
|
883
|
+
if (context.organizationId && credentials.organizationId && context.organizationId !== credentials.organizationId) {
|
|
884
|
+
throw new Error("Run 属于其他组织;请切换组织或显式提供 Session 上下文");
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
const status = await request(runPath(context.agentId, context.sessionId, runId), { values });
|
|
888
|
+
const view = await request(`${sessionPath(context.agentId, context.sessionId)}/view`, { values });
|
|
889
|
+
const message = (view.messages ?? []).find((item) => item.turn?.id === runId);
|
|
890
|
+
const events = (message?.timelineItems ?? [])
|
|
891
|
+
.filter((item) => item.type === "event")
|
|
892
|
+
.map((item) => ({
|
|
893
|
+
id: item.id,
|
|
894
|
+
kind: item.event.kind,
|
|
895
|
+
status: item.event.status,
|
|
896
|
+
title: item.event.title,
|
|
897
|
+
createdAt: item.createdAt,
|
|
898
|
+
}));
|
|
899
|
+
print({
|
|
900
|
+
...finalRunResult(context.sessionId, runId, status, view),
|
|
901
|
+
agentId: context.agentId,
|
|
902
|
+
events,
|
|
903
|
+
runtime: {
|
|
904
|
+
terminationReason: null,
|
|
905
|
+
resourceError: null,
|
|
906
|
+
availability: "not_exposed",
|
|
907
|
+
},
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
async function skillCommand(action, args) {
|
|
912
|
+
const { values, positionals } = commandArgs(args);
|
|
913
|
+
if (action === "list") {
|
|
914
|
+
const result = await request("/api/plugins?kind=skill-only", { values });
|
|
915
|
+
return print({ skills: (result.entries ?? []).filter((entry) => entry.source === "personal") });
|
|
916
|
+
}
|
|
917
|
+
if (action === "upload") {
|
|
918
|
+
expectPositionals(positionals, 1, "skill upload FILE");
|
|
919
|
+
const file = required(positionals[0], "FILE");
|
|
920
|
+
return print(await request("/api/skills/upload", { method: "POST", body: await uploadForm([file]), values }));
|
|
921
|
+
}
|
|
922
|
+
if (action === "update") {
|
|
923
|
+
expectPositionals(positionals, 2, "skill update ID FILE");
|
|
924
|
+
const skillId = encodeURIComponent(required(positionals[0], "ID"));
|
|
925
|
+
const form = await uploadForm([required(positionals[1], "FILE")]);
|
|
926
|
+
const snapshot = await request(`/api/skills/${skillId}/files?origin=personal`, { values });
|
|
927
|
+
if (!snapshot.fingerprint) throw new Error("服务端未返回 Skill fingerprint");
|
|
928
|
+
form.append("expectedFingerprint", snapshot.fingerprint);
|
|
929
|
+
return print(await request(`/api/skills/${skillId}`, { method: "PUT", body: form, values }));
|
|
930
|
+
}
|
|
931
|
+
if (action === "download") {
|
|
932
|
+
expectPositionals(positionals, 2, "skill download ID FILE");
|
|
933
|
+
const skillId = encodeURIComponent(required(positionals[0], "ID"));
|
|
934
|
+
return print(await request(`/api/skills/${skillId}/download`, { output: required(positionals[1], "FILE"), values }));
|
|
935
|
+
}
|
|
936
|
+
if (action === "delete") {
|
|
937
|
+
expectPositionals(positionals, 1, "skill delete ID");
|
|
938
|
+
const skillId = encodeURIComponent(required(positionals[0], "ID"));
|
|
939
|
+
return print(await request(`/api/skills/${skillId}`, { method: "DELETE", values }));
|
|
940
|
+
}
|
|
941
|
+
throw new Error(`未知 skill 命令:${action || "(空)"}`);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
function evaluationCasesFromFile(value) {
|
|
945
|
+
const cases = Array.isArray(value) ? value : value?.cases;
|
|
946
|
+
if (!Array.isArray(cases)) throw new Error("评测文件必须是数组或包含 cases 数组");
|
|
947
|
+
const normalized = cases.map((item, index) => {
|
|
948
|
+
if (!item || typeof item.task !== "string" || !item.task.trim() || typeof item.rubric !== "string" || !item.rubric.trim()) {
|
|
949
|
+
throw new Error(`第 ${index + 1} 条评测案例必须包含非空 task 和 rubric`);
|
|
950
|
+
}
|
|
951
|
+
return { task: item.task.trim(), rubric: item.rubric.trim() };
|
|
952
|
+
});
|
|
953
|
+
const seen = new Set();
|
|
954
|
+
for (const item of normalized) {
|
|
955
|
+
if (seen.has(item.task)) throw new Error(`评测文件包含重复 task:${item.task}`);
|
|
956
|
+
seen.add(item.task);
|
|
957
|
+
}
|
|
958
|
+
return normalized;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
function evaluationCasesPlan(current, desired, prune) {
|
|
962
|
+
const currentByTask = new Map();
|
|
963
|
+
for (const item of current) {
|
|
964
|
+
if (currentByTask.has(item.task)) throw new Error(`线上评测集包含重复 task:${item.task}`);
|
|
965
|
+
currentByTask.set(item.task, item);
|
|
966
|
+
}
|
|
967
|
+
const desiredByTask = new Map(desired.map((item) => [item.task, item]));
|
|
968
|
+
const create = desired.filter((item) => !currentByTask.has(item.task));
|
|
969
|
+
const update = desired
|
|
970
|
+
.filter((item) => currentByTask.has(item.task) && currentByTask.get(item.task).rubric !== item.rubric)
|
|
971
|
+
.map((item) => ({ id: currentByTask.get(item.task).id, ...item }));
|
|
972
|
+
const keep = desired.filter((item) => currentByTask.get(item.task)?.rubric === item.rubric);
|
|
973
|
+
const extra = current.filter((item) => !desiredByTask.has(item.task));
|
|
974
|
+
return { create, update, keep, delete: prune ? extra : [], unmanaged: prune ? [] : extra };
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
function planSummary(plan) {
|
|
978
|
+
return Object.fromEntries(Object.entries(plan).map(([key, value]) => [key, value.length]));
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
async function fetchEvaluationCases(agentId, values) {
|
|
982
|
+
const result = await request(`/api/personal-agents/${encodeURIComponent(agentId)}/evaluation-cases`, { values });
|
|
983
|
+
return result.cases ?? [];
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
async function evalCasesCommand(args) {
|
|
987
|
+
const { values, positionals } = commandArgs(args, {
|
|
988
|
+
output: { type: "string" },
|
|
989
|
+
prune: { type: "boolean", default: false },
|
|
990
|
+
});
|
|
991
|
+
const [action, agentId, file] = positionals;
|
|
992
|
+
expectPositionals(positionals, action === "list" ? 2 : 3, `eval cases ${action || "COMMAND"} AGENT_ID${action === "list" ? "" : " FILE"}`);
|
|
993
|
+
const id = required(agentId, "AGENT_ID");
|
|
994
|
+
const current = await fetchEvaluationCases(id, values);
|
|
995
|
+
if (action === "list") return print({ cases: current });
|
|
996
|
+
if (action === "export") {
|
|
997
|
+
return emit({ cases: current.map(({ task, rubric }) => ({ task, rubric })) }, required(file, "FILE"));
|
|
998
|
+
}
|
|
999
|
+
if (action !== "plan" && action !== "apply") throw new Error(`未知 eval cases 命令:${action || "(空)"}`);
|
|
1000
|
+
const desired = evaluationCasesFromFile(await readJsonFile(required(file, "FILE")));
|
|
1001
|
+
const plan = evaluationCasesPlan(current, desired, values.prune);
|
|
1002
|
+
if (action === "plan") return emit({ summary: planSummary(plan), ...plan }, values.output);
|
|
1003
|
+
|
|
1004
|
+
const base = `/api/personal-agents/${encodeURIComponent(id)}/evaluation-cases`;
|
|
1005
|
+
for (const item of plan.create) await request(base, { method: "POST", body: item, values });
|
|
1006
|
+
for (const { id: caseId, task, rubric } of plan.update) {
|
|
1007
|
+
await request(`${base}/${encodeURIComponent(caseId)}`, { method: "PUT", body: { task, rubric }, values });
|
|
1008
|
+
}
|
|
1009
|
+
for (const item of plan.delete) await request(`${base}/${encodeURIComponent(item.id)}`, { method: "DELETE", values });
|
|
1010
|
+
|
|
1011
|
+
const actual = await fetchEvaluationCases(id, values);
|
|
1012
|
+
const verified = evaluationCasesPlan(actual, desired, values.prune);
|
|
1013
|
+
if (verified.create.length || verified.update.length || verified.delete.length) throw new Error("评测集写入后校验失败,可安全重试 apply");
|
|
1014
|
+
return emit({ applied: planSummary(plan), verified: { cases: actual.length, unmanaged: verified.unmanaged.length } }, values.output);
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
function evaluationRunSpec(value) {
|
|
1018
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("评测运行文件必须是 JSON 对象");
|
|
1019
|
+
const allowed = new Set(["caseIds", "targetModelSelection", "judgeModelSelection"]);
|
|
1020
|
+
const unknown = Object.keys(value).filter((key) => !allowed.has(key));
|
|
1021
|
+
if (unknown.length) throw new Error(`评测运行文件包含最新 origin/main 不支持的字段:${unknown.join(", ")}`);
|
|
1022
|
+
const efforts = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
|
1023
|
+
for (const field of ["targetModelSelection", "judgeModelSelection"]) {
|
|
1024
|
+
const selection = value[field];
|
|
1025
|
+
if (!selection || typeof selection !== "object" || Array.isArray(selection)) throw new Error(`${field} 必须是对象`);
|
|
1026
|
+
const selectionUnknown = Object.keys(selection).filter((key) => !new Set(["modelEntryId", "reasoningEffort"]).has(key));
|
|
1027
|
+
if (selectionUnknown.length) throw new Error(`${field} 包含不支持的字段:${selectionUnknown.join(", ")}`);
|
|
1028
|
+
if (typeof selection.modelEntryId !== "string" || !selection.modelEntryId.trim()) throw new Error(`${field}.modelEntryId 不能为空`);
|
|
1029
|
+
if (!(selection.reasoningEffort === null || efforts.has(selection.reasoningEffort))) throw new Error(`${field}.reasoningEffort 不合法`);
|
|
1030
|
+
}
|
|
1031
|
+
if (!Array.isArray(value.caseIds) || value.caseIds.length === 0) throw new Error("请至少选择一个评测案例;可使用 --cases all");
|
|
1032
|
+
if (value.caseIds.some((id) => typeof id !== "string" || !id.trim()) || new Set(value.caseIds).size !== value.caseIds.length) {
|
|
1033
|
+
throw new Error("caseIds 必须是非空且不重复的字符串数组");
|
|
1034
|
+
}
|
|
1035
|
+
return value;
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
async function evalCommand(action, args) {
|
|
1039
|
+
if (action === "cases") return evalCasesCommand(args);
|
|
1040
|
+
const { values, positionals } = commandArgs(args, {
|
|
1041
|
+
cases: { type: "string" },
|
|
1042
|
+
output: { type: "string" },
|
|
1043
|
+
timeout: { type: "string", default: "1800" },
|
|
1044
|
+
wait: { type: "boolean", default: false },
|
|
1045
|
+
});
|
|
1046
|
+
const agentId = encodeURIComponent(required(positionals[0], "AGENT_ID"));
|
|
1047
|
+
if (action === "stop") {
|
|
1048
|
+
expectPositionals(positionals, 2, "eval stop AGENT_ID RUN_ID");
|
|
1049
|
+
const runId = encodeURIComponent(required(positionals[1], "RUN_ID"));
|
|
1050
|
+
return print(await request(`/api/personal-agents/${agentId}/evaluation-runs/${runId}/stop`, { method: "POST", values }));
|
|
1051
|
+
}
|
|
1052
|
+
if (action !== "run") throw new Error(`未知 eval 命令:${action || "(空)"}`);
|
|
1053
|
+
expectPositionals(positionals, 2, "eval run AGENT_ID FILE");
|
|
1054
|
+
const body = await readJsonFile(required(positionals[1], "FILE"));
|
|
1055
|
+
if (values.cases) {
|
|
1056
|
+
if (values.cases !== "all") throw new Error("--cases 当前只支持 all");
|
|
1057
|
+
body.caseIds = (await fetchEvaluationCases(positionals[0], values)).map((item) => item.id);
|
|
1058
|
+
}
|
|
1059
|
+
const started = await request(`/api/personal-agents/${agentId}/evaluation-runs`, { method: "POST", body: evaluationRunSpec(body), values });
|
|
1060
|
+
if (!values.wait) return emit(started, values.output);
|
|
1061
|
+
const runId = encodeURIComponent(started.run.id);
|
|
1062
|
+
process.stderr.write(`[decidex] evaluation run=${started.run.id}\n`);
|
|
1063
|
+
let finished;
|
|
1064
|
+
try {
|
|
1065
|
+
finished = await poll(
|
|
1066
|
+
(deadline) => request(`/api/personal-agents/${agentId}/evaluation-runs/${runId}`, { deadline, values }),
|
|
1067
|
+
(result) => ["COMPLETED", "STOPPED", "FAILED"].includes(result.run.status),
|
|
1068
|
+
positiveSeconds(values.timeout),
|
|
1069
|
+
);
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
error.message = `${error.message}; runId=${started.run.id}; 可运行 decidex eval stop ${positionals[0]} ${started.run.id}`;
|
|
1072
|
+
throw error;
|
|
1073
|
+
}
|
|
1074
|
+
await emit(finished, values.output);
|
|
1075
|
+
if (finished.run.status !== "COMPLETED") process.exitCode = 1;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
async function ontologyCommand(action, args) {
|
|
1079
|
+
const { values, positionals } = commandArgs(args, {
|
|
1080
|
+
"network-id": { type: "string" },
|
|
1081
|
+
"version-id": { type: "string" },
|
|
1082
|
+
name: { type: "string" },
|
|
1083
|
+
});
|
|
1084
|
+
if (action === "list") return print(await request("/api/biz-ontology/networks", { values }));
|
|
1085
|
+
if (action === "get") return print(await request(`/api/biz-ontology/networks/${encodeURIComponent(required(positionals[0], "ID"))}`, { values }));
|
|
1086
|
+
if (action === "export") {
|
|
1087
|
+
expectPositionals(positionals, 2, "ontology export ID FILE");
|
|
1088
|
+
const id = required(positionals[0], "ID");
|
|
1089
|
+
const query = values["version-id"] ? `?versionId=${encodeURIComponent(values["version-id"])}` : "";
|
|
1090
|
+
return print(await request(`/api/biz-ontology/networks/${encodeURIComponent(id)}/export${query}`, { output: required(positionals[1], "FILE"), values }));
|
|
1091
|
+
}
|
|
1092
|
+
if (action === "plan" || action === "apply") {
|
|
1093
|
+
expectPositionals(positionals, 1, `ontology ${action} FILE`);
|
|
1094
|
+
const file = await readJsonFile(required(positionals[0], "FILE"));
|
|
1095
|
+
const path = values["network-id"]
|
|
1096
|
+
? `/api/biz-ontology/networks/${encodeURIComponent(values["network-id"])}/import`
|
|
1097
|
+
: "/api/biz-ontology/networks/import";
|
|
1098
|
+
const body = { file, dryRun: action === "plan" };
|
|
1099
|
+
if (values.name && !values["network-id"]) body.name = values.name;
|
|
1100
|
+
return print(await request(path, { method: "POST", body, values }));
|
|
1101
|
+
}
|
|
1102
|
+
throw new Error(`未知 ontology 命令:${action || "(空)"}`);
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
async function apiCommand(args) {
|
|
1106
|
+
const { values, positionals } = commandArgs(args, {
|
|
1107
|
+
data: { type: "string" },
|
|
1108
|
+
output: { type: "string" },
|
|
1109
|
+
});
|
|
1110
|
+
expectPositionals(positionals, 2, "api METHOD PATH");
|
|
1111
|
+
const method = required(positionals[0], "METHOD").toUpperCase();
|
|
1112
|
+
const path = required(positionals[1], "PATH");
|
|
1113
|
+
const body = values.data ? await readJsonFile(values.data) : undefined;
|
|
1114
|
+
print(await request(path, { method, body, output: values.output, values }));
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
function required(value, name) {
|
|
1118
|
+
if (!value) throw new Error(`缺少 ${name}`);
|
|
1119
|
+
return value;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
function expectPositionals(positionals, count, usage) {
|
|
1123
|
+
if (positionals.length !== count) throw new Error(`用法:decidex ${usage}`);
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
async function versionCommand() {
|
|
1127
|
+
const packageJson = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
|
|
1128
|
+
print({ cliVersion: packageJson.version, protocolVersion: 1, buildCommit: process.env.DECIDEX_CLI_BUILD_COMMIT ?? null });
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
async function main() {
|
|
1132
|
+
const argv = process.argv.slice(2);
|
|
1133
|
+
const [area, action, ...args] = argv;
|
|
1134
|
+
if (!area || area === "help" || area === "--help" || area === "-h") return print(HELP.trimEnd());
|
|
1135
|
+
if (area === "--version") return versionCommand();
|
|
1136
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
1137
|
+
const detail = HELP_BY_COMMAND[`${area} ${action}`] ?? HELP_BY_COMMAND[area];
|
|
1138
|
+
return print((detail ?? HELP).trimEnd());
|
|
1139
|
+
}
|
|
1140
|
+
if (area === "auth") return authCommand(action, args);
|
|
1141
|
+
if (area === "context") return contextCommand(action, args);
|
|
1142
|
+
if (area === "org") return orgCommand(action, args);
|
|
1143
|
+
if (area === "agent") return agentCommand(action, args);
|
|
1144
|
+
if (area === "session") return sessionCommand(action, args);
|
|
1145
|
+
if (area === "run") return runCommand(action, args);
|
|
1146
|
+
if (area === "skill") return skillCommand(action, args);
|
|
1147
|
+
if (area === "eval") return evalCommand(action, args);
|
|
1148
|
+
if (area === "ontology") return ontologyCommand(action, args);
|
|
1149
|
+
if (area === "api") return apiCommand([action, ...args].filter(Boolean));
|
|
1150
|
+
if (area === "version") return versionCommand();
|
|
1151
|
+
throw new Error(`未知命令:${area}`);
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
main().catch((error) => {
|
|
1155
|
+
if (process.argv.includes("--json")) {
|
|
1156
|
+
process.stderr.write(`${JSON.stringify({ schemaVersion: 1, error: { message: error.message, httpStatus: error.httpStatus ?? null, code: error.code ?? null, requestId: error.requestId ?? null } })}\n`);
|
|
1157
|
+
} else {
|
|
1158
|
+
const command = process.argv.slice(2, 4).filter((item) => !item.startsWith("-")).join(" ");
|
|
1159
|
+
process.stderr.write(`Error: ${error.message}${command ? `\nTry: decidex ${command} --help` : ""}\n`);
|
|
1160
|
+
}
|
|
1161
|
+
process.exitCode = 1;
|
|
1162
|
+
});
|