@guandata/decidex 0.2.1 → 0.4.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/src/catalog.js ADDED
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ export const apiCatalog = JSON.parse(readFileSync(new URL("./api-catalog.json", import.meta.url), "utf8"));
4
+
5
+ export function apiOperation(id) {
6
+ const operation = apiCatalog.operations.find((item) => item.id === id);
7
+ if (!operation) throw new Error(`未知平台操作:${id};使用 decidex platform list --query 关键词 查找`);
8
+ return operation;
9
+ }
10
+
11
+ export function parameterFlag(name) {
12
+ return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
13
+ }
14
+
15
+ export function operationPath(operation, values) {
16
+ let path = operation.path;
17
+ for (const name of operation.parameters) {
18
+ const value = values[parameterFlag(name)];
19
+ if (typeof value !== "string" || !value.trim() || value === "." || value === "..") throw new Error(`缺少或无效路径参数 --${parameterFlag(name)}`);
20
+ path = path.replace(`[${name}]`, encodeURIComponent(value));
21
+ }
22
+ return path;
23
+ }
24
+
25
+ export function appendQuery(path, query) {
26
+ if (!query || typeof query !== "object" || Array.isArray(query)) throw new Error("查询参数文件必须是 JSON 对象");
27
+ const result = new URLSearchParams();
28
+ for (const [key, raw] of Object.entries(query)) {
29
+ if (raw === null || raw === undefined) continue;
30
+ for (const value of Array.isArray(raw) ? raw : [raw]) {
31
+ if (!["string", "boolean", "number"].includes(typeof value)) throw new Error(`查询参数 ${key} 必须是标量或标量数组;复杂参数请传入服务端要求的 JSON 字符串`);
32
+ result.append(key, String(value));
33
+ }
34
+ }
35
+ return `${path}${result.size ? `?${result}` : ""}`;
36
+ }
package/src/cli.js CHANGED
@@ -7,7 +7,9 @@ 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";
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";
11
13
 
12
14
  const COOKIE_NAME = "decidex_session";
13
15
  const DEFAULT_CONFIG_PATH = join(homedir(), ".config", "decidex", "config.json");
@@ -42,7 +44,7 @@ Usage:
42
44
  decidex agent models ID
43
45
  decidex agent run ID (--message TEXT | --input FILE | --attach FILE) [--model-entry-id ID] [--reasoning-effort LEVEL] [--wait] [--follow] [--output FILE] [--timeout SECONDS]
44
46
 
45
- decidex session list [--status all|running|completed] [--query TEXT] [--cursor CURSOR] [--agent-id ID]
47
+ decidex session list [--status all|running|completed] [--query TEXT] [--cursor CURSOR] [--agent-id ID] [--pinned-session-id ID] [--pinned-agent-id ID]
46
48
  decidex session view SESSION_ID [--before CURSOR | --since CURSOR]
47
49
  decidex session send SESSION_ID (--message TEXT | --input FILE) [--wait] [--follow]
48
50
  decidex session stop SESSION_ID
@@ -105,6 +107,10 @@ Usage:
105
107
  decidex automation run ID [--wait] [--follow] [--output FILE] [--timeout SECONDS]
106
108
  decidex automation runs ID [--cursor CURSOR]
107
109
 
110
+ decidex action-task list|get|suggestions|members|create|adopt|reject|complete|cancel|dispatch-info|dispatch|attachment ...
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
+
108
114
  decidex api METHOD PATH [--data FILE] [--output FILE]
109
115
  decidex version --json # local CLI version
110
116
  decidex server version # target version and commit
