@gaoding/cli 1.8.0 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/contracts/operations/agent.send/input.schema.json +1 -1
  2. package/contracts/operations/agent.send/output.schema.json +1 -1
  3. package/contracts/operations/model.get/input.schema.json +6 -0
  4. package/contracts/operations/model.get/output.schema.json +10 -1
  5. package/contracts/operations/tool.call/canvas-input.schema.json +60 -0
  6. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +42 -0
  7. package/contracts/operations/tool.call/models/image-edit-standard.schema.json +33 -0
  8. package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +27 -0
  9. package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +27 -0
  10. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +76 -0
  11. package/contracts/operations/tool.call/models/image-expand-standard.schema.json +61 -0
  12. package/contracts/operations/tool.call/models/image-layers-layout.schema.json +21 -0
  13. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +28 -0
  14. package/contracts/operations/tool.call/models/image-matting-smart.schema.json +37 -0
  15. package/contracts/operations/tool.call/models/image-matting-standard.schema.json +26 -0
  16. package/contracts/operations/tool.call/models/image-ocr.schema.json +21 -0
  17. package/contracts/operations/tool.call/models/image-remove-smart.schema.json +32 -0
  18. package/contracts/operations/tool.call/models/image-remove-standard.schema.json +27 -0
  19. package/contracts/operations/tool.call/models/image-text-edit.schema.json +46 -0
  20. package/contracts/operations/tool.call/models/image-vectorize.schema.json +21 -0
  21. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +76 -0
  22. package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +33 -0
  23. package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +27 -0
  24. package/contracts/operations/tool.call/ocr-payload.schema.json +66 -0
  25. package/contracts/operations/tool.call/output.schema.json +38 -0
  26. package/contracts/operations/tool.call/template-payload.schema.json +96 -0
  27. package/dist/bin/gd-cli.js +31 -24
  28. package/dist/bin/insmind-cli.js +31 -24
  29. package/dist/bin/task-worker.js +4 -1
  30. package/dist/src/analytics/device.js +2 -2
  31. package/dist/src/bootstrap/create-cli.js +7 -0
  32. package/dist/src/bootstrap/create-runtime.js +53 -30
  33. package/dist/src/bootstrap/run-task-worker.js +5 -1
  34. package/dist/src/bootstrap/validators.js +11 -4
  35. package/dist/src/cli/agent-commands.js +1 -0
  36. package/dist/src/cli/dam-commands.js +3 -3
  37. package/dist/src/cli/errors.js +63 -15
  38. package/dist/src/cli/model-commands.js +6 -3
  39. package/dist/src/cli/observed-errors.js +3 -1
  40. package/dist/src/cli/tool-commands.js +2 -0
  41. package/dist/src/contracts/schema.js +4 -1
  42. package/dist/src/features/agent/creative-agent-adapter.js +37 -11
  43. package/dist/src/features/agent/creative-protocol.js +31 -10
  44. package/dist/src/features/agent/creative-stream.js +54 -6
  45. package/dist/src/features/agent/resource-authorizer.js +1 -0
  46. package/dist/src/features/agent/result-reader.js +3 -1
  47. package/dist/src/features/agent/use-cases.js +15 -5
  48. package/dist/src/features/auth/credential-store.js +6 -10
  49. package/dist/src/features/auth/sso-service.js +22 -6
  50. package/dist/src/features/auth/state.js +6 -0
  51. package/dist/src/features/auth/use-cases.js +90 -32
  52. package/dist/src/features/dam/asset-projection.js +10 -1
  53. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  54. package/dist/src/features/dam/input.js +23 -0
  55. package/dist/src/features/dam/use-cases.js +32 -22
  56. package/dist/src/features/task/store.js +5 -5
  57. package/dist/src/features/task/task-background.js +67 -19
  58. package/dist/src/features/task/use-cases.js +38 -9
  59. package/dist/src/features/tool/canvas-copy.js +61 -0
  60. package/dist/src/features/tool/canvas-media.js +248 -0
  61. package/dist/src/features/tool/canvas-models.js +109 -0
  62. package/dist/src/features/tool/canvas-pricing.js +81 -0
  63. package/dist/src/features/tool/canvas-recovery.js +68 -0
  64. package/dist/src/features/tool/canvas-results.js +144 -0
  65. package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
  66. package/dist/src/features/tool/canvas-video.js +84 -0
  67. package/dist/src/features/tool/catalog.js +35 -13
  68. package/dist/src/features/tool/dynamic-schema.js +55 -25
  69. package/dist/src/features/tool/matting-billing.js +115 -0
  70. package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
  71. package/dist/src/features/tool/resource-authorizer.js +34 -0
  72. package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
  73. package/dist/src/features/tool/tool-api-adapter.js +29 -17
  74. package/dist/src/features/tool/use-cases.js +28 -3
  75. package/dist/src/platform/file-lock.js +58 -15
  76. package/dist/src/platform/input-uri.js +105 -0
  77. package/dist/src/platform/local-json-file.js +7 -4
  78. package/dist/src/platform/remote-error-evidence.js +23 -1
  79. package/dist/src/platform/safe-upload-file.js +18 -4
  80. package/dist/src/platform/schema-issues.js +18 -0
  81. package/dist/src/platform/signed-http-transport.js +77 -16
  82. package/dist/src/platform/text-output.js +55 -13
  83. package/dist/src/product/config.js +12 -1
  84. package/dist/src/telemetry/failure-summary.js +53 -2
  85. package/dist/src/telemetry/host-diagnostics.js +95 -0
  86. package/dist/src/telemetry/invocation.js +24 -3
  87. package/dist/src/telemetry/process-errors.js +2 -1
  88. package/dist/src/telemetry/sls-sink.js +66 -18
  89. package/package.json +5 -4
  90. package/skills/gd-cli/SKILL.md +2 -0
  91. package/skills/gd-cli/references/creation.md +2 -0
  92. package/skills/gd-cli/references/generation-constraints.md +3 -1
  93. package/skills/gd-cli/references/matting.md +29 -0
  94. package/skills/gd-cli/references/media-tools.md +40 -0
  95. package/skills/gd-cli/references/tool.md +4 -4
