@guandata/decidex 0.1.2 → 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,9 +7,10 @@ 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
- const BIZ_ONTOLOGY_EVIDENCE_DIR = "workspace/analysis/biz-ontology-evidence/";
13
14
 
14
15
  const HELP = `decidex - Decidex command line client
15
16
 
@@ -17,12 +18,18 @@ Usage:
17
18
  decidex auth login --base-url URL [--timeout SECONDS]
18
19
  decidex auth import --base-url URL # read decidex_session or Cookie header from stdin
19
20
  decidex auth status
21
+ decidex auth whoami # server >= 0.0.5
20
22
  decidex auth logout
21
23
  decidex context show
22
24
  decidex org use ID
23
25
 
24
26
  decidex agent list
25
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
26
33
  decidex agent apply FILE # create; update when FILE contains id
27
34
  decidex agent export ID FILE
28
35
  decidex agent import FILE # Personal Agent Transfer Bundle
@@ -33,24 +40,44 @@ Usage:
33
40
  decidex agent file delete ID FILE_ID
34
41
  decidex agent file download ID FILE_ID FILE
35
42
  decidex agent models ID
36
- 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]
37
44
 
38
- decidex session list [--status all|running|completed] [--query TEXT]
39
- 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]
40
47
  decidex session send SESSION_ID (--message TEXT | --input FILE) [--wait] [--follow]
41
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]
42
57
  decidex session artifacts list SESSION_ID
43
58
  decidex session artifacts download SESSION_ID --all --dir DIR [--overwrite]
44
- decidex session evidence list SESSION_ID
45
- decidex session evidence 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]
46
61
  decidex run diagnose RUN_ID [--session-id ID] [--agent-id ID] --json
47
62
 
48
- 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
49
71
  decidex skill upload FILE
50
- decidex skill update ID FILE
72
+ decidex skill update ID FILE [--fingerprint SHA256]
51
73
  decidex skill download ID FILE
52
74
  decidex skill delete ID
53
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
+
54
81
  decidex eval cases list AGENT_ID
55
82
  decidex eval cases export AGENT_ID FILE
56
83
  decidex eval cases plan AGENT_ID FILE [--prune]
@@ -60,17 +87,32 @@ Usage:
60
87
  decidex eval runs get AGENT_ID RUN_ID
61
88
  decidex eval runs wait AGENT_ID RUN_ID [--follow] [--output FILE] [--timeout SECONDS]
62
89
  decidex eval runs watch FILE [--parallel N] [--follow] [--output FILE] [--timeout SECONDS]
63
- decidex eval evidence download AGENT_ID RUN_ID --all --dir DIR [--overwrite]
90
+ decidex eval files download AGENT_ID RUN_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]
64
91
  decidex eval stop AGENT_ID RUN_ID
65
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]
66
96
  decidex ontology list
67
97
  decidex ontology get ID
68
98
  decidex ontology export ID FILE [--version-id ID]
69
99
  decidex ontology plan FILE [--network-id ID] [--name NAME]
70
100
  decidex ontology apply FILE [--network-id ID] [--name NAME]
71
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
+
72
108
  decidex api METHOD PATH [--data FILE] [--output FILE]
73
- 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)
74
116
 
75
117
  Environment:
76
118
  DECIDEX_BASE_URL, DECIDEX_SESSION, DECIDEX_CONFIG, DECIDEX_CHROME_PATH,
@@ -82,50 +124,74 @@ const HELP_BY_COMMAND = {
82
124
  decidex auth login --base-url URL [--timeout SECONDS]
83
125
  decidex auth import --base-url URL
84
126
  decidex auth status
127
+ decidex auth whoami # server >= 0.0.5
85
128
  decidex auth logout`,
86
129
  agent: `Usage:
87
- 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 ...
88
134
  decidex agent file list|add|delete|download ...
89
135
  decidex agent models AGENT_ID
90
136
  decidex agent run AGENT_ID (--message TEXT | --input FILE) [--wait] [--follow] [--output FILE]`,