@@ -120,6 +126,66 @@ Environment:
120
126
  `;
121
127
 
122
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
+ Server >= 0.0.7: imPush.channels[].biGroupIds / emailPush.biGroupIds select BI groups.
142
+ Before 0.0.7, include schedule when PATCHing to avoid the server's default schedule reset.
143
+ --wait --timeout covers start, polling and final reads. A timeout does not cancel the run.`,
144
+ "action-task": `Usage:
145
+ decidex action-task list [--status PENDING|ADOPTED|COMPLETED|REJECTED|CANCELED|all] [--query TEXT] [--page N]
146
+ decidex action-task suggestions SESSION_ID (--run-id ID | --message-id ID)
147
+ decidex action-task members SESSION_ID [--query TEXT]
148
+ decidex action-task create SESSION_ID FILE
149
+ decidex action-task get TASK_ID
150
+ decidex action-task dispatch-info TASK_ID [--bot-id ID]
151
+ decidex action-task dispatch TASK_ID FILE
152
+ decidex action-task attachment TASK_ID EVENT_ID INDEX FILE
153
+ decidex action-task adopt|complete TASK_ID --version N
154
+ decidex action-task reject|cancel TASK_ID --version N --note REASON
155
+
156
+ Create FILE: {messageId,suggestionId,draft:{title,description,assigneeIds:[USER_ID]}}.
157
+ Read the current version with get before changing status; 409 requires a new user decision.
158
+ Dispatch and attachment require server >= 0.0.7. INDEX starts at 0.
159
+ Dispatch FILE: {botId,recipientIds:[USER_ID],idempotencyKey,createNativeTask:false}.
160
+ Dispatch sends real notifications; createNativeTask defaults to true. Keep the same key
161
+ for the same dispatch and query dispatch-info after an uncertain response; no automatic retry.
162
+ Action tasks have no delete API.`,
163
+ tracking: `Usage:
164
+ decidex tracking list [--filter all|due] [--page N]
165
+ decidex tracking preview|lookup|create SESSION_ID --candidate-path PATH --boe-path PATH [--wait]
166
+ decidex tracking get|wait TASK_ID
167
+ decidex tracking rename TASK_ID TITLE
168
+ decidex tracking schedule TASK_ID FILE
169
+ decidex tracking pause|resume|close|delete TASK_ID
170
+ decidex tracking review TASK_ID [--data FILE] [--wait]
171
+ decidex tracking reviews TASK_ID [--cursor CURSOR]
172
+ decidex tracking report TASK_ID FILE [--initial | --review-id ID]
173
+ decidex tracking retry TASK_ID [--wait]
174
+
175
+ Candidate and BOE paths belong to the remote session. create confirms a server-validated
176
+ candidate and evidenceVersion. Schedule FILE: {reviewFrequency:"WEEKLY|MONTHLY|QUARTERLY",nextReviewAt:ISO_DATE}.
177
+ --timeout SECONDS bounds the operation and any wait (default 600).`,
178
+ platform: `Usage:
179
+ decidex platform list [--query TEXT] [--group GROUP] [--method METHOD]
180
+ decidex platform show OPERATION_ID
181
+ decidex platform call OPERATION_ID [PATH_FLAGS] [--query FILE | --query-param KEY=VALUE]
182
+ [--data JSON_FILE] [--file FIELD=FILE] [--field KEY=VALUE]
183
+ [--body-file FILE --content-type MIME] [--output FILE] [--dry-run] [--timeout SECONDS]
184
+ decidex platform coverage
185
+
186
+ show lists required path flags. --file, --field and --query-param are repeatable.
187
+ --dry-run makes no network request. Main-only operations require --allow-unreleased;
188
+ released minimum versions are checked against the target server.`,
123
189
  auth: `Usage:
124
190
  decidex auth login --base-url URL [--timeout SECONDS]
125
191
  decidex auth import --base-url URL
@@ -145,7 +211,7 @@ to stderr, so stdout or --output remains machine-readable.
145
211
  accept JSON arrays. --reasoning-effort null uses the model default.
146
212
  Use agent models AGENT_ID to discover supported catalog entries and efforts.`,
147
213
  session: `Usage:
148
- decidex session list [--status all|running|completed] [--query TEXT] [--cursor CURSOR] [--agent-id ID]
214
+ decidex session list [--status all|running|completed] [--query TEXT] [--cursor CURSOR] [--agent-id ID] [--pinned-session-id ID] [--pinned-agent-id ID]
149
215
  decidex session view SESSION_ID [--before CURSOR | --since CURSOR]
150
216
  decidex session send SESSION_ID (--message TEXT | --input FILE) [--wait] [--follow]
151
217
  decidex session stop SESSION_ID
@@ -217,12 +283,6 @@ Runtime Pod termination details require backend support.`,
217
283
  decidex ontology versions list NETWORK_ID
218
284
  decidex ontology versions get NETWORK_ID VERSION_ID
219
285
  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
