@insmind/cli 1.7.1 → 1.9.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/contracts/operations/model.get/input.schema.json +5 -0
- package/contracts/operations/model.get/output.schema.json +9 -1
- package/contracts/operations/tool.call/canvas-input.schema.json +60 -0
- package/contracts/operations/tool.call/models/image-edit-smart.schema.json +39 -0
- package/contracts/operations/tool.call/models/image-edit-standard.schema.json +31 -0
- package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +26 -0
- package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +25 -0
- package/contracts/operations/tool.call/models/image-expand-smart.schema.json +72 -0
- package/contracts/operations/tool.call/models/image-expand-standard.schema.json +58 -0
- package/contracts/operations/tool.call/models/image-layers-layout.schema.json +20 -0
- package/contracts/operations/tool.call/models/image-layers-smart.schema.json +26 -0
- package/contracts/operations/tool.call/models/image-matting-smart.schema.json +34 -0
- package/contracts/operations/tool.call/models/image-matting-standard.schema.json +24 -0
- package/contracts/operations/tool.call/models/image-ocr.schema.json +20 -0
- package/contracts/operations/tool.call/models/image-remove-smart.schema.json +30 -0
- package/contracts/operations/tool.call/models/image-remove-standard.schema.json +25 -0
- package/contracts/operations/tool.call/models/image-text-edit.schema.json +43 -0
- package/contracts/operations/tool.call/models/image-vectorize.schema.json +20 -0
- package/contracts/operations/tool.call/models/video-edit-smart.schema.json +68 -0
- package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +32 -0
- package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +26 -0
- package/contracts/operations/tool.call/ocr-payload.schema.json +65 -0
- package/contracts/operations/tool.call/output.schema.json +38 -0
- package/contracts/operations/tool.call/template-payload.schema.json +95 -0
- package/dist/src/bootstrap/create-runtime.js +61 -25
- package/dist/src/bootstrap/validators.js +1 -1
- package/dist/src/cli/action-binding.js +3 -0
- package/dist/src/cli/agent-commands.js +1 -0
- package/dist/src/cli/errors.js +43 -10
- package/dist/src/cli/model-commands.js +7 -4
- package/dist/src/cli/observed-errors.js +13 -5
- package/dist/src/cli/task-commands.js +1 -1
- package/dist/src/cli/tool-commands.js +3 -1
- package/dist/src/contracts/schema.js +4 -1
- package/dist/src/features/agent/creative-protocol.js +22 -5
- package/dist/src/features/agent/resource-authorizer.js +1 -0
- package/dist/src/features/agent/use-cases.js +15 -5
- package/dist/src/features/auth/sso-service.js +13 -4
- package/dist/src/features/dam/dam-api-adapter.js +1 -0
- package/dist/src/features/dam/file-downloader.js +23 -2
- package/dist/src/features/task/store.js +8 -4
- package/dist/src/features/task/use-cases.js +14 -11
- package/dist/src/features/tool/canvas-copy.js +61 -0
- package/dist/src/features/tool/canvas-media.js +193 -0
- package/dist/src/features/tool/canvas-models.js +109 -0
- package/dist/src/features/tool/canvas-pricing.js +81 -0
- package/dist/src/features/tool/canvas-recovery.js +68 -0
- package/dist/src/features/tool/canvas-results.js +144 -0
- package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
- package/dist/src/features/tool/canvas-video.js +84 -0
- package/dist/src/features/tool/catalog.js +35 -13
- package/dist/src/features/tool/dynamic-schema.js +52 -23
- package/dist/src/features/tool/matting-billing.js +103 -0
- package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
- package/dist/src/features/tool/resource-authorizer.js +34 -0
- package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
- package/dist/src/features/tool/tool-api-adapter.js +24 -5
- package/dist/src/features/tool/use-cases.js +28 -3
- package/dist/src/features/update/update-service.js +4 -2
- package/dist/src/platform/file-lock.js +12 -0
- package/dist/src/platform/local-json-file.js +19 -5
- package/dist/src/platform/safe-upload-file.js +18 -10
- package/dist/src/platform/schema-issues.js +47 -2
- package/dist/src/platform/text-output.js +17 -4
- package/dist/src/product/config.js +12 -1
- package/dist/src/telemetry/failure-summary.js +18 -0
- package/package.json +5 -4
- package/skills/insmind-cli/SKILL.md +2 -0
- package/skills/insmind-cli/references/creation.md +2 -0
- package/skills/insmind-cli/references/generation-constraints.md +3 -1
- package/skills/insmind-cli/references/matting.md +29 -0
- package/skills/insmind-cli/references/media-tools.md +40 -0
- package/skills/insmind-cli/references/tool.md +2 -2
|
@@ -19,6 +19,8 @@ const messages = {
|
|
|
19
19
|
save: ["保存遇到问题,请在编辑器查看作品。", "There was a problem saving. Check the design in the editor."],
|
|
20
20
|
local: ["无法读取或保存本次操作记录。", "The record for this operation could not be read or saved."],
|
|
21
21
|
update: ["本次更新未完成。", "This update did not complete."],
|
|
22
|
+
managed_update: ["请在原应用中更新此工具。", "Update this tool in the app where it was installed."],
|
|
23
|
+
editor_required: ["请先打开作品并连接编辑器。", "Open a design and connect to the editor first."],
|
|
22
24
|
output: ["结果未能完整显示。", "The result could not be fully displayed."],
|
|
23
25
|
read: ["暂时无法读取结果。", "The result cannot be read right now."],
|
|
24
26
|
tool: ["本次生成未能完成。", "This creation could not be completed."],
|
|
@@ -50,7 +52,9 @@ export function observedErrorCategory(e) {
|
|
|
50
52
|
return "account";
|
|
51
53
|
if (e.code === "USAGE_ERROR" && e.errorType === "LocalFileInputError")
|
|
52
54
|
return "input_asset";
|
|
53
|
-
if (
|
|
55
|
+
if (gd && e.operation === "dam.rename" && e.remoteCode === "00010014")
|
|
56
|
+
return "file_exists";
|
|
57
|
+
if (["USAGE_ERROR", "INVALID_ACTIONS"].includes(e.code))
|
|
54
58
|
return "input";
|
|
55
59
|
if (gd && e.operation === "dam.upload" && e.remoteCode === "36002105")
|
|
56
60
|
return "upload";
|
|
@@ -64,7 +68,9 @@ export function observedErrorCategory(e) {
|
|
|
64
68
|
|| gd && ["dam.download", "dam.get", "dam.list", "dam.search"].includes(e.operation ?? "")
|
|
65
69
|
&& e.code === "REMOTE_REQUEST_FAILED" && [403, 404].includes(e.httpStatus ?? 0))
|
|
66
70
|
return "asset_read";
|
|
67
|
-
if (
|
|
71
|
+
if (e.code === "EDITOR_SESSION_NOT_FOUND")
|
|
72
|
+
return "editor_required";
|
|
73
|
+
if (["EDITOR_NOT_CONNECTED", "EDITOR_DISCONNECTED", "EDITOR_NOT_READY"].includes(e.code))
|
|
68
74
|
return "editor";
|
|
69
75
|
if (e.code === "UNSUPPORTED_PAGE_CONTENT")
|
|
70
76
|
return "unsupported";
|
|
@@ -72,14 +78,16 @@ export function observedErrorCategory(e) {
|
|
|
72
78
|
return "save";
|
|
73
79
|
if (e.code === "LOCAL_STATE_ERROR")
|
|
74
80
|
return "local";
|
|
81
|
+
if (e.code === "UPDATE_FAILED" && e.diagnosticReason === "UPDATE_MANAGED_BY_HOST")
|
|
82
|
+
return "managed_update";
|
|
75
83
|
if (e.code === "UPDATE_FAILED")
|
|
76
84
|
return "update";
|
|
77
|
-
if (e.code === "INTERNAL_ERROR" && e.failureStage === "output")
|
|
85
|
+
if (e.diagnosticReason === "OUTPUT_STREAM_FAILED" || e.code === "INTERNAL_ERROR" && e.failureStage === "output")
|
|
78
86
|
return "output";
|
|
79
87
|
if (gd && (e.operation === "tool.call" && ["12020700", "12020791", "500"].includes(e.remoteCode ?? "")
|
|
80
88
|
|| toolOrQuery && e.remoteCode === "12020780" || e.operation === "dam.upload" && e.remoteCode === "500"))
|
|
81
89
|
return "request";
|
|
82
|
-
if (e.code === "REMOTE_PROTOCOL_INCOMPATIBLE"
|
|
90
|
+
if (e.diagnosticReason?.startsWith("SSO_RESPONSE_") || e.code === "REMOTE_PROTOCOL_INCOMPATIBLE"
|
|
83
91
|
|| ["AGENT_CONTEXT_ID_MISSING", "AGENT_USAGE_MODEL_MISSING", "RESPONSE_BODY_ALREADY_USED"].includes(e.diagnosticReason ?? ""))
|
|
84
92
|
return "read";
|
|
85
93
|
if (e.code === "TOOL_TASK_FAILED")
|
|
@@ -98,7 +106,7 @@ export function observedErrorMessage(category, e) {
|
|
|
98
106
|
return text("本次登录已超时,请重新登录。", "This sign-in timed out. Please sign in again.");
|
|
99
107
|
if (category === "account" && e.code === "ORG_INVALID")
|
|
100
108
|
return text("当前团队不可用,请重新选择团队。", "This team is unavailable. Select another team.");
|
|
101
|
-
if (category === "
|
|
109
|
+
if (category === "file_exists" && e.operation === "dam.rename" && e.remoteCode === "00010014")
|
|
102
110
|
return text("名称已存在,请换个名称。", "This name already exists. Choose another name.");
|
|
103
111
|
if (category === "asset_read" && e.code === "DAM_DOWNLOAD_FAILED")
|
|
104
112
|
return text("素材下载未完成。", "The asset download did not complete.");
|
|
@@ -45,7 +45,7 @@ export function registerTaskCommands(program, runtime) {
|
|
|
45
45
|
bindPreparedAction(get, "local-organization", async () => {
|
|
46
46
|
const id = get.processedArgs[0];
|
|
47
47
|
if (typeof id !== "string" || !validTaskId(id))
|
|
48
|
-
throw new CliUsageError();
|
|
48
|
+
throw new CliUsageError("invalid_task_id");
|
|
49
49
|
return { handled: false, input: id.toLowerCase() };
|
|
50
50
|
}, async (context, id, signal) => {
|
|
51
51
|
const result = await tasks.get({ id, state: context.state, signal });
|
|
@@ -25,7 +25,7 @@ export function registerToolCommands(program, runtime) {
|
|
|
25
25
|
const call = tool.command("call")
|
|
26
26
|
.description(text(runtime.product, "调用创作工具", "Call a creation tool"))
|
|
27
27
|
.argument("<tool>", text(runtime.product, "工具机器标识", "tool machine identifier"))
|
|
28
|
-
.option("--schema", text(runtime.product, "
|
|
28
|
+
.option("--schema", text(runtime.product, "输出按 model 区分必填字段和参数限制的输入 Schema", "output the input Schema with per-model required fields and constraints"))
|
|
29
29
|
.option("--input <file|->", text(runtime.product, "从文件或标准输入读取参数 JSON", "read argument JSON from a file or stdin"))
|
|
30
30
|
.option("--async", text(runtime.product, "提交后返回 taskId,通过 task get 查询结果", "return taskId after submission; retrieve results with task get"))
|
|
31
31
|
.allowExcessArguments(false);
|
|
@@ -37,7 +37,9 @@ export function registerToolCommands(program, runtime) {
|
|
|
37
37
|
text(runtime.product, "异步任务由本机后台进程继续等待结果;进程终止或关机可能使状态变为 unknown。", "Async work continues in a local background process; termination or shutdown may leave its state unknown."),
|
|
38
38
|
text(runtime.product, "用 task get <taskId> 查询原任务;completed 时 result 为完整结果,running/unknown 或查询超时不应重新提交。", "Query the same taskId with task get; completed includes result. Do not resubmit on running, unknown, or a query timeout."),
|
|
39
39
|
text(runtime.product, "默认等待原 Tool 结果;任务 ID 写入 stderr,stdout 保持原 JSON。", "By default, the command waits for the original Tool result; stderr shows the Task ID and stdout keeps the result JSON."),
|
|
40
|
+
text(runtime.product, "媒体 URI 字段支持 HTTP(S) 与本地 file:// URI;CLI 会按调用上传本地素材,可直接用于原图、参考素材和选区。", "Media URI fields accept HTTP(S) and local file:// URIs; the CLI uploads local inputs for the call, including source media, references and masks."),
|
|
40
41
|
text(runtime.product, `结果未收到时用 ${runtime.product.commandName} task list 找到调用,再用 ${runtime.product.commandName} task get <id> 查询,不重复生成。`, `If output is missing, use ${runtime.product.commandName} task list and ${runtime.product.commandName} task get <id> to recover it without generating again.`),
|
|
42
|
+
text(runtime.product, "完整结果为 {content,usage}。content 项为 text、resource_link(uri/name/mimeType)或 resource(resource.uri/mimeType/text);OCR 的 resource.text 是 JSON。分层返回原生模板 JSON 链接,不是 PSD;视频处理需检查实际音轨。", "Complete results are {content,usage}. Content items are text, resource_link (uri/name/mimeType), or resource (resource.uri/mimeType/text); OCR resource.text contains JSON. Layer decomposition returns a native template JSON link, not PSD; verify actual audio after video processing."),
|
|
41
43
|
text(runtime.product, "查询返回同一份 usage;Tool usage.cost 为当次目录预估价格。", "Queries return the same usage; Tool usage.cost is the catalog price estimate for that invocation."),
|
|
42
44
|
""
|
|
43
45
|
].join("\n"));
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
export function contractSchema(operation, direction) {
|
|
3
|
-
return
|
|
3
|
+
return contractDocument(`${operation}/${direction}.schema.json`);
|
|
4
|
+
}
|
|
5
|
+
export function contractDocument(path) {
|
|
6
|
+
return JSON.parse(readFileSync(new URL(`../../../contracts/operations/${path}`, import.meta.url), "utf8"));
|
|
4
7
|
}
|
|
@@ -203,8 +203,25 @@ function inferMediaType(url) {
|
|
|
203
203
|
webp: "image/webp"
|
|
204
204
|
}[extension ?? ""] ?? "application/octet-stream";
|
|
205
205
|
}
|
|
206
|
-
function
|
|
207
|
-
|
|
206
|
+
function isBillingMetadataText(text, message) {
|
|
207
|
+
if (message.role !== "function")
|
|
208
|
+
return false;
|
|
209
|
+
const extra = record(message.extra);
|
|
210
|
+
const amount = extra?.deduct_points;
|
|
211
|
+
if (nonEmptyString(extra?.task_id) === undefined
|
|
212
|
+
|| nonEmptyString(extra?.scene_code) === undefined
|
|
213
|
+
|| typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
|
|
214
|
+
return false;
|
|
215
|
+
// The Agent appends this exact metadata mirror as tool text. Require matching
|
|
216
|
+
// structured billing evidence; ordinary JSON and assistant text remain intact.
|
|
217
|
+
const fields = record(parseJson(text));
|
|
218
|
+
return fields !== undefined && Object.keys(fields).length === 2
|
|
219
|
+
&& fields.deduct_points === amount
|
|
220
|
+
&& typeof fields.balance_points === "number"
|
|
221
|
+
&& Number.isFinite(fields.balance_points) && fields.balance_points >= 0;
|
|
222
|
+
}
|
|
223
|
+
function functionResponseParts(message) {
|
|
224
|
+
const parsed = parseJson(contentOf(message)?.text);
|
|
208
225
|
const values = Array.isArray(parsed) ? parsed : parsed === undefined ? [] : [parsed];
|
|
209
226
|
const parts = [];
|
|
210
227
|
for (const value of values) {
|
|
@@ -212,7 +229,7 @@ function functionResponseParts(raw) {
|
|
|
212
229
|
if (item === undefined)
|
|
213
230
|
continue;
|
|
214
231
|
const text = nonEmptyString(item.text);
|
|
215
|
-
if (text !== undefined)
|
|
232
|
+
if (text !== undefined && !isBillingMetadataText(text, message))
|
|
216
233
|
parts.push({ text });
|
|
217
234
|
const url = nonEmptyString(item.uri ?? item.url);
|
|
218
235
|
if (url === undefined)
|
|
@@ -255,7 +272,7 @@ export function restoreCreativeResourceUrls(messages, streamed) {
|
|
|
255
272
|
const content = contentOf(message);
|
|
256
273
|
if (content?.type !== "function_response")
|
|
257
274
|
continue;
|
|
258
|
-
for (const part of functionResponseParts(
|
|
275
|
+
for (const part of functionResponseParts(message)) {
|
|
259
276
|
if (!("url" in part) || !hasAuthKey(part.url))
|
|
260
277
|
continue;
|
|
261
278
|
const identity = resourceUrlIdentity(part.url);
|
|
@@ -402,7 +419,7 @@ export function normalizeCreativeMessages(messages) {
|
|
|
402
419
|
parts.push({ text });
|
|
403
420
|
}
|
|
404
421
|
else if (content.type === "function_response") {
|
|
405
|
-
parts.push(...functionResponseParts(
|
|
422
|
+
parts.push(...functionResponseParts(message));
|
|
406
423
|
}
|
|
407
424
|
}
|
|
408
425
|
else {
|
|
@@ -8,6 +8,7 @@ function unsignedPrivateUrl(value) {
|
|
|
8
8
|
throw new RemoteProtocolError();
|
|
9
9
|
}
|
|
10
10
|
const isPrivate = /^gd-ai-[a-z0-9-]+\.dancf\.com$/iu.test(url.hostname)
|
|
11
|
+
|| /^gdesign-dam(?:-[a-z0-9-]+)?\.dancf\.com$/iu.test(url.hostname)
|
|
11
12
|
|| url.hostname === "dify-grsai.dancf.com"
|
|
12
13
|
|| url.hostname === "dify-aiznt.dancf.com";
|
|
13
14
|
if (!isPrivate || url.searchParams.get("auth_key")?.trim())
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { findModel, ToolInputError } from "../tool/catalog.js";
|
|
2
2
|
import { modelControlArgumentsAreValid } from "../tool/dynamic-schema.js";
|
|
3
|
+
import { canvasRemoteControlArguments } from "../tool/canvas-models.js";
|
|
3
4
|
import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
|
|
4
5
|
export class AgentInputError extends Error {
|
|
5
6
|
reason;
|
|
@@ -50,6 +51,7 @@ export function createAgentUseCases(dependencies) {
|
|
|
50
51
|
}
|
|
51
52
|
}
|
|
52
53
|
if (generation?.model !== undefined) {
|
|
54
|
+
const requested = generation;
|
|
53
55
|
dependencies.telemetry.annotate({ model_id: generation.model });
|
|
54
56
|
const catalog = await dependencies.telemetry.stage("catalog", () => (dependencies.catalog.load({ access, signal })));
|
|
55
57
|
signal.throwIfAborted();
|
|
@@ -60,15 +62,23 @@ export function createAgentUseCases(dependencies) {
|
|
|
60
62
|
await dependencies.telemetry.stage("input", async () => {
|
|
61
63
|
let model;
|
|
62
64
|
try {
|
|
63
|
-
model = findModel(catalog,
|
|
65
|
+
model = findModel(catalog, requested.model);
|
|
64
66
|
}
|
|
65
67
|
catch (error) {
|
|
66
68
|
if (error instanceof ToolInputError)
|
|
67
69
|
throw new AgentInputError(error.reason, "/generation/model", error);
|
|
68
70
|
throw error;
|
|
69
71
|
}
|
|
70
|
-
if (!modelControlArgumentsAreValid(model,
|
|
72
|
+
if (!modelControlArgumentsAreValid(model, requested.arguments ?? {}))
|
|
71
73
|
throw new AgentInputError("model_parameters", "/generation/arguments");
|
|
74
|
+
if (model.execution?.kind === "canvas") {
|
|
75
|
+
generation = {
|
|
76
|
+
model: model.execution.code,
|
|
77
|
+
...(requested.arguments === undefined ? {} : {
|
|
78
|
+
arguments: canvasRemoteControlArguments(model.model, requested.arguments)
|
|
79
|
+
})
|
|
80
|
+
};
|
|
81
|
+
}
|
|
72
82
|
});
|
|
73
83
|
}
|
|
74
84
|
const prepare = async () => {
|
|
@@ -128,10 +138,10 @@ export function createAgentUseCases(dependencies) {
|
|
|
128
138
|
prepared.push({
|
|
129
139
|
kind: "generation",
|
|
130
140
|
data: {
|
|
131
|
-
...(
|
|
132
|
-
...(
|
|
141
|
+
...(generation?.model === undefined ? {} : { model: generation.model }),
|
|
142
|
+
...(generation?.arguments === undefined
|
|
133
143
|
? {}
|
|
134
|
-
: { arguments: { ...
|
|
144
|
+
: { arguments: { ...generation.arguments } })
|
|
135
145
|
}
|
|
136
146
|
});
|
|
137
147
|
}
|
|
@@ -3,15 +3,19 @@ import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
|
3
3
|
import { normalizeScope } from "./state.js";
|
|
4
4
|
import { signBindOrganization } from "../../platform/signature.js";
|
|
5
5
|
export class SsoRequestError extends Error {
|
|
6
|
+
diagnosticSummary;
|
|
6
7
|
status;
|
|
7
8
|
remoteCode;
|
|
8
9
|
remoteBody;
|
|
9
|
-
|
|
10
|
+
diagnosticReason;
|
|
11
|
+
constructor(status, evidence = {}, cause, diagnosticSummary) {
|
|
10
12
|
super(status === undefined ? "无法连接稿定登录服务。" : `稿定登录服务请求失败(HTTP ${status})。`, { cause });
|
|
13
|
+
this.diagnosticSummary = diagnosticSummary;
|
|
11
14
|
this.name = "SsoRequestError";
|
|
12
15
|
this.status = status;
|
|
13
16
|
this.remoteCode = evidence.remoteCode;
|
|
14
17
|
this.remoteBody = evidence.remoteBody;
|
|
18
|
+
this.diagnosticReason = evidence.diagnosticReason;
|
|
15
19
|
}
|
|
16
20
|
}
|
|
17
21
|
export function classifyBindOutcome(input) {
|
|
@@ -42,12 +46,16 @@ export function createSsoService(options) {
|
|
|
42
46
|
}
|
|
43
47
|
}
|
|
44
48
|
return new SsoRequestError(response.status, {
|
|
49
|
+
...(response.ok ? { diagnosticReason: "SSO_RESPONSE_INVALID" } : {}),
|
|
45
50
|
...(evidence.remoteCode === undefined ? {} : { remoteCode: evidence.remoteCode }),
|
|
46
51
|
...remoteErrorEvidence({ request: requests.get(response),
|
|
47
52
|
...(evidence.remoteBody === undefined ? {} : { response: evidence.remoteBody }),
|
|
48
53
|
...(networkError === undefined ? {} : { network: networkFailure(networkError) }) })
|
|
49
54
|
}, networkError);
|
|
50
55
|
}
|
|
56
|
+
function invalidFields(response, phase, fields) {
|
|
57
|
+
return new SsoRequestError(response.status, { diagnosticReason: "SSO_RESPONSE_FIELDS_MISSING" }, undefined, { ssoPhase: phase, ssoInvalidFields: Object.entries(fields).filter(([, valid]) => !valid).map(([key]) => key).join(",") });
|
|
58
|
+
}
|
|
51
59
|
async function responseRecord(response) {
|
|
52
60
|
if (!response.ok) {
|
|
53
61
|
// OAuth pending/slow_down are normal token polling responses.
|
|
@@ -101,7 +109,8 @@ export function createSsoService(options) {
|
|
|
101
109
|
const expiresInSeconds = positiveNumber(body.expires_in);
|
|
102
110
|
const intervalSeconds = positiveNumber(body.interval);
|
|
103
111
|
if (!authorizeCode || !deviceCode || !expiresInSeconds || !intervalSeconds) {
|
|
104
|
-
throw
|
|
112
|
+
throw invalidFields(response, "authorize", { authorize_code: authorizeCode, device_code: deviceCode,
|
|
113
|
+
expires_in: expiresInSeconds, interval: intervalSeconds });
|
|
105
114
|
}
|
|
106
115
|
return { authorizeCode, deviceCode, expiresInSeconds, intervalSeconds };
|
|
107
116
|
},
|
|
@@ -123,13 +132,13 @@ export function createSsoService(options) {
|
|
|
123
132
|
const secretKey = nonEmptyString(body.sk);
|
|
124
133
|
const expiresAt = dateString(body.expires_at);
|
|
125
134
|
if (!accessKey || !secretKey || !expiresAt)
|
|
126
|
-
throw
|
|
135
|
+
throw invalidFields(response, "token", { ak: accessKey, sk: secretKey, expires_at: expiresAt });
|
|
127
136
|
let scope;
|
|
128
137
|
try {
|
|
129
138
|
scope = normalizeScope(body.scope);
|
|
130
139
|
}
|
|
131
140
|
catch {
|
|
132
|
-
throw
|
|
141
|
+
throw invalidFields(response, "token", { scope: false });
|
|
133
142
|
}
|
|
134
143
|
const result = {
|
|
135
144
|
status: "authorized",
|
|
@@ -9,6 +9,7 @@ export class DamAssetNotFoundError extends Error {
|
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
11
|
export class DamAssetNotDownloadableError extends Error {
|
|
12
|
+
diagnosticReason = "ASSET_DOWNLOAD_URL_MISSING";
|
|
12
13
|
constructor() {
|
|
13
14
|
super("该 DAM 素材当前不可下载。");
|
|
14
15
|
this.name = "DamAssetNotDownloadableError";
|
|
@@ -84,6 +84,9 @@ function safeFilename(candidate, fallback, format) {
|
|
|
84
84
|
const segments = raw.normalize("NFKC").replace(/[\u0000-\u001f\u007f]/gu, "")
|
|
85
85
|
.split(/[\\/]+/u);
|
|
86
86
|
let filename = (segments.at(-1) ?? "").trim().replace(/^\.+/u, "");
|
|
87
|
+
filename = filename.replace(/[<>:"|?*]/gu, "_").replace(/[. ]+$/u, "");
|
|
88
|
+
if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(filename))
|
|
89
|
+
filename = `_${filename}`;
|
|
87
90
|
if (filename === "" || filename === "." || filename === "..")
|
|
88
91
|
filename = "asset";
|
|
89
92
|
if (extname(filename) === "")
|
|
@@ -153,6 +156,15 @@ export function createDamFileDownloader(options = {}) {
|
|
|
153
156
|
randomId: options.randomId ?? randomUUID,
|
|
154
157
|
cwd: options.cwd ?? process.cwd
|
|
155
158
|
};
|
|
159
|
+
const warnCleanup = () => {
|
|
160
|
+
try {
|
|
161
|
+
options.warn?.("DOWNLOAD_TEMP_CLEANUP_FAILED");
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
// An advisory warning can encounter a closed stderr. It must neither
|
|
165
|
+
// roll back committed results nor replace the original download error.
|
|
166
|
+
}
|
|
167
|
+
};
|
|
156
168
|
return {
|
|
157
169
|
async download(input) {
|
|
158
170
|
input.signal.throwIfAborted();
|
|
@@ -230,8 +242,14 @@ export function createDamFileDownloader(options = {}) {
|
|
|
230
242
|
throw new DamDownloadError(cause, "commit");
|
|
231
243
|
}
|
|
232
244
|
createdFinalPaths.push(item.finalPath);
|
|
233
|
-
await dependencies.fileSystem.rm(item.temporaryPath, { force: true });
|
|
234
245
|
}
|
|
246
|
+
// Every result is committed before best-effort temporary cleanup. A
|
|
247
|
+
// host cleanup guard must never delete a successfully downloaded file.
|
|
248
|
+
let cleanupFailed = false;
|
|
249
|
+
await Promise.all(pending.map(item => dependencies.fileSystem.rm(item.temporaryPath, { force: true })
|
|
250
|
+
.catch(() => { cleanupFailed = true; })));
|
|
251
|
+
if (cleanupFailed)
|
|
252
|
+
warnCleanup();
|
|
235
253
|
return pending.map((item) => ({
|
|
236
254
|
path: item.finalPath,
|
|
237
255
|
bytes: item.bytes,
|
|
@@ -241,15 +259,18 @@ export function createDamFileDownloader(options = {}) {
|
|
|
241
259
|
catch (error) {
|
|
242
260
|
const remainingPaths = [];
|
|
243
261
|
const cleanupErrors = [];
|
|
262
|
+
let temporaryCleanupFailed = false;
|
|
244
263
|
await Promise.all(pending.map(async (item) => {
|
|
245
264
|
if (item.open)
|
|
246
265
|
await item.handle.close().catch(cause => { cleanupErrors.push(cause); });
|
|
247
266
|
await dependencies.fileSystem.rm(item.temporaryPath, { force: true }).catch(cause => {
|
|
248
267
|
remainingPaths.push(item.temporaryPath);
|
|
249
|
-
|
|
268
|
+
temporaryCleanupFailed = true;
|
|
250
269
|
});
|
|
251
270
|
}));
|
|
252
271
|
await Promise.all(createdFinalPaths.map((path) => (dependencies.fileSystem.rm(path, { force: true }).catch(cause => { remainingPaths.push(path); cleanupErrors.push(cause); }))));
|
|
272
|
+
if (temporaryCleanupFailed)
|
|
273
|
+
warnCleanup();
|
|
253
274
|
if (cleanupErrors.length)
|
|
254
275
|
throw new DamDownloadError(new AggregateError([error, ...cleanupErrors], "Download cleanup failed.", { cause: error }), "cleanup", undefined, remainingPaths);
|
|
255
276
|
if (isInterruption(error, input.signal))
|
|
@@ -28,18 +28,22 @@ export function createTaskStore(options) {
|
|
|
28
28
|
try {
|
|
29
29
|
const stat = await lstat(join(root, scope, `${id}.json`));
|
|
30
30
|
if (!stat.isFile() || stat.isSymbolicLink())
|
|
31
|
-
throw new LocalFileError(undefined);
|
|
31
|
+
throw new LocalFileError(undefined, undefined, "invalid_data", { operation: "read", step: "stat" });
|
|
32
32
|
}
|
|
33
33
|
catch (error) {
|
|
34
34
|
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
35
35
|
return null;
|
|
36
|
-
|
|
36
|
+
if (error instanceof LocalFileError)
|
|
37
|
+
throw error;
|
|
38
|
+
throw new LocalFileError(error, undefined, "io", { operation: "read", step: "stat" });
|
|
37
39
|
}
|
|
38
40
|
const text = await stateFile.readText();
|
|
39
41
|
if (text === null)
|
|
40
42
|
return null;
|
|
43
|
+
let step = "parse";
|
|
41
44
|
try {
|
|
42
45
|
const record = JSON.parse(text);
|
|
46
|
+
step = "validate";
|
|
43
47
|
if (record.version !== 1 || record.task.taskId !== id || !record.progress
|
|
44
48
|
|| typeof record.progress !== "object" || Array.isArray(record.progress))
|
|
45
49
|
throw new Error();
|
|
@@ -55,7 +59,7 @@ export function createTaskStore(options) {
|
|
|
55
59
|
return record;
|
|
56
60
|
}
|
|
57
61
|
catch (cause) {
|
|
58
|
-
throw new LocalFileError(cause);
|
|
62
|
+
throw new LocalFileError(cause, undefined, "invalid_data", { operation: "read", step });
|
|
59
63
|
}
|
|
60
64
|
},
|
|
61
65
|
async write(scope, record) {
|
|
@@ -106,7 +110,7 @@ export function createTaskStore(options) {
|
|
|
106
110
|
catch (error) {
|
|
107
111
|
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
108
112
|
return [];
|
|
109
|
-
throw new LocalFileError(error);
|
|
113
|
+
throw new LocalFileError(error, undefined, "io", { operation: "list", step: "directory_read" });
|
|
110
114
|
}
|
|
111
115
|
const records = [];
|
|
112
116
|
for (const name of names) {
|
|
@@ -159,8 +159,8 @@ export function createTaskUseCases(dependencies) {
|
|
|
159
159
|
let details;
|
|
160
160
|
if (input.operation === "agent.send")
|
|
161
161
|
details = { tool_type: "agent", tool_name: "agent" };
|
|
162
|
-
else if (generation?.model && (generation.tool
|
|
163
|
-
const name = generation.tool
|
|
162
|
+
else if (generation?.model && (generation.tool.startsWith("image.") || generation.tool.startsWith("video."))) {
|
|
163
|
+
const name = generation.tool.startsWith("image.") ? "AI绘图" : "AI视频生成";
|
|
164
164
|
details = { tool_type: name, tool_name: name, model_name: generation.model };
|
|
165
165
|
}
|
|
166
166
|
else
|
|
@@ -222,7 +222,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
222
222
|
await analyticsFact("started");
|
|
223
223
|
return;
|
|
224
224
|
}
|
|
225
|
-
Object.assign(record.progress, progress);
|
|
225
|
+
Object.assign(record.progress, withoutResourceKeys(progress));
|
|
226
226
|
if (progress.contextId)
|
|
227
227
|
record.task.contextId = progress.contextId;
|
|
228
228
|
try {
|
|
@@ -260,7 +260,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
260
260
|
clearInterval(timer);
|
|
261
261
|
const diagnostic = telemetry?.taskFailure(error).diagnostic_reason
|
|
262
262
|
?? (error instanceof RemoteRequestError ? error.diagnosticReason : undefined);
|
|
263
|
-
const observationOnly = diagnostic === "LOCAL_WAIT_INTERRUPTED" || diagnostic === "TASK_QUERY_FAILED";
|
|
263
|
+
const observationOnly = diagnostic === "LOCAL_WAIT_INTERRUPTED" || diagnostic === "TASK_QUERY_FAILED" || diagnostic === "TASK_CANCELED";
|
|
264
264
|
if (record.task.state !== "completed") {
|
|
265
265
|
const mayBeRunning = dispatched || record.progress.submissionStarted;
|
|
266
266
|
const auditRejected = isContentReviewRejection(error, { product: commandName === "insmind-cli" ? "insmind" : "gaoding", operation: input.operation });
|
|
@@ -269,13 +269,15 @@ export function createTaskUseCases(dependencies) {
|
|
|
269
269
|
&& error.remoteCode === "12020770";
|
|
270
270
|
const confirmedFailure = error instanceof ToolTaskFailedError || auditRejected || creditsRejected;
|
|
271
271
|
record.task.state = observationOnly ? "unknown" : confirmedFailure || !mayBeRunning ? "failed" : "unknown";
|
|
272
|
-
record.task.note = diagnostic === "
|
|
273
|
-
? text("
|
|
274
|
-
:
|
|
275
|
-
? text("
|
|
276
|
-
:
|
|
277
|
-
? text("
|
|
278
|
-
:
|
|
272
|
+
record.task.note = diagnostic === "TASK_CANCELED"
|
|
273
|
+
? text("生成任务已取消。", "The creation task was canceled.")
|
|
274
|
+
: diagnostic === "LOCAL_WAIT_INTERRUPTED"
|
|
275
|
+
? text("本次操作已停止等待。", "This operation stopped waiting.")
|
|
276
|
+
: confirmedFailure
|
|
277
|
+
? text("本次生成未能完成。", "This creation could not be completed.")
|
|
278
|
+
: mayBeRunning
|
|
279
|
+
? text("尚未取得任务结果。", "The task result has not been received.")
|
|
280
|
+
: text("本次生成尚未开始。", "This creation has not started.");
|
|
279
281
|
}
|
|
280
282
|
const detail = dependencies.failureNote?.(error);
|
|
281
283
|
if (detail && diagnostic !== "LOCAL_WAIT_INTERRUPTED")
|
|
@@ -325,6 +327,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
325
327
|
stored.task = { ...stored.task, state: "unknown", note: text("尚未取得任务结果。", "The task result has not been received.") };
|
|
326
328
|
}));
|
|
327
329
|
}
|
|
330
|
+
record = withoutResourceKeys(record);
|
|
328
331
|
telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
|
|
329
332
|
if (record.task.state === "completed" && record.task.result) {
|
|
330
333
|
const result = { ...record.task, result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal)) };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Product copy only. Executable constraints stay in the shared formal Schema.
|
|
2
|
+
const copy = {
|
|
3
|
+
"image-edit-standard": ["Standard image edit", "White mask pixels are processed; black pixels are protected. Supply an opaque binary PNG matching the auto-oriented source. The CLI converts service-specific mask polarity and requests source dimensions."],
|
|
4
|
+
"image-edit-smart": ["Smart image edit", "Generative editing can change details. An optional mask is rendered as a cyan outline on the target image; referenceImages are references, never a mask. Inspect changes outside the selection."],
|
|
5
|
+
"image-matting-standard": ["Standard background removal", "Preserves visible source pixels without reconstructing occluded parts. Returns a real alpha PNG at source dimensions unless cropToSubject is enabled."],
|
|
6
|
+
"image-matting-smart": ["Smart subject extraction", "Redraws the requested subject, then segments the redraw into a transparent PNG. Hidden details are generated guesses. An optional mask is a visual boundary cue. Transparent postprocessing is included; do not pay for another standard matting call."],
|
|
7
|
+
"image-remove-standard": ["Standard object removal", "Remove within white mask pixels; black pixels are protected. The opaque binary PNG mask must match the auto-oriented source. Source dimensions are requested from the service."],
|
|
8
|
+
"image-remove-smart": ["Smart object removal", "Remove objects from one target image using instructions. An optional mask is rendered as a cyan outline, not sent as another reference image. Inspect changes outside the selection."],
|
|
9
|
+
"image-enhance-standard": ["Standard image upscale", "targetLongEdge specifies the output's longest edge in pixels while retaining aspect ratio. Bounds and steps come from the current catalog."],
|
|
10
|
+
"image-enhance-smart": ["Smart image restoration", "Generative restoration may reconstruct textures, text, faces or product details. Check the user's permitted changes against the actual result."],
|
|
11
|
+
"image-expand-standard": ["Standard image expansion", "canvas and placement use auto-oriented source pixels. Origin is top-left; x goes right and y down. The original must fit without scaling. The target canvas dimensions are requested from the service."],
|
|
12
|
+
"image-expand-smart": ["Smart image expansion", "Place the source at natural size and expand its surroundings. Output uses the target aspect ratio; pixel dimensions follow the live resolution setting. Source details can change."],
|
|
13
|
+
"image-text-edit": ["Image text replacement", "replacements match complete original text. An empty to deletes it. Repeated text cannot be targeted by occurrence. Verify all unchanged text."],
|
|
14
|
+
"image-ocr": ["Image text recognition", "Returns an embedded application/json resource: image{uri,width,height}, blocks[{bbox:[left,top,right,bottom],category,text?}]. Coordinates use the returned recognition image's top-left origin in pixels."],
|
|
15
|
+
"image-layers-layout": ["Layout decomposition", "Fits the source within 3000×3000 pixels without enlargement. Returns native template JSON and actual element counts, not PSD. Editability depends on the returned layers; fonts may be substituted. Use a discovered Editor import capability to open the template."],
|
|
16
|
+
"image-layers-smart": ["Smart layer decomposition", "Fits the source within 3000×3000 pixels without enlargement; the prepared image must have at least 512×512 total pixels. Returns native template JSON and layer counts, not PSD or word-by-word OCR. maxLayers is an upper bound. Pricing uses current remote metered components."],
|
|
17
|
+
"image-vectorize": ["Image to SVG", "Returns an SVG resource. The caller inspects actual vector contents, reconstructed shapes, colors and details."],
|
|
18
|
+
"video-edit-smart": ["Smart video edit", "Duration and ratio come from the actual source. Reference videos including the source total at most 15 seconds. audioEnabled controls audio presence, not preservation of the original sound."],
|
|
19
|
+
"video-enhance-standard": ["Standard video upscale", "Uses ceil(actual seconds) for billing and requests preservation of the source video. The caller inspects actual duration, visuals and soundtrack preservation."],
|
|
20
|
+
"video-enhance-smart": ["Smart video restoration", "Generative restoration requests the source duration rounded to 2–30 seconds and may change details. The caller inspects actual duration, sound content and synchronization."]
|
|
21
|
+
};
|
|
22
|
+
export function englishCanvasCopy(model, schema) {
|
|
23
|
+
const descriptions = {
|
|
24
|
+
image: "One HTTP(S) or CLI file:// source image URI.",
|
|
25
|
+
video: "One HTTP(S) or CLI file:// source video URI.",
|
|
26
|
+
mask: "Fully opaque PNG containing only pure black and white, matching the auto-oriented source. White processes, black protects. White must be nonempty; all-white selects the entire image.",
|
|
27
|
+
cropToSubject: "Crop to the nonzero alpha subject bounds. Default keeps the final source dimensions.",
|
|
28
|
+
canvas: "Target canvas width and height in natural source pixels.",
|
|
29
|
+
placement: "Source top-left position in canvas pixels: x right, y down. No source scaling.",
|
|
30
|
+
referenceImages: "Additional image references, separate from the target image and mask.",
|
|
31
|
+
referenceVideos: "Additional reference videos. The source video remains first.",
|
|
32
|
+
referenceAudios: "Additional audio references.",
|
|
33
|
+
replacements: "Complete original/new text pairs. Empty to means delete; duplicate from entries are rejected.",
|
|
34
|
+
from: "The complete original text to replace, including punctuation and spaces.",
|
|
35
|
+
to: "Replacement text. An empty string deletes the matched original text.",
|
|
36
|
+
targetLongEdge: "Output's longest edge in pixels; aspect ratio is retained.",
|
|
37
|
+
maxLayers: "Requested layer count upper bound, not an exact output count."
|
|
38
|
+
};
|
|
39
|
+
for (const [name, property] of Object.entries(schema.properties)) {
|
|
40
|
+
if (descriptions[name])
|
|
41
|
+
property.description = descriptions[name];
|
|
42
|
+
if (property.items?.format === "uri")
|
|
43
|
+
property.items.description = "HTTP(S) or CLI file:// asset URI.";
|
|
44
|
+
for (const [child, field] of Object.entries(property.items?.properties ?? {})) {
|
|
45
|
+
if (descriptions[child])
|
|
46
|
+
field.description = descriptions[child];
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (model.endsWith("-smart") && schema.properties.mask) {
|
|
50
|
+
schema.properties.mask.description = "Fully opaque PNG containing only pure black and white, matching the auto-oriented source. Nonempty white pixels identify the target; all-white selects the entire image. The CLI converts this to a visual boundary cue, which cannot guarantee unchanged pixels outside the selection.";
|
|
51
|
+
}
|
|
52
|
+
if (model === "video-edit-smart") {
|
|
53
|
+
schema.properties.video.description = "Source video to edit, referenced as 视频1 in the prompt. HTTP(S) or CLI file:// URI.";
|
|
54
|
+
schema.properties.prompt.description = "The user's prompt is kept verbatim; the CLI only prefixes media bindings. Reference the source as 视频1, referenceVideos from 视频2, referenceImages from 图1, and referenceAudios from 音频1, each in array order. The CLI adds original filename-to-label bindings before uploading changes filenames.";
|
|
55
|
+
schema.properties.referenceImages.description = "Reference images, numbered 图1, 图2, etc. in array order.";
|
|
56
|
+
schema.properties.referenceVideos.description = "Reference videos, numbered 视频2, 视频3, etc.; 视频1 is always the source. The source and all reference videos combined must not exceed 15 seconds.";
|
|
57
|
+
schema.properties.referenceAudios.description = "Reference audio, numbered 音频1, 音频2, etc. in array order.";
|
|
58
|
+
}
|
|
59
|
+
const [title, usageDescription] = copy[model];
|
|
60
|
+
return { title, usageDescription };
|
|
61
|
+
}
|