@guandata/decidex 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +268 -16
- package/docs/api-coverage.md +51 -0
- package/package.json +4 -3
- package/src/api-catalog.json +6849 -0
- package/src/catalog.js +36 -0
- package/src/cli.js +806 -104
- package/src/compatibility.js +94 -0
package/src/cli.js
CHANGED
|
@@ -7,9 +7,12 @@ 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, adaptAutomationSchedule } from "./compatibility.js";
|
|
11
|
+
|
|
12
|
+
import { apiCatalog, apiOperation, parameterFlag, operationPath, appendQuery } from "./catalog.js";
|
|
13
|
+
|
|
10
14
|
const COOKIE_NAME = "decidex_session";
|
|
11
15
|
const DEFAULT_CONFIG_PATH = join(homedir(), ".config", "decidex", "config.json");
|
|
12
|
-
const BIZ_ONTOLOGY_EVIDENCE_DIR = "workspace/analysis/biz-ontology-evidence/";
|
|
13
16
|
|
|
14
17
|
const HELP = `decidex - Decidex command line client
|
|
15
18
|
|
|
@@ -17,12 +20,18 @@ Usage:
|
|
|
17
20
|
decidex auth login --base-url URL [--timeout SECONDS]
|
|
18
21
|
decidex auth import --base-url URL # read decidex_session or Cookie header from stdin
|
|
19
22
|
decidex auth status
|
|
23
|
+
decidex auth whoami # server >= 0.0.5
|
|
20
24
|
decidex auth logout
|
|
21
25
|
decidex context show
|
|
22
26
|
decidex org use ID
|
|
23
27
|
|
|
24
28
|
decidex agent list
|
|
25
29
|
decidex agent get ID
|
|
30
|
+
decidex agent delete ID
|
|
31
|
+
decidex agent publications ID
|
|
32
|
+
decidex agent use-scope ID OWNER|SPECIFIC_USERS|ORGANIZATION
|
|
33
|
+
decidex agent knowledge list AGENT_ID [--query TEXT] [--cursor CURSOR]
|
|
34
|
+
decidex agent knowledge add|remove AGENT_ID DOCUMENT_ID
|
|
26
35
|
decidex agent apply FILE # create; update when FILE contains id
|
|
27
36
|
decidex agent export ID FILE
|
|
28
37
|
decidex agent import FILE # Personal Agent Transfer Bundle
|
|
@@ -33,24 +42,44 @@ Usage:
|
|
|
33
42
|
decidex agent file delete ID FILE_ID
|
|
34
43
|
decidex agent file download ID FILE_ID FILE
|
|
35
44
|
decidex agent models ID
|
|
36
|
-
decidex agent run ID (--message TEXT | --input FILE) [--wait] [--follow] [--output FILE] [--timeout SECONDS]
|
|
45
|
+
decidex agent run ID (--message TEXT | --input FILE | --attach FILE) [--model-entry-id ID] [--reasoning-effort LEVEL] [--wait] [--follow] [--output FILE] [--timeout SECONDS]
|
|
37
46
|
|
|
38
|
-
decidex session list [--status all|running|completed] [--query TEXT]
|
|
39
|
-
decidex session view SESSION_ID
|
|
47
|
+
decidex session list [--status all|running|completed] [--query TEXT] [--cursor CURSOR] [--agent-id ID]
|
|
48
|
+
decidex session view SESSION_ID [--before CURSOR | --since CURSOR]
|
|
40
49
|
decidex session send SESSION_ID (--message TEXT | --input FILE) [--wait] [--follow]
|
|
41
50
|
decidex session stop SESSION_ID
|
|
51
|
+
decidex session rename SESSION_ID TITLE
|
|
52
|
+
decidex session delete SESSION_ID
|
|
53
|
+
decidex session model SESSION_ID MODEL_ENTRY_ID
|
|
54
|
+
decidex session fork SESSION_ID RUN_ID
|
|
55
|
+
decidex session queue list SESSION_ID
|
|
56
|
+
decidex session queue edit SESSION_ID DRAFT_ID (--message TEXT | --input FILE)
|
|
57
|
+
decidex session queue delete SESSION_ID DRAFT_ID
|
|
58
|
+
decidex session queue continue SESSION_ID [--wait] [--follow] [--output FILE]
|
|
42
59
|
decidex session artifacts list SESSION_ID
|
|
43
60
|
decidex session artifacts download SESSION_ID --all --dir DIR [--overwrite]
|
|
44
|
-
decidex session
|
|
45
|
-
decidex session
|
|
61
|
+
decidex session files list SESSION_ID [--scope analysis] [--suffix EXT]
|
|
62
|
+
decidex session files download SESSION_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]
|
|
46
63
|
decidex run diagnose RUN_ID [--session-id ID] [--agent-id ID] --json
|
|
47
64
|
|
|
48
|
-
decidex skill list
|
|
65
|
+
decidex skill list [--origin personal|builtin|all]
|
|
66
|
+
decidex skill references ID
|
|
67
|
+
decidex skill files list ID [--origin personal|builtin]
|
|
68
|
+
decidex skill files get ID PATH [--origin personal|builtin]
|
|
69
|
+
decidex skill files put ID PATH FILE --fingerprint SHA256
|
|
70
|
+
decidex skill credentials status ID
|
|
71
|
+
decidex skill credentials set ID ENV_NAME # read value from stdin
|
|
72
|
+
decidex skill credentials delete ID ENV_NAME
|
|
49
73
|
decidex skill upload FILE
|
|
50
|
-
decidex skill update ID FILE
|
|
74
|
+
decidex skill update ID FILE [--fingerprint SHA256]
|
|
51
75
|
decidex skill download ID FILE
|
|
52
76
|
decidex skill delete ID
|
|
53
77
|
|
|
78
|
+
decidex eval tags list AGENT_ID
|
|
79
|
+
decidex eval tags create AGENT_ID NAME
|
|
80
|
+
decidex eval tags rename AGENT_ID TAG_ID NAME
|
|
81
|
+
decidex eval tags delete AGENT_ID TAG_ID
|
|
82
|
+
|
|
54
83
|
decidex eval cases list AGENT_ID
|
|
55
84
|
decidex eval cases export AGENT_ID FILE
|
|
56
85
|
decidex eval cases plan AGENT_ID FILE [--prune]
|
|
@@ -60,17 +89,36 @@ Usage:
|
|
|
60
89
|
decidex eval runs get AGENT_ID RUN_ID
|
|
61
90
|
decidex eval runs wait AGENT_ID RUN_ID [--follow] [--output FILE] [--timeout SECONDS]
|
|
62
91
|
decidex eval runs watch FILE [--parallel N] [--follow] [--output FILE] [--timeout SECONDS]
|
|
63
|
-
decidex eval
|
|
92
|
+
decidex eval files download AGENT_ID RUN_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]
|
|
64
93
|
decidex eval stop AGENT_ID RUN_ID
|
|
65
94
|
|
|
95
|
+
decidex ontology versions list NETWORK_ID
|
|
96
|
+
decidex ontology versions get NETWORK_ID VERSION_ID
|
|
97
|
+
decidex ontology versions create NETWORK_ID [--description TEXT]
|
|
66
98
|
decidex ontology list
|
|
67
99
|
decidex ontology get ID
|
|
68
100
|
decidex ontology export ID FILE [--version-id ID]
|
|
69
101
|
decidex ontology plan FILE [--network-id ID] [--name NAME]
|
|
70
102
|
decidex ontology apply FILE [--network-id ID] [--name NAME]
|
|
71
103
|
|
|
104
|
+
decidex automation list
|
|
105
|
+
decidex automation apply FILE # create; PATCH when FILE contains id
|
|
106
|
+
decidex automation delete ID
|
|
107
|
+
decidex automation run ID [--wait] [--follow] [--output FILE] [--timeout SECONDS]
|
|
108
|
+
decidex automation runs ID [--cursor CURSOR]
|
|
109
|
+
|
|
110
|
+
decidex action-task list|get|suggestions|members|create|adopt|reject|complete|cancel ...
|
|
111
|
+
decidex tracking list|get|preview|create|lookup|wait|rename|schedule|pause|resume|close|review|reviews|report|retry|delete ...
|
|
112
|
+
decidex platform list|show|call|coverage ...
|
|
113
|
+
|
|
72
114
|
decidex api METHOD PATH [--data FILE] [--output FILE]
|
|
73
|
-
decidex version --json
|
|
115
|
+
decidex version --json # local CLI version
|
|
116
|
+
decidex server version # target version and commit
|
|
117
|
+
decidex server check [COMMAND...] # version rules and selected protocol
|
|
118
|
+
|
|
119
|
+
Turn options (agent run / session send):
|
|
120
|
+
--attach FILE (repeatable), --reasoning-effort LEVEL (null = model default),
|
|
121
|
+
--context-references FILE, --conversation-references FILE (JSON arrays)
|
|
74
122
|
|
|
75
123
|
Environment:
|
|
76
124
|
DECIDEX_BASE_URL, DECIDEX_SESSION, DECIDEX_CONFIG, DECIDEX_CHROME_PATH,
|
|
@@ -78,54 +126,129 @@ Environment:
|
|
|
78
126
|
`;
|
|
79
127
|
|
|
80
128
|
const HELP_BY_COMMAND = {
|
|
129
|
+
automation: `Usage:
|
|
130
|
+
decidex automation list
|
|
131
|
+
decidex automation apply FILE
|
|
132
|
+
decidex automation run ID [--wait] [--follow] [--output FILE] [--timeout SECONDS]
|
|
133
|
+
decidex automation runs ID [--cursor CURSOR]
|
|
134
|
+
decidex automation delete ID
|
|
135
|
+
|
|
136
|
+
FILE creates an automation; include id to PATCH an existing one. status: ACTIVE / PAUSED.
|
|
137
|
+
Server >= 0.0.6: DAILY; WEEKLY weekdays:[0..6]; MONTHLY monthDays:[1..31];
|
|
138
|
+
INTERVAL intervalMinutes:5..2147483647; ONCE runOnceAt:future ISO time.
|
|
139
|
+
On 0.0.5, one weekday is supported; newer schedules are rejected before writing.
|
|
140
|
+
Old HOURLY becomes INTERVAL(60) on 0.0.6. server check automation apply shows the protocol.
|
|
141
|
+
--wait --timeout covers start, polling and final reads. A timeout does not cancel the run.`,
|
|
142
|
+
"action-task": `Usage:
|
|
143
|
+
decidex action-task list [--status PENDING|ADOPTED|COMPLETED|REJECTED|CANCELED|all] [--query TEXT] [--page N]
|
|
144
|
+
decidex action-task suggestions SESSION_ID (--run-id ID | --message-id ID)
|
|
145
|
+
decidex action-task members SESSION_ID [--query TEXT]
|
|
146
|
+
decidex action-task create SESSION_ID FILE
|
|
147
|
+
decidex action-task get TASK_ID
|
|
148
|
+
decidex action-task adopt|complete TASK_ID --version N
|
|
149
|
+
decidex action-task reject|cancel TASK_ID --version N --note REASON
|
|
150
|
+
|
|
151
|
+
Create FILE: {messageId,suggestionId,draft:{title,description,assigneeIds:[USER_ID]}}.
|
|
152
|
+
Read the current version with get before changing status; 409 requires a new user decision.
|
|
153
|
+
Action tasks have no delete API.`,
|
|
154
|
+
tracking: `Usage:
|
|
155
|
+
decidex tracking list [--filter all|due] [--page N]
|
|
156
|
+
decidex tracking preview|lookup|create SESSION_ID --candidate-path PATH --boe-path PATH [--wait]
|
|
157
|
+
decidex tracking get|wait TASK_ID
|
|
158
|
+
decidex tracking rename TASK_ID TITLE
|
|
159
|
+
decidex tracking schedule TASK_ID FILE
|
|
160
|
+
decidex tracking pause|resume|close|delete TASK_ID
|
|
161
|
+
decidex tracking review TASK_ID [--data FILE] [--wait]
|
|
162
|
+
decidex tracking reviews TASK_ID [--cursor CURSOR]
|
|
163
|
+
decidex tracking report TASK_ID FILE [--initial | --review-id ID]
|
|
164
|
+
decidex tracking retry TASK_ID [--wait]
|
|
165
|
+
|
|
166
|
+
Candidate and BOE paths belong to the remote session. create confirms a server-validated
|
|
167
|
+
candidate and evidenceVersion. Schedule FILE: {reviewFrequency:"WEEKLY|MONTHLY|QUARTERLY",nextReviewAt:ISO_DATE}.
|
|
168
|
+
--timeout SECONDS bounds the operation and any wait (default 600).`,
|
|
169
|
+
platform: `Usage:
|
|
170
|
+
decidex platform list [--query TEXT] [--group GROUP] [--method METHOD]
|
|
171
|
+
decidex platform show OPERATION_ID
|
|
172
|
+
decidex platform call OPERATION_ID [PATH_FLAGS] [--query FILE | --query-param KEY=VALUE]
|
|
173
|
+
[--data JSON_FILE] [--file FIELD=FILE] [--field KEY=VALUE]
|
|
174
|
+
[--body-file FILE --content-type MIME] [--output FILE] [--dry-run] [--timeout SECONDS]
|
|
175
|
+
decidex platform coverage
|
|
176
|
+
|
|
177
|
+
show lists required path flags. --file, --field and --query-param are repeatable.
|
|
178
|
+
--dry-run makes no network request. Main-only operations require --allow-unreleased;
|
|
179
|
+
released minimum versions are checked against the target server.`,
|
|
81
180
|
auth: `Usage:
|
|
82
181
|
decidex auth login --base-url URL [--timeout SECONDS]
|
|
83
182
|
decidex auth import --base-url URL
|
|
84
183
|
decidex auth status
|
|
184
|
+
decidex auth whoami # server >= 0.0.5
|
|
85
185
|
decidex auth logout`,
|
|
86
186
|
agent: `Usage:
|
|
87
|
-
decidex agent list|get|apply|export|import ...
|
|
187
|
+
decidex agent list|get|apply|export|import|delete ...
|
|
188
|
+
decidex agent publications ID
|
|
189
|
+
decidex agent use-scope ID OWNER|SPECIFIC_USERS|ORGANIZATION
|
|
190
|
+
decidex agent knowledge list|add|remove ...
|
|
88
191
|
decidex agent file list|add|delete|download ...
|
|
89
192
|
decidex agent models AGENT_ID
|
|
90
193
|
decidex agent run AGENT_ID (--message TEXT | --input FILE) [--wait] [--follow] [--output FILE]`,
|
|
91
194
|
"agent run": `Usage:
|
|
92
|
-
decidex agent run AGENT_ID (--message TEXT | --input FILE) [--wait] [--follow] [--output FILE] [--timeout SECONDS]
|
|
195
|
+
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
196
|
|
|
94
197
|
With --wait, emits a stable JSON result containing sessionId, runId, status,
|
|
95
198
|
error, answer, artifacts, startedAt, finishedAt, and durationMs. --follow writes progress
|
|
96
|
-
to stderr, so stdout or --output remains machine-readable
|
|
199
|
+
to stderr, so stdout or --output remains machine-readable.
|
|
200
|
+
|
|
201
|
+
--attach FILE is repeatable. --context-references FILE and --conversation-references FILE
|
|
202
|
+
accept JSON arrays. --reasoning-effort null uses the model default.
|
|
203
|
+
Use agent models AGENT_ID to discover supported catalog entries and efforts.`,
|
|
97
204
|
session: `Usage:
|
|
98
|
-
decidex session list [--status all|running|completed] [--query TEXT]
|
|
99
|
-
decidex session view SESSION_ID
|
|
205
|
+
decidex session list [--status all|running|completed] [--query TEXT] [--cursor CURSOR] [--agent-id ID]
|
|
206
|
+
decidex session view SESSION_ID [--before CURSOR | --since CURSOR]
|
|
100
207
|
decidex session send SESSION_ID (--message TEXT | --input FILE) [--wait] [--follow]
|
|
101
208
|
decidex session stop SESSION_ID
|
|
209
|
+
decidex session rename SESSION_ID TITLE
|
|
210
|
+
decidex session delete SESSION_ID
|
|
211
|
+
decidex session model SESSION_ID MODEL_ENTRY_ID
|
|
212
|
+
decidex session fork SESSION_ID RUN_ID
|
|
213
|
+
decidex session queue list SESSION_ID
|
|
214
|
+
decidex session queue edit SESSION_ID DRAFT_ID (--message TEXT | --input FILE)
|
|
215
|
+
decidex session queue delete SESSION_ID DRAFT_ID
|
|
216
|
+
decidex session queue continue SESSION_ID [--wait] [--follow] [--output FILE]
|
|
102
217
|
decidex session artifacts ...
|
|
103
|
-
decidex session
|
|
218
|
+
decidex session files ...
|
|
104
219
|
|
|
105
220
|
With --wait, the message must start immediately; a busy session returns a conflict instead
|
|
106
221
|
of queuing an untrackable run. Without --wait, the result can be kind=direct or kind=queued.`,
|
|
107
222
|
"session artifacts": `Usage:
|
|
108
223
|
decidex session artifacts list SESSION_ID
|
|
109
224
|
decidex session artifacts download SESSION_ID --all --dir DIR [--overwrite]`,
|
|
110
|
-
"session
|
|
111
|
-
decidex session
|
|
112
|
-
decidex session
|
|
225
|
+
"session files": `Usage:
|
|
226
|
+
decidex session files list SESSION_ID [--scope analysis] [--suffix EXT]
|
|
227
|
+
decidex session files download SESSION_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]`,
|
|
113
228
|
"run diagnose": `Usage:
|
|
114
229
|
decidex run diagnose RUN_ID [--session-id ID] [--agent-id ID] --json
|
|
115
230
|
|
|
116
231
|
Without explicit IDs, the CLI uses a matching recent local Run context.
|
|
117
232
|
Runtime Pod termination details require backend support.`,
|
|
118
233
|
skill: `Usage:
|
|
119
|
-
decidex skill list
|
|
234
|
+
decidex skill list [--origin personal|builtin|all]
|
|
235
|
+
decidex skill references ID
|
|
236
|
+
decidex skill files list ID [--origin personal|builtin]
|
|
237
|
+
decidex skill files get ID PATH [--origin personal|builtin]
|
|
238
|
+
decidex skill files put ID PATH FILE --fingerprint SHA256
|
|
239
|
+
decidex skill credentials status ID
|
|
240
|
+
decidex skill credentials set ID ENV_NAME # read value from stdin
|
|
241
|
+
decidex skill credentials delete ID ENV_NAME
|
|
120
242
|
decidex skill upload FILE
|
|
121
|
-
decidex skill update ID FILE
|
|
243
|
+
decidex skill update ID FILE [--fingerprint SHA256]
|
|
122
244
|
decidex skill download ID FILE
|
|
123
245
|
decidex skill delete ID`,
|
|
124
246
|
eval: `Usage:
|
|
247
|
+
decidex eval tags list|create|rename|delete ...
|
|
125
248
|
decidex eval cases list|export|plan|apply ...
|
|
126
249
|
decidex eval run AGENT_ID FILE [--cases all] [--wait] [--follow] [--output FILE]
|
|
127
250
|
decidex eval runs list|get|wait|watch ...
|
|
128
|
-
decidex eval
|
|
251
|
+
decidex eval files download AGENT_ID RUN_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]
|
|
129
252
|
decidex eval stop AGENT_ID RUN_ID`,
|
|
130
253
|
"eval cases": `Usage:
|
|
131
254
|
decidex eval cases list AGENT_ID
|
|
@@ -137,10 +260,34 @@ Runtime Pod termination details require backend support.`,
|
|
|
137
260
|
decidex eval runs get AGENT_ID RUN_ID
|
|
138
261
|
decidex eval runs wait AGENT_ID RUN_ID [--follow] [--output FILE] [--timeout SECONDS]
|
|
139
262
|
decidex eval runs watch FILE [--parallel N] [--follow] [--output FILE] [--timeout SECONDS]`,
|
|
140
|
-
"eval
|
|
141
|
-
decidex eval
|
|
263
|
+
"eval files": `Usage:
|
|
264
|
+
decidex eval files download AGENT_ID RUN_ID --all --dir DIR [--scope analysis] [--suffix EXT] [--overwrite]`,
|
|
265
|
+
"eval tags": `Usage:
|
|
266
|
+
decidex eval tags list AGENT_ID
|
|
267
|
+
decidex eval tags create AGENT_ID NAME
|
|
268
|
+
decidex eval tags rename AGENT_ID TAG_ID NAME
|
|
269
|
+
decidex eval tags delete AGENT_ID TAG_ID`,
|
|
142
270
|
ontology: `Usage:
|
|
143
|
-
decidex ontology list|get|export|plan|apply
|
|
271
|
+
decidex ontology list|get|export|plan|apply ...
|
|
272
|
+
decidex ontology versions list|get|create ...`,
|
|
273
|
+
"ontology versions": `Usage:
|
|
274
|
+
decidex ontology versions list NETWORK_ID
|
|
275
|
+
decidex ontology versions get NETWORK_ID VERSION_ID
|
|
276
|
+
decidex ontology versions create NETWORK_ID [--description TEXT]`,
|
|
277
|
+
automation: `Usage:
|
|
278
|
+
decidex automation list
|
|
279
|
+
decidex automation apply FILE
|
|
280
|
+
decidex automation delete ID
|
|
281
|
+
decidex automation run ID [--wait] [--follow] [--output FILE] [--timeout SECONDS]
|
|
282
|
+
decidex automation runs ID [--cursor CURSOR]`,
|
|
283
|
+
server: `Usage:
|
|
284
|
+
decidex server version
|
|
285
|
+
decidex server check [COMMAND...]
|
|
286
|
+
|
|
287
|
+
Unknown rules report supported=null; a newer server alone is not proof of compatibility.`,
|
|
288
|
+
version: `Usage:
|
|
289
|
+
decidex version [--json] # local CLI version
|
|
290
|
+
decidex version --server [--json] # same as server version`,
|
|
144
291
|
api: `Usage:
|
|
145
292
|
decidex api METHOD PATH [--data FILE] [--output FILE]`,
|
|
146
293
|
};
|
|
@@ -236,7 +383,7 @@ async function request(path, { method = "GET", body, deadline, headers: extraHea
|
|
|
236
383
|
requestBody = body;
|
|
237
384
|
} else if (body instanceof Uint8Array) {
|
|
238
385
|
requestBody = body;
|
|
239
|
-
headers["content-type"]
|
|
386
|
+
headers["content-type"] ??= "application/octet-stream";
|
|
240
387
|
} else if (body !== undefined) {
|
|
241
388
|
requestBody = JSON.stringify(body);
|
|
242
389
|
headers["content-type"] = "application/json";
|
|
@@ -250,7 +397,7 @@ async function request(path, { method = "GET", body, deadline, headers: extraHea
|
|
|
250
397
|
headers,
|
|
251
398
|
body: requestBody,
|
|
252
399
|
redirect: "manual",
|
|
253
|
-
signal: remaining === null ? undefined : AbortSignal.timeout(remaining),
|
|
400
|
+
signal: remaining === null ? undefined : AbortSignal.timeout(Math.ceil(remaining)),
|
|
254
401
|
});
|
|
255
402
|
} catch (error) {
|
|
256
403
|
if (error?.name === "TimeoutError" || error?.name === "AbortError") throw new Error("等待运行完成超时");
|
|
@@ -313,6 +460,36 @@ async function readMessage(values) {
|
|
|
313
460
|
return message;
|
|
314
461
|
}
|
|
315
462
|
|
|
463
|
+
const REASONING_EFFORTS = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
|
464
|
+
const TURN_OPTIONS = {
|
|
465
|
+
attach: { type: "string", multiple: true },
|
|
466
|
+
"context-references": { type: "string" },
|
|
467
|
+
"conversation-references": { type: "string" },
|
|
468
|
+
"reasoning-effort": { type: "string" },
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
async function turnBody(values, allowModel = false) {
|
|
472
|
+
const hasContent = values.attach?.length || values["context-references"] || values["conversation-references"];
|
|
473
|
+
const body = { message: !values.message && !values.input && hasContent ? "" : await readMessage(values) };
|
|
474
|
+
if (allowModel && values["model-entry-id"]) body.modelEntryId = values["model-entry-id"];
|
|
475
|
+
if (values["reasoning-effort"] !== undefined) {
|
|
476
|
+
const effort = values["reasoning-effort"];
|
|
477
|
+
if (effort !== "null" && !REASONING_EFFORTS.has(effort)) throw new Error("--reasoning-effort 不合法;使用模型默认值时传 null");
|
|
478
|
+
body.reasoningEffort = effort === "null" ? null : effort;
|
|
479
|
+
}
|
|
480
|
+
for (const [option, key] of [["context-references", "contextReferences"], ["conversation-references", "conversationReferences"]]) {
|
|
481
|
+
if (!values[option]) continue;
|
|
482
|
+
body[key] = await readJsonFile(values[option]);
|
|
483
|
+
if (!Array.isArray(body[key])) throw new Error(`--${option} 文件必须是数组`);
|
|
484
|
+
}
|
|
485
|
+
if (!values.attach?.length) return body;
|
|
486
|
+
const form = await uploadForm(values.attach, "attachments");
|
|
487
|
+
for (const [key, value] of Object.entries(body)) {
|
|
488
|
+
form.append(key, value === null ? "" : typeof value === "string" ? value : JSON.stringify(value));
|
|
489
|
+
}
|
|
490
|
+
return form;
|
|
491
|
+
}
|
|
492
|
+
|
|
316
493
|
async function uploadForm(files, field = "file") {
|
|
317
494
|
const form = new FormData();
|
|
318
495
|
for (const file of files) {
|
|
@@ -328,13 +505,13 @@ function positiveSeconds(value, name = "timeout") {
|
|
|
328
505
|
return seconds;
|
|
329
506
|
}
|
|
330
507
|
|
|
331
|
-
async function poll(fetchValue, isTerminal, timeoutSeconds, onValue) {
|
|
332
|
-
const deadline = Date.now() + timeoutSeconds * 1000;
|
|
508
|
+
async function poll(fetchValue, isTerminal, timeoutSeconds, onValue, existingDeadline) {
|
|
509
|
+
const deadline = existingDeadline ?? Date.now() + timeoutSeconds * 1000;
|
|
333
510
|
while (Date.now() < deadline) {
|
|
334
511
|
const value = await fetchValue(deadline);
|
|
335
512
|
await onValue?.(value);
|
|
336
513
|
if (isTerminal(value)) return value;
|
|
337
|
-
await new Promise((resolveWait) => setTimeout(resolveWait, 2_000));
|
|
514
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, Math.min(2_000, Math.max(0, deadline - Date.now()))));
|
|
338
515
|
}
|
|
339
516
|
throw new Error(`等待运行完成超时(${timeoutSeconds} 秒)`);
|
|
340
517
|
}
|
|
@@ -411,7 +588,7 @@ function followProgress(view, runId, seen) {
|
|
|
411
588
|
}
|
|
412
589
|
}
|
|
413
590
|
|
|
414
|
-
async function waitForRun(agentId, sessionId, runId, values) {
|
|
591
|
+
async function waitForRun(agentId, sessionId, runId, values, existingDeadline) {
|
|
415
592
|
process.stderr.write(`[decidex] started session=${sessionId} run=${runId}\n`);
|
|
416
593
|
let lastStatus;
|
|
417
594
|
let lastHeartbeatAt = 0;
|
|
@@ -435,6 +612,7 @@ async function waitForRun(agentId, sessionId, runId, values) {
|
|
|
435
612
|
followProgress(await request(`${sessionPath(agentId, sessionId)}/view`, { deadline: runDeadline, values }), runId, seen);
|
|
436
613
|
}
|
|
437
614
|
: undefined,
|
|
615
|
+
existingDeadline,
|
|
438
616
|
);
|
|
439
617
|
const view = await request(`${sessionPath(agentId, sessionId)}/view`, { deadline: runDeadline, values });
|
|
440
618
|
return finalRunResult(sessionId, runId, finished, view);
|
|
@@ -444,8 +622,8 @@ async function waitForRun(agentId, sessionId, runId, values) {
|
|
|
444
622
|
}
|
|
445
623
|
}
|
|
446
624
|
|
|
447
|
-
async function resolveSession(sessionId, values) {
|
|
448
|
-
const result = await request(`/api/agent-sessions?sessionId=${encodeURIComponent(sessionId)}`, { values });
|
|
625
|
+
async function resolveSession(sessionId, values, deadline) {
|
|
626
|
+
const result = await request(`/api/agent-sessions?sessionId=${encodeURIComponent(sessionId)}`, { values, deadline });
|
|
449
627
|
const session = (result.sessions ?? []).find((item) => item.id === sessionId);
|
|
450
628
|
if (!session?.agentId) throw new Error(`会话不存在或无权访问:${sessionId}`);
|
|
451
629
|
return session;
|
|
@@ -456,12 +634,19 @@ async function listSessionArtifacts(agentId, sessionId, values) {
|
|
|
456
634
|
return (result.files ?? []).filter((file) => file.relativePath?.startsWith("artifacts/"));
|
|
457
635
|
}
|
|
458
636
|
|
|
459
|
-
async function
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
637
|
+
async function listSessionFiles(agentId, sessionId, values) {
|
|
638
|
+
if (values.scope && values.scope !== "analysis") throw new Error("--scope 只支持 analysis");
|
|
639
|
+
const query = new URLSearchParams({ force: "1" });
|
|
640
|
+
if (values.scope) query.set("scope", values.scope);
|
|
641
|
+
const suffix = values.suffix
|
|
642
|
+
? values.suffix.startsWith(".")
|
|
643
|
+
? values.suffix.toLowerCase()
|
|
644
|
+
: `.${values.suffix.toLowerCase()}`
|
|
645
|
+
: null;
|
|
646
|
+
if (suffix && !/^\.[a-z0-9][a-z0-9._-]{0,63}$/.test(suffix)) throw new Error("suffix 不是合法的文件后缀");
|
|
647
|
+
const result = await request(`${sessionPath(agentId, sessionId)}/files?${query}`, { values });
|
|
648
|
+
const files = result.files ?? [];
|
|
649
|
+
return suffix ? files.filter((file) => file.relativePath?.toLowerCase().endsWith(suffix)) : files;
|
|
465
650
|
}
|
|
466
651
|
|
|
467
652
|
function safeRelativeDestination(root, outputPath) {
|
|
@@ -511,11 +696,12 @@ async function writeArtifact(root, destination, bytes, overwrite) {
|
|
|
511
696
|
}
|
|
512
697
|
}
|
|
513
698
|
|
|
514
|
-
async function readStdin(label = "内容") {
|
|
699
|
+
async function readStdin(label = "内容", trim = true) {
|
|
515
700
|
if (process.stdin.isTTY) throw new Error(`请通过 stdin 传入${label}`);
|
|
516
701
|
const chunks = [];
|
|
517
702
|
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
518
|
-
|
|
703
|
+
const value = Buffer.concat(chunks).toString("utf8");
|
|
704
|
+
return trim ? value.trim() : value;
|
|
519
705
|
}
|
|
520
706
|
|
|
521
707
|
function sessionFromText(text) {
|
|
@@ -648,6 +834,48 @@ async function browserLogin(baseUrl, timeoutSeconds) {
|
|
|
648
834
|
}
|
|
649
835
|
}
|
|
650
836
|
|
|
837
|
+
let targetVersionPromise;
|
|
838
|
+
|
|
839
|
+
async function targetVersion(values, deadline = Date.now() + 10_000) {
|
|
840
|
+
targetVersionPromise ??= request("/api/app-version", { values, deadline: Math.min(deadline, Date.now() + 10_000) }).then((result) => {
|
|
841
|
+
if (!result || typeof result.version !== "string" || !result.version.trim()) throw new Error("服务端未返回有效版本号,无法检查兼容性");
|
|
842
|
+
return { version: result.version, commit: result.commit ?? null };
|
|
843
|
+
});
|
|
844
|
+
return targetVersionPromise;
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
async function commandCompatibility(command, values) {
|
|
848
|
+
const server = await targetVersion(values);
|
|
849
|
+
const result = resolveCommandCompatibility(command, server.version);
|
|
850
|
+
if (result.supported === false) throw new Error(`decidex ${command} 需要服务端 >= ${result.minVersion};目标版本为 ${server.version},该版本不支持此命令`);
|
|
851
|
+
return result;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
async function readIdentity(command, values) {
|
|
855
|
+
const compatibility = await commandCompatibility(command, values);
|
|
856
|
+
if (compatibility.protocol === "agent-list") {
|
|
857
|
+
const result = await request("/api/personal-agents", { values });
|
|
858
|
+
return { userId: null, organizationId: null, organizationIdVerified: false, agentCount: result.agents?.length ?? null, legacy: true };
|
|
859
|
+
}
|
|
860
|
+
return { ...(await request("/api/auth/context", { values })), organizationIdVerified: true, legacy: false };
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
async function serverCommand(action, args) {
|
|
864
|
+
const { values, positionals } = commandArgs(args);
|
|
865
|
+
if (!["version", "check"].includes(action)) throw new Error(`未知 server 命令:${action || "(空)"}`);
|
|
866
|
+
if (action === "version") expectPositionals(positionals, 0, "server version");
|
|
867
|
+
const server = await targetVersion(values);
|
|
868
|
+
if (action === "version") {
|
|
869
|
+
let comparable = true;
|
|
870
|
+
try { compareVersions(server.version, ADAPTED_SERVER_VERSION); } catch { comparable = false; }
|
|
871
|
+
return print({ schemaVersion: 1, ...server, comparable, adaptedVersion: ADAPTED_SERVER_VERSION, adaptedCommit: ADAPTED_SERVER_COMMIT });
|
|
872
|
+
}
|
|
873
|
+
const commands = positionals.length ? [positionals.join(" ")] : Object.keys(COMMAND_COMPATIBILITY);
|
|
874
|
+
const checks = commands.map((command) => resolveCommandCompatibility(command, server.version));
|
|
875
|
+
print({ schemaVersion: 1, server, adaptedVersion: ADAPTED_SERVER_VERSION, checks });
|
|
876
|
+
if (checks.some((check) => check.supported === false)) process.exitCode = 1;
|
|
877
|
+
}
|
|
878
|
+
|
|
651
879
|
async function authCommand(action, args) {
|
|
652
880
|
if (action === "login") {
|
|
653
881
|
const { values } = commandArgs(args, { timeout: { type: "string", default: "300" } });
|
|
@@ -656,8 +884,8 @@ async function authCommand(action, args) {
|
|
|
656
884
|
process.stderr.write("请在打开的 Chrome 窗口完成 Decidex 登录…\n");
|
|
657
885
|
const session = await browserLogin(baseUrl, timeout);
|
|
658
886
|
await saveConfig({ baseUrl, session, organizationId: null, recentRuns: [] });
|
|
659
|
-
const result = await
|
|
660
|
-
print({ authenticated: true, baseUrl,
|
|
887
|
+
const result = await readIdentity("auth login", { "base-url": baseUrl });
|
|
888
|
+
print({ authenticated: true, baseUrl, ...result });
|
|
661
889
|
return;
|
|
662
890
|
}
|
|
663
891
|
if (action === "import") {
|
|
@@ -668,17 +896,12 @@ async function authCommand(action, args) {
|
|
|
668
896
|
print({ ok: true, baseUrl });
|
|
669
897
|
return;
|
|
670
898
|
}
|
|
671
|
-
if (action === "status") {
|
|
672
|
-
const { values } = commandArgs(args);
|
|
899
|
+
if (action === "status" || action === "whoami") {
|
|
900
|
+
const { values, positionals } = commandArgs(args);
|
|
901
|
+
expectPositionals(positionals, 0, `auth ${action}`);
|
|
673
902
|
const credentials = await auth(values);
|
|
674
|
-
const result = await
|
|
675
|
-
print({
|
|
676
|
-
authenticated: true,
|
|
677
|
-
baseUrl: credentials.baseUrl,
|
|
678
|
-
organizationId: credentials.organizationId,
|
|
679
|
-
organizationIdVerified: false,
|
|
680
|
-
agentCount: result.agents?.length ?? null,
|
|
681
|
-
});
|
|
903
|
+
const result = await readIdentity(`auth ${action}`, values);
|
|
904
|
+
print({ authenticated: true, baseUrl: credentials.baseUrl, ...result });
|
|
682
905
|
return;
|
|
683
906
|
}
|
|
684
907
|
if (action === "logout") {
|
|
@@ -697,13 +920,18 @@ async function authCommand(action, args) {
|
|
|
697
920
|
throw new Error(`未知 auth 命令:${action || "(空)"}`);
|
|
698
921
|
}
|
|
699
922
|
|
|
700
|
-
async function contextCommand(action) {
|
|
923
|
+
async function contextCommand(action, args) {
|
|
701
924
|
if (action !== "show") throw new Error(`未知 context 命令:${action || "(空)"}`);
|
|
925
|
+
const { values } = commandArgs(args);
|
|
702
926
|
const stored = await readConfig();
|
|
927
|
+
const credentials = await auth(values);
|
|
928
|
+
const compatibility = await commandCompatibility("context show", values);
|
|
929
|
+
const context = compatibility.protocol === "local-context"
|
|
930
|
+
? { userId: null, organizationId: stored.baseUrl === credentials.baseUrl ? stored.organizationId ?? null : null, organizationIdVerified: false, legacy: true }
|
|
931
|
+
: { ...(await request("/api/auth/context", { values })), organizationIdVerified: true, legacy: false };
|
|
703
932
|
print({
|
|
704
|
-
baseUrl:
|
|
705
|
-
|
|
706
|
-
organizationIdVerified: false,
|
|
933
|
+
baseUrl: credentials.baseUrl,
|
|
934
|
+
...context,
|
|
707
935
|
sessionSource: process.env.DECIDEX_SESSION ? "environment" : stored.session ? "config" : null,
|
|
708
936
|
configPath: configPath(),
|
|
709
937
|
});
|
|
@@ -712,6 +940,7 @@ async function contextCommand(action) {
|
|
|
712
940
|
async function orgCommand(action, args) {
|
|
713
941
|
if (action !== "use") throw new Error(`未知 org 命令:${action || "(空)"}`);
|
|
714
942
|
const { values, positionals } = commandArgs(args);
|
|
943
|
+
expectPositionals(positionals, 1, "org use ID");
|
|
715
944
|
const result = await request("/api/auth/active-organization", {
|
|
716
945
|
method: "PATCH",
|
|
717
946
|
body: { organizationId: required(positionals[0], "ID") },
|
|
@@ -723,6 +952,10 @@ async function orgCommand(action, args) {
|
|
|
723
952
|
|
|
724
953
|
async function agentCommand(action, args) {
|
|
725
954
|
const { values, positionals } = commandArgs(args, {
|
|
955
|
+
...TURN_OPTIONS,
|
|
956
|
+
"model-entry-id": { type: "string" },
|
|
957
|
+
cursor: { type: "string" },
|
|
958
|
+
query: { type: "string" },
|
|
726
959
|
email: { type: "string" },
|
|
727
960
|
"user-id": { type: "string" },
|
|
728
961
|
input: { type: "string" },
|
|
@@ -732,7 +965,33 @@ async function agentCommand(action, args) {
|
|
|
732
965
|
follow: { type: "boolean", default: false },
|
|
733
966
|
wait: { type: "boolean", default: false },
|
|
734
967
|
});
|
|
735
|
-
if (action === "list")
|
|
968
|
+
if (action === "list") {
|
|
969
|
+
expectPositionals(positionals, 0, "agent list");
|
|
970
|
+
return print(await request("/api/personal-agents", { values }));
|
|
971
|
+
}
|
|
972
|
+
if (action === "delete" || action === "publications") {
|
|
973
|
+
expectPositionals(positionals, 1, `agent ${action} ID`);
|
|
974
|
+
const id = encodeURIComponent(required(positionals[0], "ID"));
|
|
975
|
+
return print(await request(`/api/personal-agents/${id}${action === "publications" ? "/publications" : ""}`, { method: action === "delete" ? "DELETE" : "GET", values }));
|
|
976
|
+
}
|
|
977
|
+
if (action === "use-scope") {
|
|
978
|
+
expectPositionals(positionals, 2, "agent use-scope ID OWNER|SPECIFIC_USERS|ORGANIZATION");
|
|
979
|
+
if (!["OWNER", "SPECIFIC_USERS", "ORGANIZATION"].includes(positionals[1])) throw new Error("useScope 不合法");
|
|
980
|
+
return print(await request(`/api/personal-agents/${encodeURIComponent(positionals[0])}/use-scope`, { method: "PUT", body: { useScope: positionals[1] }, values }));
|
|
981
|
+
}
|
|
982
|
+
if (action === "knowledge") {
|
|
983
|
+
const [operation, agentId, documentId] = positionals;
|
|
984
|
+
expectPositionals(positionals, operation === "list" ? 2 : 3, "agent knowledge list|add|remove AGENT_ID [DOCUMENT_ID]");
|
|
985
|
+
if (!["list", "add", "remove"].includes(operation)) throw new Error("knowledge 只支持 list、add、remove");
|
|
986
|
+
const query = new URLSearchParams();
|
|
987
|
+
if (values.query) query.set("q", values.query);
|
|
988
|
+
if (values.cursor) query.set("cursor", values.cursor);
|
|
989
|
+
const path = `/api/personal-agents/${encodeURIComponent(agentId)}/knowledge-documents`;
|
|
990
|
+
return print(await request(`${path}${operation === "list" && query.size ? `?${query}` : ""}`, {
|
|
991
|
+
method: { list: "GET", add: "POST", remove: "DELETE" }[operation],
|
|
992
|
+
body: operation === "list" ? undefined : { documentId }, values,
|
|
993
|
+
}));
|
|
994
|
+
}
|
|
736
995
|
if (action === "models") {
|
|
737
996
|
const agentId = encodeURIComponent(required(positionals[0], "AGENT_ID"));
|
|
738
997
|
const result = await request(`/api/personal-agents/${agentId}/sessions`, { values });
|
|
@@ -742,7 +1001,12 @@ async function agentCommand(action, args) {
|
|
|
742
1001
|
if (action === "apply") {
|
|
743
1002
|
expectPositionals(positionals, 1, "agent apply FILE");
|
|
744
1003
|
const spec = await readJsonFile(required(positionals[0], "FILE"));
|
|
1004
|
+
if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new Error("Agent 文件必须是 JSON 对象");
|
|
745
1005
|
const id = spec.id;
|
|
1006
|
+
if (id !== undefined && (typeof id !== "string" || !id.trim())) throw new Error("Agent id 必须是非空字符串");
|
|
1007
|
+
const allowed = new Set(["id", "name", "description", "instructions", "avatarIcon", "avatarColor", "avatarImageDataUrl", "openingMessage", "presetQuestions", "contextReferences", "bizOntologyBindings", "betaFeatures", "actionSuggestionsEnabled", "biExplorationPolicy", "pluginSelection", "useScope", "sessionDefaultModelCatalogEntryId", "sessionDefaultReasoningEffort", ...(id ? ["builtInInstructions"] : [])]);
|
|
1008
|
+
const unknown = Object.keys(spec).filter((key) => !allowed.has(key));
|
|
1009
|
+
if (unknown.length) throw new Error(`Agent 文件包含不支持的字段:${unknown.join(", ")}`);
|
|
746
1010
|
const body = { ...spec };
|
|
747
1011
|
delete body.id;
|
|
748
1012
|
return print(
|
|
@@ -802,10 +1066,11 @@ async function agentCommand(action, args) {
|
|
|
802
1066
|
expectPositionals(positionals, 1, "agent run AGENT_ID");
|
|
803
1067
|
if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
|
|
804
1068
|
const agentId = required(positionals[0], "AGENT_ID");
|
|
805
|
-
const
|
|
1069
|
+
const body = await turnBody(values, true);
|
|
1070
|
+
if (values.wait) positiveSeconds(values.timeout);
|
|
806
1071
|
const started = await request(`/api/personal-agents/${encodeURIComponent(agentId)}/sessions/start`, {
|
|
807
1072
|
method: "POST",
|
|
808
|
-
body
|
|
1073
|
+
body,
|
|
809
1074
|
values,
|
|
810
1075
|
});
|
|
811
1076
|
await rememberRunBestEffort(agentId, started.session.id, started.runId, values);
|
|
@@ -822,6 +1087,12 @@ async function agentCommand(action, args) {
|
|
|
822
1087
|
|
|
823
1088
|
async function sessionCommand(action, args) {
|
|
824
1089
|
const { values, positionals } = commandArgs(args, {
|
|
1090
|
+
...TURN_OPTIONS,
|
|
1091
|
+
"agent-id": { type: "string" },
|
|
1092
|
+
"model-entry-id": { type: "string" },
|
|
1093
|
+
before: { type: "string" },
|
|
1094
|
+
since: { type: "string" },
|
|
1095
|
+
cursor: { type: "string" },
|
|
825
1096
|
all: { type: "boolean", default: false },
|
|
826
1097
|
dir: { type: "string" },
|
|
827
1098
|
follow: { type: "boolean", default: false },
|
|
@@ -830,7 +1101,9 @@ async function sessionCommand(action, args) {
|
|
|
830
1101
|
output: { type: "string" },
|
|
831
1102
|
overwrite: { type: "boolean", default: false },
|
|
832
1103
|
query: { type: "string" },
|
|
1104
|
+
scope: { type: "string" },
|
|
833
1105
|
status: { type: "string", default: "all" },
|
|
1106
|
+
suffix: { type: "string" },
|
|
834
1107
|
timeout: { type: "string", default: "600" },
|
|
835
1108
|
wait: { type: "boolean", default: false },
|
|
836
1109
|
});
|
|
@@ -838,24 +1111,59 @@ async function sessionCommand(action, args) {
|
|
|
838
1111
|
expectPositionals(positionals, 0, "session list");
|
|
839
1112
|
if (!new Set(["all", "running", "completed"]).has(values.status)) throw new Error("--status 只支持 all、running、completed");
|
|
840
1113
|
const query = new URLSearchParams({ status: values.status });
|
|
1114
|
+
if (values.query && (values.cursor || values["agent-id"])) throw new Error("--query 不能和 --cursor 或 --agent-id 同时使用");
|
|
841
1115
|
if (values.query) query.set("q", values.query);
|
|
842
|
-
|
|
1116
|
+
if (values.cursor) query.set("cursor", values.cursor);
|
|
1117
|
+
if (values["agent-id"]) { query.set("groupMode", "agent"); query.set("agentId", values["agent-id"]); }
|
|
1118
|
+
const result = await request(`/api/agent-sessions?${query}`, { values });
|
|
1119
|
+
if (values.status !== "all") result.sessions = (result.sessions ?? []).filter((session) => values.status === "running" ? session.status === "RUNNING" : session.status !== "RUNNING");
|
|
1120
|
+
return print(result);
|
|
1121
|
+
}
|
|
1122
|
+
if (action === "queue") {
|
|
1123
|
+
const [operation, sessionId, draftId] = positionals;
|
|
1124
|
+
if (!["list", "edit", "delete", "continue"].includes(operation)) throw new Error("queue 只支持 list、edit、delete、continue");
|
|
1125
|
+
expectPositionals(positionals, ["edit", "delete"].includes(operation) ? 3 : 2, `session queue ${operation} SESSION_ID [DRAFT_ID]`);
|
|
1126
|
+
const body = operation === "edit" ? { message: await readMessage(values) } : undefined;
|
|
1127
|
+
if (values.follow && (!values.wait || operation !== "continue")) throw new Error("--follow 仅支持 queue continue --wait");
|
|
1128
|
+
if (values.wait && operation !== "continue") throw new Error("--wait 仅支持 queue continue");
|
|
1129
|
+
if (values.wait) positiveSeconds(values.timeout);
|
|
1130
|
+
const session = await resolveSession(sessionId, values);
|
|
1131
|
+
const path = `${sessionPath(session.agentId, sessionId)}/queued-turn-drafts`;
|
|
1132
|
+
const suffix = draftId ? `/${encodeURIComponent(draftId)}` : operation === "continue" ? "/continue" : "";
|
|
1133
|
+
const result = await request(`${path}${suffix}`, { method: { list: "GET", edit: "PATCH", delete: "DELETE", continue: "POST" }[operation], body, values });
|
|
1134
|
+
if (operation !== "continue") return emit(result, values.output);
|
|
1135
|
+
await rememberRunBestEffort(session.agentId, sessionId, result.runId, values);
|
|
1136
|
+
if (!values.wait) return emit(result, values.output);
|
|
1137
|
+
const finished = await waitForRun(session.agentId, sessionId, result.runId, values);
|
|
1138
|
+
await emit(finished, values.output);
|
|
1139
|
+
if (finished.status !== "SUCCEEDED") process.exitCode = 1;
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
if (["rename", "model", "fork"].includes(action)) {
|
|
1143
|
+
expectPositionals(positionals, 2, `session ${action} SESSION_ID ${action === "rename" ? "TITLE" : action === "model" ? "MODEL_ENTRY_ID" : "RUN_ID"}`);
|
|
1144
|
+
const [sessionId, value] = positionals;
|
|
1145
|
+
const session = await resolveSession(sessionId, values);
|
|
1146
|
+
const path = sessionPath(session.agentId, sessionId);
|
|
1147
|
+
return print(await request(action === "model" ? `${path}/model-selection` : action === "fork" ? `${path}/runs/${encodeURIComponent(value)}/fork` : path, {
|
|
1148
|
+
method: { rename: "PATCH", model: "PUT", fork: "POST" }[action],
|
|
1149
|
+
body: action === "rename" ? { title: value } : action === "model" ? { modelEntryId: value } : undefined, values,
|
|
1150
|
+
}));
|
|
843
1151
|
}
|
|
844
|
-
if (action === "
|
|
845
|
-
const [
|
|
846
|
-
expectPositionals(positionals, 2, `session
|
|
1152
|
+
if (action === "files") {
|
|
1153
|
+
const [filesAction, sessionIdValue] = positionals;
|
|
1154
|
+
expectPositionals(positionals, 2, `session files ${filesAction || "COMMAND"} SESSION_ID`);
|
|
847
1155
|
const sessionId = required(sessionIdValue, "SESSION_ID");
|
|
848
1156
|
const session = await resolveSession(sessionId, values);
|
|
849
|
-
const
|
|
850
|
-
if (
|
|
851
|
-
return print({ schemaVersion: 1, sessionId, agentId: session.agentId,
|
|
1157
|
+
const files = await listSessionFiles(session.agentId, sessionId, values);
|
|
1158
|
+
if (filesAction === "list") {
|
|
1159
|
+
return print({ schemaVersion: 1, sessionId, agentId: session.agentId, files });
|
|
852
1160
|
}
|
|
853
|
-
if (
|
|
854
|
-
if (!values.all) throw new Error("
|
|
1161
|
+
if (filesAction === "download") {
|
|
1162
|
+
if (!values.all) throw new Error("files download 需要 --all");
|
|
855
1163
|
const directory = resolve(required(values.dir, "--dir DIR"));
|
|
856
1164
|
await mkdir(directory, { recursive: true });
|
|
857
1165
|
const root = await realpath(directory);
|
|
858
|
-
const targets =
|
|
1166
|
+
const targets = files.map((item) => ({ item, destination: safeRelativeDestination(root, item.relativePath) }));
|
|
859
1167
|
for (const { destination } of targets) await assertSafeArtifactTarget(root, destination, values.overwrite);
|
|
860
1168
|
const downloaded = [];
|
|
861
1169
|
for (const { item, destination } of targets) {
|
|
@@ -868,19 +1176,29 @@ async function sessionCommand(action, args) {
|
|
|
868
1176
|
}
|
|
869
1177
|
return print({ schemaVersion: 1, sessionId, directory, downloaded });
|
|
870
1178
|
}
|
|
871
|
-
throw new Error(`未知 session
|
|
1179
|
+
throw new Error(`未知 session files 命令:${filesAction || "(空)"}`);
|
|
872
1180
|
}
|
|
873
1181
|
if (action !== "artifacts") {
|
|
874
1182
|
expectPositionals(positionals, 1, `session ${action || "COMMAND"} SESSION_ID`);
|
|
875
1183
|
const sessionId = required(positionals[0], "SESSION_ID");
|
|
876
1184
|
const session = await resolveSession(sessionId, values);
|
|
877
|
-
if (action === "
|
|
1185
|
+
if (action === "delete") return print(await request(sessionPath(session.agentId, sessionId), { method: "DELETE", values }));
|
|
1186
|
+
if (action === "view") {
|
|
1187
|
+
if (values.before && values.since) throw new Error("--before 和 --since 不能同时使用");
|
|
1188
|
+
const query = new URLSearchParams();
|
|
1189
|
+
if (values.before) query.set("before", values.before);
|
|
1190
|
+
if (values.since) query.set("since", values.since);
|
|
1191
|
+
return print(await request(`${sessionPath(session.agentId, sessionId)}/view${query.size ? `?${query}` : ""}`, { values }));
|
|
1192
|
+
}
|
|
878
1193
|
if (action === "stop") return print(await request(`${sessionPath(session.agentId, sessionId)}/stop`, { method: "POST", values }));
|
|
879
1194
|
if (action === "send") {
|
|
880
1195
|
if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
|
|
1196
|
+
if (values["model-entry-id"]) throw new Error("续问切换模型请先执行 session model SESSION_ID MODEL_ENTRY_ID");
|
|
1197
|
+
const body = await turnBody(values);
|
|
1198
|
+
if (values.wait) positiveSeconds(values.timeout);
|
|
881
1199
|
const started = await request(`${sessionPath(session.agentId, sessionId)}/chat`, {
|
|
882
1200
|
method: "POST",
|
|
883
|
-
body
|
|
1201
|
+
body,
|
|
884
1202
|
headers: values.wait ? { "x-decidex-queue-if-running": "false" } : undefined,
|
|
885
1203
|
values,
|
|
886
1204
|
});
|
|
@@ -971,10 +1289,43 @@ async function runCommand(action, args) {
|
|
|
971
1289
|
}
|
|
972
1290
|
|
|
973
1291
|
async function skillCommand(action, args) {
|
|
974
|
-
const { values, positionals } = commandArgs(args
|
|
1292
|
+
const { values, positionals } = commandArgs(args, {
|
|
1293
|
+
origin: { type: "string", default: "personal" },
|
|
1294
|
+
fingerprint: { type: "string" },
|
|
1295
|
+
});
|
|
1296
|
+
if (!["personal", "builtin", "all"].includes(values.origin)) throw new Error("--origin 只支持 personal、builtin、all");
|
|
1297
|
+
if (values.origin !== "personal" && !["list", "files"].includes(action)) throw new Error("该操作仅支持 personal Skill");
|
|
1298
|
+
if (action === "files") {
|
|
1299
|
+
const [operation, skillId, path, file] = positionals;
|
|
1300
|
+
if (!["list", "get", "put"].includes(operation)) throw new Error("skill files 只支持 list、get、put");
|
|
1301
|
+
expectPositionals(positionals, { list: 2, get: 3, put: 4 }[operation], `skill files ${operation} ID [PATH] [FILE]`);
|
|
1302
|
+
if (values.origin === "all" || (operation === "put" && values.origin !== "personal")) throw new Error("files 需要指定 personal 或 builtin;仅 personal 可编辑");
|
|
1303
|
+
const base = `/api/skills/${encodeURIComponent(skillId)}/files`;
|
|
1304
|
+
if (operation !== "put") {
|
|
1305
|
+
const query = new URLSearchParams({ origin: values.origin });
|
|
1306
|
+
if (path) query.set("path", path);
|
|
1307
|
+
return print(await request(`${base}?${query}`, { values }));
|
|
1308
|
+
}
|
|
1309
|
+
// A file edit must refer to the snapshot the author read, rather than silently rebasing it.
|
|
1310
|
+
const expectedFingerprint = required(values.fingerprint, "--fingerprint(从 files get 返回值获取)");
|
|
1311
|
+
const content = file === "-" ? await readStdin("Skill 文件", false) : await readFile(resolve(file), "utf8");
|
|
1312
|
+
return print(await request(base, { method: "PUT", body: { path, content, expectedFingerprint }, values }));
|
|
1313
|
+
}
|
|
1314
|
+
if (action === "credentials") {
|
|
1315
|
+
const [operation, skillId, envName] = positionals;
|
|
1316
|
+
if (!["status", "set", "delete"].includes(operation)) throw new Error("credentials 只支持 status、set、delete");
|
|
1317
|
+
expectPositionals(positionals, operation === "status" ? 2 : 3, `skill credentials ${operation} ID [ENV_NAME]`);
|
|
1318
|
+
const body = operation === "status" ? undefined : { envName };
|
|
1319
|
+
if (operation === "set") body.value = await readStdin("凭证值");
|
|
1320
|
+
return print(await request(`/api/skills/${encodeURIComponent(skillId)}/credentials`, { method: { status: "GET", set: "PUT", delete: "DELETE" }[operation], body, values }));
|
|
1321
|
+
}
|
|
1322
|
+
if (action === "references") {
|
|
1323
|
+
expectPositionals(positionals, 1, "skill references ID");
|
|
1324
|
+
return print(await request(`/api/skills/${encodeURIComponent(positionals[0])}/references`, { values }));
|
|
1325
|
+
}
|
|
975
1326
|
if (action === "list") {
|
|
976
1327
|
const result = await request("/api/plugins?kind=skill-only", { values });
|
|
977
|
-
return print({ skills: (result.entries ?? []).filter((entry) => entry.source ===
|
|
1328
|
+
return print({ skills: (result.entries ?? []).filter((entry) => values.origin === "all" || entry.source === values.origin) });
|
|
978
1329
|
}
|
|
979
1330
|
if (action === "upload") {
|
|
980
1331
|
expectPositionals(positionals, 1, "skill upload FILE");
|
|
@@ -985,9 +1336,9 @@ async function skillCommand(action, args) {
|
|
|
985
1336
|
expectPositionals(positionals, 2, "skill update ID FILE");
|
|
986
1337
|
const skillId = encodeURIComponent(required(positionals[0], "ID"));
|
|
987
1338
|
const form = await uploadForm([required(positionals[1], "FILE")]);
|
|
988
|
-
const
|
|
989
|
-
if (!
|
|
990
|
-
form.append("expectedFingerprint",
|
|
1339
|
+
const fingerprint = values.fingerprint || (await request(`/api/skills/${skillId}/files?origin=personal`, { values })).fingerprint;
|
|
1340
|
+
if (!fingerprint) throw new Error("服务端未返回 Skill fingerprint");
|
|
1341
|
+
form.append("expectedFingerprint", fingerprint);
|
|
991
1342
|
return print(await request(`/api/skills/${skillId}`, { method: "PUT", body: form, values }));
|
|
992
1343
|
}
|
|
993
1344
|
if (action === "download") {
|
|
@@ -1007,10 +1358,29 @@ function evaluationCasesFromFile(value) {
|
|
|
1007
1358
|
const cases = Array.isArray(value) ? value : value?.cases;
|
|
1008
1359
|
if (!Array.isArray(cases)) throw new Error("评测文件必须是数组或包含 cases 数组");
|
|
1009
1360
|
const normalized = cases.map((item, index) => {
|
|
1010
|
-
|
|
1011
|
-
|
|
1361
|
+
const label = `第 ${index + 1} 条评测案例`;
|
|
1362
|
+
if (item?.rubric !== undefined) throw new Error(`${label} 的 rubric 已过期,请改为 criteria: [{ text, weight, veto }]`);
|
|
1363
|
+
if (!item || typeof item.task !== "string" || !item.task.trim() || item.task.length > 5000) {
|
|
1364
|
+
throw new Error(`${label} 必须包含非空 task,且不超过 5000 个字符`);
|
|
1012
1365
|
}
|
|
1013
|
-
|
|
1366
|
+
if (!Array.isArray(item.criteria) || !item.criteria.length || item.criteria.length > 50) throw new Error(`${label} 需要 1–50 条 criteria`);
|
|
1367
|
+
const criteria = item.criteria.map((criterion) => {
|
|
1368
|
+
if (!criterion || Object.keys(criterion).some((key) => !["id", "text", "weight", "veto"].includes(key))) throw new Error(`${label} 的 criteria 字段不合法`);
|
|
1369
|
+
const { id, text, weight = 1, veto = false } = criterion;
|
|
1370
|
+
if (typeof text !== "string" || !text.trim() || text.length > 2000 || !Number.isSafeInteger(weight) || weight <= 0 || typeof veto !== "boolean") {
|
|
1371
|
+
throw new Error(`${label} 的 criteria 需要非空 text(最多 2000 字符)、正整数 weight 和布尔 veto`);
|
|
1372
|
+
}
|
|
1373
|
+
if (id !== undefined && (typeof id !== "string" || !id.trim() || id.trim().length > 100)) throw new Error(`${label} 的 criterion id 不合法`);
|
|
1374
|
+
return { ...(id === undefined ? {} : { id: id.trim() }), text, weight, veto };
|
|
1375
|
+
});
|
|
1376
|
+
const ids = criteria.filter((c) => c.id).map((c) => c.id);
|
|
1377
|
+
if (new Set(ids).size !== ids.length || !Number.isSafeInteger(criteria.reduce((sum, c) => sum + c.weight, 0))) throw new Error(`${label} 的评分 ID 重复或权重总和超限`);
|
|
1378
|
+
const tagIds = item.tagIds;
|
|
1379
|
+
if (tagIds !== undefined && (!Array.isArray(tagIds) || tagIds.some((id) => typeof id !== "string" || !id.trim()) || new Set(tagIds.map((id) => id.trim())).size !== tagIds.length)) {
|
|
1380
|
+
throw new Error(`${label} 的 tagIds 必须是不重复的非空字符串数组`);
|
|
1381
|
+
}
|
|
1382
|
+
// task/text whitespace is meaningful to the server; preserve it for export/apply round trips.
|
|
1383
|
+
return { task: item.task, criteria, ...(tagIds === undefined ? {} : { tagIds: tagIds.map((id) => id.trim()) }) };
|
|
1014
1384
|
});
|
|
1015
1385
|
const seen = new Set();
|
|
1016
1386
|
for (const item of normalized) {
|
|
@@ -1026,13 +1396,37 @@ function evaluationCasesPlan(current, desired, prune) {
|
|
|
1026
1396
|
if (currentByTask.has(item.task)) throw new Error(`线上评测集包含重复 task:${item.task}`);
|
|
1027
1397
|
currentByTask.set(item.task, item);
|
|
1028
1398
|
}
|
|
1029
|
-
const
|
|
1030
|
-
const
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1399
|
+
const create = [], update = [], keep = [];
|
|
1400
|
+
for (const item of desired) {
|
|
1401
|
+
const existing = currentByTask.get(item.task);
|
|
1402
|
+
for (const criterion of item.criteria) {
|
|
1403
|
+
if (criterion.id && !existing?.criteria.some((c) => c.id === criterion.id)) throw new Error(`案例「${item.task}」含未知评分条目 ID;新增条目请省略 ID`);
|
|
1404
|
+
}
|
|
1405
|
+
if (!existing) {
|
|
1406
|
+
create.push(item);
|
|
1407
|
+
continue;
|
|
1408
|
+
}
|
|
1409
|
+
const sameCriteria = existing.criteria.length === item.criteria.length && item.criteria.every((c, i) => {
|
|
1410
|
+
const old = existing.criteria[i];
|
|
1411
|
+
return (!c.id || c.id === old.id) && c.text === old.text && c.weight === old.weight && c.veto === old.veto;
|
|
1412
|
+
});
|
|
1413
|
+
const sameTags = item.tagIds === undefined || JSON.stringify([...item.tagIds].sort()) === JSON.stringify([...(existing.tagIds ?? [])].sort());
|
|
1414
|
+
if (sameCriteria && sameTags) keep.push(item);
|
|
1415
|
+
else {
|
|
1416
|
+
// Preserve stable criterion IDs for unchanged text, including weight/tag-only edits.
|
|
1417
|
+
const used = new Set(item.criteria.flatMap((c) => c.id ? [c.id] : []));
|
|
1418
|
+
const criteria = item.criteria.map((c) => {
|
|
1419
|
+
if (c.id) return c;
|
|
1420
|
+
const match = existing.criteria.find((old) => old.text === c.text && !used.has(old.id));
|
|
1421
|
+
if (!match) return c;
|
|
1422
|
+
used.add(match.id);
|
|
1423
|
+
return { id: match.id, ...c };
|
|
1424
|
+
});
|
|
1425
|
+
update.push({ id: existing.id, ...item, criteria });
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
const desiredTasks = new Set(desired.map((item) => item.task));
|
|
1429
|
+
const extra = current.filter((item) => !desiredTasks.has(item.task));
|
|
1036
1430
|
return { create, update, keep, delete: prune ? extra : [], unmanaged: prune ? [] : extra };
|
|
1037
1431
|
}
|
|
1038
1432
|
|
|
@@ -1056,7 +1450,7 @@ async function evalCasesCommand(args) {
|
|
|
1056
1450
|
const current = await fetchEvaluationCases(id, values);
|
|
1057
1451
|
if (action === "list") return print({ cases: current });
|
|
1058
1452
|
if (action === "export") {
|
|
1059
|
-
return emit({ cases: current.map(({ task,
|
|
1453
|
+
return emit({ cases: current.map(({ task, criteria, tagIds }) => ({ task, criteria: criteria.map(({ text, weight, veto }) => ({ text, weight, veto })), tagIds })) }, required(file, "FILE"));
|
|
1060
1454
|
}
|
|
1061
1455
|
if (action !== "plan" && action !== "apply") throw new Error(`未知 eval cases 命令:${action || "(空)"}`);
|
|
1062
1456
|
const desired = evaluationCasesFromFile(await readJsonFile(required(file, "FILE")));
|
|
@@ -1065,8 +1459,8 @@ async function evalCasesCommand(args) {
|
|
|
1065
1459
|
|
|
1066
1460
|
const base = `/api/personal-agents/${encodeURIComponent(id)}/evaluation-cases`;
|
|
1067
1461
|
for (const item of plan.create) await request(base, { method: "POST", body: item, values });
|
|
1068
|
-
for (const { id: caseId,
|
|
1069
|
-
await request(`${base}/${encodeURIComponent(caseId)}`, { method: "PUT", body
|
|
1462
|
+
for (const { id: caseId, ...body } of plan.update) {
|
|
1463
|
+
await request(`${base}/${encodeURIComponent(caseId)}`, { method: "PUT", body, values });
|
|
1070
1464
|
}
|
|
1071
1465
|
for (const item of plan.delete) await request(`${base}/${encodeURIComponent(item.id)}`, { method: "DELETE", values });
|
|
1072
1466
|
|
|
@@ -1080,8 +1474,8 @@ function evaluationRunSpec(value) {
|
|
|
1080
1474
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("评测运行文件必须是 JSON 对象");
|
|
1081
1475
|
const allowed = new Set(["caseIds", "targetModelSelection", "judgeModelSelection"]);
|
|
1082
1476
|
const unknown = Object.keys(value).filter((key) => !allowed.has(key));
|
|
1083
|
-
if (unknown.length) throw new Error(
|
|
1084
|
-
const efforts =
|
|
1477
|
+
if (unknown.length) throw new Error(`评测运行文件包含服务端 0.0.5 契约不支持的字段:${unknown.join(", ")}`);
|
|
1478
|
+
const efforts = REASONING_EFFORTS;
|
|
1085
1479
|
for (const field of ["targetModelSelection", "judgeModelSelection"]) {
|
|
1086
1480
|
const selection = value[field];
|
|
1087
1481
|
if (!selection || typeof selection !== "object" || Array.isArray(selection)) throw new Error(`${field} 必须是对象`);
|
|
@@ -1208,30 +1602,32 @@ async function evalRunsCommand(args) {
|
|
|
1208
1602
|
throw new Error(`未知 eval runs 命令:${action || "(空)"}`);
|
|
1209
1603
|
}
|
|
1210
1604
|
|
|
1211
|
-
async function
|
|
1605
|
+
async function evalFilesCommand(args) {
|
|
1212
1606
|
const { values, positionals } = commandArgs(args, {
|
|
1213
1607
|
all: { type: "boolean", default: false },
|
|
1214
1608
|
dir: { type: "string" },
|
|
1215
1609
|
overwrite: { type: "boolean", default: false },
|
|
1610
|
+
scope: { type: "string" },
|
|
1611
|
+
suffix: { type: "string" },
|
|
1216
1612
|
});
|
|
1217
1613
|
const [action, agentId, runId] = positionals;
|
|
1218
|
-
if (action !== "download") throw new Error(`未知 eval
|
|
1219
|
-
expectPositionals(positionals, 3, "eval
|
|
1220
|
-
if (!values.all) throw new Error("eval
|
|
1614
|
+
if (action !== "download") throw new Error(`未知 eval files 命令:${action || "(空)"}`);
|
|
1615
|
+
expectPositionals(positionals, 3, "eval files download AGENT_ID RUN_ID");
|
|
1616
|
+
if (!values.all) throw new Error("eval files download 需要 --all");
|
|
1221
1617
|
const result = await request(evaluationRunPath(agentId, runId), { values });
|
|
1222
1618
|
const runCases = result.run?.cases ?? [];
|
|
1223
1619
|
if (runCases.some((runCase) => !Object.hasOwn(runCase, "targetSessionId"))) {
|
|
1224
1620
|
throw new Error("Decidex 服务端未返回评测 Case 的 targetSessionId;请先升级服务端");
|
|
1225
1621
|
}
|
|
1226
|
-
const
|
|
1622
|
+
const files = (await Promise.all(runCases.map(async (runCase, index) => {
|
|
1227
1623
|
if (!runCase.targetSessionId) return [];
|
|
1228
|
-
const
|
|
1229
|
-
return
|
|
1624
|
+
const selected = await listSessionFiles(agentId, runCase.targetSessionId, values);
|
|
1625
|
+
return selected.map((file) => ({ ...file, caseId: runCase.id, casePosition: runCase.position, sessionId: runCase.targetSessionId, outputDirectory: `case-${index + 1}` }));
|
|
1230
1626
|
}))).flat();
|
|
1231
1627
|
const directory = resolve(required(values.dir, "--dir DIR"));
|
|
1232
1628
|
await mkdir(directory, { recursive: true });
|
|
1233
1629
|
const root = await realpath(directory);
|
|
1234
|
-
const targets =
|
|
1630
|
+
const targets = files.map((item) => ({ item, destination: safeRelativeDestination(root, join(item.outputDirectory, item.relativePath)) }));
|
|
1235
1631
|
for (const { destination } of targets) await assertSafeArtifactTarget(root, destination, values.overwrite);
|
|
1236
1632
|
const downloaded = [];
|
|
1237
1633
|
for (const { item, destination } of targets) {
|
|
@@ -1245,10 +1641,21 @@ async function evalEvidenceCommand(args) {
|
|
|
1245
1641
|
return print({ schemaVersion: 1, agentId, runId, directory, downloaded });
|
|
1246
1642
|
}
|
|
1247
1643
|
|
|
1644
|
+
async function evalTagsCommand(args) {
|
|
1645
|
+
const { values, positionals } = commandArgs(args);
|
|
1646
|
+
const [operation, agentId, tagId, name] = positionals;
|
|
1647
|
+
if (!["list", "create", "rename", "delete"].includes(operation)) throw new Error("eval tags 只支持 list、create、rename、delete");
|
|
1648
|
+
expectPositionals(positionals, { list: 2, create: 3, rename: 4, delete: 3 }[operation], `eval tags ${operation} AGENT_ID [TAG_ID] [NAME]`);
|
|
1649
|
+
const base = `/api/personal-agents/${encodeURIComponent(agentId)}/evaluation-case-tags`;
|
|
1650
|
+
const path = ["rename", "delete"].includes(operation) ? `${base}/${encodeURIComponent(tagId)}` : base;
|
|
1651
|
+
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 }));
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1248
1654
|
async function evalCommand(action, args) {
|
|
1249
1655
|
if (action === "cases") return evalCasesCommand(args);
|
|
1656
|
+
if (action === "tags") return evalTagsCommand(args);
|
|
1250
1657
|
if (action === "runs") return evalRunsCommand(args);
|
|
1251
|
-
if (action === "
|
|
1658
|
+
if (action === "files") return evalFilesCommand(args);
|
|
1252
1659
|
const { values, positionals } = commandArgs(args, {
|
|
1253
1660
|
cases: { type: "string" },
|
|
1254
1661
|
follow: { type: "boolean", default: false },
|
|
@@ -1264,7 +1671,10 @@ async function evalCommand(action, args) {
|
|
|
1264
1671
|
}
|
|
1265
1672
|
if (action !== "run") throw new Error(`未知 eval 命令:${action || "(空)"}`);
|
|
1266
1673
|
expectPositionals(positionals, 2, "eval run AGENT_ID FILE");
|
|
1674
|
+
if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
|
|
1675
|
+
if (values.wait) positiveSeconds(values.timeout);
|
|
1267
1676
|
const body = await readJsonFile(required(positionals[1], "FILE"));
|
|
1677
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("评测运行文件必须是 JSON 对象");
|
|
1268
1678
|
if (values.cases) {
|
|
1269
1679
|
if (values.cases !== "all") throw new Error("--cases 当前只支持 all");
|
|
1270
1680
|
body.caseIds = (await fetchEvaluationCases(positionals[0], values)).map((item) => item.id);
|
|
@@ -1281,10 +1691,18 @@ async function ontologyCommand(action, args) {
|
|
|
1281
1691
|
const { values, positionals } = commandArgs(args, {
|
|
1282
1692
|
"network-id": { type: "string" },
|
|
1283
1693
|
"version-id": { type: "string" },
|
|
1694
|
+
description: { type: "string" },
|
|
1284
1695
|
name: { type: "string" },
|
|
1285
1696
|
});
|
|
1286
1697
|
if (action === "list") return print(await request("/api/biz-ontology/networks", { values }));
|
|
1287
1698
|
if (action === "get") return print(await request(`/api/biz-ontology/networks/${encodeURIComponent(required(positionals[0], "ID"))}`, { values }));
|
|
1699
|
+
if (action === "versions") {
|
|
1700
|
+
const [operation, networkId, versionId] = positionals;
|
|
1701
|
+
if (!["list", "get", "create"].includes(operation)) throw new Error("ontology versions 只支持 list、get、create");
|
|
1702
|
+
expectPositionals(positionals, operation === "get" ? 3 : 2, `ontology versions ${operation} NETWORK_ID [VERSION_ID]`);
|
|
1703
|
+
const base = `/api/biz-ontology/networks/${encodeURIComponent(networkId)}/versions`;
|
|
1704
|
+
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 }));
|
|
1705
|
+
}
|
|
1288
1706
|
if (action === "export") {
|
|
1289
1707
|
expectPositionals(positionals, 2, "ontology export ID FILE");
|
|
1290
1708
|
const id = required(positionals[0], "ID");
|
|
@@ -1293,6 +1711,7 @@ async function ontologyCommand(action, args) {
|
|
|
1293
1711
|
}
|
|
1294
1712
|
if (action === "plan" || action === "apply") {
|
|
1295
1713
|
expectPositionals(positionals, 1, `ontology ${action} FILE`);
|
|
1714
|
+
if (values.name && values["network-id"]) throw new Error("--name 仅适用于新建本体,不能和 --network-id 同时使用");
|
|
1296
1715
|
const file = await readJsonFile(required(positionals[0], "FILE"));
|
|
1297
1716
|
const path = values["network-id"]
|
|
1298
1717
|
? `/api/biz-ontology/networks/${encodeURIComponent(values["network-id"])}/import`
|
|
@@ -1304,6 +1723,272 @@ async function ontologyCommand(action, args) {
|
|
|
1304
1723
|
throw new Error(`未知 ontology 命令:${action || "(空)"}`);
|
|
1305
1724
|
}
|
|
1306
1725
|
|
|
1726
|
+
async function automationCommand(action, args) {
|
|
1727
|
+
const { values, positionals } = commandArgs(args, {
|
|
1728
|
+
cursor: { type: "string" },
|
|
1729
|
+
output: { type: "string" },
|
|
1730
|
+
follow: { type: "boolean", default: false },
|
|
1731
|
+
wait: { type: "boolean", default: false },
|
|
1732
|
+
timeout: { type: "string", default: "600" },
|
|
1733
|
+
});
|
|
1734
|
+
const base = "/api/personal-agent-automations";
|
|
1735
|
+
if (action === "list") {
|
|
1736
|
+
expectPositionals(positionals, 0, "automation list");
|
|
1737
|
+
return print(await request(base, { values }));
|
|
1738
|
+
}
|
|
1739
|
+
if (action === "apply") {
|
|
1740
|
+
expectPositionals(positionals, 1, "automation apply FILE");
|
|
1741
|
+
const spec = await readJsonFile(positionals[0]);
|
|
1742
|
+
if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new Error("定时任务文件必须是 JSON 对象");
|
|
1743
|
+
const { id, ...body } = spec;
|
|
1744
|
+
const allowed = new Set(["name", "instructions", "personalAgentId", "schedule", "imPush", "emailPush", ...(id ? ["status"] : ["source"])]);
|
|
1745
|
+
const unknown = Object.keys(body).filter((key) => !allowed.has(key));
|
|
1746
|
+
if (unknown.length) throw new Error(`定时任务文件包含不支持的字段:${unknown.join(", ")}`);
|
|
1747
|
+
if (body.schedule !== undefined) {
|
|
1748
|
+
const compatibility = await commandCompatibility("automation apply", values);
|
|
1749
|
+
body.schedule = adaptAutomationSchedule(body.schedule, compatibility.protocol);
|
|
1750
|
+
}
|
|
1751
|
+
if (body.status !== undefined && !["ACTIVE", "PAUSED"].includes(body.status)) throw new Error("status 只能手动设置 ACTIVE 或 PAUSED;FINISHED 由服务端单次调度写入");
|
|
1752
|
+
if (id !== undefined && (typeof id !== "string" || !id.trim())) throw new Error("定时任务 id 必须是非空字符串");
|
|
1753
|
+
return print(await request(id ? `${base}/${encodeURIComponent(id)}` : base, { method: id ? "PATCH" : "POST", body, values }));
|
|
1754
|
+
}
|
|
1755
|
+
if (!["delete", "run", "runs"].includes(action)) throw new Error(`未知 automation 命令:${action || "(空)"}`);
|
|
1756
|
+
expectPositionals(positionals, 1, `automation ${action} ID`);
|
|
1757
|
+
const path = `${base}/${encodeURIComponent(positionals[0])}`;
|
|
1758
|
+
if (action === "delete") return print(await request(path, { method: "DELETE", values }));
|
|
1759
|
+
if (action === "runs") return print(await request(`${path}/runs${values.cursor ? `?cursor=${encodeURIComponent(values.cursor)}` : ""}`, { values }));
|
|
1760
|
+
if (values.follow && !values.wait) throw new Error("--follow 需要同时指定 --wait");
|
|
1761
|
+
const deadline = values.wait ? Date.now() + positiveSeconds(values.timeout) * 1000 : undefined;
|
|
1762
|
+
let started;
|
|
1763
|
+
try {
|
|
1764
|
+
started = await request(`${path}/run`, { method: "POST", deadline, values });
|
|
1765
|
+
} catch (error) {
|
|
1766
|
+
// The 0.0.5 start endpoint can keep running after the client disconnects.
|
|
1767
|
+
if (!error.httpStatus || error.httpStatus >= 500) {
|
|
1768
|
+
error.message += `;任务可能仍在服务端执行,请运行 decidex automation runs ${positionals[0]} 查看,勿直接重试触发`;
|
|
1769
|
+
}
|
|
1770
|
+
throw error;
|
|
1771
|
+
}
|
|
1772
|
+
await rememberRunBestEffort(started.personalAgentId, started.sessionId, started.runId, values);
|
|
1773
|
+
if (!values.wait) return emit(started, values.output);
|
|
1774
|
+
const finished = await waitForRun(started.personalAgentId, started.sessionId, started.runId, values, deadline);
|
|
1775
|
+
await emit(finished, values.output);
|
|
1776
|
+
if (finished.status !== "SUCCEEDED") process.exitCode = 1;
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
async function checkApiOperation(operation, values, deadline) {
|
|
1780
|
+
const server = await targetVersion(values, deadline);
|
|
1781
|
+
if (operation.minVersion && compareVersions(server.version, operation.minVersion) < 0) throw new Error(`${operation.id} 需要服务端 >= ${operation.minVersion},目标为 ${server.version}`);
|
|
1782
|
+
if (!operation.inBaseline && !values["allow-unreleased"]) throw new Error(`${operation.id} 尚不在已适配的 ${apiCatalog.baselineVersion} tag 中;确认目标已部署该接口后才能使用 --allow-unreleased`);
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
async function taskApi(id, parameters, { query = {}, body, output, values, deadline } = {}) {
|
|
1786
|
+
const operation = apiOperation(id);
|
|
1787
|
+
const flags = Object.fromEntries(Object.entries(parameters).map(([key, value]) => [parameterFlag(key), value]));
|
|
1788
|
+
const path = appendQuery(operationPath(operation, flags), query);
|
|
1789
|
+
await checkApiOperation(operation, values, deadline);
|
|
1790
|
+
return request(path, { method: operation.method, body, output, values, deadline });
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
async function actionTaskCommand(action, args) {
|
|
1794
|
+
const { values, positionals } = commandArgs(args, {
|
|
1795
|
+
status: { type: "string", default: "PENDING" }, query: { type: "string" }, page: { type: "string", default: "1" },
|
|
1796
|
+
version: { type: "string" }, note: { type: "string" }, "message-id": { type: "string" },
|
|
1797
|
+
"run-id": { type: "string" }, output: { type: "string" }, timeout: { type: "string", default: "600" },
|
|
1798
|
+
});
|
|
1799
|
+
const deadline = Date.now() + positiveSeconds(values.timeout) * 1000;
|
|
1800
|
+
if (action === "list") {
|
|
1801
|
+
expectPositionals(positionals, 0, "action-task list");
|
|
1802
|
+
if (!["PENDING", "ADOPTED", "COMPLETED", "REJECTED", "CANCELED", "all"].includes(values.status)) throw new Error("--status 不合法");
|
|
1803
|
+
const page = positiveInteger(values.page, "page");
|
|
1804
|
+
if (page > 100000) throw new Error("page 不能超过 100000");
|
|
1805
|
+
return emit(await taskApi("action-tasks.list", {}, { query: { page, status: values.status, q: values.query ?? "" }, values, deadline }), values.output);
|
|
1806
|
+
}
|
|
1807
|
+
if (["suggestions", "members", "create"].includes(action)) {
|
|
1808
|
+
expectPositionals(positionals, action === "create" ? 2 : 1, `action-task ${action} SESSION_ID${action === "create" ? " FILE" : ""}`);
|
|
1809
|
+
let body;
|
|
1810
|
+
if (action === "create") body = await readJsonFile(positionals[1]);
|
|
1811
|
+
if (action === "suggestions" && Boolean(values["message-id"]) === Boolean(values["run-id"])) throw new Error("suggestions 需要且只能指定 --message-id 或 --run-id");
|
|
1812
|
+
const sessionId = positionals[0];
|
|
1813
|
+
const session = await resolveSession(sessionId, values, deadline);
|
|
1814
|
+
let messageId = values["message-id"];
|
|
1815
|
+
if (action === "suggestions" && values["run-id"]) {
|
|
1816
|
+
const view = await request(`${sessionPath(session.agentId, sessionId)}/view`, { values, deadline });
|
|
1817
|
+
messageId = (view.messages ?? []).find((message) => message.role === "ASSISTANT" && message.turn?.id === values["run-id"])?.id;
|
|
1818
|
+
if (!messageId) throw new Error("当前会话窗口没有该 Run 的回答,请用 session view 查找后传 --message-id");
|
|
1819
|
+
}
|
|
1820
|
+
const operation = action === "members" ? "personal-agents.sessions.action-suggestions.members.list" : `personal-agents.sessions.action-suggestions.${action === "create" ? "create" : "list"}`;
|
|
1821
|
+
return emit(await taskApi(operation, { agentId: session.agentId, sessionId }, { query: action === "members" ? { q: values.query ?? "" } : action === "suggestions" ? { messageId } : {}, body, values, deadline }), values.output);
|
|
1822
|
+
}
|
|
1823
|
+
expectPositionals(positionals, 1, `action-task ${action} TASK_ID`);
|
|
1824
|
+
const parameters = { taskId: positionals[0] };
|
|
1825
|
+
if (action === "get") return emit(await taskApi("action-tasks.get", parameters, { values, deadline }), values.output);
|
|
1826
|
+
if (!["adopt", "reject", "complete", "cancel"].includes(action)) throw new Error(`未知 action-task 命令:${action || "(空)"}`);
|
|
1827
|
+
if (values.version === undefined || !/^\d+$/.test(values.version) || !Number.isSafeInteger(Number(values.version))) throw new Error("需要 --version 非负整数;从 action-task get 返回值读取,冲突后不要自动重试");
|
|
1828
|
+
if (["reject", "cancel"].includes(action) && !values.note?.trim()) throw new Error("reject / cancel 需要 --note 理由");
|
|
1829
|
+
return emit(await taskApi("action-tasks.update", parameters, { body: { action, version: Number(values.version), note: values.note ?? "" }, values, deadline }), values.output);
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
async function waitTrackingTask(taskId, values, deadline) {
|
|
1833
|
+
try {
|
|
1834
|
+
const result = await poll(() => taskApi("decision-tracking-tasks.list", {}, { query: { taskId }, values, deadline }), (result) => result.task.status !== "CREATING", positiveSeconds(values.timeout), undefined, deadline);
|
|
1835
|
+
if (!result.task.initialReportPath) process.exitCode = 1;
|
|
1836
|
+
return result;
|
|
1837
|
+
} catch (error) {
|
|
1838
|
+
error.message += `;taskId=${taskId},可运行 decidex tracking wait ${taskId} 继续查询`;
|
|
1839
|
+
throw error;
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
|
|
1843
|
+
async function trackingCommand(action, args) {
|
|
1844
|
+
const { values, positionals } = commandArgs(args, {
|
|
1845
|
+
filter: { type: "string", default: "all" }, page: { type: "string", default: "1" }, cursor: { type: "string" },
|
|
1846
|
+
"candidate-path": { type: "string" }, "boe-path": { type: "string" }, "source-message-id": { type: "string" },
|
|
1847
|
+
"next-review-at": { type: "string" }, language: { type: "string", default: "zh-CN" },
|
|
1848
|
+
data: { type: "string" }, output: { type: "string" }, initial: { type: "boolean", default: false },
|
|
1849
|
+
"review-id": { type: "string" }, wait: { type: "boolean", default: false }, timeout: { type: "string", default: "600" },
|
|
1850
|
+
});
|
|
1851
|
+
const deadline = Date.now() + positiveSeconds(values.timeout) * 1000;
|
|
1852
|
+
if (action === "list") {
|
|
1853
|
+
expectPositionals(positionals, 0, "tracking list");
|
|
1854
|
+
if (!["all", "due"].includes(values.filter)) throw new Error("--filter 只支持 all、due");
|
|
1855
|
+
const page = positiveInteger(values.page, "page");
|
|
1856
|
+
if (page > 100000) throw new Error("page 不能超过 100000");
|
|
1857
|
+
return emit(await taskApi("decision-tracking-tasks.list", {}, { query: { page, filter: values.filter }, values, deadline }), values.output);
|
|
1858
|
+
}
|
|
1859
|
+
if (["preview", "create", "lookup"].includes(action)) {
|
|
1860
|
+
expectPositionals(positionals, 1, `tracking ${action} SESSION_ID --candidate-path PATH --boe-path PATH`);
|
|
1861
|
+
const candidatePath = required(values["candidate-path"], "--candidate-path");
|
|
1862
|
+
const boePath = required(values["boe-path"], "--boe-path");
|
|
1863
|
+
const sessionId = positionals[0];
|
|
1864
|
+
const session = await resolveSession(sessionId, values, deadline);
|
|
1865
|
+
const parameters = { agentId: session.agentId, sessionId };
|
|
1866
|
+
if (action === "lookup") return emit(await taskApi("personal-agents.sessions.decision-tracking-tasks.list", parameters, { query: { candidatePath, boePath }, values, deadline }), values.output);
|
|
1867
|
+
const preview = await taskApi("personal-agents.sessions.decision-tracking-candidate-preview.list", parameters, { query: { candidatePath, boePath, language: values.language }, values, deadline });
|
|
1868
|
+
if (action === "preview") return emit(preview, values.output);
|
|
1869
|
+
if (!preview.candidate || !/^[a-f0-9]{64}$/.test(preview.evidenceVersion ?? "")) throw new Error("服务端未返回有效候选或 evidenceVersion,未创建任务");
|
|
1870
|
+
const body = { candidatePath, boePath, candidate: preview.candidate, evidenceVersion: preview.evidenceVersion };
|
|
1871
|
+
if (values["source-message-id"]) body.sourceMessageId = values["source-message-id"];
|
|
1872
|
+
if (values["next-review-at"]) body.nextReviewAt = values["next-review-at"];
|
|
1873
|
+
const result = await taskApi("personal-agents.sessions.decision-tracking-tasks.create", parameters, { body, values, deadline });
|
|
1874
|
+
return emit(values.wait ? await waitTrackingTask(result.task.id, values, deadline) : result, values.output);
|
|
1875
|
+
}
|
|
1876
|
+
expectPositionals(positionals, ["rename", "schedule", "report"].includes(action) ? 2 : 1, `tracking ${action} TASK_ID${action === "rename" ? " TITLE" : action === "schedule" ? " FILE" : action === "report" ? " FILE" : ""}`);
|
|
1877
|
+
const taskId = positionals[0];
|
|
1878
|
+
const parameters = { taskId };
|
|
1879
|
+
if (action === "wait") return emit(await waitTrackingTask(taskId, values, deadline), values.output);
|
|
1880
|
+
if (action === "get") return emit(await taskApi("decision-tracking-tasks.list", {}, { query: { taskId }, values, deadline }), values.output);
|
|
1881
|
+
if (["pause", "resume", "close"].includes(action)) return emit(await taskApi("decision-tracking-tasks.status.update", parameters, { body: { action }, values, deadline }), values.output);
|
|
1882
|
+
if (action === "rename") return emit(await taskApi("decision-tracking-tasks.title.update", parameters, { body: { title: positionals[1] }, values, deadline }), values.output);
|
|
1883
|
+
if (action === "schedule") return emit(await taskApi("decision-tracking-tasks.update", parameters, { body: await readJsonFile(positionals[1]), values, deadline }), values.output);
|
|
1884
|
+
if (action === "delete") return emit(await taskApi("decision-tracking-tasks.delete", parameters, { values, deadline }), values.output);
|
|
1885
|
+
if (action === "report") {
|
|
1886
|
+
if (values.initial && values["review-id"]) throw new Error("--initial 和 --review-id 不能同用");
|
|
1887
|
+
return print(await taskApi("decision-tracking-tasks.report.list", parameters, { query: { report: values.initial ? "initial" : undefined, reviewId: values["review-id"] }, output: positionals[1], values, deadline }));
|
|
1888
|
+
}
|
|
1889
|
+
if (action === "reviews") return emit(await taskApi("decision-tracking-tasks.reviews.list", parameters, { query: { cursor: values.cursor }, values, deadline }), values.output);
|
|
1890
|
+
if (action === "retry") {
|
|
1891
|
+
const result = await taskApi("decision-tracking-tasks.initial-report.create", parameters, { values, deadline });
|
|
1892
|
+
return emit(values.wait ? await waitTrackingTask(taskId, values, deadline) : result, values.output);
|
|
1893
|
+
}
|
|
1894
|
+
if (action === "review") {
|
|
1895
|
+
const body = values.data ? await readJsonFile(values.data) : {};
|
|
1896
|
+
const result = await taskApi("decision-tracking-tasks.reviews.create", parameters, { body, values, deadline });
|
|
1897
|
+
if (!values.wait) return emit(result, values.output);
|
|
1898
|
+
const reviewId = result.review.reviewId;
|
|
1899
|
+
process.stderr.write(`[decidex] task=${taskId} review=${reviewId}\n`);
|
|
1900
|
+
try {
|
|
1901
|
+
const history = await poll(() => taskApi("decision-tracking-tasks.reviews.list", parameters, { values, deadline }), (history) => history.reviews.some((review) => review.id === reviewId && (review.reportPath || review.exceptionReason)), positiveSeconds(values.timeout), undefined, deadline);
|
|
1902
|
+
const review = history.reviews.find((item) => item.id === reviewId);
|
|
1903
|
+
await emit({ review }, values.output);
|
|
1904
|
+
if (!review.reportPath) process.exitCode = 1;
|
|
1905
|
+
} catch (error) {
|
|
1906
|
+
error.message += `;taskId=${taskId};reviewId=${reviewId},可用 tracking reviews 查询,勿直接重试发起复核`;
|
|
1907
|
+
throw error;
|
|
1908
|
+
}
|
|
1909
|
+
return;
|
|
1910
|
+
}
|
|
1911
|
+
throw new Error(`未知 tracking 命令:${action || "(空)"}`);
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
function keyValue(value, option) {
|
|
1915
|
+
const separator = value.indexOf("=");
|
|
1916
|
+
if (separator <= 0) throw new Error(`${option} 需要 KEY=VALUE`);
|
|
1917
|
+
return [value.slice(0, separator), value.slice(separator + 1)];
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
async function platformCommand(action, args) {
|
|
1921
|
+
if (action === "coverage") {
|
|
1922
|
+
const { positionals } = commandArgs(args);
|
|
1923
|
+
expectPositionals(positionals, 0, "platform coverage");
|
|
1924
|
+
return print({ sourceCommit: apiCatalog.sourceCommit, baselineVersion: apiCatalog.baselineVersion, ...apiCatalog.coverage, definition: "操作目录的调用入口覆盖率,不等同于逐接口业务或真实环境测试覆盖率", excluded: apiCatalog.excluded });
|
|
1925
|
+
}
|
|
1926
|
+
if (action === "list") {
|
|
1927
|
+
const { values, positionals } = commandArgs(args, { query: { type: "string" }, method: { type: "string" }, group: { type: "string" } });
|
|
1928
|
+
expectPositionals(positionals, 0, "platform list");
|
|
1929
|
+
const query = values.query?.toLowerCase() ?? "";
|
|
1930
|
+
return print({ sourceCommit: apiCatalog.sourceCommit, operations: apiCatalog.operations.filter((item) => (!values.method || item.method === values.method.toUpperCase()) && (!values.group || item.group === values.group) && `${item.id} ${item.path}`.toLowerCase().includes(query)) });
|
|
1931
|
+
}
|
|
1932
|
+
if (action === "show") {
|
|
1933
|
+
const { positionals } = commandArgs(args);
|
|
1934
|
+
expectPositionals(positionals, 1, "platform show OPERATION_ID");
|
|
1935
|
+
const operation = apiOperation(positionals[0]);
|
|
1936
|
+
return print({ ...operation, requiredFlags: operation.parameters.map((name) => `--${parameterFlag(name)}`), transport: "--query FILE / --query-param KEY=VALUE; --data JSON_FILE; --file FIELD=FILE / --field KEY=VALUE; --body-file FILE; --output FILE", schemaNote: "inputHints 仅来自路由源码;业务字段与权限由目标服务端校验" });
|
|
1937
|
+
}
|
|
1938
|
+
if (action !== "call") throw new Error("platform 只支持 list、show、call、coverage");
|
|
1939
|
+
const id = required(args[0], "OPERATION_ID");
|
|
1940
|
+
const operation = apiOperation(id);
|
|
1941
|
+
const options = Object.fromEntries(operation.parameters.map((name) => [parameterFlag(name), { type: "string" }]));
|
|
1942
|
+
const { values, positionals } = commandArgs(args.slice(1), {
|
|
1943
|
+
...options,
|
|
1944
|
+
query: { type: "string" }, "query-param": { type: "string", multiple: true },
|
|
1945
|
+
data: { type: "string" }, file: { type: "string", multiple: true }, field: { type: "string", multiple: true },
|
|
1946
|
+
"body-file": { type: "string" }, "content-type": { type: "string" }, output: { type: "string" },
|
|
1947
|
+
"dry-run": { type: "boolean", default: false }, "allow-unreleased": { type: "boolean", default: false },
|
|
1948
|
+
timeout: { type: "string", default: "600" },
|
|
1949
|
+
});
|
|
1950
|
+
expectPositionals(positionals, 0, "platform call OPERATION_ID [FLAGS]");
|
|
1951
|
+
const timeout = positiveSeconds(values.timeout);
|
|
1952
|
+
const deadline = Date.now() + timeout * 1000;
|
|
1953
|
+
const path = operationPath(operation, values);
|
|
1954
|
+
const query = values.query ? await readJsonFile(values.query) : {};
|
|
1955
|
+
appendQuery(path, query);
|
|
1956
|
+
const pairs = values["query-param"] ?? [];
|
|
1957
|
+
for (const pair of pairs) {
|
|
1958
|
+
const [key, value] = keyValue(pair, "--query-param");
|
|
1959
|
+
if (Object.hasOwn(query, key)) query[key] = [...(Array.isArray(query[key]) ? query[key] : [query[key]]), value];
|
|
1960
|
+
else query[key] = value;
|
|
1961
|
+
}
|
|
1962
|
+
const url = appendQuery(path, query);
|
|
1963
|
+
const multipart = Boolean(values.file?.length || values.field?.length);
|
|
1964
|
+
if (values["body-file"] && (values.data || multipart)) throw new Error("--body-file 不能与 --data / --file / --field 同用");
|
|
1965
|
+
if (values["content-type"] && !values["body-file"]) throw new Error("--content-type 仅用于 --body-file;JSON 与 multipart 会自动设置类型");
|
|
1966
|
+
if (["GET", "HEAD"].includes(operation.method) && (values.data || values["body-file"] || multipart)) throw new Error("GET / HEAD 操作不能带请求体");
|
|
1967
|
+
let body;
|
|
1968
|
+
if (values.data) body = await readJsonFile(values.data);
|
|
1969
|
+
if (multipart) {
|
|
1970
|
+
const form = new FormData();
|
|
1971
|
+
if (body !== undefined) {
|
|
1972
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("multipart 的 --data 必须是 JSON 对象");
|
|
1973
|
+
for (const [key, value] of Object.entries(body)) form.append(key, typeof value === "string" ? value : JSON.stringify(value));
|
|
1974
|
+
}
|
|
1975
|
+
for (const value of values.field ?? []) {
|
|
1976
|
+
const [key, content] = keyValue(value, "--field");
|
|
1977
|
+
form.append(key, content);
|
|
1978
|
+
}
|
|
1979
|
+
for (const value of values.file ?? []) {
|
|
1980
|
+
const [key, file] = keyValue(value, "--file");
|
|
1981
|
+
const mime = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", pdf: "application/pdf", txt: "text/plain", md: "text/markdown", zip: "application/zip" }[file.split(".").at(-1)?.toLowerCase()] ?? "application/octet-stream";
|
|
1982
|
+
form.append(key, new Blob([await readFile(resolve(required(file, "FILE")))], { type: mime }), basename(file));
|
|
1983
|
+
}
|
|
1984
|
+
body = form;
|
|
1985
|
+
}
|
|
1986
|
+
if (values["body-file"]) body = await readFile(resolve(values["body-file"]));
|
|
1987
|
+
if (values["dry-run"]) return print({ operation: operation.id, method: operation.method, path: url, inBaseline: operation.inBaseline, minVersion: operation.minVersion, input: multipart ? "multipart" : values["body-file"] ? "binary" : values.data ? "json" : "none", output: values.output ?? null, writesRemote: false });
|
|
1988
|
+
await checkApiOperation(operation, values, deadline);
|
|
1989
|
+
return print(await request(url, { method: operation.method, body, values, deadline, headers: values["content-type"] ? { "content-type": values["content-type"] } : undefined, output: values.output }));
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1307
1992
|
async function apiCommand(args) {
|
|
1308
1993
|
const { values, positionals } = commandArgs(args, {
|
|
1309
1994
|
data: { type: "string" },
|
|
@@ -1325,7 +2010,10 @@ function expectPositionals(positionals, count, usage) {
|
|
|
1325
2010
|
if (positionals.length !== count) throw new Error(`用法:decidex ${usage}`);
|
|
1326
2011
|
}
|
|
1327
2012
|
|
|
1328
|
-
async function versionCommand() {
|
|
2013
|
+
async function versionCommand(args = []) {
|
|
2014
|
+
const { values, positionals } = commandArgs(args, { server: { type: "boolean", default: false } });
|
|
2015
|
+
expectPositionals(positionals, 0, "version [--server]");
|
|
2016
|
+
if (values.server) return serverCommand("version", args.filter((arg) => arg !== "--server"));
|
|
1329
2017
|
const packageJson = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
|
|
1330
2018
|
print({ cliVersion: packageJson.version, protocolVersion: 1, buildCommit: process.env.DECIDEX_CLI_BUILD_COMMIT ?? null });
|
|
1331
2019
|
}
|
|
@@ -1339,6 +2027,15 @@ async function main() {
|
|
|
1339
2027
|
const detail = HELP_BY_COMMAND[`${area} ${action}`] ?? HELP_BY_COMMAND[area];
|
|
1340
2028
|
return print((detail ?? HELP).trimEnd());
|
|
1341
2029
|
}
|
|
2030
|
+
const ruleCommand = Object.keys(COMMAND_COMPATIBILITY)
|
|
2031
|
+
.sort((a, b) => b.split(" ").length - a.split(" ").length)
|
|
2032
|
+
.find((command) => argv.slice(0, command.split(" ").length).join(" ") === command);
|
|
2033
|
+
// login obtains credentials first; other declared rules are checked before dispatch.
|
|
2034
|
+
if (ruleCommand && ruleCommand !== "auth login") {
|
|
2035
|
+
const baseIndex = argv.indexOf("--base-url");
|
|
2036
|
+
const inlineBase = argv.find((arg) => arg.startsWith("--base-url="));
|
|
2037
|
+
await commandCompatibility(ruleCommand, { "base-url": inlineBase ? inlineBase.slice("--base-url=".length) : baseIndex >= 0 ? argv[baseIndex + 1] : undefined });
|
|
2038
|
+
}
|
|
1342
2039
|
if (area === "auth") return authCommand(action, args);
|
|
1343
2040
|
if (area === "context") return contextCommand(action, args);
|
|
1344
2041
|
if (area === "org") return orgCommand(action, args);
|
|
@@ -1348,8 +2045,13 @@ async function main() {
|
|
|
1348
2045
|
if (area === "skill") return skillCommand(action, args);
|
|
1349
2046
|
if (area === "eval") return evalCommand(action, args);
|
|
1350
2047
|
if (area === "ontology") return ontologyCommand(action, args);
|
|
2048
|
+
if (area === "automation") return automationCommand(action, args);
|
|
2049
|
+
if (area === "action-task") return actionTaskCommand(action, args);
|
|
2050
|
+
if (area === "tracking") return trackingCommand(action, args);
|
|
2051
|
+
if (area === "platform") return platformCommand(action, args);
|
|
1351
2052
|
if (area === "api") return apiCommand([action, ...args].filter(Boolean));
|
|
1352
|
-
if (area === "
|
|
2053
|
+
if (area === "server") return serverCommand(action, args);
|
|
2054
|
+
if (area === "version") return versionCommand([action, ...args].filter(Boolean));
|
|
1353
2055
|
throw new Error(`未知命令:${area}`);
|
|
1354
2056
|
}
|
|
1355
2057
|
|