@guandata/decidex 0.1.1 → 0.2.1

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/src/cli.js CHANGED
@@ -7,6 +7,8 @@ import { homedir } from "node:os";
7
7
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
8
  import { parseArgs } from "node:util";
9
9
 
10
+ import { ADAPTED_SERVER_VERSION, ADAPTED_SERVER_COMMIT, COMMAND_COMPATIBILITY, compareVersions, resolveCommandCompatibility } from "./compatibility.js";
11
+
10
12
  const COOKIE_NAME = "decidex_session";
11
13
  const DEFAULT_CONFIG_PATH = join(homedir(), ".config", "decidex", "config.json");
12
14
 
@@ -16,12 +18,18 @@ Usage:
16
18
  decidex auth login --base-url URL [--timeout SECONDS]
17
19
  decidex auth import --base-url URL # read decidex_session or Cookie header from stdin
18
20
  decidex auth status
21
+ decidex auth whoami # server >= 0.0.5
19
22
  decidex auth logout
20
23
  decidex context show
21
24
  decidex org use ID
22
25
 
23
26
  decidex agent list
24
27
  decidex agent get ID
28
+ decidex agent delete ID
29
+ decidex agent publications ID
30
+ decidex agent use-scope ID OWNER|SPECIFIC_USERS|ORGANIZATION
31
+ decidex agent knowledge list AGENT_ID [--query TEXT] [--cursor CURSOR]
32
+ decidex agent knowledge add|remove AGENT_ID DOCUMENT_ID
25
33
  decidex agent apply FILE # create; update when FILE contains id
26
34
  decidex agent export ID FILE
27
35
  decidex agent import FILE # Personal Agent Transfer Bundle
@@ -32,22 +40,44 @@ Usage:
32
40
  decidex agent file delete ID FILE_ID
33
41
  decidex agent file download ID FILE_ID FILE
34
42
  decidex agent models ID
35
- decidex agent run ID (--message TEXT | --input FILE) [--wait] [--follow] [--output FILE] [--timeout SECONDS]
43
+ decidex agent run ID (--message TEXT | --input FILE | --attach FILE) [--model-entry-id ID] [--reasoning-effort LEVEL] [--wait] [--follow] [--output FILE] [--timeout SECONDS]
36
44
 
37
- decidex session list [--status all|running|completed] [--query TEXT]
38
- decidex session view SESSION_ID
45
+ decidex session list [--status all|running|completed] [--query TEXT] [--cursor CURSOR] [--agent-id ID]
46
+ decidex session view SESSION_ID [--before CURSOR | --since CURSOR]
39
47
  decidex session send SESSION_ID (--message TEXT | --input FILE) [--wait] [--follow]
40
48
  decidex session stop SESSION_ID
49
+ decidex session rename SESSION_ID TITLE
50
+ decidex session delete SESSION_ID
51
+ decidex session model SESSION_ID MODEL_ENTRY_ID
52
+ decidex session fork SESSION_ID RUN_ID
53
+ decidex session queue list SESSION_ID
54
+ decidex session queue edit SESSION_ID DRAFT_ID (--message TEXT | --input FILE)
55
+ decidex session queue delete SESSION_ID DRAFT_ID
56
+ decidex session queue continue SESSION_ID [--wait] [--follow] [--output FILE]
41
57
  decidex session artifacts list SESSION_ID
42
58
  decidex session artifacts download SESSION_ID --all --dir DIR [--overwrite]
59
+ decidex session files list SESSION_ID [--scope analysis] [--suffix EXT]
60
+ decidex session files download SESSION_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]
43
61
  decidex run diagnose RUN_ID [--session-id ID] [--agent-id ID] --json
44
62
 
45
- decidex skill list
63
+ decidex skill list [--origin personal|builtin|all]
64
+ decidex skill references ID
65
+ decidex skill files list ID [--origin personal|builtin]
66
+ decidex skill files get ID PATH [--origin personal|builtin]
67
+ decidex skill files put ID PATH FILE --fingerprint SHA256
68
+ decidex skill credentials status ID
69
+ decidex skill credentials set ID ENV_NAME # read value from stdin
70
+ decidex skill credentials delete ID ENV_NAME
46
71
  decidex skill upload FILE
47
- decidex skill update ID FILE
72
+ decidex skill update ID FILE [--fingerprint SHA256]
48
73
  decidex skill download ID FILE
49
74
  decidex skill delete ID
50
75
 
76
+ decidex eval tags list AGENT_ID
77
+ decidex eval tags create AGENT_ID NAME
78
+ decidex eval tags rename AGENT_ID TAG_ID NAME
79
+ decidex eval tags delete AGENT_ID TAG_ID
80
+
51
81
  decidex eval cases list AGENT_ID
52
82
  decidex eval cases export AGENT_ID FILE
53
83
  decidex eval cases plan AGENT_ID FILE [--prune]
@@ -57,16 +87,32 @@ Usage:
57
87
  decidex eval runs get AGENT_ID RUN_ID
58
88
  decidex eval runs wait AGENT_ID RUN_ID [--follow] [--output FILE] [--timeout SECONDS]
59
89
  decidex eval runs watch FILE [--parallel N] [--follow] [--output FILE] [--timeout SECONDS]
90
+ decidex eval files download AGENT_ID RUN_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]
60
91
  decidex eval stop AGENT_ID RUN_ID
61
92
 
93
+ decidex ontology versions list NETWORK_ID
94
+ decidex ontology versions get NETWORK_ID VERSION_ID
95
+ decidex ontology versions create NETWORK_ID [--description TEXT]
62
96
  decidex ontology list
63
97
  decidex ontology get ID
64
98
  decidex ontology export ID FILE [--version-id ID]
65
99
  decidex ontology plan FILE [--network-id ID] [--name NAME]
66
100
  decidex ontology apply FILE [--network-id ID] [--name NAME]
67
101
 
102
+ decidex automation list
103
+ decidex automation apply FILE # create; PATCH when FILE contains id
104
+ decidex automation delete ID
105
+ decidex automation run ID [--wait] [--follow] [--output FILE] [--timeout SECONDS]
106
+ decidex automation runs ID [--cursor CURSOR]
107
+
68
108
  decidex api METHOD PATH [--data FILE] [--output FILE]
69
- decidex version --json
109
+ decidex version --json # local CLI version
110
+ decidex server version # target version and commit
111
+ decidex server check [COMMAND...] # version rules and selected protocol
112
+
113
+ Turn options (agent run / session send):
114
+ --attach FILE (repeatable), --reasoning-effort LEVEL (null = model default),
115
+ --context-references FILE, --conversation-references FILE (JSON arrays)
70
116
 
71
117
  Environment:
72
118
  DECIDEX_BASE_URL, DECIDEX_SESSION, DECIDEX_CONFIG, DECIDEX_CHROME_PATH,
