@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.
@@ -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, { ...args, content_id: args.content_id ?? "" }), ...context.access, signal: context.signal,
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
- let total = source.duration;
183
- if (model.cost) {
184
- for (const reference of references) {
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
- const { default: sharp } = await import("sharp");
217
- let source = await media.image(args.image, context.signal);
218
- const selection = typeof args.mask === "string" ? await media.read(args.mask, context.signal) : undefined;
219
- if (protocol === "sync") {
220
- if (!dependencies.standardMatting)
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
- let prepared = source.bytes;
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
- if (id.startsWith("image-expand-")) {
256
- const canvas = args.canvas;
257
- const placement = args.placement;
258
- const geometry = expansionGeometry(source, canvas, placement);
259
- if (id === "image-expand-smart") {
260
- prepared = await expansionImage(source, canvas, placement);
261
- let a = canvas.width, b = canvas.height;
262
- while (b)
263
- [a, b] = [b, a % b];
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
- else {
271
- prepared = await sharp(source.bytes).flatten({ background: "white" }).png().toBuffer();
272
- backend.outer_wh = JSON.stringify(geometry.outer);
273
- backend.inner_xy_points = JSON.stringify(geometry.corners);
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 = source.width * source.height > 1280 * 720 ? "2K" : "1K";
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, width: source.width, height: source.height } } } : {}) };
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, args.cropToSubject === true, {
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.content[0] : item);
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, width: source.width, height: source.height });
351
+ return ocrResult(content, { uri: image, ...dimensions });
334
352
  if (protocol === "toolkit")
335
- return templateResult(content, media, context.signal, dependencies.english);
353
+ return templateResult(content);
336
354
  return presentToolContent(content, "image", dependencies.onMissingMedia);
337
355
  }
338
356
  return {
@@ -1,77 +1,14 @@
1
+ import { buildParameterModelSchema, buildToolArgumentsSchema as buildSharedToolSchema, parameterSchema } from "#model-catalog";
1
2
  import { lazySchemaCompiler } from "../../platform/schema-compiler.js";
2
3
  import { inputValidationSummary, validationIssues } from "../../platform/schema-issues.js";
3
4
  import { unavailableCanvasMediaRoles } from "./canvas-models.js";
4
5
  import { canonicalizeInputFileUris } from "../../platform/input-uri.js";
5
6
  import { ToolInputError } from "./catalog.js";
6
- function parameterSchema(parameter, includeBounds = false) {
7
- const common = {
8
- ...(parameter.description === undefined ? {} : { description: parameter.description }),
9
- ...(parameter.default === undefined ? {} : { default: parameter.default })
10
- };
11
- if (parameter.type === "uri")
12
- return { type: "string", format: "uri", ...common };
13
- if (parameter.type === "uri[]") {
14
- return { type: "array", items: { type: "string", format: "uri" }, ...common };
15
- }
16
- if (parameter.type === "number" || parameter.type === "integer") {
17
- return {
18
- type: parameter.type,
19
- ...(includeBounds && parameter.minimum !== undefined
20
- ? { minimum: parameter.minimum }
21
- : {}),
22
- ...(includeBounds && parameter.maximum !== undefined
23
- ? { maximum: parameter.maximum }
24
- : {}),
25
- ...common
26
- };
27
- }
28
- if (["boolean", "object", "array"].includes(parameter.type)) {
29
- return { type: parameter.type, ...common };
30
- }
31
- return {
32
- type: "string",
33
- ...(parameter.options === undefined
34
- ? {}
35
- : { enum: parameter.options.map((option) => option.value) }),
36
- ...common
37
- };
38
- }
39
7
  export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要调用的模型机器标识;取值来自 model list。") {
40
- const models = catalog.models.filter((model) => model.tool === tool);
41
- if (models.length === 0)
8
+ const models = catalog.models.filter(model => model.tool === tool);
9
+ if (!models.length)
42
10
  throw new ToolInputError("tool_not_found", "/tool");
43
- const properties = {
44
- model: {
45
- type: "string",
46
- enum: models.map(model => model.model),
47
- description: modelDescription
48
- }
49
- };
50
- const branches = models.map(buildModelArgumentsSchema);
51
- const fieldNames = new Set(branches.flatMap(branch => Object.keys(branch.properties)));
52
- for (const name of fieldNames) {
53
- if (name === "model")
54
- continue;
55
- const fields = branches.flatMap(branch => branch.properties[name] ? [branch.properties[name]] : []);
56
- const field = fields[0];
57
- // An open sibling may accept a completely different value at this key.
58
- // Its presence in the index must not restrict the selected model.
59
- if (branches.some(branch => !Object.hasOwn(branch.properties, name) && branch.additionalProperties)) {
60
- properties[name] = field.description ? { description: field.description } : {};
61
- }
62
- else {
63
- const variants = [...new Map(fields.map(item => [JSON.stringify(item), item])).values()];
64
- properties[name] = variants.length === 1 ? field : { anyOf: variants };
65
- }
66
- }
67
- return {
68
- type: "object",
69
- properties,
70
- required: ["model"],
71
- additionalProperties: true,
72
- allOf: models.map((model, i) => ({ if: { properties: { model: { const: model.model } }, required: ["model"] },
73
- then: branches[i] }))
74
- };
11
+ return buildSharedToolSchema(models.map(model => ({ model: model.model, schema: buildModelArgumentsSchema(model) })), modelDescription);
75
12
  }
