@insmind/cli 2.1.6 → 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/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/matting-billing.js +3 -73
- package/dist/src/features/tool/mns-catalog-adapter.js +0 -3
- 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 +4 -4
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { httpUserAgent } from "../platform/http-user-agent.js";
|
|
1
2
|
import { canvasModelBindings } from "../features/tool/canvas-models.js";
|
|
2
3
|
import { createWindAnalytics } from "../analytics/wind.js";
|
|
3
4
|
import { taskScope } from "../features/task/store.js";
|
|
@@ -43,7 +44,6 @@ import { createCanvasToolAdapter } from "../features/tool/canvas-tool-adapter.js
|
|
|
43
44
|
import { recoverCanvasTool } from "../features/tool/canvas-recovery.js";
|
|
44
45
|
import { authorizeToolResources } from "../features/tool/resource-authorizer.js";
|
|
45
46
|
import { createCanvasMedia } from "../features/tool/canvas-media.js";
|
|
46
|
-
import { createStandardMatting } from "../features/tool/matting-billing.js";
|
|
47
47
|
import { createToolUseCases } from "../features/tool/use-cases.js";
|
|
48
48
|
import { createOrgUseCases } from "../features/org/use-cases.js";
|
|
49
49
|
import { createOrgService } from "../features/org/org-service.js";
|
|
@@ -86,12 +86,16 @@ export function createProductionRuntime(options = {}) {
|
|
|
86
86
|
...(environmentLocale === undefined ? {} : { environment: environmentLocale }),
|
|
87
87
|
...(localSystemLocale === undefined ? {} : { system: localSystemLocale })
|
|
88
88
|
});
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
"
|
|
92
|
-
"
|
|
93
|
-
|
|
94
|
-
|
|
89
|
+
const userAgent = httpUserAgent(product.commandName, primarySkill.version);
|
|
90
|
+
const businessHeaders = {
|
|
91
|
+
"User-Agent": userAgent,
|
|
92
|
+
...(product.id === "insmind" ? {
|
|
93
|
+
"X-Locale": locale.locale,
|
|
94
|
+
"X-Language": locale.language,
|
|
95
|
+
"X-Market": locale.market,
|
|
96
|
+
"X-Legal-Region": locale.legalRegion
|
|
97
|
+
} : {})
|
|
98
|
+
};
|
|
95
99
|
const now = options.now ?? (() => new Date());
|
|
96
100
|
const telemetryEnvironment = options.telemetryEnvironment ?? (env.CLI_TELEMETRY_ENV === "test" ? "test" : "production");
|
|
97
101
|
const host = hostTelemetryContext(env);
|
|
@@ -149,35 +153,35 @@ export function createProductionRuntime(options = {}) {
|
|
|
149
153
|
fetch,
|
|
150
154
|
now,
|
|
151
155
|
traceparent: () => telemetry.traceparent(),
|
|
152
|
-
|
|
156
|
+
businessHeaders
|
|
153
157
|
});
|
|
154
158
|
const creditsTransport = createSignedHttpTransport({
|
|
155
159
|
baseUrl: endpoints.creditsApi,
|
|
156
160
|
fetch,
|
|
157
161
|
now,
|
|
158
162
|
traceparent: () => telemetry.traceparent(),
|
|
159
|
-
|
|
163
|
+
businessHeaders
|
|
160
164
|
});
|
|
161
165
|
const agentTransport = createSignedHttpTransport({
|
|
162
166
|
baseUrl: endpoints.agentApi,
|
|
163
167
|
fetch,
|
|
164
168
|
now,
|
|
165
169
|
traceparent: () => telemetry.traceparent(),
|
|
166
|
-
|
|
170
|
+
businessHeaders
|
|
167
171
|
});
|
|
168
172
|
const mnsTransport = createSignedHttpTransport({
|
|
169
173
|
baseUrl: endpoints.mnsApi,
|
|
170
174
|
fetch,
|
|
171
175
|
now,
|
|
172
176
|
traceparent: () => telemetry.traceparent(),
|
|
173
|
-
|
|
177
|
+
businessHeaders
|
|
174
178
|
});
|
|
175
179
|
const toolTransport = createSignedHttpTransport({
|
|
176
180
|
baseUrl: endpoints.toolApi,
|
|
177
181
|
fetch,
|
|
178
182
|
now,
|
|
179
183
|
traceparent: () => telemetry.traceparent(),
|
|
180
|
-
|
|
184
|
+
businessHeaders
|
|
181
185
|
});
|
|
182
186
|
const damTransport = createSignedHttpTransport({
|
|
183
187
|
baseUrl: endpoints.damApi,
|
|
@@ -185,11 +189,12 @@ export function createProductionRuntime(options = {}) {
|
|
|
185
189
|
now,
|
|
186
190
|
channelId: "32",
|
|
187
191
|
traceparent: () => telemetry.traceparent(),
|
|
188
|
-
|
|
192
|
+
businessHeaders
|
|
189
193
|
});
|
|
190
194
|
const sso = createSsoService({
|
|
191
195
|
ssoApi: endpoints.ssoApi,
|
|
192
196
|
clientId: product.deviceClientId,
|
|
197
|
+
userAgent,
|
|
193
198
|
traceparent: () => telemetry.traceparent(),
|
|
194
199
|
fetch,
|
|
195
200
|
now
|
|
@@ -309,7 +314,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
309
314
|
now,
|
|
310
315
|
channelId: "32",
|
|
311
316
|
traceparent: () => telemetry.traceparent(),
|
|
312
|
-
|
|
317
|
+
businessHeaders
|
|
313
318
|
}) });
|
|
314
319
|
const onPartialResourceFailure = (error) => {
|
|
315
320
|
if (!(error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
|
|
@@ -373,8 +378,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
373
378
|
const verifyToolOutput = createToolOutputVerifier(resourceAuthorizer, onMissingMedia);
|
|
374
379
|
const canvasTools = createCanvasToolAdapter({
|
|
375
380
|
transport: toolTransport, recordTransport: damTransport, resourceAuthorizer, telemetry, media: canvasMedia, onMissingMedia, onUnrepresented, english: product.id === "insmind",
|
|
376
|
-
fallback: createToolApiAdapter({ transport: toolTransport, telemetry, onUnrepresented, verifyOutput: verifyToolOutput })
|
|
377
|
-
standardMatting: createStandardMatting({ transport: toolTransport, recordTransport: damTransport, media: canvasMedia() })
|
|
381
|
+
fallback: createToolApiAdapter({ transport: toolTransport, telemetry, onUnrepresented, verifyOutput: verifyToolOutput })
|
|
378
382
|
});
|
|
379
383
|
const taskFailureNote = (error, operation = telemetry.creationContext().operation) => {
|
|
380
384
|
const outcome = mapCliError(error, { aborted: false, product, operation, failureStage: telemetry.failureStage(error) });
|
|
@@ -408,6 +412,21 @@ export function createProductionRuntime(options = {}) {
|
|
|
408
412
|
text,
|
|
409
413
|
failureNote: taskFailureNote,
|
|
410
414
|
recovery: {
|
|
415
|
+
async checkpointPartial(progress, state, signal) {
|
|
416
|
+
const pipeline = progress.toolPipeline;
|
|
417
|
+
if (pipeline?.model !== "image-matting-smart" || !pipeline.requiresFinalization || !pipeline.partialContent || !progress.toolUsage)
|
|
418
|
+
return;
|
|
419
|
+
const partial = toolOutputWithBillingUnit({ content: pipeline.partialContent, usage: progress.toolUsage }, product.billingUnit);
|
|
420
|
+
try {
|
|
421
|
+
return await authorizeTaskResult(partial, state, signal);
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
signal.throwIfAborted();
|
|
425
|
+
if (!onPartialResourceFailure(error))
|
|
426
|
+
throw error;
|
|
427
|
+
return partial;
|
|
428
|
+
}
|
|
429
|
+
},
|
|
411
430
|
async authorize(result, state, signal, progress) {
|
|
412
431
|
const authorized = await authorizeTaskResult(result, state, signal);
|
|
413
432
|
const tool = progress?.generation?.tool ?? canvasModelBindings.find(binding => binding[1] === progress?.toolPipeline?.model)?.[0];
|
|
@@ -449,7 +468,8 @@ export function createProductionRuntime(options = {}) {
|
|
|
449
468
|
try {
|
|
450
469
|
recovered = await telemetry.stage("task.query", () => recoverCanvasTool(progress, {
|
|
451
470
|
access: { credential: state.credential, organizationId: state.organization.id }, signal
|
|
452
|
-
}, { transport: toolTransport, onMissingMedia, onUnrepresented,
|
|
471
|
+
}, { transport: toolTransport, onMissingMedia, onUnrepresented,
|
|
472
|
+
onDifyTaskId: id => telemetry.annotate({ dify_task_id: id }) }));
|
|
453
473
|
}
|
|
454
474
|
catch (error) {
|
|
455
475
|
if (!(error instanceof ToolTaskFailedError) && !(error instanceof ToolTaskCanceledError))
|
package/dist/src/cli/errors.js
CHANGED
|
@@ -10,7 +10,7 @@ import { SsoRequestError } from "../features/auth/sso-service.js";
|
|
|
10
10
|
import { AuthorizedAccountContextMissingError, BrowserOpenError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
|
|
11
11
|
import { AgentInputError } from "../features/agent/use-cases.js";
|
|
12
12
|
import { ToolInputError } from "../features/tool/catalog.js";
|
|
13
|
-
import { ToolTaskFailedError, ToolTaskCanceledError
|
|
13
|
+
import { ToolTaskFailedError, ToolTaskCanceledError } from "../features/tool/tool-errors.js";
|
|
14
14
|
import { AgentAuditRejectedError } from "../features/agent/creative-protocol.js";
|
|
15
15
|
import { isContentReviewRejection } from "../features/task/creation-refusal.js";
|
|
16
16
|
import { ObjectStorageUploadError } from "../features/dam/object-storage.js";
|
|
@@ -209,7 +209,7 @@ function mapBaseCliError(error, options) {
|
|
|
209
209
|
return failure("USAGE_ERROR", "Invalid command or arguments. See --help.", 2);
|
|
210
210
|
return failure("USAGE_ERROR", "命令或参数无效,请查看 --help。", 2);
|
|
211
211
|
}
|
|
212
|
-
if (
|
|
212
|
+
if (options.product?.id !== "insmind" && options.operation === "tool.call" && isInsufficientCreditsError(error)) {
|
|
213
213
|
return failure("INSUFFICIENT_CREDITS", text("当前可用额度不足,本次生成未能完成。", "Available credits are insufficient; this creation could not complete."), 1, refusalSteps);
|
|
214
214
|
}
|
|
215
215
|
if (isContentReviewRejection(error, { product: options.product?.id ?? "gaoding", operation: options.operation })) {
|
|
@@ -36,7 +36,7 @@ export function registerTaskCommands(program, runtime) {
|
|
|
36
36
|
text("completed 时读取 result。tool.call 返回 content,agent.send 返回 message.parts。重发成品时原样复制本次结果里的完整链接,包括查询参数和签名。若本轮返回文本或补充问题,向用户转述或提问。", "On completed, read result.content for tool.call or result.message.parts for agent.send. When resending an asset, copy the complete link from this result, including its query parameters and signature. Relay text or questions to the user when that is what the turn returned."),
|
|
37
37
|
text("若稿定资源链接已过期,再查原 taskId 可刷新结构化资源的下载授权。第三方链接和正文按原样返回,CLI 不能替第三方续签。", "If a Gaoding file link has expired, query the original taskId for fresh access to structured assets. Third-party URLs and prose are returned unchanged; the CLI cannot renew another provider's signature."),
|
|
38
38
|
text("failed 时向用户说明 note 中的原因。只有错误明确说明尚未派发,才按提示修正并再调用。服务已明确拒绝时,换模型也会发起一次新创作,须有用户补充的需求或另做一次的授权。受理后状态为 unknown 时保留原 ID 核查。", "On failed, relay the cause from note. Correct and retry an input when the error confirms the request was never dispatched. After a definite service refusal, switching models starts another creation and requires a revised request or authorization from the user. On unknown after acceptance, keep and check the original ID."),
|
|
39
|
-
text("unknown
|
|
39
|
+
text("unknown 表示无法确认本次执行终态。failed 或 unknown 中的 partialResult 可交付为中间产物,例如智能抠图的重绘图;请同时说明尚未完成的步骤。", "unknown means completion cannot be confirmed. A partialResult on failed or unknown can be shared as an intermediate result, such as a smart cutout redraw. Explain which step remains incomplete."),
|
|
40
40
|
text("读取本地状态不请求组织绑定;查询远端进度或获取下载授权仍需联网授权。查询请求失败不代表生成失败,可用原 taskId 重查。", "Local status reads do not bind the organization. Remote progress and download authorization still require network access. A failed query does not mean generation failed; query the same taskId again."),
|
|
41
41
|
text("查询得到完整结果但最终缓存保存失败时仍返回结果和退出码 0;请保留 stderr 警告所指的输出,后续可能无法恢复。", "A complete result is delivered with exit code 0 if only final cache persistence fails; keep the output as warned on stderr because later recovery may be unavailable."),
|
|
42
42
|
text("最终错误为 stderr 中的 JSON error 对象;stderr 也可能有进度和警告,中断不代表远端任务取消。", "The final error is a JSON error object on stderr, which may also contain progress and warnings. Interruption does not mean the remote task was cancelled."),
|
|
@@ -93,7 +93,7 @@ export function createSsoService(options) {
|
|
|
93
93
|
try {
|
|
94
94
|
const response = await options.fetch(url, {
|
|
95
95
|
method,
|
|
96
|
-
headers: { Accept: "application/json", ...(options.traceparent ? { traceparent: options.traceparent() } : {}) },
|
|
96
|
+
headers: { Accept: "application/json", ...(options.userAgent ? { "User-Agent": options.userAgent } : {}), ...(options.traceparent ? { traceparent: options.traceparent() } : {}) },
|
|
97
97
|
signal: AbortSignal.any([
|
|
98
98
|
signal,
|
|
99
99
|
timeoutSignal
|
|
@@ -444,11 +444,18 @@ export function createTaskUseCases(dependencies) {
|
|
|
444
444
|
await usageWarning(id, record.progress.agentUsageModelMissing === true, record.progress.agentUsageAmountMissing === true);
|
|
445
445
|
return result;
|
|
446
446
|
}
|
|
447
|
+
const { checkpointPartial } = dependencies.recovery;
|
|
448
|
+
const withFailedPartialResult = async (task) => {
|
|
449
|
+
if (task.state !== "failed" || !checkpointPartial)
|
|
450
|
+
return task;
|
|
451
|
+
const partialResult = await stage("task.authorize", () => checkpointPartial(record.progress, state, signal));
|
|
452
|
+
return partialResult ? { ...task, partialResult } : task;
|
|
453
|
+
};
|
|
447
454
|
const task = summary(record);
|
|
448
455
|
if (task.state === "failed" || (task.state === "running" && !record.progress.detached)) {
|
|
449
456
|
if (record.telemetry?.steps.some(item => item.event.step === "result_received" && item.event.outcome === "failure"))
|
|
450
457
|
pendingOutput = { scope, record, rejected: true };
|
|
451
|
-
return task;
|
|
458
|
+
return withFailedPartialResult(task);
|
|
452
459
|
}
|
|
453
460
|
let recoveredFromCache = false;
|
|
454
461
|
const { failure, usageModelMissing, usageAmountMissing, ...recovered } = await stage("task.recover", async () => {
|
|
@@ -509,7 +516,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
509
516
|
pendingOutput = { scope, record };
|
|
510
517
|
if (result.result ?? result.partialResult)
|
|
511
518
|
await usageWarning(id, record.progress.agentUsageModelMissing === true, record.progress.agentUsageAmountMissing === true);
|
|
512
|
-
return result;
|
|
519
|
+
return withFailedPartialResult(result);
|
|
513
520
|
},
|
|
514
521
|
async workerStopped(state, id, error, reportedByWorker) {
|
|
515
522
|
const scope = taskScope(state);
|
|
@@ -12,8 +12,8 @@ const copy = {
|
|
|
12
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
13
|
"image-text-edit": ["Image text replacement", "replacements match complete original text. An empty to deletes it. Repeated text cannot be targeted by occurrence; actual text and layout are determined by the returned image."],
|
|
14
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", "For separating layout elements such as poster headlines, body text and background. Fits the source within 3000×3000 pixels without enlargement. Returns native template JSON and
|
|
16
|
-
"image-layers-smart": ["Smart layer decomposition", "For separating objects in a photo from each other and the background, such as a product and surrounding props. Fits the source within 3000×3000 pixels without enlargement; the service requires width × height of at least 262144 total pixels (512×512), not a 512-pixel minimum for each edge. Returns native template JSON and
|
|
15
|
+
"image-layers-layout": ["Layout decomposition", "For separating layout elements such as poster headlines, body text and background. Fits the source within 3000×3000 pixels without enlargement. Returns native template JSON and any accompanying service notes, 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", "For separating objects in a photo from each other and the background, such as a product and surrounding props. Fits the source within 3000×3000 pixels without enlargement; the service requires width × height of at least 262144 total pixels (512×512), not a 512-pixel minimum for each edge. Returns native template JSON and any accompanying service notes, not PSD or word-by-word OCR. maxLayers is an upper bound. Pricing uses current remote metered components."],
|
|
17
17
|
"image-vectorize": ["Image to SVG", "Returns an SVG resource. Shapes, colors and details may be reconstructed; actual vector contents are determined by the returned file."],
|
|
18
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
19
|
"video-enhance-standard": ["Standard video upscale", "Uses ceil(actual seconds) for billing and requests preservation of the source video. Actual duration, visuals and soundtrack are determined by the returned video."],
|
|
@@ -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
|
}
|
|
@@ -3,6 +3,9 @@ import { setTimeout as delay } from "node:timers/promises";
|
|
|
3
3
|
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
4
4
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
5
5
|
import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
6
|
+
import { isFilemsResource } from "../../platform/resource-auth-key.js";
|
|
7
|
+
import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
|
|
8
|
+
import { authorizeCanvasImage } from "./resource-authorizer.js";
|
|
6
9
|
import { createCanvasSegmenter } from "./canvas-matting.js";
|
|
7
10
|
import { ToolInputError } from "./catalog.js";
|
|
8
11
|
import { presentToolContent } from "./tool-output.js";
|
|
@@ -84,7 +87,7 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
84
87
|
await context.observe?.({ submissionStarted: true });
|
|
85
88
|
const result = await telemetry.stage("submit", () => transport.postJson({
|
|
86
89
|
path: protocol === "toolkit" ? "/ai-toolkit/design/tool-call/async" : "/gdesign/tool/v1/dify/call_async",
|
|
87
|
-
body: rpc(name,
|
|
90
|
+
body: rpc(name, args), ...context.access, signal: context.signal,
|
|
88
91
|
onDispatch: async (dispatchedAt) => { await context.observe?.({ dispatchedAt }); }
|
|
89
92
|
}));
|
|
90
93
|
if (!record(result))
|
|
@@ -109,6 +112,25 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
109
112
|
return poll;
|
|
110
113
|
}, context.signal));
|
|
111
114
|
}
|
|
115
|
+
async function serviceImage(input, media, context) {
|
|
116
|
+
let uri = input;
|
|
117
|
+
if (input.startsWith("file:"))
|
|
118
|
+
uri = await media.uploadFile(input, context.access, context.signal);
|
|
119
|
+
else {
|
|
120
|
+
const url = parseSafeRemoteAssetUrl(input);
|
|
121
|
+
if (isFilemsResource(url)) {
|
|
122
|
+
// Only an upstream rejection can tell us that this opaque key has expired.
|
|
123
|
+
if (url.searchParams.get("auth_key")?.trim())
|
|
124
|
+
return media.checkSignedImageAccess(input, context.signal);
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
// Stage third-party hosts' bytes through the existing bounded, origin-checked reader.
|
|
128
|
+
const format = /\.([a-z0-9]{1,12})$/iu.exec(url.pathname)?.[1] ?? "bin";
|
|
129
|
+
uri = await media.upload(await media.read(input, context.signal), format, context.access, context.signal);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return authorizeCanvasImage(uri, dependencies.resourceAuthorizer, context.access, context.signal);
|
|
133
|
+
}
|
|
112
134
|
async function saveResult(context, model, content) {
|
|
113
135
|
// The completed, validated result must still reach the caller on a late cache failure (ADR 0015).
|
|
114
136
|
try {
|
|
@@ -179,20 +201,9 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
179
201
|
const source = await probe(sourceUri, context.signal);
|
|
180
202
|
const rounded = Math.round(source.duration);
|
|
181
203
|
const references = args.referenceVideos ?? [];
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
try {
|
|
186
|
-
total += (await probe(reference, context.signal)).duration;
|
|
187
|
-
}
|
|
188
|
-
catch {
|
|
189
|
-
context.signal.throwIfAborted();
|
|
190
|
-
total = undefined;
|
|
191
|
-
break;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
await quote({ time: Math.ceil(source.duration), duration: rounded, ...(total === undefined ? {} : { video_urls: Math.round(total) }) });
|
|
204
|
+
// Only the primary clip needs probing for the execution arguments. Its duration can be reused for repeated references.
|
|
205
|
+
const knownTotal = references.every(uri => uri === sourceUri) ? source.duration * (references.length + 1) : undefined;
|
|
206
|
+
await quote({ time: Math.ceil(source.duration), duration: rounded, ...(knownTotal === undefined ? {} : { video_urls: Math.round(knownTotal) }) });
|
|
196
207
|
const remote = (uri) => uri.startsWith("file:") ? media.uploadFile(uri, context.access, context.signal) : uri;
|
|
197
208
|
backend.video_urls = JSON.stringify(await Promise.all([sourceUri, ...references].map(remote)));
|
|
198
209
|
if (id === "video-enhance-standard")
|
|
@@ -213,15 +224,11 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
213
224
|
const content = await call(code, serviceArguments(), context);
|
|
214
225
|
return presentToolContent(content, "video", dependencies.onMissingMedia);
|
|
215
226
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
throw new ToolInputError("matting_billing_contract_unavailable", "/model");
|
|
222
|
-
if (model.cost === undefined || model.cost.minimum !== model.cost.maximum)
|
|
223
|
-
throw new ToolInputError("matting_quote_unavailable", "/model");
|
|
224
|
-
return dependencies.standardMatting(source, context, model.cost.maximum, () => segment(source, media, context, args.cropToSubject === true));
|
|
227
|
+
if (id === "image-matting-standard") {
|
|
228
|
+
const source = await media.image(args.image, context.signal);
|
|
229
|
+
await quote({});
|
|
230
|
+
return segment(source, media, context, { protocol, model: id, stage: "preparing", requiresFinalization: true,
|
|
231
|
+
matting: { cropToSubject: args.cropToSubject === true } });
|
|
225
232
|
}
|
|
226
233
|
if (id === "image-text-edit") {
|
|
227
234
|
const replacements = args.replacements;
|
|
@@ -234,46 +241,57 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
234
241
|
return { ...fields, origin: from, new: to === "" ? "REMOVE_TEXT" : to };
|
|
235
242
|
}));
|
|
236
243
|
}
|
|
237
|
-
if (id === "image-ocr" || id === "image-text-edit") {
|
|
238
|
-
const bytes = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).flatten({ background: "white" }).jpeg().toBuffer();
|
|
239
|
-
const info = await sharp(bytes).metadata();
|
|
240
|
-
source = { bytes, width: info.width, height: info.height };
|
|
241
|
-
}
|
|
242
|
-
if (protocol === "toolkit") {
|
|
243
|
-
const bytes = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).png().toBuffer();
|
|
244
|
-
const info = await sharp(bytes).metadata();
|
|
245
|
-
source = { bytes, width: info.width, height: info.height };
|
|
246
|
-
}
|
|
247
244
|
const layerCount = mappedControls.max_layers;
|
|
248
245
|
await quote({ resolution: mappedControls.resolution,
|
|
249
246
|
max_layers: typeof layerCount === "string" && /^\d+$/u.test(layerCount) ? Number(layerCount) : layerCount });
|
|
250
|
-
|
|
251
|
-
if (selection && Object.hasOwn(selectionInstructions, id))
|
|
252
|
-
prepared = await outlineImage(source, selection);
|
|
247
|
+
const selection = typeof args.mask === "string" ? await media.read(args.mask, context.signal) : undefined;
|
|
253
248
|
if (id === "image-matting-smart")
|
|
254
249
|
backend.ratio = "original";
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
const
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
backend.ratio = `${canvas.width / a}:${canvas.height / a}`;
|
|
265
|
-
const instruction = dependencies.english
|
|
266
|
-
? "Extend the green area of the first image, keeping the original image at its position and removing the green screen."
|
|
267
|
-
: "扩展第1张图的纯绿色区域,保留原图所在位置和内容,去除绿幕。";
|
|
268
|
-
backend.prompt = typeof args.prompt === "string" ? instruction + "\n" + args.prompt : instruction;
|
|
250
|
+
let image;
|
|
251
|
+
let dimensions;
|
|
252
|
+
if (selection || id.startsWith("image-expand-") || id === "image-ocr" || id === "image-text-edit" || protocol === "toolkit") {
|
|
253
|
+
const { default: sharp } = await import("sharp");
|
|
254
|
+
let source = await media.image(args.image, context.signal);
|
|
255
|
+
if (id === "image-ocr" || id === "image-text-edit") {
|
|
256
|
+
const bytes = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).flatten({ background: "white" }).jpeg().toBuffer();
|
|
257
|
+
const info = await sharp(bytes).metadata();
|
|
258
|
+
source = { bytes, width: info.width, height: info.height };
|
|
269
259
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
260
|
+
if (protocol === "toolkit") {
|
|
261
|
+
const bytes = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).png().toBuffer();
|
|
262
|
+
const info = await sharp(bytes).metadata();
|
|
263
|
+
source = { bytes, width: info.width, height: info.height };
|
|
274
264
|
}
|
|
265
|
+
let prepared = source.bytes;
|
|
266
|
+
if (selection && Object.hasOwn(selectionInstructions, id))
|
|
267
|
+
prepared = await outlineImage(source, selection);
|
|
268
|
+
if (id.startsWith("image-expand-")) {
|
|
269
|
+
const canvas = args.canvas;
|
|
270
|
+
const placement = args.placement;
|
|
271
|
+
const geometry = expansionGeometry(source, canvas, placement);
|
|
272
|
+
if (id === "image-expand-smart") {
|
|
273
|
+
prepared = await expansionImage(source, canvas, placement);
|
|
274
|
+
let a = canvas.width, b = canvas.height;
|
|
275
|
+
while (b)
|
|
276
|
+
[a, b] = [b, a % b];
|
|
277
|
+
backend.ratio = `${canvas.width / a}:${canvas.height / a}`;
|
|
278
|
+
const instruction = dependencies.english
|
|
279
|
+
? "Extend the green area of the first image, keeping the original image at its position and removing the green screen."
|
|
280
|
+
: "扩展第1张图的纯绿色区域,保留原图所在位置和内容,去除绿幕。";
|
|
281
|
+
backend.prompt = typeof args.prompt === "string" ? instruction + "\n" + args.prompt : instruction;
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
prepared = await sharp(source.bytes).flatten({ background: "white" }).png().toBuffer();
|
|
285
|
+
backend.outer_wh = JSON.stringify(geometry.outer);
|
|
286
|
+
backend.inner_xy_points = JSON.stringify(geometry.corners);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
image = await media.upload(prepared, id === "image-ocr" || id === "image-text-edit" ? "jpg" : "png", context.access, context.signal);
|
|
290
|
+
dimensions = { width: source.width, height: source.height };
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
image = await serviceImage(args.image, media, context);
|
|
275
294
|
}
|
|
276
|
-
const image = await media.upload(prepared, id === "image-ocr" || id === "image-text-edit" ? "jpg" : "png", context.access, context.signal);
|
|
277
295
|
if (protocol === "toolkit") {
|
|
278
296
|
backend.url = image;
|
|
279
297
|
backend.type = id === "image-layers-smart" ? "seedream" : "codia";
|
|
@@ -282,7 +300,7 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
282
300
|
if (args.resolution === undefined) {
|
|
283
301
|
const tiers = Array.isArray(configuration.layerTiers) ? configuration.layerTiers
|
|
284
302
|
: Array.isArray(resolutionField?.options) ? resolutionField.options.filter(record).map(option => option.value) : [];
|
|
285
|
-
const preferred =
|
|
303
|
+
const preferred = dimensions.width * dimensions.height > 1280 * 720 ? "2K" : "1K";
|
|
286
304
|
const tier = tiers.length === 1 ? tiers[0] : tiers.includes(preferred) ? preferred : resolutionField?.default_value;
|
|
287
305
|
if (typeof tier === "string" && (!tiers.length || tiers.includes(tier)))
|
|
288
306
|
backend.resolution = tier;
|
|
@@ -318,21 +336,21 @@ export function createCanvasToolAdapter(dependencies) {
|
|
|
318
336
|
backend.contentid = backend.content_id;
|
|
319
337
|
const toolPipeline = { protocol, model: id, stage: "submitted", requiresFinalization: isMatting,
|
|
320
338
|
...(isMatting ? { matting: { cropToSubject: args.cropToSubject === true } } : {}),
|
|
321
|
-
...(id === "image-ocr" ? { verification: { ocr: { uri: image,
|
|
339
|
+
...(id === "image-ocr" ? { verification: { ocr: { uri: image, ...dimensions } } } : {}) };
|
|
322
340
|
await context.observe?.({ toolPipeline });
|
|
323
341
|
const content = await call(code, serviceArguments(), context, protocol);
|
|
324
342
|
if (id === "image-matting-smart") {
|
|
325
343
|
const sourceUri = oneResource(content);
|
|
326
344
|
const generated = await media.image(sourceUri, context.signal);
|
|
327
|
-
const result = await segment(generated, media, context,
|
|
328
|
-
...toolPipeline, matting: { cropToSubject: args.cropToSubject === true, sourceUri }
|
|
345
|
+
const result = await segment(generated, media, context, {
|
|
346
|
+
...toolPipeline, partialContent: content, matting: { cropToSubject: args.cropToSubject === true, sourceUri }
|
|
329
347
|
});
|
|
330
|
-
return content.map(item => item.type === "resource_link" ? result
|
|
348
|
+
return content.map(item => item.type === "resource_link" ? result[0] : item);
|
|
331
349
|
}
|
|
332
350
|
if (id === "image-ocr")
|
|
333
|
-
return ocrResult(content, { uri: image,
|
|
351
|
+
return ocrResult(content, { uri: image, ...dimensions });
|
|
334
352
|
if (protocol === "toolkit")
|
|
335
|
-
return templateResult(content
|
|
353
|
+
return templateResult(content);
|
|
336
354
|
return presentToolContent(content, "image", dependencies.onMissingMedia);
|
|
337
355
|
}
|
|
338
356
|
return {
|
|
@@ -3,7 +3,7 @@ import { withResponseDiagnostics } from "../../platform/signed-http-transport.js
|
|
|
3
3
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
4
4
|
import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
5
5
|
import { record } from "./canvas-results.js";
|
|
6
|
-
import { ToolTaskFailedError
|
|
6
|
+
import { ToolTaskFailedError } from "./tool-api-adapter.js";
|
|
7
7
|
// Public verification/encryption key used by the existing matting rights service.
|
|
8
8
|
const serviceKey = `-----BEGIN RSA PUBLIC KEY-----
|
|
9
9
|
MIGJAoGBANVv3G1++sfQjoTLN6pOU0ooMzAdRf3W1SItK1MJbXcg6tdBRTfvraso
|
|
@@ -25,11 +25,11 @@ export function encryptMattingParameters(text, key = serviceKey) {
|
|
|
25
25
|
}
|
|
26
26
|
export function createMattingRights(dependencies) {
|
|
27
27
|
const { transport } = dependencies;
|
|
28
|
-
return async function
|
|
28
|
+
return async function checkSettlement(parameters, context) {
|
|
29
29
|
return withResponseDiagnostics(async (onResponse) => {
|
|
30
30
|
const code = `0.${randomBytes(12).readBigUInt64BE().toString()}`;
|
|
31
31
|
const plaintext = `gaoding?key=${randomBytes(18).toString("base64url")}×tamp=${Date.now()}&verify_code=${code}&${parameters}`;
|
|
32
|
-
const result = await transport.postJson({ path, body: { data: encryptMattingParameters(plaintext, dependencies.key ?? serviceKey) },
|
|
32
|
+
const result = await transport.postJson({ path: "/open/editor/mattings/check-deducted/v2", body: { data: encryptMattingParameters(plaintext, dependencies.key ?? serviceKey) },
|
|
33
33
|
...context.access, signal: context.signal, onResponse });
|
|
34
34
|
if (!record(result))
|
|
35
35
|
throw new RemoteProtocolError();
|
|
@@ -43,73 +43,3 @@ export function createMattingRights(dependencies) {
|
|
|
43
43
|
});
|
|
44
44
|
};
|
|
45
45
|
}
|
|
46
|
-
export function createStandardMatting(dependencies) {
|
|
47
|
-
const { transport, media, recordTransport } = dependencies;
|
|
48
|
-
const rights = createMattingRights(dependencies);
|
|
49
|
-
return async (source, context, useCount, compute) => {
|
|
50
|
-
const precheck = () => rights("/open/editor/mattings/billing/precheck/v2", `use_count=${useCount}&image_quality=standard`, context);
|
|
51
|
-
const quote = await precheck();
|
|
52
|
-
if (quote.need_deduct !== undefined && typeof quote.need_deduct !== "boolean")
|
|
53
|
-
throw new RemoteProtocolError();
|
|
54
|
-
if (quote.need_deduct === true || quote.need_deduct === undefined && Number(quote.used_count) > 0) {
|
|
55
|
-
await withResponseDiagnostics(async (onResponse) => {
|
|
56
|
-
const balances = await transport.getJson({ path: "/trade/rights-overview", query: { goods_type_enums: "GAODOU" }, ...context.access, signal: context.signal, onResponse });
|
|
57
|
-
if (!Array.isArray(balances))
|
|
58
|
-
throw new RemoteProtocolError();
|
|
59
|
-
const item = balances.find(item => record(item) && item.goods_type_enum === "GAODOU" && item.identifier === "GAODOU");
|
|
60
|
-
if (!record(item))
|
|
61
|
-
throw new RemoteProtocolError();
|
|
62
|
-
const value = (raw) => { if ((typeof raw !== "number" && typeof raw !== "string") || raw === "" || !Number.isFinite(Number(raw)))
|
|
63
|
-
throw new RemoteProtocolError(); return Number(raw); };
|
|
64
|
-
const total = value(item.total), used = value(item.used), pending = value(item.wait);
|
|
65
|
-
const accountAvailable = total - used - pending;
|
|
66
|
-
const memberLimit = item.member_period_limit === undefined || item.member_period_limit === null ? undefined : value(item.member_period_limit);
|
|
67
|
-
const memberUsed = memberLimit === undefined ? undefined : value(item.member_period_used ?? 0);
|
|
68
|
-
const available = memberLimit === undefined ? accountAvailable : Math.min(accountAvailable, memberLimit - memberUsed);
|
|
69
|
-
if (available < Number(quote.used_count))
|
|
70
|
-
throw Object.assign(new ToolInsufficientCreditsError(), {
|
|
71
|
-
diagnosticSummary: { quotaDecisionSource: "cli_precheck", quotaUnit: "gaodou",
|
|
72
|
-
quotaLimitScope: memberLimit !== undefined && memberLimit - memberUsed < accountAvailable ? "member_period" : "account",
|
|
73
|
-
quotaTotal: total, quotaUsed: used, quotaPending: pending, quotaAvailable: available, quotaRequired: Number(quote.used_count),
|
|
74
|
-
...(memberLimit === undefined ? {} : { quotaMemberLimit: memberLimit, quotaMemberUsed: memberUsed }) }
|
|
75
|
-
});
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
const repositories = await recordTransport.getJson({ path: "/tb-dam/repositories", ...context.access, signal: context.signal });
|
|
79
|
-
if (!Array.isArray(repositories))
|
|
80
|
-
throw new RemoteProtocolError();
|
|
81
|
-
const draft = repositories.find(item => record(item) && item.type === 6);
|
|
82
|
-
if (!record(draft) || typeof draft.repository_id !== "string")
|
|
83
|
-
throw new RemoteProtocolError({}, undefined, "MATTING_DRAFT_REPOSITORY_MISSING");
|
|
84
|
-
const computation = await compute();
|
|
85
|
-
await context.observe?.({ toolPipeline: { protocol: "sync", model: "image-matting-standard", stage: "recording", requiresFinalization: true, partialContent: computation.content } });
|
|
86
|
-
const inputUri = await media.upload(source.bytes, "png", context.access, context.signal);
|
|
87
|
-
const base = { title: "CLI 抠图", description: "CLI 标准抠图", type: "matting", preview_lock: 0, dpi: 72, remark: "", content: "",
|
|
88
|
-
preview: { source_preview: { url: inputUri, width: source.width, height: source.height } }, pri_classify: "MATERIAL", content_format: "gdmatting",
|
|
89
|
-
url: inputUri, repository_id: draft.repository_id, is_hide: true, un_record_recent: true };
|
|
90
|
-
const postRecord = async (body) => {
|
|
91
|
-
const result = await recordTransport.postJson({ path: "/tb-dam/editors/template", body, ...context.access, signal: context.signal });
|
|
92
|
-
if (!record(result) || typeof result.id !== "string" || !result.id)
|
|
93
|
-
throw new RemoteProtocolError({}, undefined, "MATTING_RECORD_INVALID");
|
|
94
|
-
return result.id;
|
|
95
|
-
};
|
|
96
|
-
const refId = await postRecord({ ...base, type: "image" });
|
|
97
|
-
const { width, height } = source;
|
|
98
|
-
const template = { version: "2.16.5", type: "matting", global: { source: "koutu", unit: "px", dpi: 72, showWatermark: false },
|
|
99
|
-
layouts: [{ elements: [{ type: "image", metaInfo: { thirdParty: { matting: { id: refId, refId } } } }] }],
|
|
100
|
-
refs: { [refId]: { id: refId, sourceImage: inputUri, imageHeight: height, imageWidth: width, featheringRadius: 2, lines: [], hairLines: [],
|
|
101
|
-
hairDropColors: [], hairKeepColors: [], pen: [], backgroundColor: null, recoArea: [], recoLines: [], scene: computation.scene,
|
|
102
|
-
crop: { scale: 1, top: 0, left: 0, width, height }, shadow: { offsetX: 0, offsetY: 0, blur: 0, color: "rgba(0,0,0,0)" },
|
|
103
|
-
background: { color: null, image: null, position: ["center", "center"], size: "cover", repeat: "no-repeat" }, outline: [],
|
|
104
|
-
filter: { url: "", strong: 1, name: "", id: 0 }, filename: "CLI 抠图", transform: { rotate: 0 } } } };
|
|
105
|
-
const contentId = await postRecord({ ...base, width, height, origin_url: new URL(inputUri).origin + new URL(inputUri).pathname, content: JSON.stringify(template) });
|
|
106
|
-
const settlement = { contentId, refIds: [refId] };
|
|
107
|
-
await context.observe?.({ toolPipeline: { protocol: "sync", model: "image-matting-standard", stage: "settling", requiresFinalization: true,
|
|
108
|
-
partialContent: computation.content, settlement } });
|
|
109
|
-
await precheck();
|
|
110
|
-
// Never retry this write: an uncertain response must be reconciled through the original record.
|
|
111
|
-
await rights("/open/editor/mattings/complete/v2", `content_id=${contentId}&ref_ids=${refId}&image_quality=standard`, context);
|
|
112
|
-
// The adapter records the validated final result; late cache errors must not discard it.
|
|
113
|
-
return computation.content;
|
|
114
|
-
};
|
|
115
|
-
}
|
|
@@ -183,9 +183,6 @@ function normalizeModel(value, scenes, english = false) {
|
|
|
183
183
|
// With no usable quote, the same listed model can still execute.
|
|
184
184
|
const canQuote = cost && canvasPricingSupported(binding[1], configuration)
|
|
185
185
|
&& !(binding[1] === "image-layers-smart" && settings.some(value => record(value)?.key === "max_layers" && record(value)?.sku_enable === true));
|
|
186
|
-
// Standard matting actually settles this quantity. Other execution protocols never consume a quote.
|
|
187
|
-
if (binding[1] === "image-matting-standard" && (!canQuote || cost?.minimum !== cost?.maximum))
|
|
188
|
-
throw new Error("matting settlement price unavailable");
|
|
189
186
|
const bindingParameters = fixedResolutionPrices ? parameters.map(field => field.name === "resolution" && field.options
|
|
190
187
|
? { ...field, options: field.options.filter(({ value }) => Object.hasOwn(fixedResolutionPrices, value)) } : field) : parameters;
|
|
191
188
|
const listed = { ...normalized, parameters: bindingParameters, sceneSort: match.sort };
|
|
@@ -40,3 +40,13 @@ export async function authorizeToolResources(output, authorizer, access, signal)
|
|
|
40
40
|
}
|
|
41
41
|
return { ...output, content };
|
|
42
42
|
}
|
|
43
|
+
/** Obtain a service-readable image URL with this invocation's own organization. */
|
|
44
|
+
export async function authorizeCanvasImage(uri, authorizer, access, signal) {
|
|
45
|
+
if (!authorizer)
|
|
46
|
+
return uri;
|
|
47
|
+
const { message } = await authorizer.authorize({ message: { parts: [{ url: uri, mediaType: "application/octet-stream" }] } }, access, signal);
|
|
48
|
+
const part = message.parts[0];
|
|
49
|
+
if (!part?.url)
|
|
50
|
+
throw new RemoteProtocolError();
|
|
51
|
+
return part.url;
|
|
52
|
+
}
|
|
@@ -5,7 +5,7 @@ import { RemoteRequestError, withResponseDiagnostics } from "../../platform/sign
|
|
|
5
5
|
import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
6
6
|
import { ToolTaskFailedError, ToolTaskCanceledError } from "./tool-errors.js";
|
|
7
7
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
8
|
-
export { ToolTaskFailedError, ToolTaskCanceledError
|
|
8
|
+
export { ToolTaskFailedError, ToolTaskCanceledError } from "./tool-errors.js";
|
|
9
9
|
import { mediaFilename } from "../../platform/media-type.js";
|
|
10
10
|
const MAX_JAVA_LONG = 9223372036854775807n;
|
|
11
11
|
function isRecord(value) {
|
|
@@ -12,13 +12,6 @@ export class ToolTaskFailedError extends Error {
|
|
|
12
12
|
this.diagnosticReason = evidence.diagnosticReason;
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
-
export class ToolInsufficientCreditsError extends ToolTaskFailedError {
|
|
16
|
-
diagnosticReason = "INSUFFICIENT_CREDITS";
|
|
17
|
-
constructor() {
|
|
18
|
-
super();
|
|
19
|
-
this.name = "ToolInsufficientCreditsError";
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
15
|
export class ToolTaskCanceledError extends Error {
|
|
23
16
|
diagnosticReason = "TASK_CANCELED";
|
|
24
17
|
constructor() { super("用户已取消生成任务。"); this.name = "ToolTaskCanceledError"; }
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type, release } from "node:os";
|
|
2
|
+
export function httpUserAgent(command, version, system = {
|
|
3
|
+
type: type(), release: release(), arch: process.arch, node: process.versions.node
|
|
4
|
+
}) {
|
|
5
|
+
const comment = `${system.type} ${system.release}; ${system.arch}; Node.js/${system.node}`
|
|
6
|
+
.replace(/[^\x20-\x7e]/gu, "_").replace(/[\\()]/gu, "\\$&");
|
|
7
|
+
return `node (${comment}) ${command}/${version}`;
|
|
8
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@insmind/cli",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.7",
|
|
4
4
|
"description": "insMind command-line interface for agents and people.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -50,8 +50,8 @@
|
|
|
50
50
|
"#model-catalog": "./dist/shared/model-catalog/index.js"
|
|
51
51
|
},
|
|
52
52
|
"gaodingRelease": {
|
|
53
|
-
"sourceCommit": "
|
|
54
|
-
"pipelineId": "
|
|
55
|
-
"pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/
|
|
53
|
+
"sourceCommit": "5ad82af1858a5e5e20c3b0018b28fe3a4a53071a",
|
|
54
|
+
"pipelineId": "268194",
|
|
55
|
+
"pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/268194"
|
|
56
56
|
}
|
|
57
57
|
}
|