@@ -1,3 +1,5 @@
1
+ import { buildModelArgumentsSchema } from "./dynamic-schema.js";
2
+ import { hasCanvasMetering } from "./canvas-pricing.js";
1
3
  export const defaultToolDefinitions = [
2
4
  {
3
5
  name: "image.generate",
@@ -8,7 +10,18 @@ export const defaultToolDefinitions = [
8
10
  name: "video.generate",
9
11
  title: "视频生成",
10
12
  description: "使用已发布的视频模型,根据文本及可选图片、视频或音频生成视频。"
11
- }
13
+ },
14
+ { name: "image.edit", title: "图片改图", description: "修改原图内容;标准模型使用选区,智能模型可按指令修改。" },
15
+ { name: "image.matting", title: "图片抠图", description: "标准抠图保留源像素;智能抠图先重绘补全再分割。最终交付透明 PNG。" },
16
+ { name: "image.remove", title: "图片消除", description: "移除指定对象并补齐背景。" },
17
+ { name: "image.enhance", title: "图片变清晰", description: "标准超分或生成式修复;智能修复可能改变细节。" },
18
+ { name: "image.expand", title: "图片扩图", description: "按目标画布和原图位置补绘外围。" },
19
+ { name: "image.text_edit", title: "图片改字", description: "按原文替换或删除图片文字,不承诺定位重复原文中的某一次。" },
20
+ { name: "image.ocr", title: "图片文字识别", description: "返回实际识别图尺寸、文字、类别和像素坐标。" },
21
+ { name: "image.layers", title: "图片图文分层", description: "交付原生稿定模板 JSON,保留图层结构。" },
22
+ { name: "image.vectorize", title: "图片转矢量", description: "将位图转换为 SVG。" },
23
+ { name: "video.edit", title: "视频修改", description: "按原视频修改内容,时长由真实素材推导。" },
24
+ { name: "video.enhance", title: "视频变清晰", description: "标准超分或生成式视频修复。" }
12
25
  ];
13
26
  export class ToolInputError extends Error {
14
27
  reason;
@@ -37,7 +50,7 @@ function summary(model) {
37
50
  model: model.model,
38
51
  title: model.title,
39
52
  ...(model.description === undefined ? {} : { description: model.description }),
40
- ...(model.cost === undefined ? {} : { cost: model.cost }),
53
+ ...(model.cost === undefined || hasCanvasMetering(model) ? {} : { cost: model.cost }),
41
54
  ...(model.estimatedTime === undefined ? {} : { estimatedTime: model.estimatedTime })
42
55
  };
43
56
  }
