@insmind/cli 2.1.5 → 2.1.7
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/dist/shared/model-catalog/fields.js +114 -0
- package/dist/shared/model-catalog/index.js +3 -0
- package/dist/shared/model-catalog/inline-schema.js +72 -0
- package/dist/shared/model-catalog/schema.js +80 -0
- package/dist/src/bootstrap/create-runtime.js +37 -17
- package/dist/src/cli/errors.js +2 -2
- package/dist/src/cli/task-commands.js +1 -1
- package/dist/src/features/auth/sso-service.js +1 -1
- package/dist/src/features/task/use-cases.js +9 -2
- package/dist/src/features/tool/canvas-copy.js +2 -2
- package/dist/src/features/tool/canvas-matting.js +37 -70
- package/dist/src/features/tool/canvas-media.js +69 -63
- package/dist/src/features/tool/canvas-models.js +3 -3
- package/dist/src/features/tool/canvas-recovery.js +17 -5
- package/dist/src/features/tool/canvas-results.js +13 -43
- package/dist/src/features/tool/canvas-tool-adapter.js +81 -63
- package/dist/src/features/tool/dynamic-schema.js +5 -90
- package/dist/src/features/tool/matting-billing.js +3 -73
- package/dist/src/features/tool/mns-catalog-adapter.js +1 -98
- package/dist/src/features/tool/resource-authorizer.js +10 -0
- package/dist/src/features/tool/tool-api-adapter.js +1 -1
- package/dist/src/features/tool/tool-errors.js +0 -7
- package/dist/src/platform/http-user-agent.js +8 -0
- package/package.json +7 -4
|
@@ -1,84 +1,52 @@
|
|
|
1
1
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
2
|
import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
3
|
-
import {
|
|
3
|
+
import { authorizeCanvasImage } from "./resource-authorizer.js";
|
|
4
4
|
import { composeMatting } from "./canvas-media.js";
|
|
5
5
|
import { canvasContent, link, oneResource, record } from "./canvas-results.js";
|
|
6
|
-
import {
|
|
7
|
-
function parseSyncResult(value) {
|
|
8
|
-
if (!record(value))
|
|
9
|
-
throw new RemoteProtocolError();
|
|
10
|
-
if (record(value.error))
|
|
11
|
-
throw new ToolTaskFailedError(remoteErrorEvidence(value.error));
|
|
12
|
-
if (value.error)
|
|
13
|
-
throw new RemoteProtocolError(remoteErrorEvidence(value));
|
|
14
|
-
if (!record(value.result)) {
|
|
15
|
-
if (typeof value.task_id === "string" && value.task_id)
|
|
16
|
-
return { state: "pending" };
|
|
17
|
-
throw new RemoteProtocolError();
|
|
18
|
-
}
|
|
19
|
-
if (value.result.isError === true)
|
|
20
|
-
throw new ToolTaskFailedError(remoteErrorEvidence(value.result));
|
|
21
|
-
if ((value.result.isError !== undefined && value.result.isError !== false) || !Array.isArray(value.result.content))
|
|
22
|
-
throw new RemoteProtocolError();
|
|
23
|
-
const content = value.result.content;
|
|
24
|
-
const status = content.find(item => record(item) && item.type === "task");
|
|
25
|
-
if (record(status) && record(status.task)) {
|
|
26
|
-
if (["NOT_PASSED", "FAIL"].includes(String(status.task.status)))
|
|
27
|
-
throw new ToolTaskFailedError(remoteErrorEvidence(value));
|
|
28
|
-
if (status.task.status === "CANCELED")
|
|
29
|
-
throw new ToolTaskCanceledError();
|
|
30
|
-
return { state: "pending" };
|
|
31
|
-
}
|
|
32
|
-
if (!content.length)
|
|
33
|
-
return { state: "pending" };
|
|
34
|
-
return { state: "complete", content: content.map(canvasContent) };
|
|
35
|
-
}
|
|
6
|
+
import { queryToolResult, ToolTaskFailedError } from "./tool-api-adapter.js";
|
|
36
7
|
export function createCanvasSegmenter(dependencies) {
|
|
37
|
-
const { transport,
|
|
38
|
-
async function
|
|
8
|
+
const { transport, wait, resourceAuthorizer, telemetry } = dependencies;
|
|
9
|
+
async function call(name, image, context, options) {
|
|
39
10
|
let taskId = options.taskId;
|
|
40
11
|
if (!taskId) {
|
|
41
12
|
if (options.main)
|
|
42
13
|
await context.observe?.({ submissionStarted: true });
|
|
43
|
-
const
|
|
14
|
+
const submit = () => transport.postJson({ path: "/gdesign/tool/v1/dify/call_async",
|
|
44
15
|
body: { jsonrpc: "2.0", id: 0, method: "tools/call", params: { name, arguments: { image } } }, ...context.access, signal: context.signal,
|
|
45
|
-
...(options.main ? { onDispatch: async (dispatchedAt) => {
|
|
46
|
-
|
|
47
|
-
} } : {}) });
|
|
16
|
+
...(options.main ? { onDispatch: async (dispatchedAt) => { await context.observe?.({ dispatchedAt }); } } : {}) });
|
|
17
|
+
const response = await (options.main && telemetry ? telemetry.stage("submit", submit) : submit());
|
|
48
18
|
if (!record(response))
|
|
49
19
|
throw new RemoteProtocolError();
|
|
50
|
-
if (
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
await options.accepted?.(taskId);
|
|
57
|
-
}
|
|
58
|
-
const direct = parseSyncResult(response);
|
|
59
|
-
if (direct.state === "complete")
|
|
60
|
-
return direct.content;
|
|
61
|
-
if (!taskId)
|
|
20
|
+
if (record(response.error))
|
|
21
|
+
throw new ToolTaskFailedError(remoteErrorEvidence(response.error));
|
|
22
|
+
if (record(response.result) && response.result.isError === true)
|
|
23
|
+
throw new ToolTaskFailedError(remoteErrorEvidence(response.result));
|
|
24
|
+
if (!record(response.result) || response.result.isError !== false || typeof response.task_id !== "string" || !response.task_id.trim())
|
|
62
25
|
throw new RemoteProtocolError();
|
|
26
|
+
taskId = response.task_id;
|
|
27
|
+
// Save each non-idempotent child's receipt before acknowledging the public task.
|
|
28
|
+
await options.accepted(taskId);
|
|
29
|
+
if (options.main) {
|
|
30
|
+
await context.observe?.({ remoteTaskId: taskId, accepted: true });
|
|
31
|
+
telemetry?.annotate({ task_id: taskId });
|
|
32
|
+
}
|
|
63
33
|
}
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
return oneResource(authorized.content);
|
|
34
|
+
const read = () => wait(async () => {
|
|
35
|
+
const result = await queryToolResult(transport, { ...context.access, signal: context.signal, taskId, normalize: canvasContent,
|
|
36
|
+
...(options.main && telemetry ? { onDifyTaskId: (id) => telemetry.annotate({ dify_task_id: id }) } : {}) });
|
|
37
|
+
if (result.state === "failed")
|
|
38
|
+
throw result.error;
|
|
39
|
+
return result;
|
|
40
|
+
}, context.signal);
|
|
41
|
+
return options.main && telemetry ? telemetry.stage("wait", read) : read();
|
|
73
42
|
}
|
|
74
|
-
return async function segment(source, media, context,
|
|
75
|
-
let stage = redraw
|
|
76
|
-
let state = redraw
|
|
43
|
+
return async function segment(source, media, context, redraw) {
|
|
44
|
+
let stage = redraw.stage;
|
|
45
|
+
let state = redraw.matting;
|
|
77
46
|
async function checkpoint(next, update) {
|
|
78
47
|
state = { ...state, ...update };
|
|
79
48
|
stage = next;
|
|
80
|
-
|
|
81
|
-
await context.observe?.({ toolPipeline: { ...redraw, stage, matting: state } });
|
|
49
|
+
await context.observe?.({ toolPipeline: { ...redraw, stage, matting: state } });
|
|
82
50
|
}
|
|
83
51
|
if (!state.inputUri) {
|
|
84
52
|
const { default: sharp } = await import("sharp");
|
|
@@ -93,12 +61,11 @@ export function createCanvasSegmenter(dependencies) {
|
|
|
93
61
|
// Resume by its known ID; never submit the uncertain child again.
|
|
94
62
|
if (stage === next && !taskId)
|
|
95
63
|
throw new RemoteProtocolError({}, undefined, "MATTING_CHILD_RECEIPT_UNKNOWN");
|
|
96
|
-
const uri = taskId ? inputUri : await
|
|
64
|
+
const uri = taskId ? inputUri : await authorizeCanvasImage(inputUri, resourceAuthorizer, context.access, context.signal);
|
|
97
65
|
context.signal.throwIfAborted();
|
|
98
66
|
await checkpoint(next, {});
|
|
99
|
-
return
|
|
100
|
-
|
|
101
|
-
accepted: id => checkpoint(next, { [key]: id }) });
|
|
67
|
+
return call(name, uri, context, { ...(taskId ? { taskId } : {}), main: redraw.model === "image-matting-standard" && key === "classifyTaskId",
|
|
68
|
+
accepted: id => checkpoint(next, { [key]: id, childProtocol: "dify" }) });
|
|
102
69
|
}
|
|
103
70
|
if (state.category === undefined) {
|
|
104
71
|
const classification = await child("matting-classify", "classifying", "classifyTaskId");
|
|
@@ -115,9 +82,9 @@ export function createCanvasSegmenter(dependencies) {
|
|
|
115
82
|
const mask = await child(scene, "segmenting", "segmentTaskId");
|
|
116
83
|
await checkpoint("compositing", { maskUri: oneResource(mask) });
|
|
117
84
|
}
|
|
118
|
-
const maskUri = await
|
|
119
|
-
const bytes = await composeMatting(source, await media.read(maskUri, context.signal), category === 1 ? "alpha" : "red",
|
|
85
|
+
const maskUri = await authorizeCanvasImage(state.maskUri, resourceAuthorizer, context.access, context.signal);
|
|
86
|
+
const bytes = await composeMatting(source, await media.read(maskUri, context.signal), category === 1 ? "alpha" : "red", state.cropToSubject);
|
|
120
87
|
const finalUri = await media.upload(bytes, "png", context.access, context.signal);
|
|
121
|
-
return
|
|
88
|
+
return link(finalUri, "cutout.png", "image/png");
|
|
122
89
|
};
|
|
123
90
|
}
|
|
@@ -20,24 +20,8 @@ function mediaFailure(phase, summary, status, cause) {
|
|
|
20
20
|
return new RemoteRequestError(status, false, {}, cause, `MEDIA_${phase.toUpperCase()}_FAILED`, { ...summary, mediaPhase: phase });
|
|
21
21
|
}
|
|
22
22
|
export function createCanvasMedia(dependencies) {
|
|
23
|
-
|
|
24
|
-
const renewed = new Map();
|
|
25
|
-
async function readWithEvidence(uri, signal, limit = 64 * 1024 * 1024) {
|
|
23
|
+
async function fetchRemote(uri, signal) {
|
|
26
24
|
signal.throwIfAborted();
|
|
27
|
-
if (uri.startsWith("file:")) {
|
|
28
|
-
const file = await inspectUploadFile({ url: uri, signal });
|
|
29
|
-
if (file.size > limit)
|
|
30
|
-
throw new ToolInputError("media_too_large", "/arguments");
|
|
31
|
-
try {
|
|
32
|
-
const bytes = await readFile(file.filePath, { signal });
|
|
33
|
-
return { bytes, summary: { ...uriShape(uri), mediaPhase: "read", mediaBytesRead: bytes.length } };
|
|
34
|
-
}
|
|
35
|
-
catch (cause) {
|
|
36
|
-
if (signal.aborted)
|
|
37
|
-
throw signal.reason;
|
|
38
|
-
throw new LocalFileInputError(cause, "file_read_failed", { ...uriShape(uri), mediaPhase: "read" });
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
25
|
let url = parseSafeRemoteAssetUrl(uri);
|
|
42
26
|
const protectedOrigin = isFilemsResource(url);
|
|
43
27
|
let authKey;
|
|
@@ -46,7 +30,9 @@ export function createCanvasMedia(dependencies) {
|
|
|
46
30
|
while (redirects <= 5) {
|
|
47
31
|
if (protectedOrigin) {
|
|
48
32
|
const existing = url.searchParams.get("auth_key");
|
|
49
|
-
if (
|
|
33
|
+
if (freshKey !== undefined)
|
|
34
|
+
url = new URL(withFilemsAuthKey(url.href, freshKey));
|
|
35
|
+
else if (existing?.trim())
|
|
50
36
|
authKey = existing;
|
|
51
37
|
else {
|
|
52
38
|
if (!authKey) {
|
|
@@ -102,45 +88,77 @@ export function createCanvasMedia(dependencies) {
|
|
|
102
88
|
await response.body?.cancel().catch(() => undefined);
|
|
103
89
|
throw mediaFailure("request", summary, response.status);
|
|
104
90
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
91
|
+
return { response, summary, uri: freshKey === undefined ? uri : withFilemsAuthKey(uri, freshKey) };
|
|
92
|
+
}
|
|
93
|
+
throw mediaFailure("redirect", responseDiagnostics(url, 5));
|
|
94
|
+
}
|
|
95
|
+
async function checkSignedImageAccess(uri, signal) {
|
|
96
|
+
const probeSignal = AbortSignal.any([signal, AbortSignal.timeout(2000)]);
|
|
97
|
+
try {
|
|
98
|
+
const verified = await fetchRemote(uri, probeSignal);
|
|
99
|
+
await verified.response.body?.cancel().catch(() => undefined);
|
|
100
|
+
signal.throwIfAborted();
|
|
101
|
+
return verified.uri;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
signal.throwIfAborted();
|
|
105
|
+
// A local observation cannot rule out access by the processing service.
|
|
106
|
+
// The original URL was validated by the caller; never send a redirect target.
|
|
107
|
+
return uri;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async function readWithEvidence(uri, signal, limit = 64 * 1024 * 1024) {
|
|
111
|
+
signal.throwIfAborted();
|
|
112
|
+
if (uri.startsWith("file:")) {
|
|
113
|
+
const file = await inspectUploadFile({ url: uri, signal });
|
|
114
|
+
if (file.size > limit)
|
|
115
|
+
throw new ToolInputError("media_too_large", "/arguments");
|
|
113
116
|
try {
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
while (true) {
|
|
117
|
-
const { value, done } = await reader.read();
|
|
118
|
-
if (done)
|
|
119
|
-
break;
|
|
120
|
-
size += value.byteLength;
|
|
121
|
-
if (size > limit)
|
|
122
|
-
throw new ToolInputError("media_too_large", "/arguments");
|
|
123
|
-
chunks.push(Buffer.from(value));
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
finally {
|
|
127
|
-
await reader.cancel().catch(() => undefined);
|
|
128
|
-
reader.releaseLock();
|
|
129
|
-
}
|
|
117
|
+
const bytes = await readFile(file.filePath, { signal });
|
|
118
|
+
return { bytes, summary: { ...uriShape(uri), mediaPhase: "read", mediaBytesRead: bytes.length } };
|
|
130
119
|
}
|
|
131
120
|
catch (cause) {
|
|
132
121
|
if (signal.aborted)
|
|
133
122
|
throw signal.reason;
|
|
134
|
-
|
|
135
|
-
if (cause instanceof ToolInputError)
|
|
136
|
-
throw Object.assign(cause, { diagnosticSummary: evidence });
|
|
137
|
-
throw mediaFailure("read", evidence, response.status, cause);
|
|
123
|
+
throw new LocalFileInputError(cause, "file_read_failed", { ...uriShape(uri), mediaPhase: "read" });
|
|
138
124
|
}
|
|
139
|
-
if (freshKey !== undefined)
|
|
140
|
-
renewed.set(uri, withFilemsAuthKey(uri, freshKey));
|
|
141
|
-
return { bytes: Buffer.concat(chunks), summary: { ...summary, mediaPhase: "read", mediaBytesRead: size }, status: response.status };
|
|
142
125
|
}
|
|
143
|
-
|
|
126
|
+
const { response, summary } = await fetchRemote(uri, signal);
|
|
127
|
+
if (!response.body)
|
|
128
|
+
throw mediaFailure("read", summary, response.status);
|
|
129
|
+
if (Number(response.headers.get("content-length")) > limit) {
|
|
130
|
+
await response.body.cancel().catch(() => undefined);
|
|
131
|
+
throw Object.assign(new ToolInputError("media_too_large", "/arguments"), { diagnosticSummary: { ...summary, mediaPhase: "read" } });
|
|
132
|
+
}
|
|
133
|
+
const chunks = [];
|
|
134
|
+
let size = 0;
|
|
135
|
+
try {
|
|
136
|
+
const reader = response.body.getReader();
|
|
137
|
+
try {
|
|
138
|
+
while (true) {
|
|
139
|
+
const { value, done } = await reader.read();
|
|
140
|
+
if (done)
|
|
141
|
+
break;
|
|
142
|
+
size += value.byteLength;
|
|
143
|
+
if (size > limit)
|
|
144
|
+
throw new ToolInputError("media_too_large", "/arguments");
|
|
145
|
+
chunks.push(Buffer.from(value));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
await reader.cancel().catch(() => undefined);
|
|
150
|
+
reader.releaseLock();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch (cause) {
|
|
154
|
+
if (signal.aborted)
|
|
155
|
+
throw signal.reason;
|
|
156
|
+
const evidence = { ...summary, mediaPhase: "read", mediaBytesRead: Math.min(size, 64 * 1024 * 1024) };
|
|
157
|
+
if (cause instanceof ToolInputError)
|
|
158
|
+
throw Object.assign(cause, { diagnosticSummary: evidence });
|
|
159
|
+
throw mediaFailure("read", evidence, response.status, cause);
|
|
160
|
+
}
|
|
161
|
+
return { bytes: Buffer.concat(chunks), summary: { ...summary, mediaPhase: "read", mediaBytesRead: size }, status: response.status };
|
|
144
162
|
}
|
|
145
163
|
async function read(uri, signal, limit) {
|
|
146
164
|
return (await readWithEvidence(uri, signal, limit)).bytes;
|
|
@@ -180,19 +198,7 @@ export function createCanvasMedia(dependencies) {
|
|
|
180
198
|
// Keep the actual input extension/MIME for audio references instead of renaming every file .mp3.
|
|
181
199
|
return (await dependencies.uploader.upload({ url: uri }, access, signal)).url;
|
|
182
200
|
}
|
|
183
|
-
return { read, image, upload, uploadFile,
|
|
184
|
-
}
|
|
185
|
-
/** A media limit reached while retrieving a result is a delivery failure, not a user input error. */
|
|
186
|
-
export async function readOutputMedia(media, uri, signal) {
|
|
187
|
-
try {
|
|
188
|
-
return await media.read(uri, signal);
|
|
189
|
-
}
|
|
190
|
-
catch (cause) {
|
|
191
|
-
signal.throwIfAborted();
|
|
192
|
-
if (!(cause instanceof ToolInputError))
|
|
193
|
-
throw cause;
|
|
194
|
-
throw new RemoteProtocolError({}, cause, cause.reason === "media_too_large" ? "TOOL_OUTPUT_MEDIA_TOO_LARGE" : "TOOL_OUTPUT_READ_FAILED");
|
|
195
|
-
}
|
|
201
|
+
return { read, image, upload, uploadFile, checkSignedImageAccess };
|
|
196
202
|
}
|
|
197
203
|
function maskConversionError(cause) {
|
|
198
204
|
return new ToolInputError("mask_geometry_or_format", "/arguments/mask", [], cause);
|
|
@@ -7,7 +7,7 @@ import { ToolInputError } from "./catalog.js";
|
|
|
7
7
|
export const canvasModelBindings = [
|
|
8
8
|
["image.edit", "image-edit-standard", "canvas-quick-image-edit", "canvas-image-edit", "标准改图", "dify"],
|
|
9
9
|
["image.edit", "image-edit-smart", "canvas-smart-image-edit", "canvas-image-edit", "智能改图", "dify"],
|
|
10
|
-
["image.matting", "image-matting-standard", "old_matting", "canvas-image-matting", "标准抠图", "
|
|
10
|
+
["image.matting", "image-matting-standard", "old_matting", "canvas-image-matting", "标准抠图", "dify"],
|
|
11
11
|
["image.matting", "image-matting-smart", "canvas-smart-matting", "canvas-image-matting", "智能抠图", "dify"],
|
|
12
12
|
["image.remove", "image-remove-standard", "canvas-quick-image-remove", "canvas-image-remove", "标准消除", "dify"],
|
|
13
13
|
["image.remove", "image-remove-smart", "canvas-image-remove-smart", "canvas-image-remove", "智能消除", "dify"],
|
|
@@ -144,8 +144,8 @@ export function canvasModel(raw, binding, configuration, english = false) {
|
|
|
144
144
|
"image-expand-smart": "按自然尺寸和像素坐标放置原图、补绘外围;智能输出采用目标比例,像素尺寸由当前分辨率选项决定,可能改变原图细节。",
|
|
145
145
|
"image-text-edit": "replacements 用完整原文匹配;空 to 表示删除。重复原文无法指定某一次出现;实际文字与版式以返回图片为准。",
|
|
146
146
|
"image-ocr": "返回 application/json 内嵌资源,内容为 image{uri,width,height} 和 blocks[{bbox:[left,top,right,bottom],category,text?}];坐标以返回识别图的左上角为原点,单位像素。",
|
|
147
|
-
"image-layers-layout": "用于拆分版式元素,例如海报的标题、正文和底图。输入按比例缩小到3000×3000范围内,不放大小图。返回原生模板 JSON
|
|
148
|
-
"image-layers-smart": "用于分开照片中的物件和背景,例如商品与周围的摆件。输入按比例缩小到3000×3000范围内,不放大小图;服务要求处理后宽×高至少262144总像素(512×512),不是每条边都至少512。把图片拆为独立物件图层,返回原生模板 JSON
|
|
147
|
+
"image-layers-layout": "用于拆分版式元素,例如海报的标题、正文和底图。输入按比例缩小到3000×3000范围内,不放大小图。返回原生模板 JSON 资源和服务附带的说明;文字/图片/矢量的实际可编辑程度以模板图层为准,字体可能替换。不是PSD。通过已发现的 Editor 导入能力使用模板。",
|
|
148
|
+
"image-layers-smart": "用于分开照片中的物件和背景,例如商品与周围的摆件。输入按比例缩小到3000×3000范围内,不放大小图;服务要求处理后宽×高至少262144总像素(512×512),不是每条边都至少512。把图片拆为独立物件图层,返回原生模板 JSON 和服务附带的说明;maxLayers 是图层数量上限,按当前远端计费组件计价。不是逐字OCR或PSD。",
|
|
149
149
|
"image-vectorize": "返回 SVG 资源;形状、颜色和细节可能重建,实际矢量内容以返回文件为准。",
|
|
150
150
|
"video-edit-smart": "从原视频推导时长与比例;原片与全部参考视频的合计时长不超过15秒。audioEnabled 控制输出是否有音轨,不承诺原音轨内容不变。智能处理可能改动画面与声音。",
|
|
151
151
|
"video-enhance-standard": "标准视频超分,从实际输入时长计费(向上取整秒),请求保持原视频;实际时长、画面及原声以返回视频为准。",
|
|
@@ -16,25 +16,37 @@ export async function recoverCanvasTool(progress, context, dependencies) {
|
|
|
16
16
|
return { state: "complete", content: pipeline.partialContent, fromCheckpoint: true };
|
|
17
17
|
if (!["dify", "toolkit", "sync"].includes(pipeline.protocol))
|
|
18
18
|
return unknown();
|
|
19
|
-
if (pipeline.model === "image-matting-standard") {
|
|
19
|
+
if (pipeline.model === "image-matting-standard" && pipeline.protocol === "sync") {
|
|
20
20
|
if (pipeline.settlement && pipeline.partialContent) {
|
|
21
21
|
const { contentId, refIds } = pipeline.settlement;
|
|
22
|
-
const result = await createMattingRights(dependencies)(
|
|
22
|
+
const result = await createMattingRights(dependencies)(`content_id=${encodeURIComponent(contentId)}&ref_ids=${encodeURIComponent(refIds.join(","))}&image_quality=standard`, context);
|
|
23
23
|
// Zero outstanding rights confirms this record is deliverable; it says nothing about the actual debit.
|
|
24
24
|
if (result.used_count === 0)
|
|
25
25
|
return { state: "complete", content: pipeline.partialContent, fromCheckpoint: true };
|
|
26
26
|
}
|
|
27
27
|
return unknown();
|
|
28
28
|
}
|
|
29
|
+
const childId = pipeline.matting?.segmentTaskId ?? pipeline.matting?.classifyTaskId;
|
|
30
|
+
if (pipeline.requiresFinalization && (pipeline.matting?.childProtocol === "dify" || pipeline.model === "image-matting-standard")) {
|
|
31
|
+
if (!childId)
|
|
32
|
+
return unknown();
|
|
33
|
+
const child = await queryToolResult(dependencies.transport, { ...context.access, signal: context.signal, taskId: childId, normalize: canvasContent,
|
|
34
|
+
...(childId === progress.remoteTaskId && dependencies.onDifyTaskId ? { onDifyTaskId: dependencies.onDifyTaskId } : {}) });
|
|
35
|
+
if (child.state === "failed")
|
|
36
|
+
throw child.error;
|
|
37
|
+
// Child text and masks are private working data, never the caller's finished image.
|
|
38
|
+
return pipeline.partialContent ? unknown() : child.state === "pending" ? { state: "pending" } : unknown();
|
|
39
|
+
}
|
|
29
40
|
if (!progress.remoteTaskId || pipeline.protocol === "sync")
|
|
30
41
|
return unknown();
|
|
31
42
|
const response = pipeline.protocol === "toolkit"
|
|
32
43
|
? await queryToolkitResult(dependencies.transport, progress.remoteTaskId, context, dependencies.onUnrepresented)
|
|
33
|
-
: await queryToolResult(dependencies.transport, { ...context.access, signal: context.signal, taskId: progress.remoteTaskId, normalize: canvasContent,
|
|
44
|
+
: await queryToolResult(dependencies.transport, { ...context.access, signal: context.signal, taskId: progress.remoteTaskId, normalize: canvasContent,
|
|
45
|
+
...(dependencies.onDifyTaskId ? { onDifyTaskId: dependencies.onDifyTaskId } : {}), onUnrepresented: dependencies.onUnrepresented });
|
|
34
46
|
if (response.state === "failed")
|
|
35
47
|
throw response.error;
|
|
36
48
|
if (response.state === "pending")
|
|
37
|
-
return { state: "pending" };
|
|
49
|
+
return pipeline.requiresFinalization && pipeline.partialContent ? unknown() : { state: "pending" };
|
|
38
50
|
// A smart matting generation is only intermediate; recovery must not submit its segmentation.
|
|
39
51
|
if (pipeline.requiresFinalization)
|
|
40
52
|
return { state: "unknown", content: response.content };
|
|
@@ -44,7 +56,7 @@ export async function recoverCanvasTool(progress, context, dependencies) {
|
|
|
44
56
|
content = verification?.ocr ? ocrResult(response.content, verification.ocr) : response.content;
|
|
45
57
|
}
|
|
46
58
|
else if (model.startsWith("image-layers-"))
|
|
47
|
-
content =
|
|
59
|
+
content = templateResult(response.content);
|
|
48
60
|
else
|
|
49
61
|
content = presentToolContent(response.content, model.startsWith("video-") ? "video" : "image", dependencies.onMissingMedia);
|
|
50
62
|
return { state: "complete", content };
|
|
@@ -4,7 +4,6 @@ import { contractDocument } from "../../contracts/schema.js";
|
|
|
4
4
|
import { parseHttpAssetUrl, parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
|
|
5
5
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
6
6
|
import { normalizeToolContent } from "./tool-api-adapter.js";
|
|
7
|
-
import { readOutputMedia } from "./canvas-media.js";
|
|
8
7
|
export function record(value) {
|
|
9
8
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
10
9
|
}
|
|
@@ -48,7 +47,6 @@ function canvasContract(file) {
|
|
|
48
47
|
return validate(value);
|
|
49
48
|
};
|
|
50
49
|
}
|
|
51
|
-
const validateTemplate = canvasContract("tool.call/template-payload.schema.json");
|
|
52
50
|
const validateOcr = canvasContract("tool.call/ocr-payload.schema.json");
|
|
53
51
|
function assertOcrPayload(payload) {
|
|
54
52
|
if (!validateOcr(payload))
|
|
@@ -90,54 +88,26 @@ export function ocrResult(content, image, id = randomUUID()) {
|
|
|
90
88
|
}
|
|
91
89
|
return result;
|
|
92
90
|
}
|
|
93
|
-
export
|
|
94
|
-
|
|
95
|
-
(part.mimeType === "application/json" || part.name.toLowerCase().endsWith(".json"))
|
|
96
|
-
|
|
91
|
+
export function templateResult(content) {
|
|
92
|
+
if (content.some(part => part.type === "resource_link" &&
|
|
93
|
+
(part.mimeType === "application/json" || part.name.toLowerCase().endsWith(".json"))))
|
|
94
|
+
return content;
|
|
95
|
+
const links = content.flatMap((part, index) => {
|
|
97
96
|
if (part.type !== "text")
|
|
98
97
|
return [];
|
|
98
|
+
const uri = part.text.trim();
|
|
99
|
+
if (/\s/u.test(uri))
|
|
100
|
+
return [];
|
|
99
101
|
try {
|
|
100
|
-
parseHttpAssetUrl(
|
|
101
|
-
return /\s/u.test(part.text.trim()) ? [] : [i];
|
|
102
|
+
parseHttpAssetUrl(uri);
|
|
102
103
|
}
|
|
103
104
|
catch {
|
|
104
105
|
return [];
|
|
105
106
|
}
|
|
107
|
+
return [{ index, uri }];
|
|
106
108
|
});
|
|
107
|
-
if (
|
|
109
|
+
if (links.length !== 1)
|
|
108
110
|
return content;
|
|
109
|
-
const index =
|
|
110
|
-
|
|
111
|
-
const uri = selected.type === "text" ? selected.text.trim() : selected.type === "resource_link" ? selected.uri : "";
|
|
112
|
-
const result = [...content];
|
|
113
|
-
if (selected.type === "text")
|
|
114
|
-
result[index] = link(uri, "template.json", "application/json")[0];
|
|
115
|
-
try {
|
|
116
|
-
const bytes = await readOutputMedia(media, outputUri(uri), signal);
|
|
117
|
-
const resolved = media.deliveryUri?.(uri) ?? uri;
|
|
118
|
-
const part = result[index];
|
|
119
|
-
if (part?.type === "resource_link" && resolved !== uri)
|
|
120
|
-
result[index] = { ...part, uri: resolved };
|
|
121
|
-
const template = JSON.parse(bytes.toString("utf8"));
|
|
122
|
-
if (!validateTemplate(template) || !record(template) || !Array.isArray(template.pages))
|
|
123
|
-
throw new RemoteProtocolError();
|
|
124
|
-
const types = new Map();
|
|
125
|
-
const stack = template.pages.flatMap((page) => page.elements);
|
|
126
|
-
while (stack.length) {
|
|
127
|
-
const element = stack.pop();
|
|
128
|
-
if (!record(element) || typeof element.type !== "string")
|
|
129
|
-
continue;
|
|
130
|
-
types.set(element.type, (types.get(element.type) ?? 0) + 1);
|
|
131
|
-
if (Array.isArray(element.elements))
|
|
132
|
-
stack.push(...element.elements);
|
|
133
|
-
}
|
|
134
|
-
const counts = [...types].map(([type, count]) => `${type}: ${count}`).join("; ");
|
|
135
|
-
result.push({ type: "text", text: english ? `Native template, ${counts}. The editor matches fonts and may substitute missing fonts.`
|
|
136
|
-
: `原生模板,${counts}。字体由编辑器匹配,缺失字体可能替换。` });
|
|
137
|
-
}
|
|
138
|
-
catch {
|
|
139
|
-
signal.throwIfAborted();
|
|
140
|
-
result.push({ type: "text", text: english ? "The template link is included. Its layer summary is unavailable." : "已返回模板链接,暂未取得图层摘要。" });
|
|
141
|
-
}
|
|
142
|
-
return result;
|
|
111
|
+
const { index, uri } = links[0];
|
|
112
|
+
return content.map((part, i) => i === index ? link(uri, "template.json", "application/json")[0] : part);
|
|
143
113
|
}
|