91
137
  "agent run": `Usage:
92
- 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]
93
139
 
94
140
  With --wait, emits a stable JSON result containing sessionId, runId, status,
95
141
  error, answer, artifacts, startedAt, finishedAt, and durationMs. --follow writes progress
96
- 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.`,
97
147
  session: `Usage:
98
- decidex session list [--status all|running|completed] [--query TEXT]
99
- 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]
100
150
  decidex session send SESSION_ID (--message TEXT | --input FILE) [--wait] [--follow]
101
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]
102
160
  decidex session artifacts ...
103
- decidex session evidence ...
161
+ decidex session files ...
104
162
 
105
163
  With --wait, the message must start immediately; a busy session returns a conflict instead
106
164
  of queuing an untrackable run. Without --wait, the result can be kind=direct or kind=queued.`,
107
165
  "session artifacts": `Usage:
108
166
  decidex session artifacts list SESSION_ID
109
167
  decidex session artifacts download SESSION_ID --all --dir DIR [--overwrite]`,
110
- "session evidence": `Usage:
111
- decidex session evidence list SESSION_ID
112
- decidex session evidence 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]`,
113
171
  "run diagnose": `Usage:
114
172
  decidex run diagnose RUN_ID [--session-id ID] [--agent-id ID] --json
115
173
 
116
174
  Without explicit IDs, the CLI uses a matching recent local Run context.
117
175
  Runtime Pod termination details require backend support.`,
118
176
  skill: `Usage:
119
- 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
120
185
  decidex skill upload FILE
121
- decidex skill update ID FILE
186
+ decidex skill update ID FILE [--fingerprint SHA256]
122
187
  decidex skill download ID FILE
123
188
  decidex skill delete ID`,
124
189
  eval: `Usage:
190
+ decidex eval tags list|create|rename|delete ...
125
191
  decidex eval cases list|export|plan|apply ...
126
192
  decidex eval run AGENT_ID FILE [--cases all] [--wait] [--follow] [--output FILE]
127
193
  decidex eval runs list|get|wait|watch ...
128
- decidex eval evidence download AGENT_ID RUN_ID --all --dir DIR [--overwrite]
194
+ decidex eval files download AGENT_ID RUN_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]
129
195
  decidex eval stop AGENT_ID RUN_ID`,
130
196
  "eval cases": `Usage:
131
197
  decidex eval cases list AGENT_ID
@@ -137,10 +203,34 @@ Runtime Pod termination details require backend support.`,
137
203
  decidex eval runs get AGENT_ID RUN_ID
138
204
  decidex eval runs wait AGENT_ID RUN_ID [--follow] [--output FILE] [--timeout SECONDS]
139
205
  decidex eval runs watch FILE [--parallel N] [--follow] [--output FILE] [--timeout SECONDS]`,
140
- "eval evidence": `Usage:
141
- decidex eval evidence download AGENT_ID RUN_ID --all --dir DIR [--overwrite]`,
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`,
142
213
  ontology: `Usage:
143
- 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`,
144
234
  api: `Usage:
145
235
  decidex api METHOD PATH [--data FILE] [--output FILE]`,
146
236
  };
@@ -313,6 +403,36 @@ async function readMessage(values) {
313
403
  return message;
314
404
  }
315
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
+
316
436
  async function uploadForm(files, field = "file") {
317
437
  const form = new FormData();
318
438
  for (const file of files) {
@@ -328,13 +448,13 @@ function positiveSeconds(value, name = "timeout") {
328
448
  return seconds;
329
449
  }
330
450
 
331
- async function poll(fetchValue, isTerminal, timeoutSeconds, onValue) {
332
- const deadline = Date.now() + timeoutSeconds * 1000;
451
+ async function poll(fetchValue, isTerminal, timeoutSeconds, onValue, existingDeadline) {
452
+ const deadline = existingDeadline ?? Date.now() + timeoutSeconds * 1000;
333
453
  while (Date.now() < deadline) {
334
454
  const value = await fetchValue(deadline);
335
455
  await onValue?.(value);
336
456
  if (isTerminal(value)) return value;
337
- 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()))));
338
458
  }
339
459
  throw new Error(`等待运行完成超时(${timeoutSeconds} 秒)`);