76
13
  export function buildModelArgumentsSchema(model) {
77
14
  const managed = model.execution?.kind === "canvas" ? ["content_id", "contentid", "async"] : ["content_id", "contentid"];
@@ -85,29 +22,7 @@ export function buildModelArgumentsSchema(model) {
85
22
  }
86
23
  return { ...schema, propertyNames: { not: { enum: [...managed, ...unavailable] } } };
87
24
  }
88
- const properties = {
89
- ...Object.fromEntries(Object.entries(model.optionalControls ?? {}).filter(([key]) => !managed.includes(key))),
90
- model: {
91
- type: "string",
92
- const: model.model,
93
- description: "要调用的模型机器标识。"
94
- }
95
- };
96
- for (const parameter of model.parameters) {
97
- properties[parameter.name] = parameterSchema(parameter, true);
98
- }
99
- return {
100
- type: "object",
101
- properties,
102
- required: [
103
- "model",
104
- ...model.parameters
105
- .filter((parameter) => parameter.required)
106
- .map((parameter) => parameter.name)
107
- ],
108
- additionalProperties: true,
109
- propertyNames: { not: { enum: managed } }
110
- };
25
+ return buildParameterModelSchema(model, managed);
111
26
  }
112
27
  const compiler = lazySchemaCompiler({ allErrors: true, strict: true });
113
28
  /** Enforce structure that the CLI actually reads or transforms. Business controls go to the service. */
@@ -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, ToolInsufficientCreditsError } from "./tool-api-adapter.js";
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 rights(path, parameters, context) {
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")}&timestamp=${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
- }
@@ -1,3 +1,4 @@
1
+ import { cleanCatalogText as cleanText, normalizeParameter as parameter } from "#model-catalog";
1
2
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
2
3
  import { defaultToolDefinitions } from "./catalog.js";
3
4
  import { canvasModel, canvasModelBindings, canvasSceneCodes } from "./canvas-models.js";
@@ -12,13 +13,6 @@ const rootTools = {
12
13
  "AI-video-generation": "video.generate"
13
14
  };
14
15
  const toolOrder = Object.fromEntries(defaultToolDefinitions.map((tool, index) => [tool.name, index]));