@@ -57,14 +70,21 @@ export function projectModelList(catalog, tool, tools = defaultToolDefinitions)
57
70
  .map(summary)
58
71
  };
59
72
  }
60
- export function findModel(catalog, model) {
61
- const found = catalog.models.find((candidate) => candidate.model === model);
62
- if (found === undefined)
63
- throw new ToolInputError("model_not_found", "/model");
64
- return found;
73
+ export function findModel(catalog, model, tool) {
74
+ const matches = catalog.models.filter(candidate => candidate.model === model);
75
+ if (tool !== undefined)
76
+ return findToolModel(catalog, tool, model);
77
+ const legacy = matches.find(candidate => candidate.tool === "image.generate" || candidate.tool === "video.generate");
78
+ if (legacy)
79
+ return legacy;
80
+ if (matches.length === 1)
81
+ return matches[0];
82
+ if (matches.length > 1)
83
+ throw new ToolInputError("model_tool_required", "/tool");
84
+ throw new ToolInputError("model_not_found", "/model");
65
85
  }
66
- export function projectModelDetail(catalog, model) {
67
- const found = findModel(catalog, model);
86
+ export function projectModelDetail(catalog, model, tool) {
87
+ const found = findModel(catalog, model, tool);
68
88
  return {
69
89
  ...summary(found),
70
90
  ...(found.usageDescription === undefined
@@ -73,12 +93,14 @@ export function projectModelDetail(catalog, model) {
73
93
  ...(found.outputMediaTypes === undefined
74
94
  ? {}
75
95
  : { outputMediaTypes: found.outputMediaTypes }),
76
- parameters: found.parameters
96
+ parameters: found.parameters,
97
+ inputSchema: { ...buildModelArgumentsSchema(found) }
77
98
  };
78
99
  }
79
100
  export function findToolModel(catalog, tool, model) {
80
- const found = findModel(catalog, model);
81
- if (found.tool !== tool)
82
- throw new ToolInputError("model_tool_mismatch", "/model");
101
+ const found = catalog.models.find(candidate => candidate.model === model && candidate.tool === tool);
102
+ if (!found)
103
+ throw new ToolInputError(catalog.models.some(candidate => candidate.model === model)
104
+ ? "model_tool_mismatch" : "model_not_found", "/model");
83
105
  return found;
84
106
  }
@@ -1,6 +1,8 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import addFormatsImport, {} from "ajv-formats";
3
- import { validationIssues } from "../../platform/schema-issues.js";
3
+ import { canvasControlParameterNames } from "./canvas-models.js";
4
+ import { inputValidationSummary, validationIssues } from "../../platform/schema-issues.js";
5
+ import { canonicalizeInputFileUris } from "../../platform/input-uri.js";
4
6
  import { ToolInputError } from "./catalog.js";
5
7
  function parameterSchema(parameter, includeBounds = false) {
6
8
  const common = {
@@ -12,9 +14,9 @@ function parameterSchema(parameter, includeBounds = false) {
12
14
  if (parameter.type === "uri[]") {
13
15
  return { type: "array", items: { type: "string", format: "uri" }, ...common };
14
16
  }
15
- if (parameter.type === "number") {
17
+ if (parameter.type === "number" || parameter.type === "integer") {
16
18
  return {
17
- type: "number",
19
+ type: parameter.type,
18
20
  ...(includeBounds && parameter.minimum !== undefined
19
21
  ? { minimum: parameter.minimum }
20
22
  : {}),
@@ -24,6 +26,9 @@ function parameterSchema(parameter, includeBounds = false) {
24
26
  ...common
25
27
  };
26
28
  }
29
+ if (["boolean", "object", "array"].includes(parameter.type)) {
30
+ return { type: parameter.type, ...common };
31
+ }
27
32
  return {
28
33
  type: "string",
29
34
  ...(parameter.options === undefined
@@ -33,6 +38,9 @@ function parameterSchema(parameter, includeBounds = false) {
33
38
  };
34
39
  }
35
40
  function sameShape(left, right) {
41
+ if (left.type === "object" || left.type === "array" || right.type === "object" || right.type === "array") {
42
+ return JSON.stringify(left) === JSON.stringify(right);
43
+ }
36
44
  return left.type === right.type
37
45
  && left.format === right.format
38
46
  && left.items?.format === right.items?.format;
@@ -68,10 +76,13 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
68
76
  }
69
77
  };
70
78
  for (const model of models) {
71
- for (const parameter of model.parameters) {
72
- const next = parameterSchema(parameter);
73
- const current = properties[parameter.name];
74
- properties[parameter.name] = current === undefined ? next : mergeSchema(current, next);
79
+ const selected = model.inputSchema ? buildModelArgumentsSchema(model).properties
80
+ : Object.fromEntries(model.parameters.map(parameter => [parameter.name, parameterSchema(parameter)]));
81
+ for (const [name, next] of Object.entries(selected)) {
82
+ if (name === "model")
83
+ continue;
84
+ const current = properties[name];
85
+ properties[name] = current === undefined ? next : mergeSchema(current, next);
75
86
  }
76
87
  }
77
88
  return {
@@ -84,6 +95,8 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
84
95
  };
85
96
  }
86
97
  export function buildModelArgumentsSchema(model) {
98
+ if (model.inputSchema)
99
+ return structuredClone(model.inputSchema);
87
100
  const properties = {
88
101
  model: {
89
102
  type: "string",
@@ -117,9 +130,10 @@ function controlArgumentsValidator(model) {
117
130
  for (const parameter of model.parameters) {
118
131
  if (parameter.name === "prompt"
119
132
  || parameter.type === "uri"
120
- || parameter.type === "uri[]")
133
+ || parameter.type === "uri[]"
134
+ || (model.execution?.kind === "canvas" && !canvasControlParameterNames.has(parameter.name)))
121
135
  continue;
122
- properties[parameter.name] = parameterSchema(parameter, true);
136
+ properties[parameter.name] = buildModelArgumentsSchema(model).properties[parameter.name];
123
137
  }
124
138
  return ajv.compile({
125
139
  type: "object",
@@ -130,32 +144,48 @@ function controlArgumentsValidator(model) {
130
144
  }
131
145
  export function assertModelArguments(model, value) {
132
146
  const validate = validator(model);
133
- if (!validate(value))
134
- throw new ToolInputError("model_parameters", "/arguments", validationIssues(validate.errors));
135
- if (!sliderStepsAreValid(model, value)) {
136
- throw new ToolInputError("model_parameters", "/arguments");
147
+ canonicalizeInputFileUris(value, validate.schema);
148
+ if (!validate(value)) {
149
+ const issues = validationIssues(validate.errors, value, validate.schema);
150
+ throw Object.assign(new ToolInputError("model_parameters", "/arguments", issues), { diagnosticSummary: inputValidationSummary(issues, value, "/arguments") });
151
+ }
152
+ const stepIssues = sliderStepIssues(model, value);
153
+ if (stepIssues.length) {
154
+ throw Object.assign(new ToolInputError("model_parameters", "/arguments", stepIssues), { diagnosticSummary: inputValidationSummary(stepIssues, value, "/arguments") });
137
155
  }
138
156
  }
139
- function sliderStepsAreValid(model, value) {
140
- return model.parameters.every((parameter) => {
157
+ function sliderStepIssues(model, value) {
158
+ const issues = [];
159
+ for (const parameter of model.parameters) {
141
160
  if (parameter.step === undefined || !Object.hasOwn(value, parameter.name))
142
- return true;
161
+ continue;
143
162
  const candidate = value[parameter.name];
144
163
  const minimum = parameter.minimum;
145
- if (typeof candidate !== "number" || minimum === undefined || parameter.step <= 0) {
146
- return false;
164
+ let valid = false;
165
+ if (typeof candidate === "number" && minimum !== undefined && parameter.step > 0) {
166
+ const steps = (candidate - minimum) / parameter.step;
167
+ const nearestStep = Math.round(steps);
168
+ const expected = minimum + nearestStep * parameter.step;
169
+ const tolerance = Number.EPSILON * Math.max(1, Math.abs(candidate), Math.abs(expected), Math.abs(minimum), Math.abs(nearestStep * parameter.step)) * 2;
170
+ valid = Math.abs(candidate - expected) <= tolerance;
147
171
  }
148
- const steps = (candidate - minimum) / parameter.step;
149
- const nearestStep = Math.round(steps);
150
- const expected = minimum + nearestStep * parameter.step;
151
- const tolerance = Number.EPSILON * Math.max(1, Math.abs(candidate), Math.abs(expected), Math.abs(minimum), Math.abs(nearestStep * parameter.step)) * 2;
152
- return Math.abs(candidate - expected) <= tolerance;
153
- });
172
+ if (!valid)
173
+ issues.push({
174
+ field: `/${parameter.name.replace(/~/gu, "~0").replace(/\//gu, "~1")}`.slice(0, 256),
175
+ rule: "step",
176
+ message: minimum === undefined || parameter.step <= 0
177
+ ? "must match the model's slider configuration"
178
+ : `must be ${minimum} plus a whole number of steps of ${parameter.step}`
179
+ });
180
+ if (issues.length === 8)
181
+ break;
182
+ }
183
+ return issues;
154
184
  }
155
185
  export function modelControlArgumentsAreValid(model, value) {
156
186
  return typeof value === "object"
157
187
  && value !== null
158
188
  && !Array.isArray(value)
159
189
  && controlArgumentsValidator(model)(value)
160
- && sliderStepsAreValid(model, value);
190
+ && sliderStepIssues(model, value).length === 0;
161
191
  }
@@ -0,0 +1,115 @@
1
+ import { constants, createPublicKey, publicEncrypt, randomBytes, verify } from "node:crypto";
2
+ import { withResponseDiagnostics } from "../../platform/signed-http-transport.js";
3
+ import { RemoteProtocolError } from "../../platform/remote-protocol.js";
4
+ import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
5
+ import { record } from "./canvas-results.js";
6
+ import { ToolTaskFailedError, ToolInsufficientCreditsError } from "./tool-api-adapter.js";
7
+ // Public verification/encryption key used by the existing matting rights service.
8
+ const serviceKey = `-----BEGIN RSA PUBLIC KEY-----
9
+ MIGJAoGBANVv3G1++sfQjoTLN6pOU0ooMzAdRf3W1SItK1MJbXcg6tdBRTfvraso
10
+ 4MBNJ6TDOKB2ffO7MtaFHHCo2mxS7/WQF1IJbojXzXt35pja+SsMnuI+050Piwwy
11
+ O/YHzh9Idr3qaXCzOnkfs6JNOKT50pp4xs3b0U5ZXytg4eRTQ1eXAgMBAAE=
12
+ -----END RSA PUBLIC KEY-----`;
13
+ /** NodeRSA's OAEP/SHA-1 chunking, retained at the service boundary. */
14
+ export function encryptMattingParameters(text, key = serviceKey) {
15
+ const publicKey = createPublicKey(key);
16
+ const keyBytes = Math.ceil(publicKey.asymmetricKeyDetails.modulusLength / 8);
17
+ const data = Buffer.from(text);
18
+ const blocks = Math.ceil(data.length / (keyBytes - 42));
19
+ const blockSize = Math.ceil(data.length / blocks);
20
+ const encrypted = [];
21
+ for (let offset = 0; offset < data.length; offset += blockSize) {
22
+ encrypted.push(publicEncrypt({ key: publicKey, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha1" }, data.subarray(offset, offset + blockSize)));
23
+ }
24
+ return Buffer.concat(encrypted).toString("base64");
25
+ }
26
+ export function createMattingRights(dependencies) {
27
+ const { transport } = dependencies;
28
+ return async function rights(path, parameters, context) {
29
+ return withResponseDiagnostics(async (onResponse) => {
30
+ const code = `0.${randomBytes(12).readBigUInt64BE().toString()}`;
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) },
33
+ ...context.access, signal: context.signal, onResponse });
34
+ if (!record(result))
35
+ throw new RemoteProtocolError();
36
+ if (result.code !== undefined && result.code !== 0 && result.code !== "0")
37
+ throw new ToolTaskFailedError(remoteErrorEvidence(result));
38
+ if (typeof result.export_permit !== "string" || !verify("RSA-SHA256", Buffer.from(code), dependencies.key ?? serviceKey, Buffer.from(result.export_permit, "base64"))
39
+ || typeof result.used_count !== "number" || !Number.isFinite(result.used_count) || result.used_count < 0) {
40
+ throw new RemoteProtocolError({}, undefined, "MATTING_BILLING_VERIFICATION_FAILED");
41
+ }
42
+ return result;
43
+ });
44
+ };
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,16 +1,17 @@
1
1
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
2
+ import { defaultToolDefinitions } from "./catalog.js";
3
+ import { canvasModel, canvasModelBindings, canvasSceneCodes } from "./canvas-models.js";
4
+ import { canvasPricingSupported } from "./canvas-pricing.js";
2
5
  export const ROOT_SCENE_CODES = [
3
6
  "image-model-art",
4
7
  "AI-video-generation"
5
8
  ];
9
+ export const CATALOG_SCENE_CODES = [...ROOT_SCENE_CODES, ...canvasSceneCodes];
6
10
  const rootTools = {
7
11
  "image-model-art": "image.generate",
8
12
  "AI-video-generation": "video.generate"
9
13
  };
10
- const toolOrder = {
11
- "image.generate": 0,
12
- "video.generate": 1
13
- };
14
+ const toolOrder = Object.fromEntries(defaultToolDefinitions.map((tool, index) => [tool.name, index]));
14
15
  const multiUriKeys = new Set([
15
16
  "image_urls",
16
17
  "reference_images",
@@ -61,8 +62,19 @@ function collectScenes(raw) {
61
62
  scenes.push({ code: rootCode, tool: rootTools[rootCode], sort: number(root.sort) });
62
63
  }
63
64
  }
64
- if (scenes.length === 0)
65
- throw new Error("empty scenes");
65
+ for (const rootCode of canvasSceneCodes) {
66
+ const root = roots.get(rootCode);
67
+ if (!root)
68
+ continue;
69
+ const binding = canvasModelBindings.find(binding => binding[3] === rootCode);
70
+ scenes.push({ code: rootCode, tool: binding[0], sort: number(root.sort) });
71
+ // Canvas pickers include first-level children; generic generation keeps its existing root membership.
72
+ for (const child of roots.values()) {
73
+ if (child.parent_id === root.id && child !== root) {
74
+ scenes.push({ code: requiredText(child.code), tool: binding[0], sort: number(child.sort) });
75
+ }
76
+ }
77
+ }
66
78
  return scenes;
67
79
  }
68
80
  function parameter(value) {
@@ -144,7 +156,7 @@ function range(values, unit) {
144
156
  const bounds = { minimum: Math.min(...values), maximum: Math.max(...values) };
145
157
  return unit === "gaodou" ? { unit, ...bounds } : { unit, ...bounds };
146
158
  }
147
- function normalizeModel(value, scenes) {
159
+ function normalizeModel(value, scenes, english = false) {
148
160
  const item = record(value);
149
161
  const model = record(item?.model);
150
162
  if (item === undefined || model === undefined || !Array.isArray(item.skus)) {
@@ -152,7 +164,7 @@ function normalizeModel(value, scenes) {
152
164
  }
153
165
  const activeSkus = item.skus.map(record).filter((sku) => sku !== undefined && sku.status === 1);
154
166
  if (activeSkus.length === 0)
155
- return undefined;
167
+ return [];
156
168
  const code = requiredText(model.code);
157
169
  const title = requiredText(model.name);
158
170
  if (!Array.isArray(model.scene_categories))
@@ -164,7 +176,7 @@ function normalizeModel(value, scenes) {
164
176
  || left.sort - right.sort);
165
177
  const scene = matches[0];
166
178
  if (scene === undefined)
167
- return undefined;
179
+ return [];
168
180
  if (typeof model.input_field_settings !== "string")
169
181
  throw new Error("missing settings");
170
182
  const settings = JSON.parse(model.input_field_settings);
@@ -175,9 +187,10 @@ function normalizeModel(value, scenes) {
175
187
  .filter((item) => item !== undefined);
176
188
  const description = cleanText(model.description);
177
189
  const usageDescription = cleanText(model.tool_description);
178
- const outputMediaTypes = Array.isArray(model.output_mime_types)
179
- ? model.output_mime_types.map(text).filter((item) => item !== undefined)
180
- : [];
190
+ const mimeTypes = typeof model.output_mime_types === "string"
191
+ ? JSON.parse(model.output_mime_types) : model.output_mime_types;
192
+ const outputMediaTypes = Array.isArray(mimeTypes)
193
+ ? mimeTypes.map(text).filter((item) => item !== undefined) : [];
181
194
  const costs = activeSkus
182
195
  .map((sku) => sku.point_cost)
183
196
  .filter((value) => typeof value === "number"
@@ -188,7 +201,7 @@ function normalizeModel(value, scenes) {
188
201
  && Number.isFinite(value) && value >= 0);
189
202
  const cost = range(costs, "gaodou");
190
203
  const estimatedTime = range(times, "second");
191
- return {
204
+ const normalized = {
192
205
  tool: scene.tool,
193
206
  model: code,
194
207
  title,
@@ -201,6 +214,36 @@ function normalizeModel(value, scenes) {
201
214
  sceneSort: scene.sort,
202
215
  modelSort: number(model.sort)
203
216
  };
217
+ const result = [];
218
+ for (const match of matches) {
219
+ if (ROOT_SCENE_CODES.some(root => root === match.code)) {
220
+ result.push({ ...normalized, tool: match.tool, sceneSort: match.sort });
221
+ continue;
222
+ }
223
+ const binding = canvasModelBindings.find(binding => binding[2] === code
224
+ && (binding[3] === match.code || binding[0] === match.tool));
225
+ if (!binding)
226
+ continue; // A category association is insufficient to execute an unknown protocol.
227
+ if (!cost)
228
+ throw new Error("canvas pricing unavailable");
229
+ if (!canvasPricingSupported(binding[1], { billingComponents: item.billing_components }))
230
+ throw new Error("canvas component pricing unsupported");
231
+ if (binding[1] === "image-layers-smart") {
232
+ const components = Array.isArray(item.billing_components) ? item.billing_components.map(record) : [];
233
+ if (settings.some(value => record(value)?.key === "max_layers" && record(value)?.sku_enable === true)
234
+ || !components.some(component => component?.parameter_key === "max_layers"
235
+ && component.quantity_mode === "METERED" && component.price_source === "SKU"
236
+ && (component.min_quantity === undefined || component.min_quantity === null || component.min_quantity === 0)
237
+ && (component.max_quantity === undefined || component.max_quantity === null || Number(component.max_quantity) >= 17))) {
238
+ throw new Error("layer metered pricing unavailable");
239
+ }
240
+ }
241
+ result.push(canvasModel({ ...normalized, sceneSort: match.sort }, binding, {
242
+ fields: settings,
243
+ ...(item.billing_components === undefined ? {} : { billingComponents: item.billing_components })
244
+ }, english));
245
+ }
246
+ return result;
204
247
  }
205
248
  export function createMnsCatalogAdapter(dependencies) {
206
249
  return {
@@ -209,7 +252,7 @@ export function createMnsCatalogAdapter(dependencies) {
209
252
  try {
210
253
  const rawScenes = await dependencies.transport.getJson({
211
254
  path: "/mns/scene-categories",
212
- query: { codes: ROOT_SCENE_CODES.join(",") },
255
+ query: { codes: CATALOG_SCENE_CODES.join(",") },
213
256
  credential: access.credential,
214
257
  organizationId: access.organizationId,
215
258
  signal
@@ -217,6 +260,8 @@ export function createMnsCatalogAdapter(dependencies) {
217
260
  if (!Array.isArray(rawScenes))
218
261
  throw new Error("invalid scene response");
219
262
  const scenes = collectScenes(rawScenes);
263
+ if (scenes.length === 0)
264
+ return { models: [], warnings: [] };
220
265
  const rawModels = await dependencies.transport.getJson({
221
266
  path: "/mns/models",
222
267
  query: { codes: scenes.map((scene) => scene.code).join(",") },
@@ -232,11 +277,13 @@ export function createMnsCatalogAdapter(dependencies) {
232
277
  let invalidCount = 0;
233
278
  for (const rawModel of rawModels) {
234
279
  try {
235
- const model = normalizeModel(rawModel, sceneMap);
236
- if (model === undefined || seen.has(model.model))
237
- continue;
238
- seen.add(model.model);
239
- models.push(model);
280
+ for (const model of normalizeModel(rawModel, sceneMap, dependencies.english)) {
281
+ const key = `${model.tool}\0${model.model}`;
282
+ if (seen.has(key))
283
+ continue;
284
+ seen.add(key);
285
+ models.push(model);
286
+ }
240
287
  }
241
288
  catch {
242
289
  invalidCount += 1;
@@ -0,0 +1,34 @@
1
+ import { readOcrPayload } from "./canvas-results.js";
2
+ import { RemoteProtocolError } from "../../platform/remote-protocol.js";
3
+ /** Reauthorize both top-level media and the OCR image reference, without interpreting arbitrary text as URLs. */
4
+ export async function authorizeToolResources(output, authorizer, access, signal) {
5
+ const references = [];
6
+ for (const [index, part] of output.content.entries()) {
7
+ if (part.type === "resource_link")
8
+ references.push({ index, uri: part.uri, mediaType: part.mimeType ?? "application/octet-stream" });
9
+ else if (output.usage.model === "image-ocr" && part.type === "resource") {
10
+ const ocr = readOcrPayload(part.resource.text);
11
+ references.push({ index, uri: ocr.image.uri, mediaType: "image/jpeg", ocr });
12
+ }
13
+ }
14
+ if (!references.length)
15
+ return output;
16
+ const parts = references.map(reference => ({ url: reference.uri, mediaType: reference.mediaType }));
17
+ const authorized = await authorizer.authorize({
18
+ message: { contextId: "resource-authorization", parts: [parts[0], ...parts.slice(1)] },
19
+ usage: { cost: { unit: "gaodou", amount: 0 }, items: [] }
20
+ }, access, signal);
21
+ const content = [...output.content];
22
+ for (const [index, reference] of references.entries()) {
23
+ const part = content[reference.index];
24
+ const authorizedPart = authorized.message.parts[index];
25
+ if (!authorizedPart || !("url" in authorizedPart))
26
+ throw new RemoteProtocolError();
27
+ if (part.type === "resource_link")
28
+ content[reference.index] = { ...part, uri: authorizedPart.url };
29
+ else if (part.type === "resource" && reference.ocr)
30
+ content[reference.index] = { ...part, resource: { ...part.resource,
31
+ text: JSON.stringify({ ...reference.ocr, image: { ...reference.ocr.image, uri: authorizedPart.url } }) } };
32
+ }
33
+ return { ...output, content };
34
+ }
@@ -0,0 +1,35 @@
1
+ import { canvasModel, canvasModelBindings } from "./canvas-models.js";
2
+ import { RemoteRequestError } from "../../platform/signed-http-transport.js";
3
+ import { record } from "./canvas-results.js";
4
+ const bindingForCode = (code) => canvasModelBindings.find(binding => binding[2] === code)[1];
5
+ /** Legacy scenes have fixed protocols, unlike the MNS model pickers. Availability is read separately. */
6
+ export function createSceneCatalogAdapter(dependencies) {
7
+ return { async load(input) {
8
+ const catalog = await dependencies.catalog.load(input);
9
+ for (const code of ["TextEdit", "new-image-ocr"]) {
10
+ try {
11
+ const scene = await dependencies.transport.getJson({ path: `/gdesign/tool/manage/scenes/code/${code}`, ...input.access, signal: input.signal });
12
+ if (!record(scene) || scene.scene_code !== code || scene.status !== 1)
13
+ continue;
14
+ const binding = canvasModelBindings.find(binding => binding[2] === code);
15
+ const cost = scene.is_free === true ? 0 : typeof scene.point_rights === "number" && Number.isFinite(scene.point_rights) && scene.point_rights >= 0 ? scene.point_rights : undefined;
16
+ if (cost === undefined) {
17
+ catalog.warnings.push(dependencies.english ? `Current pricing is unavailable for ${binding[1]}.` : `${binding[1]} 的当前报价不可用。`);
18
+ continue;
19
+ }
20
+ const raw = { tool: binding[0], model: code, title: binding[4], sceneSort: 0, modelSort: 0, parameters: [],
21
+ ...(cost === undefined ? {} : { cost: { unit: "gaodou", minimum: cost, maximum: cost } }),
22
+ outputMediaTypes: code === "new-image-ocr" ? ["application/json"] : ["image/jpeg", "image/png"] };
23
+ catalog.models.push(canvasModel(raw, binding, {}, dependencies.english));
24
+ }
25
+ catch (error) {
26
+ input.signal.throwIfAborted();
27
+ if (error instanceof RemoteRequestError && error.status === 404)
28
+ continue;
29
+ // Do not misreport a network failure as a published offline state.
30
+ catalog.warnings.push(dependencies.english ? `Unable to verify the current availability of ${bindingForCode(code)}.` : `暂时无法核实 ${bindingForCode(code)} 的当前可用性。`);
31
+ }
32
+ }
33
+ return catalog;
34
+ } };
35
+ }