@@ -78,45 +124,74 @@ const HELP_BY_COMMAND = {
78
124
  decidex auth login --base-url URL [--timeout SECONDS]
79
125
  decidex auth import --base-url URL
80
126
  decidex auth status
127
+ decidex auth whoami # server >= 0.0.5
81
128
  decidex auth logout`,
82
129
  agent: `Usage:
83
- decidex agent list|get|apply|export|import ...
130
+ decidex agent list|get|apply|export|import|delete ...
131
+ decidex agent publications ID
132
+ decidex agent use-scope ID OWNER|SPECIFIC_USERS|ORGANIZATION
133
+ decidex agent knowledge list|add|remove ...
84
134
  decidex agent file list|add|delete|download ...
85
135
  decidex agent models AGENT_ID
86
136
  decidex agent run AGENT_ID (--message TEXT | --input FILE) [--wait] [--follow] [--output FILE]`,
87
137
  "agent run": `Usage:
88
- decidex agent run AGENT_ID (--message TEXT | --input FILE) [--wait] [--follow] [--output FILE] [--timeout SECONDS]
138
+ decidex agent run AGENT_ID (--message TEXT | --input FILE | --attach FILE) [--model-entry-id ID] [--reasoning-effort LEVEL] [--wait] [--follow] [--output FILE] [--timeout SECONDS]
89
139
 
90
140
  With --wait, emits a stable JSON result containing sessionId, runId, status,
91
141
  error, answer, artifacts, startedAt, finishedAt, and durationMs. --follow writes progress
92
- to stderr, so stdout or --output remains machine-readable.`,
142
+ to stderr, so stdout or --output remains machine-readable.
143
+
144
+ --attach FILE is repeatable. --context-references FILE and --conversation-references FILE
145
+ accept JSON arrays. --reasoning-effort null uses the model default.
146
+ Use agent models AGENT_ID to discover supported catalog entries and efforts.`,
93
147
  session: `Usage:
94
- decidex session list [--status all|running|completed] [--query TEXT]
95
- decidex session view SESSION_ID
148
+ decidex session list [--status all|running|completed] [--query TEXT] [--cursor CURSOR] [--agent-id ID]
149
+ decidex session view SESSION_ID [--before CURSOR | --since CURSOR]
96
150
  decidex session send SESSION_ID (--message TEXT | --input FILE) [--wait] [--follow]
97
151
  decidex session stop SESSION_ID
152
+ decidex session rename SESSION_ID TITLE
153
+ decidex session delete SESSION_ID
154
+ decidex session model SESSION_ID MODEL_ENTRY_ID
155
+ decidex session fork SESSION_ID RUN_ID
156
+ decidex session queue list SESSION_ID
157
+ decidex session queue edit SESSION_ID DRAFT_ID (--message TEXT | --input FILE)
158
+ decidex session queue delete SESSION_ID DRAFT_ID
159
+ decidex session queue continue SESSION_ID [--wait] [--follow] [--output FILE]
98
160
  decidex session artifacts ...
161
+ decidex session files ...
99
162
 
100
163
  With --wait, the message must start immediately; a busy session returns a conflict instead
101
164
  of queuing an untrackable run. Without --wait, the result can be kind=direct or kind=queued.`,
102
165
  "session artifacts": `Usage:
103
166
  decidex session artifacts list SESSION_ID
104
167
  decidex session artifacts download SESSION_ID --all --dir DIR [--overwrite]`,
168
+ "session files": `Usage:
169
+ decidex session files list SESSION_ID [--scope analysis] [--suffix EXT]
170
+ decidex session files download SESSION_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]`,
105
171
  "run diagnose": `Usage:
106
172
  decidex run diagnose RUN_ID [--session-id ID] [--agent-id ID] --json
107
173
 
108
174
  Without explicit IDs, the CLI uses a matching recent local Run context.
109
175
  Runtime Pod termination details require backend support.`,
110
176
  skill: `Usage:
111
- decidex skill list
177
+ decidex skill list [--origin personal|builtin|all]
178
+ decidex skill references ID
179
+ decidex skill files list ID [--origin personal|builtin]
180
+ decidex skill files get ID PATH [--origin personal|builtin]
181
+ decidex skill files put ID PATH FILE --fingerprint SHA256
182
+ decidex skill credentials status ID
183
+ decidex skill credentials set ID ENV_NAME # read value from stdin
184
+ decidex skill credentials delete ID ENV_NAME
112
185
  decidex skill upload FILE
113
- decidex skill update ID FILE
186
+ decidex skill update ID FILE [--fingerprint SHA256]
114
187
  decidex skill download ID FILE
115
188
  decidex skill delete ID`,
116
189
  eval: `Usage:
190
+ decidex eval tags list|create|rename|delete ...
117
191
  decidex eval cases list|export|plan|apply ...
118
192
  decidex eval run AGENT_ID FILE [--cases all] [--wait] [--follow] [--output FILE]
119
193
  decidex eval runs list|get|wait|watch ...
194
+ decidex eval files download AGENT_ID RUN_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]
120
195
  decidex eval stop AGENT_ID RUN_ID`,
121
196
  "eval cases": `Usage:
122
197
  decidex eval cases list AGENT_ID
@@ -128,8 +203,34 @@ Runtime Pod termination details require backend support.`,
128
203
  decidex eval runs get AGENT_ID RUN_ID
129
204
  decidex eval runs wait AGENT_ID RUN_ID [--follow] [--output FILE] [--timeout SECONDS]
130
205
  decidex eval runs watch FILE [--parallel N] [--follow] [--output FILE] [--timeout SECONDS]`,
206
+ "eval files": `Usage:
207
+ decidex eval files download AGENT_ID RUN_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]`,
208
+ "eval tags": `Usage:
209
+ decidex eval tags list AGENT_ID
210
+ decidex eval tags create AGENT_ID NAME
211
+ decidex eval tags rename AGENT_ID TAG_ID NAME
212
+ decidex eval tags delete AGENT_ID TAG_ID`,
131
213
  ontology: `Usage:
132
- decidex ontology list|get|export|plan|apply ...`,
214
+ decidex ontology list|get|export|plan|apply ...
215
+ decidex ontology versions list|get|create ...`,
216
+ "ontology versions": `Usage:
217
+ decidex ontology versions list NETWORK_ID
218
+ decidex ontology versions get NETWORK_ID VERSION_ID
219
+ decidex ontology versions create NETWORK_ID [--description TEXT]`,
220
+ automation: `Usage:
221
+ decidex automation list
222
+ decidex automation apply FILE
223
+ decidex automation delete ID
224
+ decidex automation run ID [--wait] [--follow] [--output FILE] [--timeout SECONDS]
225
+ decidex automation runs ID [--cursor CURSOR]`,
226
+ server: `Usage:
227
+ decidex server version
228
+ decidex server check [COMMAND...]
229
+
230
+ Unknown rules report supported=null; a newer server alone is not proof of compatibility.`,
231
+ version: `Usage:
232
+ decidex version [--json] # local CLI version
233
+ decidex version --server [--json] # same as server version`,
133
234
  api: `Usage:
134
235
  decidex api METHOD PATH [--data FILE] [--output FILE]`,
135
236
  };
@@ -302,6 +403,36 @@ async function readMessage(values) {
302
403
  return message;
303
404
  }
304
405
 
