@insmind/cli 2.0.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/contracts/operations/agent.send/input.schema.json +1 -77
- package/contracts/operations/credits.get/input.schema.json +8 -0
- package/contracts/operations/credits.get/output.schema.json +92 -0
- package/contracts/operations/credits.usage.get/input.schema.json +17 -0
- package/contracts/operations/credits.usage.get/output.schema.json +46 -0
- package/contracts/operations/credits.usage.list/input.schema.json +27 -0
- package/contracts/operations/credits.usage.list/output.schema.json +135 -0
- package/contracts/operations/dam.folder.list/input.schema.json +0 -1
- package/contracts/operations/dam.folder.list/output.schema.json +1 -2
- package/contracts/operations/dam.list/input.schema.json +3 -6
- package/contracts/operations/dam.list/output.schema.json +1 -2
- package/contracts/operations/dam.search/input.schema.json +3 -6
- package/contracts/operations/dam.search/output.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
- package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
- package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
- package/dist/bin/postinstall.js +22 -6
- package/dist/bin/task-worker.js +2 -2
- package/dist/src/bootstrap/create-cli.js +31 -15
- package/dist/src/bootstrap/create-runtime.js +103 -30
- package/dist/src/bootstrap/run-task-worker.js +6 -2
- package/dist/src/bootstrap/validators.js +4 -1
- package/dist/src/cli/action-binding.js +17 -50
- package/dist/src/cli/agent-commands.js +11 -11
- package/dist/src/cli/auth-commands.js +2 -1
- package/dist/src/cli/creation-help.js +9 -0
- package/dist/src/cli/credits-command.js +127 -16
- package/dist/src/cli/dam-commands.js +10 -14
- package/dist/src/cli/editor-commands.js +7 -5
- package/dist/src/cli/errors.js +81 -22
- package/dist/src/cli/host-input.js +64 -5
- package/dist/src/cli/model-commands.js +9 -3
- package/dist/src/cli/observed-errors.js +7 -3
- package/dist/src/cli/org-commands.js +3 -1
- package/dist/src/cli/presenter.js +4 -0
- package/dist/src/cli/task-commands.js +6 -2
- package/dist/src/cli/tool-commands.js +12 -11
- package/dist/src/cli/update-command.js +24 -1
- package/dist/src/features/agent/creative-agent-adapter.js +6 -2
- package/dist/src/features/agent/creative-protocol.js +8 -29
- package/dist/src/features/agent/resource-authorizer.js +25 -17
- package/dist/src/features/agent/result-reader.js +31 -14
- package/dist/src/features/agent/use-cases.js +6 -31
- package/dist/src/features/credits/amount.js +51 -0
- package/dist/src/features/credits/response.js +11 -0
- package/dist/src/features/credits/use-cases.js +200 -30
- package/dist/src/features/dam/asset-projection.js +3 -6
- package/dist/src/features/dam/dam-api-adapter.js +30 -15
- package/dist/src/features/dam/repository-catalog.js +30 -21
- package/dist/src/features/dam/use-cases.js +12 -7
- package/dist/src/features/editor/bridge-client.js +0 -2
- package/dist/src/features/editor/public-url.js +1 -36
- package/dist/src/features/editor/session.js +3 -2
- package/dist/src/features/editor/use-cases.js +27 -2
- package/dist/src/features/org/org-service.js +10 -1
- package/dist/src/features/org/use-cases.js +18 -4
- package/dist/src/features/task/process-owner.js +54 -0
- package/dist/src/features/task/store.js +37 -10
- package/dist/src/features/task/task-background.js +5 -2
- package/dist/src/features/task/use-cases.js +184 -84
- package/dist/src/features/tool/argument-paths.js +14 -0
- package/dist/src/features/tool/canvas-copy.js +28 -15
- package/dist/src/features/tool/canvas-matting.js +123 -0
- package/dist/src/features/tool/canvas-media.js +100 -52
- package/dist/src/features/tool/canvas-models.js +66 -33
- package/dist/src/features/tool/canvas-pricing.js +12 -0
- package/dist/src/features/tool/canvas-recovery.js +13 -30
- package/dist/src/features/tool/canvas-results.js +79 -87
- package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
- package/dist/src/features/tool/canvas-video.js +44 -37
- package/dist/src/features/tool/dynamic-schema.js +39 -40
- package/dist/src/features/tool/ffprobe-executable.js +21 -0
- package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
- package/dist/src/features/tool/resource-authorizer.js +11 -3
- package/dist/src/features/tool/tool-api-adapter.js +73 -82
- package/dist/src/features/tool/tool-errors.js +25 -0
- package/dist/src/features/tool/tool-output.js +15 -0
- package/dist/src/features/tool/use-cases.js +74 -98
- package/dist/src/features/update/check-schema.js +17 -0
- package/dist/src/features/update/host-receipt.js +30 -0
- package/dist/src/features/update/notice-output.js +30 -0
- package/dist/src/features/update/update-lock.js +80 -0
- package/dist/src/features/update/update-notification.js +129 -240
- package/dist/src/features/update/update-service.js +95 -21
- package/dist/src/platform/media-type.js +46 -0
- package/dist/src/platform/public-url.js +35 -0
- package/dist/src/platform/remote-error-evidence.js +33 -6
- package/dist/src/platform/resource-auth-key.js +35 -1
- package/dist/src/platform/safe-upload-file.js +36 -41
- package/dist/src/platform/signature.js +3 -1
- package/dist/src/platform/signed-http-transport.js +14 -6
- package/dist/src/platform/url-safety.js +6 -1
- package/dist/src/platform/webm-header.js +41 -0
- package/dist/src/telemetry/command-route.js +38 -0
- package/dist/src/telemetry/command-routes.json +1 -0
- package/dist/src/telemetry/failure-summary.js +1 -1
- package/dist/src/telemetry/invocation.js +1 -2
- package/dist/src/telemetry/process-errors.js +17 -33
- package/dist/src/telemetry/sanitize.js +19 -4
- package/dist/src/telemetry/sls-sink.js +8 -0
- package/package.json +4 -4
- package/skills/insmind-cli/SKILL.md +19 -5
- package/skills/insmind-cli/references/agent.md +9 -4
- package/skills/insmind-cli/references/creation.md +3 -1
- package/skills/insmind-cli/references/editor.md +7 -5
- package/skills/insmind-cli/references/errors.md +20 -9
- package/skills/insmind-cli/references/matting.md +3 -5
- package/skills/insmind-cli/references/media-tools.md +10 -4
- package/skills/insmind-cli/references/tool.md +9 -15
- package/skills/insmind-cli/references/update.md +2 -0
package/dist/bin/task-worker.js
CHANGED
|
@@ -28,7 +28,7 @@ else {
|
|
|
28
28
|
for (const key of Object.keys(endpoints))
|
|
29
29
|
endpoints[key] = new URL(job.endpoints[key]);
|
|
30
30
|
const runtime = createProductionRuntime({
|
|
31
|
-
processRole: job.operation === "
|
|
31
|
+
processRole: job.operation === "agent.send" ? "agent_worker" : "tool_worker",
|
|
32
32
|
...(job.telemetryVersion ? { telemetryVersion: job.telemetryVersion } : {}),
|
|
33
33
|
...(job.telemetryTrackingUrl ? { telemetryTrackingUrl: new URL(job.telemetryTrackingUrl) } : {}),
|
|
34
34
|
...(job.telemetryEnvironment ? { telemetryEnvironment: job.telemetryEnvironment } : {}),
|
|
@@ -38,7 +38,7 @@ else {
|
|
|
38
38
|
await runTaskWorker({ runtime, job, signal: controller.signal, send });
|
|
39
39
|
}
|
|
40
40
|
catch (error) {
|
|
41
|
-
await reportProcessError(error, { operation: "bootstrap", processRole: currentJob?.operation === "
|
|
41
|
+
await reportProcessError(error, { operation: "bootstrap", processRole: currentJob?.operation === "agent.send" ? "agent_worker" : "tool_worker", startedAt, signal: controller.signal,
|
|
42
42
|
stateDirectory: currentJob?.product === "insmind" ? ".insmind" : ".gd",
|
|
43
43
|
...(currentJob?.telemetryTrackingUrl ? { trackingUrl: new URL(currentJob.telemetryTrackingUrl) } : {}),
|
|
44
44
|
...(currentJob?.telemetryEnvironment ? { environment: currentJob.telemetryEnvironment } : {}),
|
|
@@ -35,22 +35,19 @@ export function createCli(runtime, options) {
|
|
|
35
35
|
writeErr: () => undefined
|
|
36
36
|
});
|
|
37
37
|
program.addHelpText("after", runtime.product.id === "insmind"
|
|
38
|
-
? "\nstdout contains command results; stderr contains progress, warnings and errors. Fixed JSON commands, --json and --json-errors use {error:{code,message,details?,trace_id?}} for final errors. stderr may contain multiple messages.\nExit codes: 0 success, 1 execution failure, 2 invalid input, 130 local interruption; dispatched work may still be active.\n"
|
|
39
|
-
: "\nstdout
|
|
38
|
+
? "\nChoose by the object and goal: tool list discovers generation and processing of attached images/videos (including text replacement, layers and vectors); editor operates elements in a connected work; agent send handles planning and multi-turn creation. A capability absent from Editor may be available as a Tool.\nRead the selected command's --help. Use its advertised --schema for JSON structure and model get for live model inputs. --input takes a JSON file path or - with complete JSON on stdin; media URI fields inside JSON take URLs.\nstdout contains command results; human-readable views can include an update notice. stderr contains progress, warnings and errors. Fixed JSON commands, --json and --json-errors use {error:{code,message,details?,trace_id?}} for final errors. stderr may contain multiple messages.\nExit codes: 0 command success (async acceptance and successful queries still require checking task state), 1 execution failure, 2 invalid input, 130 local interruption; dispatched work may still be active.\n"
|
|
39
|
+
: "\n按对象和目标选入口:tool list 发现生成及附件图片/视频处理能力(含改字、分层、矢量化);editor 操作已连接作品的元素;agent send 负责策划和持续多轮创作。Editor 未提供的操作仍可能由 Tool 提供。\n先读所选命令 --help;结构化输入从其公开的 --schema 发现,模型参数从 model get 查询。--input 接收 JSON 文件路径,或用 - 从 stdin 传完整 JSON;JSON 内的媒体 URI 字段接收 URL。\nstdout 输出命令结果,人类可读视图可以附带升级提醒;stderr 输出进度、警告和错误。固定 JSON 命令、--json 和 --json-errors 的最终错误使用 {error:{code,message,details?,trace_id?}},stderr 可能包含多条信息。\n退出码:0 命令成功(异步受理、查询成功仍须查看任务状态),1 执行失败,2 输入无效,130 本地中断;已派发的工作可能仍在继续。\n");
|
|
40
40
|
if (runtime.product.id === "insmind") {
|
|
41
41
|
program.option("--locale <locale>", "locale for service-owned business descriptions");
|
|
42
42
|
}
|
|
43
43
|
configureActionEnvironment(program, {
|
|
44
44
|
policies: runtime.accessPolicies,
|
|
45
45
|
signal: options.signal,
|
|
46
|
-
telemetry: runtime.telemetry
|
|
47
|
-
updateNotification: runtime.updateNotification
|
|
46
|
+
telemetry: runtime.telemetry
|
|
48
47
|
});
|
|
49
48
|
registerAuthCommands(program, runtime);
|
|
50
49
|
if (runtime.product.exposesOrganizations)
|
|
51
50
|
registerOrgCommands(program, runtime);
|
|
52
|
-
else
|
|
53
|
-
registerCreditsCommand(program, runtime);
|
|
54
51
|
registerAgentCommands(program, runtime);
|
|
55
52
|
registerToolCommands(program, runtime);
|
|
56
53
|
registerModelCommands(program, runtime);
|
|
@@ -58,6 +55,7 @@ export function createCli(runtime, options) {
|
|
|
58
55
|
registerDamCommands(program, runtime);
|
|
59
56
|
registerUpdateCommand(program, runtime);
|
|
60
57
|
registerTaskCommands(program, runtime);
|
|
58
|
+
registerCreditsCommand(program, runtime);
|
|
61
59
|
assertAllLeafCommandsBound(program);
|
|
62
60
|
outputs.set(program, runtime);
|
|
63
61
|
if (runtime.analytics)
|
|
@@ -65,7 +63,11 @@ export function createCli(runtime, options) {
|
|
|
65
63
|
return program;
|
|
66
64
|
}
|
|
67
65
|
export async function executeCli(options) {
|
|
68
|
-
|
|
66
|
+
const definition = invocationDefinition(options.program, options.argv);
|
|
67
|
+
await options.telemetry.issue(definition);
|
|
68
|
+
const automaticNotice = definition.operation !== "update" && !definition.operation.startsWith("update.");
|
|
69
|
+
let informational = false;
|
|
70
|
+
let help = false;
|
|
69
71
|
try {
|
|
70
72
|
try {
|
|
71
73
|
await options.program.parseAsync(options.argv, { from: "user" });
|
|
@@ -73,12 +75,16 @@ export async function executeCli(options) {
|
|
|
73
75
|
catch (error) {
|
|
74
76
|
if (!isHelpOutcome(error))
|
|
75
77
|
throw error;
|
|
76
|
-
|
|
77
|
-
|
|
78
|
+
informational = true;
|
|
79
|
+
help = error instanceof CommanderError && error.code === "commander.helpDisplayed";
|
|
78
80
|
options.signal.throwIfAborted();
|
|
79
81
|
}
|
|
80
82
|
await options.telemetry.stage("output", async () => { await outputs.get(options.program)?.io.flush?.(); });
|
|
81
83
|
await outputs.get(options.program)?.tasks.outputCompleted();
|
|
84
|
+
if (automaticNotice)
|
|
85
|
+
await checkUpdateNotification(options.updateNotification, options.signal, help || options.presenter.humanResult ? "text" : "machine");
|
|
86
|
+
if (informational)
|
|
87
|
+
options.signal.throwIfAborted();
|
|
82
88
|
await sendFinished(options, { outcome: "success" });
|
|
83
89
|
return 0;
|
|
84
90
|
}
|
|
@@ -103,12 +109,19 @@ export async function executeCli(options) {
|
|
|
103
109
|
const { cli_task_id: taskId, operation } = options.telemetry.creationContext();
|
|
104
110
|
if (taskId && outcome.failure && ["agent.send", "tool.call"].includes(operation)) {
|
|
105
111
|
const details = outcome.failure.details;
|
|
106
|
-
|
|
112
|
+
const refused = ["TOOL_TASK_FAILED", "INSUFFICIENT_CREDITS"].includes(outcome.failure.code)
|
|
113
|
+
|| ["audit_rejected", "input_audit_rejected", "output_audit_rejected"].includes(details?.reason ?? "");
|
|
114
|
+
const recovery = { ...details, cli_task_id: taskId };
|
|
115
|
+
if (outcome.exitCode !== 2 && !refused && details?.phase !== "input_upload_before_dispatch") {
|
|
116
|
+
recovery.next_steps = [
|
|
107
117
|
...(details?.next_steps ?? []),
|
|
108
118
|
`${options.product?.commandName ?? "gd-cli"} task get ${taskId}`,
|
|
109
|
-
options.product?.id === "insmind"
|
|
110
|
-
|
|
111
|
-
|
|
119
|
+
options.product?.id === "insmind"
|
|
120
|
+
? "If the outcome is still unknown, tell the user and keep this ID for recovery. Do not start another creation."
|
|
121
|
+
: "原任务结果仍未知时,向用户说明并保留此 ID 供取回。不要另发创作。"
|
|
122
|
+
];
|
|
123
|
+
}
|
|
124
|
+
outcome.failure.details = recovery;
|
|
112
125
|
}
|
|
113
126
|
const telemetryError = classifyTelemetryError(error, { aborted: isInterruption(error, options.signal),
|
|
114
127
|
operation: options.telemetry.creationContext().operation, failureStage: options.telemetry.failureStage(error), ...(options.product ? { product: options.product } : {}) });
|
|
@@ -129,6 +142,9 @@ export async function executeCli(options) {
|
|
|
129
142
|
}
|
|
130
143
|
if (errorDelivered)
|
|
131
144
|
await outputs.get(options.program)?.tasks.outputCompleted(error);
|
|
145
|
+
if (errorDelivered && automaticNotice && outcome.exitCode === 1 && definition.operation !== "unknown") {
|
|
146
|
+
await checkUpdateNotification(options.updateNotification, options.signal, "machine");
|
|
147
|
+
}
|
|
132
148
|
await sendFinished(options, outcome.kind === "interrupted"
|
|
133
149
|
? { outcome: "interrupted", error }
|
|
134
150
|
: {
|
|
@@ -149,9 +165,9 @@ export async function executeCli(options) {
|
|
|
149
165
|
return outcome.exitCode;
|
|
150
166
|
}
|
|
151
167
|
}
|
|
152
|
-
async function checkUpdateNotification(updateNotification, signal) {
|
|
168
|
+
async function checkUpdateNotification(updateNotification, signal, output) {
|
|
153
169
|
try {
|
|
154
|
-
await updateNotification.check(signal);
|
|
170
|
+
await updateNotification.check(signal, output);
|
|
155
171
|
}
|
|
156
172
|
catch {
|
|
157
173
|
// Version availability must never change the requested command outcome.
|
|
@@ -1,12 +1,16 @@
|
|
|
1
|
+
import { canvasModelBindings } from "../features/tool/canvas-models.js";
|
|
1
2
|
import { createWindAnalytics } from "../analytics/wind.js";
|
|
2
3
|
import { taskScope } from "../features/task/store.js";
|
|
4
|
+
import { noticeWriter, sameTerminal } from "../features/update/notice-output.js";
|
|
3
5
|
import { createTextOutput } from "../platform/text-output.js";
|
|
4
6
|
import { TaskNotFoundError } from "../features/task/use-cases.js";
|
|
5
7
|
import { homedir } from "node:os";
|
|
6
8
|
import { createTaskBackgroundLauncher, TaskBackgroundError } from "../features/task/task-background.js";
|
|
7
9
|
import { createTaskStore } from "../features/task/store.js";
|
|
8
|
-
import { createTaskUseCases } from "../features/task/use-cases.js";
|
|
10
|
+
import { createTaskUseCases, taskStartedNotice } from "../features/task/use-cases.js";
|
|
9
11
|
import { readAgentResult } from "../features/agent/result-reader.js";
|
|
12
|
+
import { createToolOutputVerifier, presentToolContent } from "../features/tool/tool-output.js";
|
|
13
|
+
import { RemoteProtocolError } from "../platform/remote-protocol.js";
|
|
10
14
|
import { queryToolResult, ToolTaskFailedError, ToolTaskCanceledError } from "../features/tool/tool-api-adapter.js";
|
|
11
15
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
12
16
|
import { dirname, join } from "node:path";
|
|
@@ -188,7 +192,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
188
192
|
});
|
|
189
193
|
const org = createOrgUseCases({
|
|
190
194
|
store,
|
|
191
|
-
org: createOrgService({ transport: orgTransport }),
|
|
195
|
+
org: createOrgService({ transport: orgTransport, onPartial: count => partialWarning("ORG_LIST_PARTIAL", `有 ${count} 条组织记录无法读取,已返回可确认的组织。`, `${count} organization record(s) could not be read.`) }),
|
|
192
196
|
sso,
|
|
193
197
|
telemetry,
|
|
194
198
|
...(product.exposesOrganizations
|
|
@@ -213,7 +217,9 @@ export function createProductionRuntime(options = {}) {
|
|
|
213
217
|
});
|
|
214
218
|
const credits = createCreditsUseCases({
|
|
215
219
|
transport: creditsTransport,
|
|
216
|
-
|
|
220
|
+
onPartial: () => partialWarning("CREDITS_RECORDS_PARTIAL", "部分账单记录或可选字段无法表示,已返回可确认的流水;不要据此推算完整账单。", "Some billing records or optional fields could not be represented. Known records are included; do not infer a complete bill."),
|
|
221
|
+
billingUnit: product.billingUnit,
|
|
222
|
+
now
|
|
217
223
|
});
|
|
218
224
|
const storageUpload = createDamStorageUploader({
|
|
219
225
|
transport: damTransport,
|
|
@@ -225,6 +231,10 @@ export function createProductionRuntime(options = {}) {
|
|
|
225
231
|
writeError: io.writeError,
|
|
226
232
|
product
|
|
227
233
|
});
|
|
234
|
+
function partialWarning(code, zh, en) {
|
|
235
|
+
telemetry.annotate({ warning_codes: [code] });
|
|
236
|
+
presenter.warning(text(zh, en));
|
|
237
|
+
}
|
|
228
238
|
const browser = createBrowserOpener();
|
|
229
239
|
const validators = createContractValidators({
|
|
230
240
|
organizations: product.exposesOrganizations
|
|
@@ -236,8 +246,15 @@ export function createProductionRuntime(options = {}) {
|
|
|
236
246
|
? { invalidModelWarning: (count) => `Ignored ${count} invalid model configuration${count === 1 ? "" : "s"}.` }
|
|
237
247
|
: {})
|
|
238
248
|
}) });
|
|
239
|
-
const damApi = createDamApiAdapter({
|
|
240
|
-
|
|
249
|
+
const damApi = createDamApiAdapter({
|
|
250
|
+
transport: damTransport,
|
|
251
|
+
onPartial: count => partialWarning("DAM_LIST_PARTIAL", `有 ${count} 条素材库记录无法表示,已返回其余记录。`, `${count} unreadable record(s); the other records are included.`),
|
|
252
|
+
onPaginationFallback: () => partialWarning("DAM_PAGINATION_INCOMPLETE", "服务未提供完整分页信息;缺失的总数或结束标记按本页结果推导。", "The service omitted pagination information; a missing total or end marker was inferred from this page.")
|
|
253
|
+
});
|
|
254
|
+
const damRepositories = createDamRepositoryCatalog({ transport: damTransport, onPartial: source => {
|
|
255
|
+
const label = source === "team" ? "团队" : source === "personal" ? "个人" : "企业";
|
|
256
|
+
partialWarning("DAM_REPOSITORIES_PARTIAL", `${label}库来源或其中部分记录无法读取,已列出可确认的资源库。`, `The ${source} repository source was unavailable or incomplete. Known repositories are included.`);
|
|
257
|
+
} });
|
|
241
258
|
const damOperations = createDamOperationExecutor({
|
|
242
259
|
now: () => now().getTime(),
|
|
243
260
|
sleep: async (milliseconds, signal) => {
|
|
@@ -290,7 +307,14 @@ export function createProductionRuntime(options = {}) {
|
|
|
290
307
|
traceparent: () => telemetry.traceparent(),
|
|
291
308
|
...(businessHeaders ? { businessHeaders } : {})
|
|
292
309
|
}) });
|
|
293
|
-
const
|
|
310
|
+
const onPartialResourceFailure = (error) => {
|
|
311
|
+
if (!(error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
|
|
312
|
+
|| !["RESOURCE_AUTH_REQUEST_FAILED", "RESOURCE_AUTH_INVALID_RESPONSE"].includes(error.diagnosticReason ?? ""))
|
|
313
|
+
return false;
|
|
314
|
+
partialWarning("RESOURCE_AUTH_PARTIAL", "部分私有资源链接尚未取得访问授权;已保留原链接及其他可用内容,请使用原任务再次取件,不要重做。", "Some private links could not be authorized. The original links and other content are included. Query the same task; do not resubmit.");
|
|
315
|
+
return true;
|
|
316
|
+
};
|
|
317
|
+
const resourceAuthorizer = createAgentResourceAuthorizer({ authKeys: resourceAuthKeys, onPartialResourceFailure });
|
|
294
318
|
const accessPolicies = createAccessPolicies({ store, now, refreshCurrentOrganization: org.refreshCurrentOrganization });
|
|
295
319
|
const authorizeTaskAccess = async (state, signal) => {
|
|
296
320
|
await telemetry.stage("access", async () => {
|
|
@@ -302,24 +326,59 @@ export function createProductionRuntime(options = {}) {
|
|
|
302
326
|
}
|
|
303
327
|
});
|
|
304
328
|
};
|
|
305
|
-
const authorizeTaskResult = async (result, state, signal,
|
|
329
|
+
const authorizeTaskResult = async (result, state, signal, source = "stored") => {
|
|
306
330
|
if ("message" in result)
|
|
307
331
|
validators.agentSendOutput(result);
|
|
308
332
|
else
|
|
309
333
|
validators.toolCallOutput(result);
|
|
310
334
|
// Bind only if this result actually needs a fresh resource token.
|
|
311
|
-
const taskAuthorizer = createAgentResourceAuthorizer({
|
|
335
|
+
const taskAuthorizer = createAgentResourceAuthorizer({
|
|
336
|
+
onPartialResourceFailure,
|
|
337
|
+
// Re-reading an existing result can repair an expired official link without probing anyone's URLs.
|
|
338
|
+
...(source !== "upstream" ? { onSignedRefreshFailure(error) {
|
|
339
|
+
if (!(error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
|
|
340
|
+
|| !["RESOURCE_AUTH_REQUEST_FAILED", "RESOURCE_AUTH_INVALID_RESPONSE"].includes(error.diagnosticReason ?? ""))
|
|
341
|
+
return false;
|
|
342
|
+
telemetry.annotate({ warning_codes: ["TASK_RESOURCE_REFRESH_UNAVAILABLE"] });
|
|
343
|
+
presenter.warning(text("资源授权暂未更新,已返回原签名链接;如仍无法打开,请稍后用原任务 ID 查询。", "The resource key could not be refreshed. The original signed URL is included; if it cannot be opened, query the same task ID later."));
|
|
344
|
+
return true;
|
|
345
|
+
} } : {}),
|
|
346
|
+
authKeys: {
|
|
312
347
|
async getAuthKey(access, tokenSignal) {
|
|
313
|
-
if (
|
|
348
|
+
if (source === "stored")
|
|
314
349
|
await authorizeTaskAccess(state, tokenSignal);
|
|
315
350
|
return resourceAuthKeys.getAuthKey(access, tokenSignal);
|
|
316
351
|
}
|
|
317
|
-
}
|
|
352
|
+
}
|
|
353
|
+
});
|
|
318
354
|
const access = { credential: state.credential, organizationId: state.organization.id };
|
|
319
355
|
if ("message" in result)
|
|
320
356
|
return taskAuthorizer.authorize(result, access, signal);
|
|
321
357
|
return authorizeToolResources(result, taskAuthorizer, access, signal);
|
|
322
358
|
};
|
|
359
|
+
const canvasMedia = (access) => createCanvasMedia({ fetch, uploader: transientUploader,
|
|
360
|
+
...(access ? { filems: { access, authKeys: resourceAuthKeys } } : {}) });
|
|
361
|
+
const onMissingMedia = (kind) => {
|
|
362
|
+
telemetry.annotate({ warning_codes: ["TOOL_EXPECTED_MEDIA_UNIDENTIFIED"] });
|
|
363
|
+
presenter.warning(text(`已交付服务返回的内容,未发现明确标记为${kind === "video" ? "视频" : "图片"}的资源;请按实际内容交付,勿重新提交。`, `The returned content is included. No resource was identified as ${kind}; report what was received and do not resubmit.`));
|
|
364
|
+
};
|
|
365
|
+
const onUnrepresented = () => {
|
|
366
|
+
telemetry.annotate({ warning_codes: ["TOOL_PART_UNREPRESENTABLE"] });
|
|
367
|
+
presenter.warning(text("已返回可表示的内容,另有无法读取的附件。", "The representable content is included; another attachment could not be read."));
|
|
368
|
+
};
|
|
369
|
+
const verifyToolOutput = createToolOutputVerifier(resourceAuthorizer, onMissingMedia);
|
|
370
|
+
const canvasTools = createCanvasToolAdapter({
|
|
371
|
+
transport: toolTransport, recordTransport: damTransport, resourceAuthorizer, telemetry, media: canvasMedia, onMissingMedia, onUnrepresented, english: product.id === "insmind",
|
|
372
|
+
fallback: createToolApiAdapter({ transport: toolTransport, telemetry, onUnrepresented, verifyOutput: verifyToolOutput }),
|
|
373
|
+
standardMatting: createStandardMatting({ transport: toolTransport, recordTransport: damTransport, media: canvasMedia() })
|
|
374
|
+
});
|
|
375
|
+
const taskFailureNote = (error, operation = telemetry.creationContext().operation) => {
|
|
376
|
+
const outcome = mapCliError(error, { aborted: false, product, operation, failureStage: telemetry.failureStage(error) });
|
|
377
|
+
if (outcome.kind !== "failure")
|
|
378
|
+
return "";
|
|
379
|
+
const details = outcome.failure.details;
|
|
380
|
+
return [outcome.failure.message, details?.remote_code, details?.remote_message].filter(Boolean).join(" ");
|
|
381
|
+
};
|
|
323
382
|
const tasks = createTaskUseCases({
|
|
324
383
|
telemetry,
|
|
325
384
|
...(analytics ? { analytics } : {}),
|
|
@@ -333,6 +392,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
333
392
|
store: createTaskStore({
|
|
334
393
|
...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {}),
|
|
335
394
|
stateDirectory: product.stateDirectory,
|
|
395
|
+
onUnreadableRecords: count => partialWarning("TASK_LIST_PARTIAL", `有 ${count} 条本地任务记录无法读取,已列出可读取的记录。`, `${count} local task record(s) could not be read. Readable records are included.`),
|
|
336
396
|
validateSummary: task => validators.taskListResult({ tasks: [task] }),
|
|
337
397
|
validate: validators.taskResult
|
|
338
398
|
}),
|
|
@@ -342,12 +402,19 @@ export function createProductionRuntime(options = {}) {
|
|
|
342
402
|
warning: message => presenter.warning(message),
|
|
343
403
|
commandName: product.commandName,
|
|
344
404
|
text,
|
|
345
|
-
failureNote:
|
|
346
|
-
const outcome = mapCliError(error, { aborted: false, product, operation: telemetry.creationContext().operation, failureStage: telemetry.failureStage(error) });
|
|
347
|
-
return outcome.kind === "failure" ? outcome.failure.message : "";
|
|
348
|
-
},
|
|
405
|
+
failureNote: taskFailureNote,
|
|
349
406
|
recovery: {
|
|
350
|
-
authorize
|
|
407
|
+
async authorize(result, state, signal, progress) {
|
|
408
|
+
const authorized = await authorizeTaskResult(result, state, signal);
|
|
409
|
+
const tool = progress?.generation?.tool ?? canvasModelBindings.find(binding => binding[1] === progress?.toolPipeline?.model)?.[0];
|
|
410
|
+
if ("content" in authorized && tool && tool !== "image.ocr" && tool !== "image.layers") {
|
|
411
|
+
if (tool.startsWith("video."))
|
|
412
|
+
presentToolContent(authorized.content, "video", onMissingMedia);
|
|
413
|
+
else if (tool.startsWith("image."))
|
|
414
|
+
presentToolContent(authorized.content, "image", onMissingMedia);
|
|
415
|
+
}
|
|
416
|
+
return authorized;
|
|
417
|
+
},
|
|
351
418
|
async agent(progress, state, signal) {
|
|
352
419
|
if (!progress.contextId || !progress.localMessageId)
|
|
353
420
|
return {
|
|
@@ -359,14 +426,18 @@ export function createProductionRuntime(options = {}) {
|
|
|
359
426
|
credential: state.credential, organizationId: state.organization.id, signal
|
|
360
427
|
});
|
|
361
428
|
return { state: "unknown",
|
|
429
|
+
...(snapshot.usageAmountMissing ? { usageAmountMissing: true } : {}),
|
|
362
430
|
...(snapshot.usageModelMissing ? { usageModelMissing: true } : {}),
|
|
363
431
|
note: snapshot.partialResult
|
|
364
432
|
? text("已找到部分内容,尚未取得完整结果。", "Some content was found, but the complete result has not been received.")
|
|
365
433
|
: text("尚未取得任务结果。", "The task result has not been received."),
|
|
366
|
-
...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal,
|
|
434
|
+
...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal, "upstream") } : {})
|
|
367
435
|
};
|
|
368
436
|
},
|
|
369
437
|
async tool(progress, state, signal) {
|
|
438
|
+
// Never interpret an unpublished candidate's Run receipt as a Dify task.
|
|
439
|
+
if (Object.hasOwn(progress, "toolRun"))
|
|
440
|
+
return { state: "unknown", note: text("该实验版本任务不支持继续远端查询。请保留原任务记录用于排查,不要重复提交。", "Remote recovery is unavailable for this experimental task. Keep its original record for diagnosis; do not resubmit.") };
|
|
370
441
|
if (progress.toolPipeline) {
|
|
371
442
|
const pipeline = progress.toolPipeline;
|
|
372
443
|
await authorizeTaskAccess(state, signal);
|
|
@@ -374,7 +445,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
374
445
|
try {
|
|
375
446
|
recovered = await telemetry.stage("task.query", () => recoverCanvasTool(progress, {
|
|
376
447
|
access: { credential: state.credential, organizationId: state.organization.id }, signal
|
|
377
|
-
}, { transport: toolTransport, media: canvasMedia, english: product.id === "insmind" }));
|
|
448
|
+
}, { transport: toolTransport, onMissingMedia, onUnrepresented, media: canvasMedia({ credential: state.credential, organizationId: state.organization.id }), english: product.id === "insmind" }));
|
|
378
449
|
}
|
|
379
450
|
catch (error) {
|
|
380
451
|
if (!(error instanceof ToolTaskFailedError) && !(error instanceof ToolTaskCanceledError))
|
|
@@ -382,17 +453,18 @@ export function createProductionRuntime(options = {}) {
|
|
|
382
453
|
const outcome = mapCliError(error, { aborted: false, product, operation: "task.get", failureStage: "task.query" });
|
|
383
454
|
return { state: "failed", note: outcome.failure?.message ?? text("本次处理未能完成。", "This processing could not be completed."), failure: error };
|
|
384
455
|
}
|
|
456
|
+
const source = "fromCheckpoint" in recovered && recovered.fromCheckpoint ? "checkpoint" : "upstream";
|
|
385
457
|
if (recovered.state === "complete" && progress.toolUsage)
|
|
386
458
|
return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
|
|
387
459
|
content: recovered.content, usage: progress.toolUsage
|
|
388
|
-
}, product.billingUnit), state, signal,
|
|
460
|
+
}, product.billingUnit), state, signal, source) };
|
|
389
461
|
if (recovered.state === "pending")
|
|
390
462
|
return { state: "running", note: text("任务仍在处理中。", "The task is still processing.") };
|
|
391
463
|
const partialContent = recovered.state === "unknown" ? recovered.content : undefined;
|
|
392
464
|
return { state: "unknown", note: text(`处理停留在 ${pipeline.stage} 阶段,尚未交付完整结果。查询不会重新处理、上传或结算;请保留任务 ID 排查,勿重复提交。`, `Processing reached ${pipeline.stage}; no complete result was delivered. Querying does not process, upload, or settle again. Keep the task ID for diagnosis; do not resubmit.`),
|
|
393
465
|
...(partialContent && progress.toolUsage ? { partialResult: await authorizeTaskResult(toolOutputWithBillingUnit({
|
|
394
466
|
content: partialContent, usage: progress.toolUsage
|
|
395
|
-
}, product.billingUnit), state, signal,
|
|
467
|
+
}, product.billingUnit), state, signal, source) } : {}) };
|
|
396
468
|
}
|
|
397
469
|
if (!progress.remoteTaskId || !progress.toolUsage)
|
|
398
470
|
return {
|
|
@@ -404,7 +476,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
404
476
|
try {
|
|
405
477
|
response = await telemetry.stage("task.query", async () => {
|
|
406
478
|
const result = await queryToolResult(toolTransport, {
|
|
407
|
-
taskId, credential: state.credential, organizationId: state.organization.id, signal,
|
|
479
|
+
taskId, credential: state.credential, organizationId: state.organization.id, signal, onUnrepresented,
|
|
408
480
|
onDifyTaskId: id => telemetry.annotate({ dify_task_id: id })
|
|
409
481
|
});
|
|
410
482
|
if (result.difyTaskId)
|
|
@@ -423,8 +495,8 @@ export function createProductionRuntime(options = {}) {
|
|
|
423
495
|
if (response.state === "pending")
|
|
424
496
|
return { state: "running", note: text("任务仍在处理中。", "The task is still processing.") };
|
|
425
497
|
return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
|
|
426
|
-
content: response.content, usage: progress.toolUsage
|
|
427
|
-
}, product.billingUnit), state, signal,
|
|
498
|
+
content: await verifyToolOutput(response.content, progress.generation?.tool === "video.generate" ? "video" : "image", { access: { credential: state.credential, organizationId: state.organization.id }, signal }), usage: progress.toolUsage
|
|
499
|
+
}, product.billingUnit), state, signal, "upstream") };
|
|
428
500
|
}
|
|
429
501
|
}
|
|
430
502
|
});
|
|
@@ -438,19 +510,17 @@ export function createProductionRuntime(options = {}) {
|
|
|
438
510
|
}),
|
|
439
511
|
telemetry
|
|
440
512
|
}), product.billingUnit);
|
|
441
|
-
const canvasMedia = createCanvasMedia({ fetch, uploader: transientUploader });
|
|
442
513
|
const tool = withToolBillingUnit(createToolUseCases({
|
|
443
514
|
catalog: modelCatalog,
|
|
444
515
|
tools: product.tools,
|
|
445
516
|
...(product.id === "insmind" ? { modelDescription: "Model machine identifier from model list." } : {}),
|
|
446
|
-
execution:
|
|
447
|
-
fallback: createToolApiAdapter({ transport: toolTransport, telemetry }),
|
|
448
|
-
standardMatting: createStandardMatting({ transport: toolTransport, recordTransport: damTransport, media: canvasMedia }) }),
|
|
517
|
+
execution: canvasTools,
|
|
449
518
|
uploader: transientUploader,
|
|
450
519
|
warn: (message) => { presenter.warning(message); },
|
|
451
520
|
telemetry
|
|
452
521
|
}), product.billingUnit);
|
|
453
522
|
const editor = createEditorUseCases({
|
|
523
|
+
onPartial: count => partialWarning("EDITOR_SNAPSHOT_PARTIAL", `有 ${count} 个元素无法表示,已返回其余元素。`, `${count} unsupported element(s); the other elements are included.`),
|
|
454
524
|
session: createEditorSession({
|
|
455
525
|
store: createEditorSessionStateStore({
|
|
456
526
|
...(options.homeDirectory === undefined
|
|
@@ -504,7 +574,8 @@ export function createProductionRuntime(options = {}) {
|
|
|
504
574
|
installationOwner,
|
|
505
575
|
...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {}),
|
|
506
576
|
...(options.env ? { env: options.env } : {}),
|
|
507
|
-
|
|
577
|
+
diagnosticOnly: !io.stderrTerminal && env.CLI_UPDATE_NOTICE_FORMAT !== "offer",
|
|
578
|
+
notify: noticeWriter(stdout, stderr, sameTerminal(rawIo.stdout, rawIo.stderr), env.CLI_UPDATE_NOTICE_FORMAT === "offer", text("提示: ", "Notice: ")),
|
|
508
579
|
...(product.id === "insmind" ? {
|
|
509
580
|
stateDirectoryName: product.stateDirectory,
|
|
510
581
|
registryUrl: `https://registry.npmjs.org/${encodeURIComponent(product.npmPackage)}`,
|
|
@@ -530,11 +601,13 @@ export function createProductionRuntime(options = {}) {
|
|
|
530
601
|
telemetryEnvironment, telemetryVersion: options.telemetryVersion ?? primarySkill.version, origin: telemetry.creationContext(),
|
|
531
602
|
telemetryTrackingUrl: String(options.telemetryTrackingUrl ?? product.telemetryUrl),
|
|
532
603
|
locale: locale.locale, endpoints: Object.fromEntries(Object.entries(endpoints).map(([key, value]) => [key, String(value)]))
|
|
533
|
-
}, signal, task => {
|
|
604
|
+
}, signal, (task, creationTraceId) => {
|
|
534
605
|
startedId = task.taskId;
|
|
606
|
+
if (creationTraceId)
|
|
607
|
+
telemetry.annotate({ creation_trace_id: creationTraceId });
|
|
535
608
|
telemetry.annotate({ cli_task_id: task.taskId, execution_mode: "async", result_state: task.state });
|
|
536
|
-
presenter.notice(
|
|
537
|
-
});
|
|
609
|
+
presenter.notice(taskStartedNotice(task.taskId, product.commandName, "async", text));
|
|
610
|
+
}, facts => telemetry.annotate(facts));
|
|
538
611
|
}
|
|
539
612
|
catch (error) {
|
|
540
613
|
if (startedId)
|
|
@@ -8,7 +8,9 @@ export async function runTaskWorker(options) {
|
|
|
8
8
|
const { job, signal, send } = options;
|
|
9
9
|
runtime.telemetry.useSignal(signal);
|
|
10
10
|
runtime.telemetry.select({ operation: job.operation, mode: () => "execute" });
|
|
11
|
-
runtime.telemetry.annotate({ ...(job.origin ? {
|
|
11
|
+
runtime.telemetry.annotate({ ...(job.origin ? { host_application: job.origin.host_application ?? "unknown" } : {}),
|
|
12
|
+
...(job.origin ? { creation_trace_id: job.origin.trace_id } : {}),
|
|
13
|
+
account_id: job.state.account?.id, organization_id: job.state.organization.id,
|
|
12
14
|
parameters: { ...job.input }, execution_mode: "async" });
|
|
13
15
|
let completion = { outcome: "success" };
|
|
14
16
|
let started = false;
|
|
@@ -21,6 +23,7 @@ export async function runTaskWorker(options) {
|
|
|
21
23
|
runtime.validators.toolCallInput(job.input);
|
|
22
24
|
await runtime.tasks.track({
|
|
23
25
|
state: job.state,
|
|
26
|
+
signal,
|
|
24
27
|
operation: job.operation,
|
|
25
28
|
label: job.label,
|
|
26
29
|
executionMode: "async",
|
|
@@ -32,7 +35,8 @@ export async function runTaskWorker(options) {
|
|
|
32
35
|
}
|
|
33
36
|
if ((progress.accepted || progress.remoteTaskId) && !accepted) {
|
|
34
37
|
accepted = true;
|
|
35
|
-
send({ type: "accepted", task
|
|
38
|
+
send({ type: "accepted", task,
|
|
39
|
+
...(job.operation === "tool.call" ? { execution_protocol: progress.toolPipeline?.protocol ?? "dify" } : {}) });
|
|
36
40
|
}
|
|
37
41
|
},
|
|
38
42
|
run: async (observe) => {
|
|
@@ -3,7 +3,7 @@ import { canonicalizeInputFileUris } from "../platform/input-uri.js";
|
|
|
3
3
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
4
4
|
import addFormatsImport, {} from "ajv-formats";
|
|
5
5
|
import { agentInputSchema } from "../contracts/creation-input.js";
|
|
6
|
-
import { contractSchema } from "../contracts/schema.js";
|
|
6
|
+
import { contractDocument, contractSchema } from "../contracts/schema.js";
|
|
7
7
|
const agentSendOutputSchema = contractSchema("agent.send", "output");
|
|
8
8
|
const authStatusSchema = contractSchema("auth.status", "output");
|
|
9
9
|
const damDeleteInputSchema = contractSchema("dam.delete", "input");
|
|
@@ -123,6 +123,9 @@ export function createContractValidators(options = {}) {
|
|
|
123
123
|
const taskResult = ajv.compile(runOutputSchema);
|
|
124
124
|
const taskListResult = ajv.compile(contractSchema("task.list", "output"));
|
|
125
125
|
return {
|
|
126
|
+
creditsOutput: assertion(ajv.compile(contractSchema("credits.get", "output")), OutputContractError),
|
|
127
|
+
creditsUsageListOutput: assertion(ajv.compile(contractSchema("credits.usage.list", "output")), OutputContractError),
|
|
128
|
+
creditsUsageGetOutput: assertion(ajv.compile(contractSchema("credits.usage.get", "output")), OutputContractError),
|
|
126
129
|
taskResult: assertion(taskResult, OutputContractError),
|
|
127
130
|
taskListResult: assertion(taskListResult, OutputContractError),
|
|
128
131
|
agentSendInput: assertion(agentSendInput, InputContractError),
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { identifyInvocation } from "../telemetry/command-route.js";
|
|
1
2
|
import { jsonErrorsRequested } from "../platform/error-output-mode.js";
|
|
2
3
|
const environments = new WeakMap();
|
|
3
4
|
const boundPolicies = new WeakMap();
|
|
4
5
|
const jsonCommands = new WeakSet();
|
|
5
6
|
const selectedCommands = new WeakMap();
|
|
7
|
+
const commandDefinitions = new WeakMap();
|
|
6
8
|
/** Declare the existing fixed JSON contract alongside the command registration. */
|
|
7
9
|
export function jsonOutput(command) {
|
|
8
10
|
jsonCommands.add(command);
|
|
@@ -15,7 +17,7 @@ export function errorUsesJson(program, argv) {
|
|
|
15
17
|
return true;
|
|
16
18
|
const command = selectedCommands.get(program);
|
|
17
19
|
if (command)
|
|
18
|
-
return jsonCommands.has(command) || command.
|
|
20
|
+
return jsonCommands.has(command) || command.optsWithGlobals().json === true;
|
|
19
21
|
return jsonErrorsRequested(argv);
|
|
20
22
|
}
|
|
21
23
|
export function configureActionEnvironment(program, environment) {
|
|
@@ -30,7 +32,6 @@ export function bindAction(command, policy, handler, telemetry) {
|
|
|
30
32
|
const environment = environments.get(rootCommand(command));
|
|
31
33
|
if (!environment)
|
|
32
34
|
throw new Error("CLI action environment is missing.");
|
|
33
|
-
await checkUpdateNotification(environment, telemetry);
|
|
34
35
|
const context = await environment.telemetry.stage("access", async () => {
|
|
35
36
|
const authorized = await environment.policies[policy].authorize(environment.signal);
|
|
36
37
|
if (authorized.policy !== policy) {
|
|
@@ -51,7 +52,6 @@ export function bindPreparedAction(command, policy, prepare, run, telemetry) {
|
|
|
51
52
|
const environment = environments.get(rootCommand(command));
|
|
52
53
|
if (!environment)
|
|
53
54
|
throw new Error("CLI action environment is missing.");
|
|
54
|
-
await checkUpdateNotification(environment, telemetry);
|
|
55
55
|
const prepared = await environment.telemetry.stage("input", () => prepare(environment.signal));
|
|
56
56
|
if (prepared.handled)
|
|
57
57
|
return;
|
|
@@ -66,16 +66,6 @@ export function bindPreparedAction(command, policy, prepare, run, telemetry) {
|
|
|
66
66
|
await run(context, prepared.input, environment.signal);
|
|
67
67
|
});
|
|
68
68
|
}
|
|
69
|
-
async function checkUpdateNotification(environment, telemetry) {
|
|
70
|
-
if (telemetry?.operation === "update")
|
|
71
|
-
return;
|
|
72
|
-
try {
|
|
73
|
-
await environment.updateNotification.check(environment.signal);
|
|
74
|
-
}
|
|
75
|
-
catch {
|
|
76
|
-
// Version availability must never change the requested command outcome.
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
69
|
export function assertAllLeafCommandsBound(program) {
|
|
80
70
|
for (const command of leafCommands(program)) {
|
|
81
71
|
if (!boundPolicies.has(command)) {
|
|
@@ -96,6 +86,7 @@ function rootCommand(command) {
|
|
|
96
86
|
}
|
|
97
87
|
function bindTelemetrySelection(command, definition) {
|
|
98
88
|
definition ??= { operation: commandPath(command).split(" ").slice(1).join(".") };
|
|
89
|
+
commandDefinitions.set(command, definition);
|
|
99
90
|
if (!command.parent)
|
|
100
91
|
throw new Error(`Telemetry command has no parent: ${command.name()}`);
|
|
101
92
|
command.parent.hook("preSubcommand", (parent, selected) => {
|
|
@@ -116,44 +107,20 @@ function annotateAccessContext(telemetry, context) {
|
|
|
116
107
|
organization_id: context.state.organization?.id
|
|
117
108
|
});
|
|
118
109
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
let command = program;
|
|
122
|
-
let unknown = false;
|
|
123
|
-
let mode = "execute";
|
|
124
|
-
for (let i = 0; i < argv.length; i++) {
|
|
125
|
-
const token = argv[i];
|
|
126
|
-
if (token === "--")
|
|
127
|
-
break;
|
|
128
|
-
if (token === "-h" || token === "--help") {
|
|
129
|
-
mode = "help";
|
|
130
|
-
continue;
|
|
131
|
-
}
|
|
132
|
-
if (token === "-V" || token === "--version") {
|
|
133
|
-
mode = "version";
|
|
134
|
-
continue;
|
|
135
|
-
}
|
|
136
|
-
if (token.startsWith("-")) {
|
|
137
|
-
const flag = token.split("=")[0];
|
|
138
|
-
const option = [...command.options, ...program.options].find(item => item.long === flag || item.short === flag);
|
|
139
|
-
if (option?.long === "--schema" && mode === "execute")
|
|
140
|
-
mode = "schema";
|
|
141
|
-
if (option?.required && !token.includes("="))
|
|
142
|
-
i++;
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
if (command.commands.length) {
|
|
146
|
-
const child = command.commands.find(item => item.name() === token || item.aliases().includes(token));
|
|
147
|
-
if (!child) {
|
|
148
|
-
unknown = true;
|
|
149
|
-
break;
|
|
150
|
-
}
|
|
151
|
-
command = child;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
110
|
+
export function commandRoute(command) {
|
|
111
|
+
const definition = commandDefinitions.get(command);
|
|
154
112
|
const path = commandPath(command).split(" ").slice(1).join(".");
|
|
155
|
-
const
|
|
156
|
-
|
|
113
|
+
const children = Object.create(null);
|
|
114
|
+
for (const child of command.commands) {
|
|
115
|
+
const route = commandRoute(child);
|
|
116
|
+
for (const name of [child.name(), ...child.aliases()])
|
|
117
|
+
children[name] = route;
|
|
118
|
+
}
|
|
119
|
+
return { operation: definition?.operation ?? (path || "unknown"), action: !!definition,
|
|
120
|
+
options: command.options.map(option => option.flags), children };
|
|
121
|
+
}
|
|
122
|
+
export function invocationDefinition(program, argv) {
|
|
123
|
+
return identifyInvocation(commandRoute(program), argv);
|
|
157
124
|
}
|
|
158
125
|
function commandPath(command) {
|
|
159
126
|
const names = [];
|