340
460
  }
@@ -411,7 +531,7 @@ function followProgress(view, runId, seen) {
411
531
  }
412
532
  }
413
533
 
414
- async function waitForRun(agentId, sessionId, runId, values) {
534
+ async function waitForRun(agentId, sessionId, runId, values, existingDeadline) {
415
535
  process.stderr.write(`[decidex] started session=${sessionId} run=${runId}\n`);
416
536
  let lastStatus;
417
537
  let lastHeartbeatAt = 0;
@@ -435,6 +555,7 @@ async function waitForRun(agentId, sessionId, runId, values) {
435
555
  followProgress(await request(`${sessionPath(agentId, sessionId)}/view`, { deadline: runDeadline, values }), runId, seen);
436
556
  }
437
557
  : undefined,
558
+ existingDeadline,
438
559
  );
439
560
  const view = await request(`${sessionPath(agentId, sessionId)}/view`, { deadline: runDeadline, values });
440
561
  return finalRunResult(sessionId, runId, finished, view);
@@ -456,12 +577,19 @@ async function listSessionArtifacts(agentId, sessionId, values) {
456
577
  return (result.files ?? []).filter((file) => file.relativePath?.startsWith("artifacts/"));
457
578
  }
458
579
 
459
- async function listSessionEvidence(agentId, sessionId, values) {
460
- const result = await request(`${sessionPath(agentId, sessionId)}/files?force=1&evidence=1`, { values });
461
- return (result.files ?? []).filter((file) => {
462
- const name = file.relativePath?.slice(BIZ_ONTOLOGY_EVIDENCE_DIR.length);
463
- return file.relativePath?.startsWith(BIZ_ONTOLOGY_EVIDENCE_DIR) && name && !name.includes("/") && name.toLowerCase().endsWith(".boe");
464
- });
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;
465
593
  }
466
594
 
467
595
  function safeRelativeDestination(root, outputPath) {
@@ -511,11 +639,12 @@ async function writeArtifact(root, destination, bytes, overwrite) {
511
639
  }
512
640
  }
513
641
 
514
- async function readStdin(label = "内容") {
642
+ async function readStdin(label = "内容", trim = true) {
515
643
  if (process.stdin.isTTY) throw new Error(`请通过 stdin 传入${label}`);
516
644
  const chunks = [];
517
645
  for await (const chunk of process.stdin) chunks.push(chunk);
518
- return Buffer.concat(chunks).toString("utf8").trim();
646
+ const value = Buffer.concat(chunks).toString("utf8");
647
+ return trim ? value.trim() : value;
519
648
  }
520
649
 
521
650
  function sessionFromText(text) {
@@ -648,6 +777,48 @@ async function browserLogin(baseUrl, timeoutSeconds) {
648
777
  }
649
778
  }
650
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
+
651
822
  async function authCommand(action, args) {
652
823
  if (action === "login") {
653
824
  const { values } = commandArgs(args, { timeout: { type: "string", default: "300" } });
@@ -656,8 +827,8 @@ async function authCommand(action, args) {
656
827
  process.stderr.write("请在打开的 Chrome 窗口完成 Decidex 登录…\n");
657
828
  const session = await browserLogin(baseUrl, timeout);
658
829
  await saveConfig({ baseUrl, session, organizationId: null, recentRuns: [] });
659
- const result = await request("/api/personal-agents", { values: { "base-url": baseUrl } });
660
- 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 });
661
832
  return;
662
833
  }
663
834
  if (action === "import") {
@@ -668,17 +839,12 @@ async function authCommand(action, args) {
668
839
  print({ ok: true, baseUrl });
669
840
  return;
670
841
  }
671
- if (action === "status") {
672
- const { values } = commandArgs(args);
842
+ if (action === "status" || action === "whoami") {
843
+ const { values, positionals } = commandArgs(args);
844
+ expectPositionals(positionals, 0, `auth ${action}`);
673
845
  const credentials = await auth(values);
674
- const result = await request("/api/personal-agents", { values });
675
- print({
676
- authenticated: true,
677
- baseUrl: credentials.baseUrl,
678
- organizationId: credentials.organizationId,
679
- organizationIdVerified: false,
680
- agentCount: result.agents?.length ?? null,
681
- });
846
+ const result = await readIdentity(`auth ${action}`, values);
847
+ print({ authenticated: true, baseUrl: credentials.baseUrl, ...result });
682
848
  return;
683
849
  }
684
850
  if (action === "logout") {
@@ -697,13 +863,18 @@ async function authCommand(action, args) {
697
863
  throw new Error(`未知 auth 命令:${action || "(空)"}`);
698
864
  }
699
865
 
700
- async function contextCommand(action) {
866
+ async function contextCommand(action, args) {
701
867
  if (action !== "show") throw new Error(`未知 context 命令:${action || "(空)"}`);
868
+ const { values } = commandArgs(args);
702
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 };
703
875
  print({
704
- baseUrl: process.env.DECIDEX_BASE_URL || stored.baseUrl || null,
705
- organizationId: stored.organizationId ?? null,
706
- organizationIdVerified: false,
876
+ baseUrl: credentials.baseUrl,
877
+ ...context,
707
878
  sessionSource: process.env.DECIDEX_SESSION ? "environment" : stored.session ? "config" : null,
708
879
  configPath: configPath(),
709
880
  });
@@ -712,6 +883,7 @@ async function contextCommand(action) {
712
883
  async function orgCommand(action, args) {
713
884
  if (action !== "use") throw new Error(`未知 org 命令:${action || "(空)"}`);
714
885
  const { values, positionals } = commandArgs(args);
886
+ expectPositionals(positionals, 1, "org use ID");
715
887
  const result = await request("/api/auth/active-organization", {
716
888
  method: "PATCH",
717
889
  body: { organizationId: required(positionals[0], "ID") },
@@ -723,6 +895,10 @@ async function orgCommand(action, args) {
723
895
 
724
896
  async function agentCommand(action, args) {
725
897
  const { values, positionals } = commandArgs(args, {
898
+ ...TURN_OPTIONS,
899
+ "model-entry-id": { type: "string" },
900
+ cursor: { type: "string" },
901
+ query: { type: "string" },
726
902
  email: { type: "string" },
727
903
  "user-id": { type: "string" },
728
904
  input: { type: "string" },
@@ -732,7 +908,33 @@ async function agentCommand(action, args) {
732
908
  follow: { type: "boolean", default: false },
733
909
  wait: { type: "boolean", default: false },
734
910
  });
735
- 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
+ }
736
938
  if (action === "models") {
737
939
  const agentId = encodeURIComponent(required(positionals[0], "AGENT_ID"));
738
940
  const result = await request(`/api/personal-agents/${agentId}/sessions`, { values });
@@ -742,7 +944,12 @@ async function agentCommand(action, args) {
742
944
  if (action === "apply") {
743
945
  expectPositionals(positionals, 1, "agent apply FILE");
744
946
  const spec = await readJsonFile(required(positionals[0], "FILE"));
947
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new Error("Agent 文件必须是 JSON 对象");
745
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(", ")}`);
746
953
  const body = { ...spec };
747
954
  delete body.id;
748
955
  return print(
@@ -802,10 +1009,11 @@ async function agentCommand(action, args) {
802
1009
  expectPositionals(positionals, 1, "agent run AGENT_ID");
803
1010
  if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
804
1011
  const agentId = required(positionals[0], "AGENT_ID");
805
- const message = await readMessage(values);
1012
+ const body = await turnBody(values, true);
1013
+ if (values.wait) positiveSeconds(values.timeout);
806
1014
  const started = await request(`/api/personal-agents/${encodeURIComponent(agentId)}/sessions/start`, {
807
1015
  method: "POST",
808
- body: { message },
1016
+ body,
809
1017
  values,
810
1018
  });
811
1019
  await rememberRunBestEffort(agentId, started.session.id, started.runId, values);
@@ -822,6 +1030,12 @@ async function agentCommand(action, args) {
822
1030
 
823
1031
  async function sessionCommand(action, args) {
824
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" },
825
1039
  all: { type: "boolean", default: false },
826
1040
  dir: { type: "string" },
827
1041
  follow: { type: "boolean", default: false },
@@ -830,7 +1044,9 @@ async function sessionCommand(action, args) {
830
1044
  output: { type: "string" },
831
1045
  overwrite: { type: "boolean", default: false },
832
1046
  query: { type: "string" },
1047
+ scope: { type: "string" },
833
1048
  status: { type: "string", default: "all" },
1049
+ suffix: { type: "string" },
834
1050
  timeout: { type: "string", default: "600" },
835
1051
  wait: { type: "boolean", default: false },
836
1052
  });
@@ -838,24 +1054,59 @@ async function sessionCommand(action, args) {
838
1054
  expectPositionals(positionals, 0, "session list");
839
1055
  if (!new Set(["all", "running", "completed"]).has(values.status)) throw new Error("--status 只支持 all、running、completed");
840
1056
  const query = new URLSearchParams({ status: values.status });
1057
+ if (values.query && (values.cursor || values["agent-id"])) throw new Error("--query 不能和 --cursor 或 --agent-id 同时使用");
841
1058
  if (values.query) query.set("q", values.query);
842
- 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
+ }));
843
1094
  }
844
- if (action === "evidence") {
845
- const [evidenceAction, sessionIdValue] = positionals;
846
- expectPositionals(positionals, 2, `session evidence ${evidenceAction || "COMMAND"} SESSION_ID`);
1095
+ if (action === "files") {
1096
+ const [filesAction, sessionIdValue] = positionals;
1097
+ expectPositionals(positionals, 2, `session files ${filesAction || "COMMAND"} SESSION_ID`);
847
1098
  const sessionId = required(sessionIdValue, "SESSION_ID");
848
1099
  const session = await resolveSession(sessionId, values);
849
- const evidence = await listSessionEvidence(session.agentId, sessionId, values);
850
- if (evidenceAction === "list") {
851
- return print({ schemaVersion: 1, sessionId, agentId: session.agentId, evidence });
1100
+ const files = await listSessionFiles(session.agentId, sessionId, values);
1101
+ if (filesAction === "list") {
1102
+ return print({ schemaVersion: 1, sessionId, agentId: session.agentId, files });
852
1103
  }
853
- if (evidenceAction === "download") {
854
- if (!values.all) throw new Error("evidence download 需要 --all");
1104
+ if (filesAction === "download") {
1105
+ if (!values.all) throw new Error("files download 需要 --all");
855
1106
  const directory = resolve(required(values.dir, "--dir DIR"));
856
1107
  await mkdir(directory, { recursive: true });
857
1108
  const root = await realpath(directory);
858
- const targets = evidence.map((item) => ({ item, destination: safeRelativeDestination(root, item.name) }));
1109
+ const targets = files.map((item) => ({ item, destination: safeRelativeDestination(root, item.relativePath) }));
859
1110
  for (const { destination } of targets) await assertSafeArtifactTarget(root, destination, values.overwrite);
860
1111
  const downloaded = [];
861
1112
  for (const { item, destination } of targets) {
@@ -868,19 +1119,29 @@ async function sessionCommand(action, args) {
868
1119
  }
869
1120
  return print({ schemaVersion: 1, sessionId, directory, downloaded });
870
1121
  }
871
- throw new Error(`未知 session evidence 命令:${evidenceAction || "(空)"}`);
1122
+ throw new Error(`未知 session files 命令:${filesAction || "(空)"}`);
872
1123
  }
873
1124
  if (action !== "artifacts") {
874
1125
  expectPositionals(positionals, 1, `session ${action || "COMMAND"} SESSION_ID`);
875
1126
  const sessionId = required(positionals[0], "SESSION_ID");
876
1127
  const session = await resolveSession(sessionId, values);
877
- 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
+ }
878
1136
  if (action === "stop") return print(await request(`${sessionPath(session.agentId, sessionId)}/stop`, { method: "POST", values }));
879
1137
  if (action === "send") {
880
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);
881
1142
  const started = await request(`${sessionPath(session.agentId, sessionId)}/chat`, {
882
1143
  method: "POST",
883
- body: { message: await readMessage(values) },
1144
+ body,
884
1145
  headers: values.wait ? { "x-decidex-queue-if-running": "false" } : undefined,
885
1146
  values,
886
1147
  });
@@ -971,10 +1232,43 @@ async function runCommand(action, args) {
971
1232
  }
972
1233
 
973
1234
  async function skillCommand(action, args) {
974
- 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
+ }
975
1269
  if (action === "list") {
976
1270
  const result = await request("/api/plugins?kind=skill-only", { values });
977
- 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) });
978
1272
  }
979
1273
  if (action === "upload") {
980
1274
  expectPositionals(positionals, 1, "skill upload FILE");
@@ -985,9 +1279,9 @@ async function skillCommand(action, args) {
985
1279
  expectPositionals(positionals, 2, "skill update ID FILE");
986
1280
  const skillId = encodeURIComponent(required(positionals[0], "ID"));
987
1281
  const form = await uploadForm([required(positionals[1], "FILE")]);
988
- const snapshot = await request(`/api/skills/${skillId}/files?origin=personal`, { values });
989
- if (!snapshot.fingerprint) throw new Error("服务端未返回 Skill fingerprint");
990
- 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);
991
1285
  return print(await request(`/api/skills/${skillId}`, { method: "PUT", body: form, values }));
992
1286
  }
993
1287
  if (action === "download") {
@@ -1007,10 +1301,29 @@ function evaluationCasesFromFile(value) {
1007
1301
  const cases = Array.isArray(value) ? value : value?.cases;
1008
1302
  if (!Array.isArray(cases)) throw new Error("评测文件必须是数组或包含 cases 数组");
1009
1303
  const normalized = cases.map((item, index) => {
1010
- if (!item || typeof item.task !== "string" || !item.task.trim() || typeof item.rubric !== "string" || !item.rubric.trim()) {
1011
- 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 个字符`);
1012
1308
  }
1013
- 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()) }) };
1014
1327
  });
1015
1328
  const seen = new Set();
1016
1329
  for (const item of normalized) {
@@ -1026,13 +1339,37 @@ function evaluationCasesPlan(current, desired, prune) {
1026
1339
  if (currentByTask.has(item.task)) throw new Error(`线上评测集包含重复 task:${item.task}`);
1027
1340
  currentByTask.set(item.task, item);
1028
1341
  }
1029
- const desiredByTask = new Map(desired.map((item) => [item.task, item]));
1030
- const create = desired.filter((item) => !currentByTask.has(item.task));
1031
- const update = desired
1032
- .filter((item) => currentByTask.has(item.task) && currentByTask.get(item.task).rubric !== item.rubric)
1033
- .map((item) => ({ id: currentByTask.get(item.task).id, ...item }));
1034
- const keep = desired.filter((item) => currentByTask.get(item.task)?.rubric === item.rubric);
1035
- 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));
1036
1373
  return { create, update, keep, delete: prune ? extra : [], unmanaged: prune ? [] : extra };
1037
1374
  }
1038
1375
 
@@ -1056,7 +1393,7 @@ async function evalCasesCommand(args) {
1056
1393
  const current = await fetchEvaluationCases(id, values);
1057
1394
  if (action === "list") return print({ cases: current });
1058
1395
  if (action === "export") {
1059
- 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"));
1060
1397
  }
1061
1398
  if (action !== "plan" && action !== "apply") throw new Error(`未知 eval cases 命令:${action || "(空)"}`);
1062
1399
  const desired = evaluationCasesFromFile(await readJsonFile(required(file, "FILE")));
@@ -1065,8 +1402,8 @@ async function evalCasesCommand(args) {
1065
1402
 
1066
1403
  const base = `/api/personal-agents/${encodeURIComponent(id)}/evaluation-cases`;
1067
1404
  for (const item of plan.create) await request(base, { method: "POST", body: item, values });
1068
- for (const { id: caseId, task, rubric } of plan.update) {
1069
- 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 });
1070
1407
  }
1071
1408
  for (const item of plan.delete) await request(`${base}/${encodeURIComponent(item.id)}`, { method: "DELETE", values });
1072
1409
 
@@ -1080,8 +1417,8 @@ function evaluationRunSpec(value) {
1080
1417
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("评测运行文件必须是 JSON 对象");
1081
1418
  const allowed = new Set(["caseIds", "targetModelSelection", "judgeModelSelection"]);
1082
1419
  const unknown = Object.keys(value).filter((key) => !allowed.has(key));
1083
- if (unknown.length) throw new Error(`评测运行文件包含最新 origin/main 不支持的字段:${unknown.join(", ")}`);
1084
- 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;
1085
1422
  for (const field of ["targetModelSelection", "judgeModelSelection"]) {
1086
1423
  const selection = value[field];
1087
1424
  if (!selection || typeof selection !== "object" || Array.isArray(selection)) throw new Error(`${field} 必须是对象`);
@@ -1208,30 +1545,32 @@ async function evalRunsCommand(args) {
1208
1545
  throw new Error(`未知 eval runs 命令:${action || "(空)"}`);
1209
1546
  }
1210
1547
 
1211
- async function evalEvidenceCommand(args) {
1548
+ async function evalFilesCommand(args) {
1212
1549
  const { values, positionals } = commandArgs(args, {
1213
1550
  all: { type: "boolean", default: false },
1214
1551
  dir: { type: "string" },
1215
1552
  overwrite: { type: "boolean", default: false },
1553
+ scope: { type: "string" },
1554
+ suffix: { type: "string" },
1216
1555
  });
1217
1556
  const [action, agentId, runId] = positionals;
1218
- if (action !== "download") throw new Error(`未知 eval evidence 命令:${action || "(空)"}`);
1219
- expectPositionals(positionals, 3, "eval evidence download AGENT_ID RUN_ID");
1220
- if (!values.all) throw new Error("eval evidence download 需要 --all");
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");
1221
1560
  const result = await request(evaluationRunPath(agentId, runId), { values });
1222
1561
  const runCases = result.run?.cases ?? [];
1223
1562
  if (runCases.some((runCase) => !Object.hasOwn(runCase, "targetSessionId"))) {
1224
1563
  throw new Error("Decidex 服务端未返回评测 Case 的 targetSessionId;请先升级服务端");
1225
1564
  }
1226
- const evidence = (await Promise.all(runCases.map(async (runCase, index) => {
1565
+ const files = (await Promise.all(runCases.map(async (runCase, index) => {
1227
1566
  if (!runCase.targetSessionId) return [];
1228
- const files = await listSessionEvidence(agentId, runCase.targetSessionId, values);
1229
- return files.map((file) => ({ ...file, caseId: runCase.id, casePosition: runCase.position, sessionId: runCase.targetSessionId, outputDirectory: `case-${index + 1}` }));
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}` }));
1230
1569
  }))).flat();
1231
1570
  const directory = resolve(required(values.dir, "--dir DIR"));
1232
1571
  await mkdir(directory, { recursive: true });
1233
1572
  const root = await realpath(directory);
1234
- const targets = evidence.map((item) => ({ item, destination: safeRelativeDestination(root, join(item.outputDirectory, item.name)) }));
1573
+ const targets = files.map((item) => ({ item, destination: safeRelativeDestination(root, join(item.outputDirectory, item.relativePath)) }));
1235
1574
  for (const { destination } of targets) await assertSafeArtifactTarget(root, destination, values.overwrite);
1236
1575
  const downloaded = [];
1237
1576
  for (const { item, destination } of targets) {
@@ -1245,10 +1584,21 @@ async function evalEvidenceCommand(args) {
1245
1584
  return print({ schemaVersion: 1, agentId, runId, directory, downloaded });
1246
1585
  }
1247
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
+
1248
1597
  async function evalCommand(action, args) {
1249
1598
  if (action === "cases") return evalCasesCommand(args);
1599
+ if (action === "tags") return evalTagsCommand(args);
1250
1600
  if (action === "runs") return evalRunsCommand(args);
1251
- if (action === "evidence") return evalEvidenceCommand(args);
1601
+ if (action === "files") return evalFilesCommand(args);
1252
1602
  const { values, positionals } = commandArgs(args, {
1253
1603
  cases: { type: "string" },
1254
1604
  follow: { type: "boolean", default: false },
@@ -1264,7 +1614,10 @@ async function evalCommand(action, args) {
1264
1614
  }
1265
1615
  if (action !== "run") throw new Error(`未知 eval 命令:${action || "(空)"}`);
1266
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);
1267
1619
  const body = await readJsonFile(required(positionals[1], "FILE"));
1620
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("评测运行文件必须是 JSON 对象");
1268
1621
  if (values.cases) {
1269
1622
  if (values.cases !== "all") throw new Error("--cases 当前只支持 all");
1270
1623
  body.caseIds = (await fetchEvaluationCases(positionals[0], values)).map((item) => item.id);
@@ -1281,10 +1634,18 @@ async function ontologyCommand(action, args) {
1281
1634
  const { values, positionals } = commandArgs(args, {
1282
1635
  "network-id": { type: "string" },
1283
1636
  "version-id": { type: "string" },
1637
+ description: { type: "string" },
1284
1638
  name: { type: "string" },
1285
1639
  });
1286
1640
  if (action === "list") return print(await request("/api/biz-ontology/networks", { values }));
1287
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
+ }
1288
1649
  if (action === "export") {
1289
1650
  expectPositionals(positionals, 2, "ontology export ID FILE");
1290
1651
  const id = required(positionals[0], "ID");
@@ -1293,6 +1654,7 @@ async function ontologyCommand(action, args) {
1293
1654
  }
1294
1655
  if (action === "plan" || action === "apply") {
1295
1656
  expectPositionals(positionals, 1, `ontology ${action} FILE`);
1657
+ if (values.name && values["network-id"]) throw new Error("--name 仅适用于新建本体,不能和 --network-id 同时使用");
1296
1658
  const file = await readJsonFile(required(positionals[0], "FILE"));
1297
1659
  const path = values["network-id"]
1298
1660
  ? `/api/biz-ontology/networks/${encodeURIComponent(values["network-id"])}/import`
@@ -1304,6 +1666,59 @@ async function ontologyCommand(action, args) {
1304
1666
  throw new Error(`未知 ontology 命令:${action || "(空)"}`);
1305
1667
  }
1306
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
+
1307
1722
  async function apiCommand(args) {
1308
1723
  const { values, positionals } = commandArgs(args, {
1309
1724
  data: { type: "string" },
@@ -1325,7 +1740,10 @@ function expectPositionals(positionals, count, usage) {
1325
1740
  if (positionals.length !== count) throw new Error(`用法:decidex ${usage}`);
1326
1741
  }
1327
1742
 
1328
- 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"));
1329
1747
  const packageJson = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
1330
1748
  print({ cliVersion: packageJson.version, protocolVersion: 1, buildCommit: process.env.DECIDEX_CLI_BUILD_COMMIT ?? null });
1331
1749
  }
@@ -1339,6 +1757,15 @@ async function main() {
1339
1757
  const detail = HELP_BY_COMMAND[`${area} ${action}`] ?? HELP_BY_COMMAND[area];
1340
1758
  return print((detail ?? HELP).trimEnd());
1341
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
+ }
1342
1769
  if (area === "auth") return authCommand(action, args);
1343
1770
  if (area === "context") return contextCommand(action, args);
1344
1771
  if (area === "org") return orgCommand(action, args);
@@ -1348,8 +1775,10 @@ async function main() {
1348
1775
  if (area === "skill") return skillCommand(action, args);
1349
1776
  if (area === "eval") return evalCommand(action, args);
1350
1777
  if (area === "ontology") return ontologyCommand(action, args);
1778
+ if (area === "automation") return automationCommand(action, args);
1351
1779
  if (area === "api") return apiCommand([action, ...args].filter(Boolean));
1352
- if (area === "version") return versionCommand();
1780
+ if (area === "server") return serverCommand(action, args);
1781
+ if (area === "version") return versionCommand([action, ...args].filter(Boolean));
1353
1782
  throw new Error(`未知命令:${area}`);
1354
1783
  }
1355
1784