406
+ const REASONING_EFFORTS = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
407
+ const TURN_OPTIONS = {
408
+ attach: { type: "string", multiple: true },
409
+ "context-references": { type: "string" },
410
+ "conversation-references": { type: "string" },
411
+ "reasoning-effort": { type: "string" },
412
+ };
413
+
414
+ async function turnBody(values, allowModel = false) {
415
+ const hasContent = values.attach?.length || values["context-references"] || values["conversation-references"];
416
+ const body = { message: !values.message && !values.input && hasContent ? "" : await readMessage(values) };
417
+ if (allowModel && values["model-entry-id"]) body.modelEntryId = values["model-entry-id"];
418
+ if (values["reasoning-effort"] !== undefined) {
419
+ const effort = values["reasoning-effort"];
420
+ if (effort !== "null" && !REASONING_EFFORTS.has(effort)) throw new Error("--reasoning-effort 不合法;使用模型默认值时传 null");
421
+ body.reasoningEffort = effort === "null" ? null : effort;
422
+ }
423
+ for (const [option, key] of [["context-references", "contextReferences"], ["conversation-references", "conversationReferences"]]) {
424
+ if (!values[option]) continue;
425
+ body[key] = await readJsonFile(values[option]);
426
+ if (!Array.isArray(body[key])) throw new Error(`--${option} 文件必须是数组`);
427
+ }
428
+ if (!values.attach?.length) return body;
429
+ const form = await uploadForm(values.attach, "attachments");
430
+ for (const [key, value] of Object.entries(body)) {
431
+ form.append(key, value === null ? "" : typeof value === "string" ? value : JSON.stringify(value));
432
+ }
433
+ return form;
434
+ }
435
+
305
436
  async function uploadForm(files, field = "file") {
306
437
  const form = new FormData();
307
438
  for (const file of files) {
@@ -317,13 +448,13 @@ function positiveSeconds(value, name = "timeout") {
317
448
  return seconds;
318
449
  }
319
450
 
320
- async function poll(fetchValue, isTerminal, timeoutSeconds, onValue) {
321
- const deadline = Date.now() + timeoutSeconds * 1000;
451
+ async function poll(fetchValue, isTerminal, timeoutSeconds, onValue, existingDeadline) {
452
+ const deadline = existingDeadline ?? Date.now() + timeoutSeconds * 1000;
322
453
  while (Date.now() < deadline) {
323
454
  const value = await fetchValue(deadline);
324
455
  await onValue?.(value);
325
456
  if (isTerminal(value)) return value;
326
- await new Promise((resolveWait) => setTimeout(resolveWait, 2_000));
457
+ await new Promise((resolveWait) => setTimeout(resolveWait, Math.min(2_000, Math.max(0, deadline - Date.now()))));
327
458
  }
328
459
  throw new Error(`等待运行完成超时(${timeoutSeconds} 秒)`);
329
460
  }
@@ -400,7 +531,7 @@ function followProgress(view, runId, seen) {
400
531
  }
401
532
  }
402
533
 
403
- async function waitForRun(agentId, sessionId, runId, values) {
534
+ async function waitForRun(agentId, sessionId, runId, values, existingDeadline) {
404
535
  process.stderr.write(`[decidex] started session=${sessionId} run=${runId}\n`);
405
536
  let lastStatus;
406
537
  let lastHeartbeatAt = 0;
@@ -424,6 +555,7 @@ async function waitForRun(agentId, sessionId, runId, values) {
424
555
  followProgress(await request(`${sessionPath(agentId, sessionId)}/view`, { deadline: runDeadline, values }), runId, seen);
425
556
  }
426
557
  : undefined,
558
+ existingDeadline,
427
559
  );
428
560
  const view = await request(`${sessionPath(agentId, sessionId)}/view`, { deadline: runDeadline, values });
429
561
  return finalRunResult(sessionId, runId, finished, view);
@@ -445,13 +577,32 @@ async function listSessionArtifacts(agentId, sessionId, values) {
445
577
  return (result.files ?? []).filter((file) => file.relativePath?.startsWith("artifacts/"));
446
578
  }
447
579
 
448
- function safeDestination(root, artifactPath) {
449
- const destination = resolve(root, artifactPath.replace(/^artifacts\//, ""));
580
+ async function listSessionFiles(agentId, sessionId, values) {
581
+ if (values.scope && values.scope !== "analysis") throw new Error("--scope 只支持 analysis");
582
+ const query = new URLSearchParams({ force: "1" });
583
+ if (values.scope) query.set("scope", values.scope);
584
+ const suffix = values.suffix
585
+ ? values.suffix.startsWith(".")
586
+ ? values.suffix.toLowerCase()
587
+ : `.${values.suffix.toLowerCase()}`
588
+ : null;
589
+ if (suffix && !/^\.[a-z0-9][a-z0-9._-]{0,63}$/.test(suffix)) throw new Error("suffix 不是合法的文件后缀");
590
+ const result = await request(`${sessionPath(agentId, sessionId)}/files?${query}`, { values });
591
+ const files = result.files ?? [];
592
+ return suffix ? files.filter((file) => file.relativePath?.toLowerCase().endsWith(suffix)) : files;
593
+ }
594
+
595
+ function safeRelativeDestination(root, outputPath) {
596
+ const destination = resolve(root, outputPath);
450
597
  const child = relative(root, destination);
451
- if (!child || child.startsWith("..") || isAbsolute(child)) throw new Error(`非法产物路径:${artifactPath}`);
598
+ if (!child || child.startsWith("..") || isAbsolute(child)) throw new Error(`非法输出路径:${outputPath}`);
452
599
  return destination;
453
600
  }
454
601
 
602
+ function safeDestination(root, artifactPath) {
603
+ return safeRelativeDestination(root, artifactPath.replace(/^artifacts\//, ""));
604
+ }
605
+
455
606
  async function assertSafeArtifactTarget(root, destination, overwrite) {
456
607
  let current = root;
457
608
  for (const part of relative(root, dirname(destination)).split(sep).filter((item) => item && item !== ".")) {
@@ -488,11 +639,12 @@ async function writeArtifact(root, destination, bytes, overwrite) {
488
639
  }
489
640
  }
490
641
 
491
- async function readStdin(label = "内容") {
642
+ async function readStdin(label = "内容", trim = true) {
492
643
  if (process.stdin.isTTY) throw new Error(`请通过 stdin 传入${label}`);
493
644
  const chunks = [];
494
645
  for await (const chunk of process.stdin) chunks.push(chunk);
495
- return Buffer.concat(chunks).toString("utf8").trim();
646
+ const value = Buffer.concat(chunks).toString("utf8");
647
+ return trim ? value.trim() : value;
496
648
  }
497
649
 
498
650
  function sessionFromText(text) {
@@ -625,6 +777,48 @@ async function browserLogin(baseUrl, timeoutSeconds) {
625
777
  }
626
778
  }
627
779
 
780
+ let targetVersionPromise;
781
+
782
+ async function targetVersion(values) {
783
+ targetVersionPromise ??= request("/api/app-version", { values, deadline: Date.now() + 10_000 }).then((result) => {
784
+ if (!result || typeof result.version !== "string" || !result.version.trim()) throw new Error("服务端未返回有效版本号,无法检查兼容性");
785
+ return { version: result.version, commit: result.commit ?? null };
786
+ });
787
+ return targetVersionPromise;
788
+ }
789
+
790
+ async function commandCompatibility(command, values) {
791
+ const server = await targetVersion(values);
792
+ const result = resolveCommandCompatibility(command, server.version);
793
+ if (result.supported === false) throw new Error(`decidex ${command} 需要服务端 >= ${result.minVersion};目标版本为 ${server.version},该版本不支持此命令`);
794
+ return result;
795
+ }
796
+
797
+ async function readIdentity(command, values) {
798
+ const compatibility = await commandCompatibility(command, values);
799
+ if (compatibility.protocol === "agent-list") {
800
+ const result = await request("/api/personal-agents", { values });
801
+ return { userId: null, organizationId: null, organizationIdVerified: false, agentCount: result.agents?.length ?? null, legacy: true };
802
+ }
803
+ return { ...(await request("/api/auth/context", { values })), organizationIdVerified: true, legacy: false };
804
+ }
805
+
806
+ async function serverCommand(action, args) {
807
+ const { values, positionals } = commandArgs(args);
808
+ if (!["version", "check"].includes(action)) throw new Error(`未知 server 命令:${action || "(空)"}`);
809
+ if (action === "version") expectPositionals(positionals, 0, "server version");
810
+ const server = await targetVersion(values);
811
+ if (action === "version") {
812
+ let comparable = true;
813
+ try { compareVersions(server.version, ADAPTED_SERVER_VERSION); } catch { comparable = false; }
814
+ return print({ schemaVersion: 1, ...server, comparable, adaptedVersion: ADAPTED_SERVER_VERSION, adaptedCommit: ADAPTED_SERVER_COMMIT });
815
+ }
816
+ const commands = positionals.length ? [positionals.join(" ")] : Object.keys(COMMAND_COMPATIBILITY);
817
+ const checks = commands.map((command) => resolveCommandCompatibility(command, server.version));
818
+ print({ schemaVersion: 1, server, adaptedVersion: ADAPTED_SERVER_VERSION, checks });
819
+ if (checks.some((check) => check.supported === false)) process.exitCode = 1;
820
+ }
821
+
628
822
  async function authCommand(action, args) {
629
823
  if (action === "login") {
630
824
  const { values } = commandArgs(args, { timeout: { type: "string", default: "300" } });
@@ -633,8 +827,8 @@ async function authCommand(action, args) {
633
827
  process.stderr.write("请在打开的 Chrome 窗口完成 Decidex 登录…\n");
634
828
  const session = await browserLogin(baseUrl, timeout);
635
829
  await saveConfig({ baseUrl, session, organizationId: null, recentRuns: [] });
636
- const result = await request("/api/personal-agents", { values: { "base-url": baseUrl } });
637
- print({ authenticated: true, baseUrl, agentCount: result.agents?.length ?? null });
830
+ const result = await readIdentity("auth login", { "base-url": baseUrl });
831
+ print({ authenticated: true, baseUrl, ...result });
638
832
  return;
639
833
  }
640
834
  if (action === "import") {
@@ -645,17 +839,12 @@ async function authCommand(action, args) {
645
839
  print({ ok: true, baseUrl });
646
840
  return;
647
841
  }
648
- if (action === "status") {
649
- const { values } = commandArgs(args);
842
+ if (action === "status" || action === "whoami") {
843
+ const { values, positionals } = commandArgs(args);
844
+ expectPositionals(positionals, 0, `auth ${action}`);
650
845
  const credentials = await auth(values);
651
- const result = await request("/api/personal-agents", { values });
652
- print({
653
- authenticated: true,
654
- baseUrl: credentials.baseUrl,
655
- organizationId: credentials.organizationId,
656
- organizationIdVerified: false,
657
- agentCount: result.agents?.length ?? null,
658
- });
846
+ const result = await readIdentity(`auth ${action}`, values);
847
+ print({ authenticated: true, baseUrl: credentials.baseUrl, ...result });
659
848
  return;
660
849
  }
661
850
  if (action === "logout") {
@@ -674,13 +863,18 @@ async function authCommand(action, args) {
674
863
  throw new Error(`未知 auth 命令:${action || "(空)"}`);
675
864
  }
676
865
 
677
- async function contextCommand(action) {
866
+ async function contextCommand(action, args) {
678
867
  if (action !== "show") throw new Error(`未知 context 命令:${action || "(空)"}`);
868
+ const { values } = commandArgs(args);
679
869
  const stored = await readConfig();
870
+ const credentials = await auth(values);
871
+ const compatibility = await commandCompatibility("context show", values);
872
+ const context = compatibility.protocol === "local-context"
873
+ ? { userId: null, organizationId: stored.baseUrl === credentials.baseUrl ? stored.organizationId ?? null : null, organizationIdVerified: false, legacy: true }
874
+ : { ...(await request("/api/auth/context", { values })), organizationIdVerified: true, legacy: false };
680
875
  print({
681
- baseUrl: process.env.DECIDEX_BASE_URL || stored.baseUrl || null,
682
- organizationId: stored.organizationId ?? null,
683
- organizationIdVerified: false,
876
+ baseUrl: credentials.baseUrl,
877
+ ...context,
684
878
  sessionSource: process.env.DECIDEX_SESSION ? "environment" : stored.session ? "config" : null,
685
879
  configPath: configPath(),
686
880
  });
@@ -689,6 +883,7 @@ async function contextCommand(action) {
689
883
  async function orgCommand(action, args) {
690
884
  if (action !== "use") throw new Error(`未知 org 命令:${action || "(空)"}`);
691
885
  const { values, positionals } = commandArgs(args);
886
+ expectPositionals(positionals, 1, "org use ID");
692
887
  const result = await request("/api/auth/active-organization", {
693
888
  method: "PATCH",
694
889
  body: { organizationId: required(positionals[0], "ID") },
@@ -700,6 +895,10 @@ async function orgCommand(action, args) {
700
895
 
701
896
  async function agentCommand(action, args) {
702
897
  const { values, positionals } = commandArgs(args, {
898
+ ...TURN_OPTIONS,
899
+ "model-entry-id": { type: "string" },
900
+ cursor: { type: "string" },
901
+ query: { type: "string" },
703
902
  email: { type: "string" },
704
903
  "user-id": { type: "string" },
705
904
  input: { type: "string" },
@@ -709,7 +908,33 @@ async function agentCommand(action, args) {
709
908
  follow: { type: "boolean", default: false },
710
909
  wait: { type: "boolean", default: false },
711
910
  });
712
- if (action === "list") return print(await request("/api/personal-agents", { values }));
911
+ if (action === "list") {
912
+ expectPositionals(positionals, 0, "agent list");
913
+ return print(await request("/api/personal-agents", { values }));
914
+ }
915
+ if (action === "delete" || action === "publications") {
916
+ expectPositionals(positionals, 1, `agent ${action} ID`);
917
+ const id = encodeURIComponent(required(positionals[0], "ID"));
918
+ return print(await request(`/api/personal-agents/${id}${action === "publications" ? "/publications" : ""}`, { method: action === "delete" ? "DELETE" : "GET", values }));
919
+ }
920
+ if (action === "use-scope") {
921
+ expectPositionals(positionals, 2, "agent use-scope ID OWNER|SPECIFIC_USERS|ORGANIZATION");
922
+ if (!["OWNER", "SPECIFIC_USERS", "ORGANIZATION"].includes(positionals[1])) throw new Error("useScope 不合法");
923
+ return print(await request(`/api/personal-agents/${encodeURIComponent(positionals[0])}/use-scope`, { method: "PUT", body: { useScope: positionals[1] }, values }));
924
+ }
925
+ if (action === "knowledge") {
926
+ const [operation, agentId, documentId] = positionals;
927
+ expectPositionals(positionals, operation === "list" ? 2 : 3, "agent knowledge list|add|remove AGENT_ID [DOCUMENT_ID]");
928
+ if (!["list", "add", "remove"].includes(operation)) throw new Error("knowledge 只支持 list、add、remove");
929
+ const query = new URLSearchParams();
930
+ if (values.query) query.set("q", values.query);
931
+ if (values.cursor) query.set("cursor", values.cursor);
932
+ const path = `/api/personal-agents/${encodeURIComponent(agentId)}/knowledge-documents`;
933
+ return print(await request(`${path}${operation === "list" && query.size ? `?${query}` : ""}`, {
934
+ method: { list: "GET", add: "POST", remove: "DELETE" }[operation],
935
+ body: operation === "list" ? undefined : { documentId }, values,
936
+ }));
937
+ }
713
938
  if (action === "models") {
714
939
  const agentId = encodeURIComponent(required(positionals[0], "AGENT_ID"));
715
940
  const result = await request(`/api/personal-agents/${agentId}/sessions`, { values });
@@ -719,7 +944,12 @@ async function agentCommand(action, args) {
719
944
  if (action === "apply") {
720
945
  expectPositionals(positionals, 1, "agent apply FILE");
721
946
  const spec = await readJsonFile(required(positionals[0], "FILE"));
947
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new Error("Agent 文件必须是 JSON 对象");
722
948
  const id = spec.id;
949
+ if (id !== undefined && (typeof id !== "string" || !id.trim())) throw new Error("Agent id 必须是非空字符串");
950
+ const allowed = new Set(["id", "name", "description", "instructions", "avatarIcon", "avatarColor", "avatarImageDataUrl", "openingMessage", "presetQuestions", "contextReferences", "bizOntologyBindings", "betaFeatures", "actionSuggestionsEnabled", "biExplorationPolicy", "pluginSelection", "useScope", "sessionDefaultModelCatalogEntryId", "sessionDefaultReasoningEffort", ...(id ? ["builtInInstructions"] : [])]);
951
+ const unknown = Object.keys(spec).filter((key) => !allowed.has(key));
952
+ if (unknown.length) throw new Error(`Agent 文件包含不支持的字段:${unknown.join(", ")}`);
723
953
  const body = { ...spec };
724
954
  delete body.id;
725
955
  return print(
@@ -779,10 +1009,11 @@ async function agentCommand(action, args) {
779
1009
  expectPositionals(positionals, 1, "agent run AGENT_ID");
780
1010
  if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
781
1011
  const agentId = required(positionals[0], "AGENT_ID");
782
- const message = await readMessage(values);
1012
+ const body = await turnBody(values, true);
1013
+ if (values.wait) positiveSeconds(values.timeout);
783
1014
  const started = await request(`/api/personal-agents/${encodeURIComponent(agentId)}/sessions/start`, {
784
1015
  method: "POST",
785
- body: { message },
1016
+ body,
786
1017
  values,
787
1018
  });
788
1019
  await rememberRunBestEffort(agentId, started.session.id, started.runId, values);
@@ -799,6 +1030,12 @@ async function agentCommand(action, args) {
799
1030
 
800
1031
  async function sessionCommand(action, args) {
801
1032
  const { values, positionals } = commandArgs(args, {
1033
+ ...TURN_OPTIONS,
1034
+ "agent-id": { type: "string" },
1035
+ "model-entry-id": { type: "string" },
1036
+ before: { type: "string" },
1037
+ since: { type: "string" },
1038
+ cursor: { type: "string" },
802
1039
  all: { type: "boolean", default: false },
803
1040
  dir: { type: "string" },
804
1041
  follow: { type: "boolean", default: false },
@@ -807,7 +1044,9 @@ async function sessionCommand(action, args) {
807
1044
  output: { type: "string" },
808
1045
  overwrite: { type: "boolean", default: false },
809
1046
  query: { type: "string" },
1047
+ scope: { type: "string" },
810
1048
  status: { type: "string", default: "all" },
1049
+ suffix: { type: "string" },
811
1050
  timeout: { type: "string", default: "600" },
812
1051
  wait: { type: "boolean", default: false },
813
1052
  });
@@ -815,20 +1054,94 @@ async function sessionCommand(action, args) {
815
1054
  expectPositionals(positionals, 0, "session list");
816
1055
  if (!new Set(["all", "running", "completed"]).has(values.status)) throw new Error("--status 只支持 all、running、completed");
817
1056
  const query = new URLSearchParams({ status: values.status });
1057
+ if (values.query && (values.cursor || values["agent-id"])) throw new Error("--query 不能和 --cursor 或 --agent-id 同时使用");
818
1058
  if (values.query) query.set("q", values.query);
819
- return print(await request(`/api/agent-sessions?${query}`, { values }));
1059
+ if (values.cursor) query.set("cursor", values.cursor);
1060
+ if (values["agent-id"]) { query.set("groupMode", "agent"); query.set("agentId", values["agent-id"]); }
1061
+ const result = await request(`/api/agent-sessions?${query}`, { values });
1062
+ if (values.status !== "all") result.sessions = (result.sessions ?? []).filter((session) => values.status === "running" ? session.status === "RUNNING" : session.status !== "RUNNING");
1063
+ return print(result);
1064
+ }
1065
+ if (action === "queue") {
1066
+ const [operation, sessionId, draftId] = positionals;
1067
+ if (!["list", "edit", "delete", "continue"].includes(operation)) throw new Error("queue 只支持 list、edit、delete、continue");
1068
+ expectPositionals(positionals, ["edit", "delete"].includes(operation) ? 3 : 2, `session queue ${operation} SESSION_ID [DRAFT_ID]`);
1069
+ const body = operation === "edit" ? { message: await readMessage(values) } : undefined;
1070
+ if (values.follow && (!values.wait || operation !== "continue")) throw new Error("--follow 仅支持 queue continue --wait");
1071
+ if (values.wait && operation !== "continue") throw new Error("--wait 仅支持 queue continue");
1072
+ if (values.wait) positiveSeconds(values.timeout);
1073
+ const session = await resolveSession(sessionId, values);
1074
+ const path = `${sessionPath(session.agentId, sessionId)}/queued-turn-drafts`;
1075
+ const suffix = draftId ? `/${encodeURIComponent(draftId)}` : operation === "continue" ? "/continue" : "";
1076
+ const result = await request(`${path}${suffix}`, { method: { list: "GET", edit: "PATCH", delete: "DELETE", continue: "POST" }[operation], body, values });
1077
+ if (operation !== "continue") return emit(result, values.output);
1078
+ await rememberRunBestEffort(session.agentId, sessionId, result.runId, values);
1079
+ if (!values.wait) return emit(result, values.output);
1080
+ const finished = await waitForRun(session.agentId, sessionId, result.runId, values);
1081
+ await emit(finished, values.output);
1082
+ if (finished.status !== "SUCCEEDED") process.exitCode = 1;
1083
+ return;
1084
+ }
1085
+ if (["rename", "model", "fork"].includes(action)) {
1086
+ expectPositionals(positionals, 2, `session ${action} SESSION_ID ${action === "rename" ? "TITLE" : action === "model" ? "MODEL_ENTRY_ID" : "RUN_ID"}`);
1087
+ const [sessionId, value] = positionals;
1088
+ const session = await resolveSession(sessionId, values);
1089
+ const path = sessionPath(session.agentId, sessionId);
1090
+ return print(await request(action === "model" ? `${path}/model-selection` : action === "fork" ? `${path}/runs/${encodeURIComponent(value)}/fork` : path, {
1091
+ method: { rename: "PATCH", model: "PUT", fork: "POST" }[action],
1092
+ body: action === "rename" ? { title: value } : action === "model" ? { modelEntryId: value } : undefined, values,
1093
+ }));
1094
+ }
1095
+ if (action === "files") {
1096
+ const [filesAction, sessionIdValue] = positionals;
1097
+ expectPositionals(positionals, 2, `session files ${filesAction || "COMMAND"} SESSION_ID`);
1098
+ const sessionId = required(sessionIdValue, "SESSION_ID");
1099
+ const session = await resolveSession(sessionId, values);
1100
+ const files = await listSessionFiles(session.agentId, sessionId, values);
1101
+ if (filesAction === "list") {
1102
+ return print({ schemaVersion: 1, sessionId, agentId: session.agentId, files });
1103
+ }
1104
+ if (filesAction === "download") {
1105
+ if (!values.all) throw new Error("files download 需要 --all");
1106
+ const directory = resolve(required(values.dir, "--dir DIR"));
1107
+ await mkdir(directory, { recursive: true });
1108
+ const root = await realpath(directory);
1109
+ const targets = files.map((item) => ({ item, destination: safeRelativeDestination(root, item.relativePath) }));
1110
+ for (const { destination } of targets) await assertSafeArtifactTarget(root, destination, values.overwrite);
1111
+ const downloaded = [];
1112
+ for (const { item, destination } of targets) {
1113
+ const bytes = await request(`${sessionPath(session.agentId, sessionId)}/files/content?path=${encodeURIComponent(item.relativePath)}&download=1`, {
1114
+ returnBytes: true,
1115
+ values,
1116
+ });
1117
+ await writeArtifact(root, destination, bytes, values.overwrite);
1118
+ downloaded.push({ ...item, path: destination });
1119
+ }
1120
+ return print({ schemaVersion: 1, sessionId, directory, downloaded });
1121
+ }
1122
+ throw new Error(`未知 session files 命令:${filesAction || "(空)"}`);
820
1123
  }
821
1124
  if (action !== "artifacts") {
822
1125
  expectPositionals(positionals, 1, `session ${action || "COMMAND"} SESSION_ID`);
823
1126
  const sessionId = required(positionals[0], "SESSION_ID");
824
1127
  const session = await resolveSession(sessionId, values);
825
- if (action === "view") return print(await request(`${sessionPath(session.agentId, sessionId)}/view`, { values }));
1128
+ if (action === "delete") return print(await request(sessionPath(session.agentId, sessionId), { method: "DELETE", values }));
1129
+ if (action === "view") {
1130
+ if (values.before && values.since) throw new Error("--before 和 --since 不能同时使用");
1131
+ const query = new URLSearchParams();
1132
+ if (values.before) query.set("before", values.before);
1133
+ if (values.since) query.set("since", values.since);
1134
+ return print(await request(`${sessionPath(session.agentId, sessionId)}/view${query.size ? `?${query}` : ""}`, { values }));
1135
+ }
826
1136
  if (action === "stop") return print(await request(`${sessionPath(session.agentId, sessionId)}/stop`, { method: "POST", values }));
827
1137
  if (action === "send") {
828
1138
  if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
1139
+ if (values["model-entry-id"]) throw new Error("续问切换模型请先执行 session model SESSION_ID MODEL_ENTRY_ID");
1140
+ const body = await turnBody(values);
1141
+ if (values.wait) positiveSeconds(values.timeout);
829
1142
  const started = await request(`${sessionPath(session.agentId, sessionId)}/chat`, {
830
1143
  method: "POST",
831
- body: { message: await readMessage(values) },
1144
+ body,
832
1145
  headers: values.wait ? { "x-decidex-queue-if-running": "false" } : undefined,
833
1146
  values,
834
1147
  });
@@ -919,10 +1232,43 @@ async function runCommand(action, args) {
919
1232
  }
920
1233
 
921
1234
  async function skillCommand(action, args) {
922
- const { values, positionals } = commandArgs(args);
1235
+ const { values, positionals } = commandArgs(args, {
1236
+ origin: { type: "string", default: "personal" },
1237
+ fingerprint: { type: "string" },
1238
+ });
1239
+ if (!["personal", "builtin", "all"].includes(values.origin)) throw new Error("--origin 只支持 personal、builtin、all");
1240
+ if (values.origin !== "personal" && !["list", "files"].includes(action)) throw new Error("该操作仅支持 personal Skill");
1241
+ if (action === "files") {
1242
+ const [operation, skillId, path, file] = positionals;
1243
+ if (!["list", "get", "put"].includes(operation)) throw new Error("skill files 只支持 list、get、put");
1244
+ expectPositionals(positionals, { list: 2, get: 3, put: 4 }[operation], `skill files ${operation} ID [PATH] [FILE]`);
1245
+ if (values.origin === "all" || (operation === "put" && values.origin !== "personal")) throw new Error("files 需要指定 personal 或 builtin;仅 personal 可编辑");
1246
+ const base = `/api/skills/${encodeURIComponent(skillId)}/files`;
1247
+ if (operation !== "put") {
1248
+ const query = new URLSearchParams({ origin: values.origin });
1249
+ if (path) query.set("path", path);
1250
+ return print(await request(`${base}?${query}`, { values }));
1251
+ }
1252
+ // A file edit must refer to the snapshot the author read, rather than silently rebasing it.
1253
+ const expectedFingerprint = required(values.fingerprint, "--fingerprint(从 files get 返回值获取)");
1254
+ const content = file === "-" ? await readStdin("Skill 文件", false) : await readFile(resolve(file), "utf8");
1255
+ return print(await request(base, { method: "PUT", body: { path, content, expectedFingerprint }, values }));
1256
+ }
1257
+ if (action === "credentials") {
1258
+ const [operation, skillId, envName] = positionals;
1259
+ if (!["status", "set", "delete"].includes(operation)) throw new Error("credentials 只支持 status、set、delete");
1260
+ expectPositionals(positionals, operation === "status" ? 2 : 3, `skill credentials ${operation} ID [ENV_NAME]`);
1261
+ const body = operation === "status" ? undefined : { envName };
1262
+ if (operation === "set") body.value = await readStdin("凭证值");
1263
+ return print(await request(`/api/skills/${encodeURIComponent(skillId)}/credentials`, { method: { status: "GET", set: "PUT", delete: "DELETE" }[operation], body, values }));
1264
+ }
1265
+ if (action === "references") {
1266
+ expectPositionals(positionals, 1, "skill references ID");
1267
+ return print(await request(`/api/skills/${encodeURIComponent(positionals[0])}/references`, { values }));
1268
+ }
923
1269
  if (action === "list") {
924
1270
  const result = await request("/api/plugins?kind=skill-only", { values });
925
- return print({ skills: (result.entries ?? []).filter((entry) => entry.source === "personal") });
1271
+ return print({ skills: (result.entries ?? []).filter((entry) => values.origin === "all" || entry.source === values.origin) });
926
1272
  }
927
1273
  if (action === "upload") {
928
1274
  expectPositionals(positionals, 1, "skill upload FILE");
@@ -933,9 +1279,9 @@ async function skillCommand(action, args) {
933
1279
  expectPositionals(positionals, 2, "skill update ID FILE");
934
1280
  const skillId = encodeURIComponent(required(positionals[0], "ID"));
935
1281
  const form = await uploadForm([required(positionals[1], "FILE")]);
936
- const snapshot = await request(`/api/skills/${skillId}/files?origin=personal`, { values });
937
- if (!snapshot.fingerprint) throw new Error("服务端未返回 Skill fingerprint");
938
- form.append("expectedFingerprint", snapshot.fingerprint);
1282
+ const fingerprint = values.fingerprint || (await request(`/api/skills/${skillId}/files?origin=personal`, { values })).fingerprint;
1283
+ if (!fingerprint) throw new Error("服务端未返回 Skill fingerprint");
1284
+ form.append("expectedFingerprint", fingerprint);
939
1285
  return print(await request(`/api/skills/${skillId}`, { method: "PUT", body: form, values }));
940
1286
  }
941
1287
  if (action === "download") {
@@ -955,10 +1301,29 @@ function evaluationCasesFromFile(value) {
955
1301
  const cases = Array.isArray(value) ? value : value?.cases;
956
1302
  if (!Array.isArray(cases)) throw new Error("评测文件必须是数组或包含 cases 数组");
957
1303
  const normalized = cases.map((item, index) => {
958
- if (!item || typeof item.task !== "string" || !item.task.trim() || typeof item.rubric !== "string" || !item.rubric.trim()) {
959
- throw new Error(`第 ${index + 1} 条评测案例必须包含非空 task 和 rubric`);
1304
+ const label = `第 ${index + 1} 条评测案例`;
1305
+ if (item?.rubric !== undefined) throw new Error(`${label} 的 rubric 已过期,请改为 criteria: [{ text, weight, veto }]`);
1306
+ if (!item || typeof item.task !== "string" || !item.task.trim() || item.task.length > 5000) {
1307
+ throw new Error(`${label} 必须包含非空 task,且不超过 5000 个字符`);
960
1308
  }
961
- return { task: item.task.trim(), rubric: item.rubric.trim() };
1309
+ if (!Array.isArray(item.criteria) || !item.criteria.length || item.criteria.length > 50) throw new Error(`${label} 需要 1–50 条 criteria`);
1310
+ const criteria = item.criteria.map((criterion) => {
1311
+ if (!criterion || Object.keys(criterion).some((key) => !["id", "text", "weight", "veto"].includes(key))) throw new Error(`${label} 的 criteria 字段不合法`);
1312
+ const { id, text, weight = 1, veto = false } = criterion;
1313
+ if (typeof text !== "string" || !text.trim() || text.length > 2000 || !Number.isSafeInteger(weight) || weight <= 0 || typeof veto !== "boolean") {
1314
+ throw new Error(`${label} 的 criteria 需要非空 text(最多 2000 字符)、正整数 weight 和布尔 veto`);
1315
+ }
1316
+ if (id !== undefined && (typeof id !== "string" || !id.trim() || id.trim().length > 100)) throw new Error(`${label} 的 criterion id 不合法`);
1317
+ return { ...(id === undefined ? {} : { id: id.trim() }), text, weight, veto };
1318
+ });
1319
+ const ids = criteria.filter((c) => c.id).map((c) => c.id);
1320
+ if (new Set(ids).size !== ids.length || !Number.isSafeInteger(criteria.reduce((sum, c) => sum + c.weight, 0))) throw new Error(`${label} 的评分 ID 重复或权重总和超限`);
1321
+ const tagIds = item.tagIds;
1322
+ if (tagIds !== undefined && (!Array.isArray(tagIds) || tagIds.some((id) => typeof id !== "string" || !id.trim()) || new Set(tagIds.map((id) => id.trim())).size !== tagIds.length)) {
1323
+ throw new Error(`${label} 的 tagIds 必须是不重复的非空字符串数组`);
1324
+ }
1325
+ // task/text whitespace is meaningful to the server; preserve it for export/apply round trips.
1326
+ return { task: item.task, criteria, ...(tagIds === undefined ? {} : { tagIds: tagIds.map((id) => id.trim()) }) };
962
1327
  });
963
1328
  const seen = new Set();
964
1329
  for (const item of normalized) {
@@ -974,13 +1339,37 @@ function evaluationCasesPlan(current, desired, prune) {
974
1339
  if (currentByTask.has(item.task)) throw new Error(`线上评测集包含重复 task:${item.task}`);
975
1340
  currentByTask.set(item.task, item);
976
1341
  }
977
- const desiredByTask = new Map(desired.map((item) => [item.task, item]));
978
- const create = desired.filter((item) => !currentByTask.has(item.task));
979
- const update = desired
980
- .filter((item) => currentByTask.has(item.task) && currentByTask.get(item.task).rubric !== item.rubric)
981
- .map((item) => ({ id: currentByTask.get(item.task).id, ...item }));
982
- const keep = desired.filter((item) => currentByTask.get(item.task)?.rubric === item.rubric);
983
- const extra = current.filter((item) => !desiredByTask.has(item.task));
1342
+ const create = [], update = [], keep = [];
1343
+ for (const item of desired) {
1344
+ const existing = currentByTask.get(item.task);
1345
+ for (const criterion of item.criteria) {
1346
+ if (criterion.id && !existing?.criteria.some((c) => c.id === criterion.id)) throw new Error(`案例「${item.task}」含未知评分条目 ID;新增条目请省略 ID`);
1347
+ }
1348
+ if (!existing) {
1349
+ create.push(item);
1350
+ continue;
1351
+ }
1352
+ const sameCriteria = existing.criteria.length === item.criteria.length && item.criteria.every((c, i) => {
1353
+ const old = existing.criteria[i];
1354
+ return (!c.id || c.id === old.id) && c.text === old.text && c.weight === old.weight && c.veto === old.veto;
1355
+ });
1356
+ const sameTags = item.tagIds === undefined || JSON.stringify([...item.tagIds].sort()) === JSON.stringify([...(existing.tagIds ?? [])].sort());
1357
+ if (sameCriteria && sameTags) keep.push(item);
1358
+ else {
1359
+ // Preserve stable criterion IDs for unchanged text, including weight/tag-only edits.
1360
+ const used = new Set(item.criteria.flatMap((c) => c.id ? [c.id] : []));
1361
+ const criteria = item.criteria.map((c) => {
1362
+ if (c.id) return c;
1363
+ const match = existing.criteria.find((old) => old.text === c.text && !used.has(old.id));
1364
+ if (!match) return c;
1365
+ used.add(match.id);
1366
+ return { id: match.id, ...c };
1367
+ });
1368
+ update.push({ id: existing.id, ...item, criteria });
1369
+ }
1370
+ }
1371
+ const desiredTasks = new Set(desired.map((item) => item.task));
1372
+ const extra = current.filter((item) => !desiredTasks.has(item.task));
984
1373
  return { create, update, keep, delete: prune ? extra : [], unmanaged: prune ? [] : extra };
985
1374
  }
986
1375
 
@@ -1004,7 +1393,7 @@ async function evalCasesCommand(args) {
1004
1393
  const current = await fetchEvaluationCases(id, values);
1005
1394
  if (action === "list") return print({ cases: current });
1006
1395
  if (action === "export") {
1007
- return emit({ cases: current.map(({ task, rubric }) => ({ task, rubric })) }, required(file, "FILE"));
1396
+ return emit({ cases: current.map(({ task, criteria, tagIds }) => ({ task, criteria: criteria.map(({ text, weight, veto }) => ({ text, weight, veto })), tagIds })) }, required(file, "FILE"));
1008
1397
  }
1009
1398
  if (action !== "plan" && action !== "apply") throw new Error(`未知 eval cases 命令:${action || "(空)"}`);
1010
1399
  const desired = evaluationCasesFromFile(await readJsonFile(required(file, "FILE")));
@@ -1013,8 +1402,8 @@ async function evalCasesCommand(args) {
1013
1402
 
1014
1403
  const base = `/api/personal-agents/${encodeURIComponent(id)}/evaluation-cases`;
1015
1404
  for (const item of plan.create) await request(base, { method: "POST", body: item, values });
1016
- for (const { id: caseId, task, rubric } of plan.update) {
1017
- await request(`${base}/${encodeURIComponent(caseId)}`, { method: "PUT", body: { task, rubric }, values });
1405
+ for (const { id: caseId, ...body } of plan.update) {
1406
+ await request(`${base}/${encodeURIComponent(caseId)}`, { method: "PUT", body, values });
1018
1407
  }
1019
1408
  for (const item of plan.delete) await request(`${base}/${encodeURIComponent(item.id)}`, { method: "DELETE", values });
1020
1409
 
@@ -1028,8 +1417,8 @@ function evaluationRunSpec(value) {
1028
1417
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("评测运行文件必须是 JSON 对象");
1029
1418
  const allowed = new Set(["caseIds", "targetModelSelection", "judgeModelSelection"]);
1030
1419
  const unknown = Object.keys(value).filter((key) => !allowed.has(key));
1031
- if (unknown.length) throw new Error(`评测运行文件包含最新 origin/main 不支持的字段:${unknown.join(", ")}`);
1032
- const efforts = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
1420
+ if (unknown.length) throw new Error(`评测运行文件包含服务端 0.0.5 契约不支持的字段:${unknown.join(", ")}`);
1421
+ const efforts = REASONING_EFFORTS;
1033
1422
  for (const field of ["targetModelSelection", "judgeModelSelection"]) {
1034
1423
  const selection = value[field];
1035
1424
  if (!selection || typeof selection !== "object" || Array.isArray(selection)) throw new Error(`${field} 必须是对象`);
@@ -1156,9 +1545,60 @@ async function evalRunsCommand(args) {
1156
1545
  throw new Error(`未知 eval runs 命令:${action || "(空)"}`);
1157
1546
  }
1158
1547
 
1548
+ async function evalFilesCommand(args) {
1549
+ const { values, positionals } = commandArgs(args, {
1550
+ all: { type: "boolean", default: false },
1551
+ dir: { type: "string" },
1552
+ overwrite: { type: "boolean", default: false },
1553
+ scope: { type: "string" },
1554
+ suffix: { type: "string" },
1555
+ });
1556
+ const [action, agentId, runId] = positionals;
1557
+ if (action !== "download") throw new Error(`未知 eval files 命令:${action || "(空)"}`);
1558
+ expectPositionals(positionals, 3, "eval files download AGENT_ID RUN_ID");
1559
+ if (!values.all) throw new Error("eval files download 需要 --all");
1560
+ const result = await request(evaluationRunPath(agentId, runId), { values });
1561
+ const runCases = result.run?.cases ?? [];
1562
+ if (runCases.some((runCase) => !Object.hasOwn(runCase, "targetSessionId"))) {
1563
+ throw new Error("Decidex 服务端未返回评测 Case 的 targetSessionId;请先升级服务端");
1564
+ }
1565
+ const files = (await Promise.all(runCases.map(async (runCase, index) => {
1566
+ if (!runCase.targetSessionId) return [];
1567
+ const selected = await listSessionFiles(agentId, runCase.targetSessionId, values);
1568
+ return selected.map((file) => ({ ...file, caseId: runCase.id, casePosition: runCase.position, sessionId: runCase.targetSessionId, outputDirectory: `case-${index + 1}` }));
1569
+ }))).flat();
1570
+ const directory = resolve(required(values.dir, "--dir DIR"));
1571
+ await mkdir(directory, { recursive: true });
1572
+ const root = await realpath(directory);
1573
+ const targets = files.map((item) => ({ item, destination: safeRelativeDestination(root, join(item.outputDirectory, item.relativePath)) }));
1574
+ for (const { destination } of targets) await assertSafeArtifactTarget(root, destination, values.overwrite);
1575
+ const downloaded = [];
1576
+ for (const { item, destination } of targets) {
1577
+ const bytes = await request(`${sessionPath(agentId, item.sessionId)}/files/content?path=${encodeURIComponent(item.relativePath)}&download=1`, {
1578
+ returnBytes: true,
1579
+ values,
1580
+ });
1581
+ await writeArtifact(root, destination, bytes, values.overwrite);
1582
+ downloaded.push({ caseId: item.caseId, casePosition: item.casePosition, sessionId: item.sessionId, name: item.name, relativePath: item.relativePath, path: destination });
1583
+ }
1584
+ return print({ schemaVersion: 1, agentId, runId, directory, downloaded });
1585
+ }
1586
+
1587
+ async function evalTagsCommand(args) {
1588
+ const { values, positionals } = commandArgs(args);
1589
+ const [operation, agentId, tagId, name] = positionals;
1590
+ if (!["list", "create", "rename", "delete"].includes(operation)) throw new Error("eval tags 只支持 list、create、rename、delete");
1591
+ expectPositionals(positionals, { list: 2, create: 3, rename: 4, delete: 3 }[operation], `eval tags ${operation} AGENT_ID [TAG_ID] [NAME]`);
1592
+ const base = `/api/personal-agents/${encodeURIComponent(agentId)}/evaluation-case-tags`;
1593
+ const path = ["rename", "delete"].includes(operation) ? `${base}/${encodeURIComponent(tagId)}` : base;
1594
+ return print(await request(path, { method: { list: "GET", create: "POST", rename: "PUT", delete: "DELETE" }[operation], body: operation === "create" ? { name: tagId } : operation === "rename" ? { name } : undefined, values }));
1595
+ }
1596
+
1159
1597
  async function evalCommand(action, args) {
1160
1598
  if (action === "cases") return evalCasesCommand(args);
1599
+ if (action === "tags") return evalTagsCommand(args);
1161
1600
  if (action === "runs") return evalRunsCommand(args);
1601
+ if (action === "files") return evalFilesCommand(args);
1162
1602
  const { values, positionals } = commandArgs(args, {
1163
1603
  cases: { type: "string" },
1164
1604
  follow: { type: "boolean", default: false },
@@ -1174,7 +1614,10 @@ async function evalCommand(action, args) {
1174
1614
  }
1175
1615
  if (action !== "run") throw new Error(`未知 eval 命令:${action || "(空)"}`);
1176
1616
  expectPositionals(positionals, 2, "eval run AGENT_ID FILE");
1617
+ if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
1618
+ if (values.wait) positiveSeconds(values.timeout);
1177
1619
  const body = await readJsonFile(required(positionals[1], "FILE"));
1620
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("评测运行文件必须是 JSON 对象");
1178
1621
  if (values.cases) {
1179
1622
  if (values.cases !== "all") throw new Error("--cases 当前只支持 all");
1180
1623
  body.caseIds = (await fetchEvaluationCases(positionals[0], values)).map((item) => item.id);
@@ -1191,10 +1634,18 @@ async function ontologyCommand(action, args) {
1191
1634
  const { values, positionals } = commandArgs(args, {
1192
1635
  "network-id": { type: "string" },
1193
1636
  "version-id": { type: "string" },
1637
+ description: { type: "string" },
1194
1638
  name: { type: "string" },
1195
1639
  });
1196
1640
  if (action === "list") return print(await request("/api/biz-ontology/networks", { values }));
1197
1641
  if (action === "get") return print(await request(`/api/biz-ontology/networks/${encodeURIComponent(required(positionals[0], "ID"))}`, { values }));
1642
+ if (action === "versions") {
1643
+ const [operation, networkId, versionId] = positionals;
1644
+ if (!["list", "get", "create"].includes(operation)) throw new Error("ontology versions 只支持 list、get、create");
1645
+ expectPositionals(positionals, operation === "get" ? 3 : 2, `ontology versions ${operation} NETWORK_ID [VERSION_ID]`);
1646
+ const base = `/api/biz-ontology/networks/${encodeURIComponent(networkId)}/versions`;
1647
+ return print(await request(operation === "get" ? `${base}/${encodeURIComponent(versionId)}` : base, { method: operation === "create" ? "POST" : "GET", body: operation === "create" ? { ...(values.description === undefined ? {} : { description: values.description }) } : undefined, values }));
1648
+ }
1198
1649
  if (action === "export") {
1199
1650
  expectPositionals(positionals, 2, "ontology export ID FILE");
1200
1651
  const id = required(positionals[0], "ID");
@@ -1203,6 +1654,7 @@ async function ontologyCommand(action, args) {
1203
1654
  }
1204
1655
  if (action === "plan" || action === "apply") {
1205
1656
  expectPositionals(positionals, 1, `ontology ${action} FILE`);
1657
+ if (values.name && values["network-id"]) throw new Error("--name 仅适用于新建本体,不能和 --network-id 同时使用");
1206
1658
  const file = await readJsonFile(required(positionals[0], "FILE"));
1207
1659
  const path = values["network-id"]
1208
1660
  ? `/api/biz-ontology/networks/${encodeURIComponent(values["network-id"])}/import`
@@ -1214,6 +1666,59 @@ async function ontologyCommand(action, args) {
1214
1666
  throw new Error(`未知 ontology 命令:${action || "(空)"}`);
1215
1667
  }
1216
1668
 
1669
+ async function automationCommand(action, args) {
1670
+ const { values, positionals } = commandArgs(args, {
1671
+ cursor: { type: "string" },
1672
+ output: { type: "string" },
1673
+ follow: { type: "boolean", default: false },
1674
+ wait: { type: "boolean", default: false },
1675
+ timeout: { type: "string", default: "600" },
1676
+ });
1677
+ const base = "/api/personal-agent-automations";
1678
+ if (action === "list") {
1679
+ expectPositionals(positionals, 0, "automation list");
1680
+ return print(await request(base, { values }));
1681
+ }
1682
+ if (action === "apply") {
1683
+ expectPositionals(positionals, 1, "automation apply FILE");
1684
+ const spec = await readJsonFile(positionals[0]);
1685
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new Error("定时任务文件必须是 JSON 对象");
1686
+ const { id, ...body } = spec;
1687
+ const allowed = new Set(["name", "instructions", "personalAgentId", "schedule", "imPush", "emailPush", ...(id ? ["status"] : ["source"])]);
1688
+ const unknown = Object.keys(body).filter((key) => !allowed.has(key));
1689
+ if (unknown.length) throw new Error(`定时任务文件包含不支持的字段:${unknown.join(", ")}`);
1690
+ if (body.schedule !== undefined) {
1691
+ const schedule = body.schedule;
1692
+ if (!schedule || typeof schedule !== "object" || Array.isArray(schedule) || !["HOURLY", "DAILY", "WEEKLY"].includes(schedule.kind)) throw new Error("0.0.5 调度只支持 HOURLY、DAILY、WEEKLY");
1693
+ if (Object.keys(schedule).some((key) => !["kind", "timeOfDayMinutes", "weekday"].includes(key))) throw new Error("0.0.5 调度仅支持 kind、timeOfDayMinutes、weekday;不支持 weekdays 等新版参数");
1694
+ }
1695
+ if (id !== undefined && (typeof id !== "string" || !id.trim())) throw new Error("定时任务 id 必须是非空字符串");
1696
+ return print(await request(id ? `${base}/${encodeURIComponent(id)}` : base, { method: id ? "PATCH" : "POST", body, values }));
1697
+ }
1698
+ if (!["delete", "run", "runs"].includes(action)) throw new Error(`未知 automation 命令:${action || "(空)"}`);
1699
+ expectPositionals(positionals, 1, `automation ${action} ID`);
1700
+ const path = `${base}/${encodeURIComponent(positionals[0])}`;
1701
+ if (action === "delete") return print(await request(path, { method: "DELETE", values }));
1702
+ if (action === "runs") return print(await request(`${path}/runs${values.cursor ? `?cursor=${encodeURIComponent(values.cursor)}` : ""}`, { values }));
1703
+ if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
1704
+ const deadline = values.wait ? Date.now() + positiveSeconds(values.timeout) * 1000 : undefined;
1705
+ let started;
1706
+ try {
1707
+ started = await request(`${path}/run`, { method: "POST", deadline, values });
1708
+ } catch (error) {
1709
+ // The 0.0.5 start endpoint can keep running after the client disconnects.
1710
+ if (!error.httpStatus || error.httpStatus >= 500) {
1711
+ error.message += `;任务可能仍在服务端执行,请运行 decidex automation runs ${positionals[0]} 查看,勿直接重试触发`;
1712
+ }
1713
+ throw error;
1714
+ }
1715
+ await rememberRunBestEffort(started.personalAgentId, started.sessionId, started.runId, values);
1716
+ if (!values.wait) return emit(started, values.output);
1717
+ const finished = await waitForRun(started.personalAgentId, started.sessionId, started.runId, values, deadline);
1718
+ await emit(finished, values.output);
1719
+ if (finished.status !== "SUCCEEDED") process.exitCode = 1;
1720
+ }
1721
+
1217
1722
  async function apiCommand(args) {
1218
1723
  const { values, positionals } = commandArgs(args, {
1219
1724
  data: { type: "string" },
@@ -1235,7 +1740,10 @@ function expectPositionals(positionals, count, usage) {
1235
1740
  if (positionals.length !== count) throw new Error(`用法:decidex ${usage}`);
1236
1741
  }
1237
1742
 
1238
- async function versionCommand() {
1743
+ async function versionCommand(args = []) {
1744
+ const { values, positionals } = commandArgs(args, { server: { type: "boolean", default: false } });
1745
+ expectPositionals(positionals, 0, "version [--server]");
1746
+ if (values.server) return serverCommand("version", args.filter((arg) => arg !== "--server"));
1239
1747
  const packageJson = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
1240
1748
  print({ cliVersion: packageJson.version, protocolVersion: 1, buildCommit: process.env.DECIDEX_CLI_BUILD_COMMIT ?? null });
1241
1749
  }
@@ -1249,6 +1757,15 @@ async function main() {
1249
1757
  const detail = HELP_BY_COMMAND[`${area} ${action}`] ?? HELP_BY_COMMAND[area];
1250
1758
  return print((detail ?? HELP).trimEnd());
1251
1759
  }
1760
+ const ruleCommand = Object.keys(COMMAND_COMPATIBILITY)
1761
+ .sort((a, b) => b.split(" ").length - a.split(" ").length)
1762
+ .find((command) => argv.slice(0, command.split(" ").length).join(" ") === command);
1763
+ // login obtains credentials first; other declared rules are checked before dispatch.
1764
+ if (ruleCommand && ruleCommand !== "auth login") {
1765
+ const baseIndex = argv.indexOf("--base-url");
1766
+ const inlineBase = argv.find((arg) => arg.startsWith("--base-url="));
1767
+ await commandCompatibility(ruleCommand, { "base-url": inlineBase ? inlineBase.slice("--base-url=".length) : baseIndex >= 0 ? argv[baseIndex + 1] : undefined });
1768
+ }
1252
1769
  if (area === "auth") return authCommand(action, args);
1253
1770
  if (area === "context") return contextCommand(action, args);
1254
1771
  if (area === "org") return orgCommand(action, args);
@@ -1258,8 +1775,10 @@ async function main() {
1258
1775
  if (area === "skill") return skillCommand(action, args);
1259
1776
  if (area === "eval") return evalCommand(action, args);
1260
1777
  if (area === "ontology") return ontologyCommand(action, args);
1778
+ if (area === "automation") return automationCommand(action, args);
1261
1779
  if (area === "api") return apiCommand([action, ...args].filter(Boolean));
1262
- if (area === "version") return versionCommand();
1780
+ if (area === "server") return serverCommand(action, args);
1781
+ if (area === "version") return versionCommand([action, ...args].filter(Boolean));
1263
1782
  throw new Error(`未知命令:${area}`);
1264
1783
  }
1265
1784