15
- const multiUriKeys = new Set([
16
- "image_urls",
17
- "reference_images",
18
- "file_urls",
19
- "video_urls",
20
- "audio_urls"
21
- ]);
22
16
  function record(value) {
23
17
  return typeof value === "object" && value !== null && !Array.isArray(value)
24
18
  ? value
@@ -39,12 +33,6 @@ function requiredText(value) {
39
33
  function number(value, fallback = 0) {
40
34
  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
41
35
  }
42
- function cleanText(value) {
43
- const result = text(value);
44
- if (result === undefined)
45
- return undefined;
46
- return text(result.replace(/\{icon:\{[^{}]*\}\}/g, ""));
47
- }
48
36
  function collectScenes(raw) {
49
37
  const roots = new Map();
50
38
  for (const value of raw) {
@@ -77,88 +65,6 @@ function collectScenes(raw) {
77
65
  }
78
66
  return scenes;
79
67
  }
80
- function parameter(value, optionalControls) {
81
- const field = record(value);
82
- if (field === undefined)
83
- throw new Error("invalid parameter");
84
- if (field.is_open !== true)
85
- return undefined;
86
- const name = requiredText(field.key);
87
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name))
88
- return undefined;
89
- const sourceType = requiredText(field.type);
90
- const type = sourceType === "SLIDER"
91
- ? "number"
92
- : multiUriKeys.has(name)
93
- ? "uri[]"
94
- : name === "start_frame" || name === "end_frame" || sourceType === "IMAGE" || sourceType === "VIDEO"
95
- ? "uri"
96
- : sourceType === "NUMBER"
97
- ? "number"
98
- : sourceType === "TEXT" || sourceType === "INPUT" || sourceType === "SELECT"
99
- ? "string"
100
- : undefined;
101
- if (type === undefined) {
102
- if (field.required === true)
103
- throw new Error("unsupported required parameter");
104
- const description = text(field.description) ?? text(field.label);
105
- optionalControls[name] = description ? { description } : {};
106
- return undefined;
107
- }
108
- let minimum;
109
- let maximum;
110
- let step;
111
- if (sourceType === "SLIDER") {
112
- if (typeof field.min !== "number" || !Number.isFinite(field.min)
113
- || typeof field.max !== "number" || !Number.isFinite(field.max)
114
- || typeof field.step !== "number" || !Number.isFinite(field.step)
115
- || field.min > field.max || field.step <= 0) {
116
- throw new Error("invalid slider constraints");
117
- }
118
- minimum = field.min;
119
- maximum = field.max;
120
- step = field.step;
121
- }
122
- let options;
123
- if (sourceType === "SELECT") {
124
- if (!Array.isArray(field.options))
125
- throw new Error("invalid options");
126
- options = field.options.map((value) => {
127
- const option = record(value);
128
- if (option === undefined)
129
- throw new Error("invalid option");
130
- const label = text(option.label);
131
- return {
132
- value: requiredText(option.value),
133
- ...(label === undefined ? {} : { label })
134
- };
135
- });
136
- if (options.length === 0)
137
- throw new Error("empty options");
138
- }
139
- const rawDescription = text(field.description) ?? text(field.label);
140
- // MNS documents the service's wire encoding. Public URI-list inputs are native arrays.
141
- const description = type === "uri[]" ? rawDescription
142
- ?.replace(/JSON 数组的字符串/gu, "原生 JSON 数组")
143
- .replace(/(?:例如|如)\s*(?:\\*["“])?\[.*?\](?:\\*["”])*/gu, '例如 ["https://example.com/media.png"]') : rawDescription;
144
- const defaultValue = field.default_value;
145
- const hasDefault = defaultValue !== undefined
146
- && defaultValue !== null
147
- && !(typeof defaultValue === "string" && defaultValue.trim() === "");
148
- return {
149
- name,
150
- type,
151
- required: field.required === true,
152
- ...(minimum === undefined ? {} : { minimum }),
153
- ...(maximum === undefined ? {} : { maximum }),
154
- ...(step === undefined ? {} : { step }),
155
- ...(description === undefined ? {} : { description }),
156
- ...(hasDefault
157
- ? { default: defaultValue }
158
- : {}),
159
- ...(options === undefined ? {} : { options })
160
- };
161
- }
162
68
  function range(values, unit) {
163
69
  if (values.length === 0)
164
70
  return undefined;
@@ -277,9 +183,6 @@ function normalizeModel(value, scenes, english = false) {
277
183
  // With no usable quote, the same listed model can still execute.
278
184
  const canQuote = cost && canvasPricingSupported(binding[1], configuration)
279
185
  && !(binding[1] === "image-layers-smart" && settings.some(value => record(value)?.key === "max_layers" && record(value)?.sku_enable === true));
280
- // Standard matting actually settles this quantity. Other execution protocols never consume a quote.
281
- if (binding[1] === "image-matting-standard" && (!canQuote || cost?.minimum !== cost?.maximum))
282
- throw new Error("matting settlement price unavailable");
283
186
  const bindingParameters = fixedResolutionPrices ? parameters.map(field => field.name === "resolution" && field.options
284
187
  ? { ...field, options: field.options.filter(({ value }) => Object.hasOwn(fixedResolutionPrices, value)) } : field) : parameters;
285
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, ToolInsufficientCreditsError } from "./tool-errors.js";
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.5",
3
+ "version": "2.1.7",
4
4
  "description": "insMind command-line interface for agents and people.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -46,9 +46,12 @@
46
46
  "devDependencies": {
47
47
  "@gaoding/cli": "workspace:*"
48
48
  },
49
+ "imports": {
50
+ "#model-catalog": "./dist/shared/model-catalog/index.js"
51
+ },
49
52
  "gaodingRelease": {
50
- "sourceCommit": "dd07bc1432494f88eaa2d3a0976e6415cda8bc1b",
51
- "pipelineId": "259288",
52
- "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/259288"
53
+ "sourceCommit": "5ad82af1858a5e5e20c3b0018b28fe3a4a53071a",
54
+ "pipelineId": "268194",
55
+ "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/268194"
53
56
  }
54
57
  }