286
  server: `Usage:
227
287
  decidex server version
228
288
  decidex server check [COMMAND...]
@@ -326,7 +386,7 @@ async function request(path, { method = "GET", body, deadline, headers: extraHea
326
386
  requestBody = body;
327
387
  } else if (body instanceof Uint8Array) {
328
388
  requestBody = body;
329
- headers["content-type"] = "application/octet-stream";
389
+ headers["content-type"] ??= "application/octet-stream";
330
390
  } else if (body !== undefined) {
331
391
  requestBody = JSON.stringify(body);
332
392
  headers["content-type"] = "application/json";
@@ -340,7 +400,7 @@ async function request(path, { method = "GET", body, deadline, headers: extraHea
340
400
  headers,
341
401
  body: requestBody,
342
402
  redirect: "manual",
343
- signal: remaining === null ? undefined : AbortSignal.timeout(remaining),
403
+ signal: remaining === null ? undefined : AbortSignal.timeout(Math.ceil(remaining)),
344
404
  });
345
405
  } catch (error) {
346
406
  if (error?.name === "TimeoutError" || error?.name === "AbortError") throw new Error("等待运行完成超时");
@@ -565,8 +625,8 @@ async function waitForRun(agentId, sessionId, runId, values, existingDeadline) {
565
625
  }
566
626
  }
567
627
 
568
- async function resolveSession(sessionId, values) {
569
- const result = await request(`/api/agent-sessions?sessionId=${encodeURIComponent(sessionId)}`, { values });
628
+ async function resolveSession(sessionId, values, deadline) {
629
+ const result = await request(`/api/agent-sessions?sessionId=${encodeURIComponent(sessionId)}`, { values, deadline });
570
630
  const session = (result.sessions ?? []).find((item) => item.id === sessionId);
571
631
  if (!session?.agentId) throw new Error(`会话不存在或无权访问:${sessionId}`);
572
632
  return session;
@@ -779,8 +839,8 @@ async function browserLogin(baseUrl, timeoutSeconds) {
779
839
 
780
840
  let targetVersionPromise;
781
841
 
782
- async function targetVersion(values) {
783
- targetVersionPromise ??= request("/api/app-version", { values, deadline: Date.now() + 10_000 }).then((result) => {
842
+ async function targetVersion(values, deadline = Date.now() + 10_000) {
843
+ targetVersionPromise ??= request("/api/app-version", { values, deadline: Math.min(deadline, Date.now() + 10_000) }).then((result) => {
784
844
  if (!result || typeof result.version !== "string" || !result.version.trim()) throw new Error("服务端未返回有效版本号,无法检查兼容性");
785
845
  return { version: result.version, commit: result.commit ?? null };
786
846
  });
@@ -947,11 +1007,19 @@ async function agentCommand(action, args) {
947
1007
  if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new Error("Agent 文件必须是 JSON 对象");
948
1008
  const id = spec.id;
949
1009
  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"] : [])]);
1010
+ const allowed = new Set(["id", "name", "description", "instructions", "avatarIcon", "avatarColor", "avatarImageDataUrl", "openingMessage", "presetQuestions", "contextReferences", "bizOntologyBindings", "betaFeatures", "actionSuggestionsEnabled", "biUserPropertiesEnabled", "biUserPropertyKeys", "biExplorationPolicy", "pluginSelection", "useScope", "sessionDefaultModelCatalogEntryId", "sessionDefaultReasoningEffort", ...(id ? ["builtInInstructions"] : [])]);
951
1011
  const unknown = Object.keys(spec).filter((key) => !allowed.has(key));
952
1012
  if (unknown.length) throw new Error(`Agent 文件包含不支持的字段:${unknown.join(", ")}`);
953
1013
  const body = { ...spec };
954
1014
  delete body.id;
1015
+ if (body.biUserPropertiesEnabled !== undefined || body.biUserPropertyKeys !== undefined) {
1016
+ if (body.biUserPropertiesEnabled !== undefined && typeof body.biUserPropertiesEnabled !== "boolean") throw new Error("biUserPropertiesEnabled 必须是布尔值");
1017
+ if (body.biUserPropertyKeys !== undefined) {
1018
+ if (!Array.isArray(body.biUserPropertyKeys) || body.biUserPropertyKeys.length > 20 || body.biUserPropertyKeys.some((key) => typeof key !== "string" || !key.trim() || key.trim().length > 200)) throw new Error("biUserPropertyKeys 最多 20 项,每项为 1..200 字符的属性 Key");
1019
+ body.biUserPropertyKeys = [...new Set(body.biUserPropertyKeys.map((key) => key.trim()))];
1020
+ }
1021
+ await commandCompatibility("agent apply bi-user-properties", values);
1022
+ }
955
1023
  return print(
956
1024
  await request(id ? `/api/personal-agents/${encodeURIComponent(id)}` : "/api/personal-agents", {
957
1025
  method: id ? "PUT" : "POST",
@@ -1032,6 +1100,8 @@ async function sessionCommand(action, args) {
1032
1100
  const { values, positionals } = commandArgs(args, {
1033
1101
  ...TURN_OPTIONS,
1034
1102
  "agent-id": { type: "string" },
1103
+ "pinned-session-id": { type: "string", multiple: true },
1104
+ "pinned-agent-id": { type: "string", multiple: true },
1035
1105
  "model-entry-id": { type: "string" },
1036
1106
  before: { type: "string" },
1037
1107
  since: { type: "string" },
@@ -1058,6 +1128,12 @@ async function sessionCommand(action, args) {
1058
1128
  if (values.query) query.set("q", values.query);
1059
1129
  if (values.cursor) query.set("cursor", values.cursor);
1060
1130
  if (values["agent-id"]) { query.set("groupMode", "agent"); query.set("agentId", values["agent-id"]); }
1131
+ for (const [flag, parameter] of [["pinned-session-id", "pinnedSessionIds"], ["pinned-agent-id", "pinnedAgentIds"]]) {
1132
+ if (!values[flag]?.length) continue;
1133
+ if (values[flag].some((id) => !id.trim() || id.trim().length > 200)) throw new Error(`--${flag} 需要 1..200 字符的 ID`);
1134
+ await commandCompatibility("session list pinned", values);
1135
+ query.set(parameter, JSON.stringify([...new Set(values[flag].map((id) => id.trim()))]));
1136
+ }
1061
1137
  const result = await request(`/api/agent-sessions?${query}`, { values });
1062
1138
  if (values.status !== "all") result.sessions = (result.sessions ?? []).filter((session) => values.status === "running" ? session.status === "RUNNING" : session.status !== "RUNNING");
1063
1139
  return print(result);
@@ -1687,12 +1763,17 @@ async function automationCommand(action, args) {
1687
1763
  const allowed = new Set(["name", "instructions", "personalAgentId", "schedule", "imPush", "emailPush", ...(id ? ["status"] : ["source"])]);
1688
1764
  const unknown = Object.keys(body).filter((key) => !allowed.has(key));
1689
1765
  if (unknown.length) throw new Error(`定时任务文件包含不支持的字段:${unknown.join(", ")}`);
1766
+ if (body.emailPush?.biGroupIds !== undefined || body.imPush?.channels?.some((channel) => channel.biGroupIds !== undefined)) await commandCompatibility("automation apply bi-groups", values);
1690
1767
  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 等新版参数");
1768
+ const compatibility = await commandCompatibility("automation apply", values);
1769
+ body.schedule = adaptAutomationSchedule(body.schedule, compatibility.protocol);
1694
1770
  }
1771
+ if (body.status !== undefined && !["ACTIVE", "PAUSED"].includes(body.status)) throw new Error("status 只能手动设置 ACTIVE 或 PAUSED;FINISHED 由服务端单次调度写入");
1695
1772
  if (id !== undefined && (typeof id !== "string" || !id.trim())) throw new Error("定时任务 id 必须是非空字符串");
1773
+ if (id && body.schedule === undefined) {
1774
+ const server = await targetVersion(values);
1775
+ if (!resolveCommandCompatibility("automation apply partial", server.version).supported) throw new Error(`目标 ${server.version} 省略 schedule 的更新可能重置计划;请在文件中附上原 schedule,或升级服务端到 >= 0.0.7`);
1776
+ }
1696
1777
  return print(await request(id ? `${base}/${encodeURIComponent(id)}` : base, { method: id ? "PATCH" : "POST", body, values }));
1697
1778
  }
1698
1779
  if (!["delete", "run", "runs"].includes(action)) throw new Error(`未知 automation 命令:${action || "(空)"}`);
@@ -1719,6 +1800,231 @@ async function automationCommand(action, args) {
1719
1800
  if (finished.status !== "SUCCEEDED") process.exitCode = 1;
1720
1801
  }
1721
1802
 
1803
+ async function checkApiOperation(operation, values, deadline) {
1804
+ const server = await targetVersion(values, deadline);
1805
+ if (operation.minVersion && compareVersions(server.version, operation.minVersion) < 0) throw new Error(`${operation.id} 需要服务端 >= ${operation.minVersion},目标为 ${server.version}`);
1806
+ if (!operation.inBaseline && !values["allow-unreleased"]) throw new Error(`${operation.id} 尚不在已适配的 ${apiCatalog.baselineVersion} tag 中;确认目标已部署该接口后才能使用 --allow-unreleased`);
1807
+ }
1808
+
1809
+ async function taskApi(id, parameters, { query = {}, body, output, values, deadline } = {}) {
1810
+ const operation = apiOperation(id);
1811
+ const flags = Object.fromEntries(Object.entries(parameters).map(([key, value]) => [parameterFlag(key), value]));
1812
+ const path = appendQuery(operationPath(operation, flags), query);
1813
+ await checkApiOperation(operation, values, deadline);
1814
+ return request(path, { method: operation.method, body, output, values, deadline });
1815
+ }
1816
+
1817
+ async function actionTaskCommand(action, args) {
1818
+ const { values, positionals } = commandArgs(args, {
1819
+ status: { type: "string", default: "PENDING" }, query: { type: "string" }, page: { type: "string", default: "1" },
1820
+ version: { type: "string" }, note: { type: "string" }, "message-id": { type: "string" },
1821
+ "run-id": { type: "string" }, "bot-id": { type: "string" }, output: { type: "string" }, timeout: { type: "string", default: "600" },
1822
+ });
1823
+ const deadline = Date.now() + positiveSeconds(values.timeout) * 1000;
1824
+ if (action === "attachment") {
1825
+ expectPositionals(positionals, 4, "action-task attachment TASK_ID EVENT_ID INDEX FILE");
1826
+ if (!/^\d{1,4}$/.test(positionals[2])) throw new Error("附件 INDEX 必须是 0..9999 的整数(从 0 开始)");
1827
+ return print(await taskApi("action-tasks.events.attachments.get", { taskId: positionals[0], eventId: positionals[1], index: positionals[2] }, { output: positionals[3], values, deadline }));
1828
+ }
1829
+ if (action === "dispatch") {
1830
+ expectPositionals(positionals, 2, "action-task dispatch TASK_ID FILE");
1831
+ const body = await readJsonFile(positionals[1]);
1832
+ if (!body || typeof body !== "object" || Array.isArray(body) || typeof body.idempotencyKey !== "string" || !body.idempotencyKey.trim() || body.idempotencyKey.length > 80) throw new Error("分发文件需要 1..80 字符的 idempotencyKey;同一次分发保持此值不变,超时后先查询 dispatch-info");
1833
+ return emit(await taskApi("action-tasks.dispatch.create", { taskId: positionals[0] }, { body, values, deadline }), values.output);
1834
+ }
1835
+ if (action === "list") {
1836
+ expectPositionals(positionals, 0, "action-task list");
1837
+ if (!["PENDING", "ADOPTED", "COMPLETED", "REJECTED", "CANCELED", "all"].includes(values.status)) throw new Error("--status 不合法");
1838
+ const page = positiveInteger(values.page, "page");
1839
+ if (page > 100000) throw new Error("page 不能超过 100000");
1840
+ return emit(await taskApi("action-tasks.list", {}, { query: { page, status: values.status, q: values.query ?? "" }, values, deadline }), values.output);
1841
+ }
1842
+ if (["suggestions", "members", "create"].includes(action)) {
1843
+ expectPositionals(positionals, action === "create" ? 2 : 1, `action-task ${action} SESSION_ID${action === "create" ? " FILE" : ""}`);
1844
+ let body;
1845
+ if (action === "create") body = await readJsonFile(positionals[1]);
1846
+ if (action === "suggestions" && Boolean(values["message-id"]) === Boolean(values["run-id"])) throw new Error("suggestions 需要且只能指定 --message-id 或 --run-id");
1847
+ const sessionId = positionals[0];
1848
+ const session = await resolveSession(sessionId, values, deadline);
1849
+ let messageId = values["message-id"];
1850
+ if (action === "suggestions" && values["run-id"]) {
1851
+ const view = await request(`${sessionPath(session.agentId, sessionId)}/view`, { values, deadline });
1852
+ messageId = (view.messages ?? []).find((message) => message.role === "ASSISTANT" && message.turn?.id === values["run-id"])?.id;
1853
+ if (!messageId) throw new Error("当前会话窗口没有该 Run 的回答,请用 session view 查找后传 --message-id");
1854
+ }
1855
+ const operation = action === "members" ? "personal-agents.sessions.action-suggestions.members.list" : `personal-agents.sessions.action-suggestions.${action === "create" ? "create" : "list"}`;
1856
+ return emit(await taskApi(operation, { agentId: session.agentId, sessionId }, { query: action === "members" ? { q: values.query ?? "" } : action === "suggestions" ? { messageId } : {}, body, values, deadline }), values.output);
1857
+ }
1858
+ expectPositionals(positionals, 1, `action-task ${action} TASK_ID`);
1859
+ const parameters = { taskId: positionals[0] };
1860
+ if (action === "dispatch-info") return emit(await taskApi("action-tasks.dispatch.list", parameters, { query: values["bot-id"] ? { botId: values["bot-id"] } : {}, values, deadline }), values.output);
1861
+ if (action === "get") return emit(await taskApi("action-tasks.get", parameters, { values, deadline }), values.output);
1862
+ if (!["adopt", "reject", "complete", "cancel"].includes(action)) throw new Error(`未知 action-task 命令:${action || "(空)"}`);
1863
+ if (values.version === undefined || !/^\d+$/.test(values.version) || !Number.isSafeInteger(Number(values.version))) throw new Error("需要 --version 非负整数;从 action-task get 返回值读取,冲突后不要自动重试");
1864
+ if (["reject", "cancel"].includes(action) && !values.note?.trim()) throw new Error("reject / cancel 需要 --note 理由");
1865
+ return emit(await taskApi("action-tasks.update", parameters, { body: { action, version: Number(values.version), note: values.note ?? "" }, values, deadline }), values.output);
1866
+ }
1867
+
1868
+ async function waitTrackingTask(taskId, values, deadline) {
1869
+ try {
1870
+ const result = await poll(() => taskApi("decision-tracking-tasks.list", {}, { query: { taskId }, values, deadline }), (result) => result.task.status !== "CREATING", positiveSeconds(values.timeout), undefined, deadline);
1871
+ if (!result.task.initialReportPath) process.exitCode = 1;
1872
+ return result;
1873
+ } catch (error) {
1874
+ error.message += `;taskId=${taskId},可运行 decidex tracking wait ${taskId} 继续查询`;
1875
+ throw error;
1876
+ }
1877
+ }
1878
+
1879
+ async function trackingCommand(action, args) {
1880
+ const { values, positionals } = commandArgs(args, {
1881
+ filter: { type: "string", default: "all" }, page: { type: "string", default: "1" }, cursor: { type: "string" },
1882
+ "candidate-path": { type: "string" }, "boe-path": { type: "string" }, "source-message-id": { type: "string" },
1883
+ "next-review-at": { type: "string" }, language: { type: "string", default: "zh-CN" },
1884
+ data: { type: "string" }, output: { type: "string" }, initial: { type: "boolean", default: false },
1885
+ "review-id": { type: "string" }, wait: { type: "boolean", default: false }, timeout: { type: "string", default: "600" },
1886
+ });
1887
+ const deadline = Date.now() + positiveSeconds(values.timeout) * 1000;
1888
+ if (action === "list") {
1889
+ expectPositionals(positionals, 0, "tracking list");
1890
+ if (!["all", "due"].includes(values.filter)) throw new Error("--filter 只支持 all、due");
1891
+ const page = positiveInteger(values.page, "page");
1892
+ if (page > 100000) throw new Error("page 不能超过 100000");
1893
+ return emit(await taskApi("decision-tracking-tasks.list", {}, { query: { page, filter: values.filter }, values, deadline }), values.output);
1894
+ }
1895
+ if (["preview", "create", "lookup"].includes(action)) {
1896
+ expectPositionals(positionals, 1, `tracking ${action} SESSION_ID --candidate-path PATH --boe-path PATH`);
1897
+ const candidatePath = required(values["candidate-path"], "--candidate-path");
1898
+ const boePath = required(values["boe-path"], "--boe-path");
1899
+ const sessionId = positionals[0];
1900
+ const session = await resolveSession(sessionId, values, deadline);
1901
+ const parameters = { agentId: session.agentId, sessionId };
1902
+ if (action === "lookup") return emit(await taskApi("personal-agents.sessions.decision-tracking-tasks.list", parameters, { query: { candidatePath, boePath }, values, deadline }), values.output);
1903
+ const preview = await taskApi("personal-agents.sessions.decision-tracking-candidate-preview.list", parameters, { query: { candidatePath, boePath, language: values.language }, values, deadline });
1904
+ if (action === "preview") return emit(preview, values.output);
1905
+ if (!preview.candidate || !/^[a-f0-9]{64}$/.test(preview.evidenceVersion ?? "")) throw new Error("服务端未返回有效候选或 evidenceVersion,未创建任务");
1906
+ const body = { candidatePath, boePath, candidate: preview.candidate, evidenceVersion: preview.evidenceVersion };
1907
+ if (values["source-message-id"]) body.sourceMessageId = values["source-message-id"];
1908
+ if (values["next-review-at"]) body.nextReviewAt = values["next-review-at"];
1909
+ const result = await taskApi("personal-agents.sessions.decision-tracking-tasks.create", parameters, { body, values, deadline });
1910
+ return emit(values.wait ? await waitTrackingTask(result.task.id, values, deadline) : result, values.output);
1911
+ }
1912
+ expectPositionals(positionals, ["rename", "schedule", "report"].includes(action) ? 2 : 1, `tracking ${action} TASK_ID${action === "rename" ? " TITLE" : action === "schedule" ? " FILE" : action === "report" ? " FILE" : ""}`);
1913
+ const taskId = positionals[0];
1914
+ const parameters = { taskId };
1915
+ if (action === "wait") return emit(await waitTrackingTask(taskId, values, deadline), values.output);
1916
+ if (action === "get") return emit(await taskApi("decision-tracking-tasks.list", {}, { query: { taskId }, values, deadline }), values.output);
1917
+ if (["pause", "resume", "close"].includes(action)) return emit(await taskApi("decision-tracking-tasks.status.update", parameters, { body: { action }, values, deadline }), values.output);
1918
+ if (action === "rename") return emit(await taskApi("decision-tracking-tasks.title.update", parameters, { body: { title: positionals[1] }, values, deadline }), values.output);
1919
+ if (action === "schedule") return emit(await taskApi("decision-tracking-tasks.update", parameters, { body: await readJsonFile(positionals[1]), values, deadline }), values.output);
1920
+ if (action === "delete") return emit(await taskApi("decision-tracking-tasks.delete", parameters, { values, deadline }), values.output);
1921
+ if (action === "report") {
1922
+ if (values.initial && values["review-id"]) throw new Error("--initial 和 --review-id 不能同用");
1923
+ 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 }));
1924
+ }
1925
+ if (action === "reviews") return emit(await taskApi("decision-tracking-tasks.reviews.list", parameters, { query: { cursor: values.cursor }, values, deadline }), values.output);
1926
+ if (action === "retry") {
1927
+ const result = await taskApi("decision-tracking-tasks.initial-report.create", parameters, { values, deadline });
1928
+ return emit(values.wait ? await waitTrackingTask(taskId, values, deadline) : result, values.output);
1929
+ }
1930
+ if (action === "review") {
1931
+ const body = values.data ? await readJsonFile(values.data) : {};
1932
+ const result = await taskApi("decision-tracking-tasks.reviews.create", parameters, { body, values, deadline });
1933
+ if (!values.wait) return emit(result, values.output);
1934
+ const reviewId = result.review.reviewId;
1935
+ process.stderr.write(`[decidex] task=${taskId} review=${reviewId}\n`);
1936
+ try {
1937
+ 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);
1938
+ const review = history.reviews.find((item) => item.id === reviewId);
1939
+ await emit({ review }, values.output);
1940
+ if (!review.reportPath) process.exitCode = 1;
1941
+ } catch (error) {
1942
+ error.message += `;taskId=${taskId};reviewId=${reviewId},可用 tracking reviews 查询,勿直接重试发起复核`;
1943
+ throw error;
1944
+ }
1945
+ return;
1946
+ }
1947
+ throw new Error(`未知 tracking 命令:${action || "(空)"}`);
1948
+ }
1949
+
1950
+ function keyValue(value, option) {
1951
+ const separator = value.indexOf("=");
1952
+ if (separator <= 0) throw new Error(`${option} 需要 KEY=VALUE`);
1953
+ return [value.slice(0, separator), value.slice(separator + 1)];
1954
+ }
1955
+
1956
+ async function platformCommand(action, args) {
1957
+ if (action === "coverage") {
1958
+ const { positionals } = commandArgs(args);
1959
+ expectPositionals(positionals, 0, "platform coverage");
1960
+ return print({ sourceCommit: apiCatalog.sourceCommit, baselineVersion: apiCatalog.baselineVersion, ...apiCatalog.coverage, definition: "操作目录的调用入口覆盖率,不等同于逐接口业务或真实环境测试覆盖率", excluded: apiCatalog.excluded });
1961
+ }
1962
+ if (action === "list") {
1963
+ const { values, positionals } = commandArgs(args, { query: { type: "string" }, method: { type: "string" }, group: { type: "string" } });
1964
+ expectPositionals(positionals, 0, "platform list");
1965
+ const query = values.query?.toLowerCase() ?? "";
1966
+ 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)) });
1967
+ }
1968
+ if (action === "show") {
1969
+ const { positionals } = commandArgs(args);
1970
+ expectPositionals(positionals, 1, "platform show OPERATION_ID");
1971
+ const operation = apiOperation(positionals[0]);
1972
+ 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 仅来自路由源码;业务字段与权限由目标服务端校验" });
1973
+ }
1974
+ if (action !== "call") throw new Error("platform 只支持 list、show、call、coverage");
1975
+ const id = required(args[0], "OPERATION_ID");
1976
+ const operation = apiOperation(id);
1977
+ const options = Object.fromEntries(operation.parameters.map((name) => [parameterFlag(name), { type: "string" }]));
1978
+ const { values, positionals } = commandArgs(args.slice(1), {
1979
+ ...options,
1980
+ query: { type: "string" }, "query-param": { type: "string", multiple: true },
1981
+ data: { type: "string" }, file: { type: "string", multiple: true }, field: { type: "string", multiple: true },
1982
+ "body-file": { type: "string" }, "content-type": { type: "string" }, output: { type: "string" },
1983
+ "dry-run": { type: "boolean", default: false }, "allow-unreleased": { type: "boolean", default: false },
1984
+ timeout: { type: "string", default: "600" },
1985
+ });
1986
+ expectPositionals(positionals, 0, "platform call OPERATION_ID [FLAGS]");
1987
+ const timeout = positiveSeconds(values.timeout);
1988
+ const deadline = Date.now() + timeout * 1000;
1989
+ const path = operationPath(operation, values);
1990
+ const query = values.query ? await readJsonFile(values.query) : {};
1991
+ appendQuery(path, query);
1992
+ const pairs = values["query-param"] ?? [];
1993
+ for (const pair of pairs) {
1994
+ const [key, value] = keyValue(pair, "--query-param");
1995
+ if (Object.hasOwn(query, key)) query[key] = [...(Array.isArray(query[key]) ? query[key] : [query[key]]), value];
1996
+ else query[key] = value;
1997
+ }
1998
+ const url = appendQuery(path, query);
1999
+ const multipart = Boolean(values.file?.length || values.field?.length);
2000
+ if (values["body-file"] && (values.data || multipart)) throw new Error("--body-file 不能与 --data / --file / --field 同用");
2001
+ if (values["content-type"] && !values["body-file"]) throw new Error("--content-type 仅用于 --body-file;JSON 与 multipart 会自动设置类型");
2002
+ if (["GET", "HEAD"].includes(operation.method) && (values.data || values["body-file"] || multipart)) throw new Error("GET / HEAD 操作不能带请求体");
2003
+ let body;
2004
+ if (values.data) body = await readJsonFile(values.data);
2005
+ if (multipart) {
2006
+ const form = new FormData();
2007
+ if (body !== undefined) {
2008
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("multipart 的 --data 必须是 JSON 对象");
2009
+ for (const [key, value] of Object.entries(body)) form.append(key, typeof value === "string" ? value : JSON.stringify(value));
2010
+ }
2011
+ for (const value of values.field ?? []) {
2012
+ const [key, content] = keyValue(value, "--field");
2013
+ form.append(key, content);
2014
+ }
2015
+ for (const value of values.file ?? []) {
2016
+ const [key, file] = keyValue(value, "--file");
2017
+ 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";
2018
+ form.append(key, new Blob([await readFile(resolve(required(file, "FILE")))], { type: mime }), basename(file));
2019
+ }
2020
+ body = form;
2021
+ }
2022
+ if (values["body-file"]) body = await readFile(resolve(values["body-file"]));
2023
+ 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 });
2024
+ await checkApiOperation(operation, values, deadline);
2025
+ return print(await request(url, { method: operation.method, body, values, deadline, headers: values["content-type"] ? { "content-type": values["content-type"] } : undefined, output: values.output }));
2026
+ }
2027
+
1722
2028
  async function apiCommand(args) {
1723
2029
  const { values, positionals } = commandArgs(args, {
1724
2030
  data: { type: "string" },
@@ -1776,6 +2082,9 @@ async function main() {
1776
2082
  if (area === "eval") return evalCommand(action, args);
1777
2083
  if (area === "ontology") return ontologyCommand(action, args);
1778
2084
  if (area === "automation") return automationCommand(action, args);
2085
+ if (area === "action-task") return actionTaskCommand(action, args);
2086
+ if (area === "tracking") return trackingCommand(action, args);
2087
+ if (area === "platform") return platformCommand(action, args);
1779
2088
  if (area === "api") return apiCommand([action, ...args].filter(Boolean));
1780
2089
  if (area === "server") return serverCommand(action, args);
1781
2090
  if (area === "version") return versionCommand([action, ...args].filter(Boolean));
@@ -1,5 +1,5 @@
1
- export const ADAPTED_SERVER_VERSION = "0.0.5";
2
- export const ADAPTED_SERVER_COMMIT = "3e0ad67d9aa087b92cf6e60f9d501657ac4a625f";
1
+ export const ADAPTED_SERVER_VERSION = "0.0.7";
2
+ export const ADAPTED_SERVER_COMMIT = "cfdf08dbab954510ea1ebb4dba6a50d6b2af8c82";
3
3
 
4
4
  // Version boundaries must be backed by release tags, not the current main version.
5
5
  // /api/auth/context first appears between tags 0.0.4 and 0.0.5 (a860e97ad).
@@ -8,8 +8,56 @@ export const COMMAND_COMPATIBILITY = {
8
8
  "auth status": { protocol: "identity-context", legacy: { before: "0.0.5", protocol: "agent-list" } },
9
9
  "auth login": { protocol: "identity-context", legacy: { before: "0.0.5", protocol: "agent-list" } },
10
10
  "context show": { protocol: "identity-context", legacy: { before: "0.0.5", protocol: "local-context" } },
11
+ // 0.0.6 changes the automation schedule contract; 0.0.5 strips unknown fields.
12
+ "automation apply": { protocol: "schedule-v2", legacy: { before: "0.0.6", protocol: "schedule-v1" } },
13
+ // These fields first appear in the 0.0.7 release; older schemas strip or reject them.
14
+ "agent apply bi-user-properties": { minVersion: "0.0.7" },
15
+ "session list pinned": { minVersion: "0.0.7" },
16
+ "automation apply bi-groups": { minVersion: "0.0.7" },
17
+ "automation apply partial": { minVersion: "0.0.7" },
11
18
  };
12
19
 
20
+ export function adaptAutomationSchedule(input, protocol, now = Date.now()) {
21
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("schedule 必须是 JSON 对象");
22
+ const schedule = { ...input };
23
+ const fields = {
24
+ HOURLY: ["timeOfDayMinutes", "weekday"], DAILY: ["timeOfDayMinutes", "weekday"],
25
+ WEEKLY: ["timeOfDayMinutes", "weekday", "weekdays"], MONTHLY: ["timeOfDayMinutes", "monthDays"],
26
+ INTERVAL: ["intervalMinutes"], ONCE: ["runOnceAt"],
27
+ };
28
+ if (!Object.hasOwn(fields, schedule.kind)) throw new Error("schedule.kind 只支持 HOURLY、DAILY、WEEKLY、MONTHLY、INTERVAL、ONCE");
29
+ const unknown = Object.keys(schedule).filter((key) => key !== "kind" && !fields[schedule.kind].includes(key));
30
+ if (unknown.length) throw new Error(`${schedule.kind} 调度不支持字段:${unknown.join(", ")}`);
31
+ const integer = (value, name, min, max) => {
32
+ if (!Number.isInteger(value) || value < min || value > max) throw new Error(`${name} 必须是 ${min}..${max} 的整数`);
33
+ };
34
+ if (schedule.timeOfDayMinutes !== undefined) integer(schedule.timeOfDayMinutes, "timeOfDayMinutes", 0, 1439);
35
+ if (schedule.weekday !== undefined) integer(schedule.weekday, "weekday", 0, 6);
36
+ for (const [name, min, max] of [["weekdays", 0, 6], ["monthDays", 1, 31]]) {
37
+ if (schedule[name] === undefined && !(name === "monthDays" && schedule.kind === "MONTHLY")) continue;
38
+ if (!Array.isArray(schedule[name]) || !schedule[name].length) throw new Error(`${name} 必须是非空数组`);
39
+ schedule[name].forEach((value) => integer(value, name, min, max));
40
+ schedule[name] = [...new Set(schedule[name])].sort((a, b) => a - b);
41
+ }
42
+ if (schedule.kind === "INTERVAL") integer(schedule.intervalMinutes, "intervalMinutes", 5, 2_147_483_647);
43
+ if (schedule.kind === "ONCE" && (typeof schedule.runOnceAt !== "string" || !Number.isFinite(Date.parse(schedule.runOnceAt)) || Date.parse(schedule.runOnceAt) <= now)) throw new Error("runOnceAt 必须是晚于当前时间的有效日期,建议使用带时区的 ISO 8601 时间");
44
+ if (protocol === "schedule-v1") {
45
+ if (!["HOURLY", "DAILY", "WEEKLY"].includes(schedule.kind)) throw new Error(`${schedule.kind} 调度需要服务端 >= 0.0.6`);
46
+ if (schedule.weekdays) {
47
+ if (schedule.weekdays.length !== 1) throw new Error("0.0.5 调度仅支持单个 weekday;多星期调度需要服务端 >= 0.0.6");
48
+ schedule.weekday = schedule.weekdays[0];
49
+ delete schedule.weekdays;
50
+ }
51
+ return schedule;
52
+ }
53
+ if (schedule.kind === "HOURLY") return { kind: "INTERVAL", intervalMinutes: 60 };
54
+ if (schedule.kind === "WEEKLY") {
55
+ if (schedule.weekdays === undefined && schedule.weekday !== undefined) schedule.weekdays = [schedule.weekday];
56
+ delete schedule.weekday;
57
+ }
58
+ return schedule;
59
+ }
60
+
13
61
  function parseVersion(value) {
14
62
  const match = typeof value === "string" && value.match(/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);
15
63
  if (!match) throw new Error(`无法比较服务端版本:${JSON.stringify(value)};需要 SemVer 版本号`);