@insmind/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.
- package/contracts/operations/model.get/input.schema.json +5 -0
- package/contracts/operations/model.get/output.schema.json +9 -1
- package/contracts/operations/tool.call/canvas-input.schema.json +60 -0
- package/contracts/operations/tool.call/models/image-edit-smart.schema.json +39 -0
- package/contracts/operations/tool.call/models/image-edit-standard.schema.json +31 -0
- package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +26 -0
- package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +25 -0
- package/contracts/operations/tool.call/models/image-expand-smart.schema.json +72 -0
- package/contracts/operations/tool.call/models/image-expand-standard.schema.json +58 -0
- package/contracts/operations/tool.call/models/image-layers-layout.schema.json +20 -0
- package/contracts/operations/tool.call/models/image-layers-smart.schema.json +26 -0
- package/contracts/operations/tool.call/models/image-matting-smart.schema.json +34 -0
- package/contracts/operations/tool.call/models/image-matting-standard.schema.json +24 -0
- package/contracts/operations/tool.call/models/image-ocr.schema.json +20 -0
- package/contracts/operations/tool.call/models/image-remove-smart.schema.json +30 -0
- package/contracts/operations/tool.call/models/image-remove-standard.schema.json +25 -0
- package/contracts/operations/tool.call/models/image-text-edit.schema.json +43 -0
- package/contracts/operations/tool.call/models/image-vectorize.schema.json +20 -0
- package/contracts/operations/tool.call/models/video-edit-smart.schema.json +68 -0
- package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +32 -0
- package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +26 -0
- package/contracts/operations/tool.call/ocr-payload.schema.json +65 -0
- package/contracts/operations/tool.call/output.schema.json +38 -0
- package/contracts/operations/tool.call/template-payload.schema.json +95 -0
- package/dist/bin/insmind-cli.js +31 -24
- package/dist/bin/task-worker.js +4 -1
- package/dist/src/analytics/device.js +2 -2
- package/dist/src/bootstrap/create-cli.js +7 -0
- package/dist/src/bootstrap/create-runtime.js +53 -30
- package/dist/src/bootstrap/run-task-worker.js +5 -1
- package/dist/src/bootstrap/validators.js +11 -4
- package/dist/src/cli/agent-commands.js +1 -0
- package/dist/src/cli/dam-commands.js +3 -3
- package/dist/src/cli/errors.js +63 -15
- package/dist/src/cli/model-commands.js +6 -3
- package/dist/src/cli/observed-errors.js +3 -1
- package/dist/src/cli/tool-commands.js +2 -0
- package/dist/src/contracts/schema.js +4 -1
- package/dist/src/features/agent/creative-agent-adapter.js +37 -11
- package/dist/src/features/agent/creative-protocol.js +31 -10
- package/dist/src/features/agent/creative-stream.js +54 -6
- package/dist/src/features/agent/resource-authorizer.js +1 -0
- package/dist/src/features/agent/result-reader.js +3 -1
- package/dist/src/features/agent/use-cases.js +15 -5
- package/dist/src/features/auth/credential-store.js +6 -10
- package/dist/src/features/auth/sso-service.js +22 -6
- package/dist/src/features/auth/state.js +6 -0
- package/dist/src/features/auth/use-cases.js +90 -32
- package/dist/src/features/dam/asset-projection.js +10 -1
- package/dist/src/features/dam/dam-api-adapter.js +30 -15
- package/dist/src/features/dam/input.js +23 -0
- package/dist/src/features/dam/use-cases.js +32 -22
- package/dist/src/features/task/store.js +5 -5
- package/dist/src/features/task/task-background.js +67 -19
- package/dist/src/features/task/use-cases.js +38 -9
- package/dist/src/features/tool/canvas-copy.js +61 -0
- package/dist/src/features/tool/canvas-media.js +248 -0
- package/dist/src/features/tool/canvas-models.js +109 -0
- package/dist/src/features/tool/canvas-pricing.js +81 -0
- package/dist/src/features/tool/canvas-recovery.js +68 -0
- package/dist/src/features/tool/canvas-results.js +144 -0
- package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
- package/dist/src/features/tool/canvas-video.js +84 -0
- package/dist/src/features/tool/catalog.js +35 -13
- package/dist/src/features/tool/dynamic-schema.js +55 -25
- package/dist/src/features/tool/matting-billing.js +115 -0
- package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
- package/dist/src/features/tool/resource-authorizer.js +34 -0
- package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
- package/dist/src/features/tool/tool-api-adapter.js +29 -17
- package/dist/src/features/tool/use-cases.js +28 -3
- package/dist/src/platform/file-lock.js +58 -15
- package/dist/src/platform/input-uri.js +105 -0
- package/dist/src/platform/local-json-file.js +7 -4
- package/dist/src/platform/remote-error-evidence.js +23 -1
- package/dist/src/platform/safe-upload-file.js +18 -4
- package/dist/src/platform/schema-issues.js +18 -0
- package/dist/src/platform/signed-http-transport.js +77 -16
- package/dist/src/platform/text-output.js +55 -13
- package/dist/src/product/config.js +12 -1
- package/dist/src/telemetry/failure-summary.js +53 -2
- package/dist/src/telemetry/host-diagnostics.js +95 -0
- package/dist/src/telemetry/invocation.js +24 -3
- package/dist/src/telemetry/process-errors.js +2 -1
- package/dist/src/telemetry/sls-sink.js +66 -18
- package/package.json +5 -4
- package/skills/insmind-cli/SKILL.md +2 -0
- package/skills/insmind-cli/references/creation.md +2 -0
- package/skills/insmind-cli/references/generation-constraints.md +3 -1
- package/skills/insmind-cli/references/matting.md +29 -0
- package/skills/insmind-cli/references/media-tools.md +40 -0
- package/skills/insmind-cli/references/tool.md +1 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { fork } from "node:child_process";
|
|
2
2
|
import { safeFailureSummary } from "../../telemetry/failure-summary.js";
|
|
3
|
+
import { validTaskId } from "./store.js";
|
|
3
4
|
function diagnosticToken(value, pattern) {
|
|
4
5
|
return typeof value === "string" && pattern.test(value) ? value : undefined;
|
|
5
6
|
}
|
|
@@ -65,55 +66,102 @@ export class TaskBackgroundError extends Error {
|
|
|
65
66
|
this.diagnostics = safe;
|
|
66
67
|
}
|
|
67
68
|
}
|
|
69
|
+
export function taskWorkerUnavailableError(options) {
|
|
70
|
+
const diagnosticSummary = {
|
|
71
|
+
workerPhase: options.phase,
|
|
72
|
+
...(options.pid === undefined ? {} : { workerPid: options.pid }),
|
|
73
|
+
...(options.exitCode === undefined ? {} : { workerExitCode: options.exitCode }),
|
|
74
|
+
...(options.signal === undefined ? {} : { workerSignal: options.signal })
|
|
75
|
+
};
|
|
76
|
+
const diagnostics = taskWorkerDiagnostics(options.cause ?? new Error("Background process unavailable."), {
|
|
77
|
+
outcome: "failure", diagnosticReason: "TASK_WORKER_UNAVAILABLE", diagnosticSummary
|
|
78
|
+
}, `worker.${options.phase}`);
|
|
79
|
+
const systemCode = diagnostics.causes?.find(cause => cause.system_code)?.system_code;
|
|
80
|
+
if (systemCode)
|
|
81
|
+
diagnostics.diagnostic_summary = safeFailureSummary({ ...diagnosticSummary, systemCode }) ?? {};
|
|
82
|
+
return new TaskBackgroundError({
|
|
83
|
+
code: "TASK_WORKER_UNAVAILABLE",
|
|
84
|
+
message: options.product === "insmind"
|
|
85
|
+
? "The background process did not return a receipt. Check task list/get before submitting again."
|
|
86
|
+
: "后台进程未返回受理回执。请先用 task list/get 查询,勿重复提交。",
|
|
87
|
+
...(options.taskId && validTaskId(options.taskId) ? { details: { cli_task_id: options.taskId } } : {})
|
|
88
|
+
}, 1, diagnostics);
|
|
89
|
+
}
|
|
68
90
|
export function createTaskBackgroundLauncher(options) {
|
|
69
91
|
return {
|
|
70
92
|
submit(job, signal, started) {
|
|
71
93
|
signal.throwIfAborted();
|
|
72
94
|
return new Promise((resolve, reject) => {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
95
|
+
let child;
|
|
96
|
+
try {
|
|
97
|
+
child = (options.fork ?? fork)(options.workerPath, [], {
|
|
98
|
+
detached: true,
|
|
99
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
100
|
+
execArgv: [],
|
|
101
|
+
env: { ...process.env, ...options.env }
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
catch (cause) {
|
|
105
|
+
reject(taskWorkerUnavailableError({ product: job.product, phase: "spawn", cause }));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
79
108
|
let settled = false;
|
|
109
|
+
let taskId;
|
|
110
|
+
let disconnectTimer;
|
|
80
111
|
const finish = (result) => {
|
|
81
112
|
if (settled)
|
|
82
113
|
return;
|
|
83
114
|
settled = true;
|
|
115
|
+
clearTimeout(disconnectTimer);
|
|
84
116
|
signal.removeEventListener("abort", aborted);
|
|
85
117
|
// The one-task worker owns the request after handoff, including when
|
|
86
118
|
// the caller is interrupted or loses the receipt.
|
|
87
|
-
|
|
88
|
-
child.
|
|
119
|
+
try {
|
|
120
|
+
if (child.connected)
|
|
121
|
+
child.disconnect();
|
|
122
|
+
}
|
|
123
|
+
catch { /* Teardown cannot replace the receipt or original failure. */ }
|
|
89
124
|
child.unref();
|
|
90
125
|
if (result instanceof Error)
|
|
91
126
|
reject(result);
|
|
92
127
|
else
|
|
93
128
|
resolve(result);
|
|
94
129
|
};
|
|
95
|
-
const unavailable = () => finish(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}));
|
|
130
|
+
const unavailable = (phase, cause, exitCode, signal) => finish(taskWorkerUnavailableError({ product: job.product, phase, cause,
|
|
131
|
+
...(child.pid === undefined ? {} : { pid: child.pid }),
|
|
132
|
+
...(taskId === undefined ? {} : { taskId }),
|
|
133
|
+
...(exitCode === null || exitCode === undefined ? {} : { exitCode }),
|
|
134
|
+
...(signal ? { signal } : {}) }));
|
|
101
135
|
const aborted = () => finish(signal.reason instanceof Error ? signal.reason : new Error("SIGINT"));
|
|
102
|
-
child.on("error", unavailable);
|
|
103
|
-
child.once("exit", unavailable);
|
|
136
|
+
child.on("error", cause => unavailable(child.pid === undefined ? "spawn" : taskId ? "before_accepted" : "before_started", cause));
|
|
137
|
+
child.once("exit", (code, signal) => unavailable(taskId ? "before_accepted" : "before_started", undefined, code, signal));
|
|
138
|
+
child.once("disconnect", () => {
|
|
139
|
+
if (settled)
|
|
140
|
+
return;
|
|
141
|
+
// Node can close IPC just before emitting exit. Allow that terminal
|
|
142
|
+
// event a bounded turn so its actual code/signal is not lost.
|
|
143
|
+
disconnectTimer = setTimeout(() => unavailable("ipc_disconnect"), 100);
|
|
144
|
+
});
|
|
104
145
|
child.on("message", (message) => {
|
|
105
146
|
if (settled)
|
|
106
147
|
return;
|
|
107
|
-
if (message.type === "started")
|
|
148
|
+
if (message.type === "started") {
|
|
149
|
+
taskId = message.task.taskId;
|
|
108
150
|
started(message.task);
|
|
151
|
+
}
|
|
109
152
|
else if (message.type === "accepted")
|
|
110
153
|
finish(message.task);
|
|
111
154
|
else if (message.type === "error")
|
|
112
155
|
finish(new TaskBackgroundError(message.failure, message.exitCode, message.diagnostics));
|
|
113
156
|
});
|
|
114
157
|
signal.addEventListener("abort", aborted, { once: true });
|
|
115
|
-
|
|
116
|
-
|
|
158
|
+
try {
|
|
159
|
+
child.send(job, error => { if (error)
|
|
160
|
+
unavailable("ipc_send", error); });
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
unavailable("ipc_send", error);
|
|
164
|
+
}
|
|
117
165
|
});
|
|
118
166
|
}
|
|
119
167
|
};
|
|
@@ -58,13 +58,24 @@ export function createTaskUseCases(dependencies) {
|
|
|
58
58
|
const telemetry = dependencies.telemetry;
|
|
59
59
|
let pendingOutput;
|
|
60
60
|
const warnedTasks = new Set();
|
|
61
|
+
const warnedUsageTasks = new Set();
|
|
61
62
|
const stage = (name, run) => telemetry ? telemetry.stage(name, run) : run();
|
|
62
|
-
function
|
|
63
|
+
async function warn(stageName, message) {
|
|
64
|
+
await stage(stageName, async () => { (dependencies.warning ?? dependencies.notice)(message); }).catch(() => undefined);
|
|
65
|
+
}
|
|
66
|
+
async function cacheWarning(id) {
|
|
63
67
|
if (warnedTasks.has(id))
|
|
64
68
|
return;
|
|
65
69
|
warnedTasks.add(id);
|
|
66
70
|
telemetry?.annotate({ warning_codes: ["TASK_CACHE_UNAVAILABLE"] });
|
|
67
|
-
(
|
|
71
|
+
await warn("task.cache_warning", text(`任务 ${id} 的本地记录未能保存,task get 可能无法恢复。请保留本次输出,不要重新提交创作。`, `The local record for task ${id} could not be saved; task get may not recover it. Keep this output and do not submit the creation again.`));
|
|
72
|
+
}
|
|
73
|
+
async function usageWarning(id, incomplete) {
|
|
74
|
+
if (!incomplete || warnedUsageTasks.has(id))
|
|
75
|
+
return;
|
|
76
|
+
warnedUsageTasks.add(id);
|
|
77
|
+
telemetry?.annotate({ warning_codes: ["AGENT_USAGE_MODEL_MISSING"] });
|
|
78
|
+
await warn("task.usage_warning", text("已保留创作结果和服务端确认的实际费用;部分计费明细缺少模型标识,未推断模型或费用。请勿重复提交创作。", "The creation result and confirmed actual charges are retained. Some charge details have no model identifier; no model or fee was inferred. Do not submit the creation again."));
|
|
68
79
|
}
|
|
69
80
|
async function fact(scope, record, state, at, error) {
|
|
70
81
|
if (!telemetry || !record.telemetry)
|
|
@@ -159,8 +170,8 @@ export function createTaskUseCases(dependencies) {
|
|
|
159
170
|
let details;
|
|
160
171
|
if (input.operation === "agent.send")
|
|
161
172
|
details = { tool_type: "agent", tool_name: "agent" };
|
|
162
|
-
else if (generation?.model && (generation.tool
|
|
163
|
-
const name = generation.tool
|
|
173
|
+
else if (generation?.model && (generation.tool.startsWith("image.") || generation.tool.startsWith("video."))) {
|
|
174
|
+
const name = generation.tool.startsWith("image.") ? "AI绘图" : "AI视频生成";
|
|
164
175
|
details = { tool_type: name, tool_name: name, model_name: generation.model };
|
|
165
176
|
}
|
|
166
177
|
else
|
|
@@ -185,6 +196,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
185
196
|
if (error instanceof TaskStoreError)
|
|
186
197
|
error.context = { cli_task_id: record.task.taskId, phase,
|
|
187
198
|
request_sent: dispatched, accepted: record.progress.accepted === true || !!record.progress.remoteTaskId,
|
|
199
|
+
acceptance_durable: durableAcceptance,
|
|
188
200
|
result_state: record.task.state };
|
|
189
201
|
return error;
|
|
190
202
|
}
|
|
@@ -222,7 +234,11 @@ export function createTaskUseCases(dependencies) {
|
|
|
222
234
|
await analyticsFact("started");
|
|
223
235
|
return;
|
|
224
236
|
}
|
|
225
|
-
Object.assign(record.progress, progress);
|
|
237
|
+
Object.assign(record.progress, withoutResourceKeys(progress));
|
|
238
|
+
telemetry?.annotate({ diagnostic_summary: {
|
|
239
|
+
...(progress.contextId ? { agentContextId: progress.contextId } : {}),
|
|
240
|
+
...(progress.localMessageId ? { localMessageId: progress.localMessageId } : {})
|
|
241
|
+
} });
|
|
226
242
|
if (progress.contextId)
|
|
227
243
|
record.task.contextId = progress.contextId;
|
|
228
244
|
try {
|
|
@@ -232,7 +248,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
232
248
|
if (!(error instanceof LocalFileError) || !dispatched || (input.executionMode === "async" && !durableAcceptance)) {
|
|
233
249
|
throw storageContext(error, dispatched ? "after_dispatch" : "before_dispatch");
|
|
234
250
|
}
|
|
235
|
-
cacheWarning(record.task.taskId);
|
|
251
|
+
await cacheWarning(record.task.taskId);
|
|
236
252
|
return;
|
|
237
253
|
}
|
|
238
254
|
durableAcceptance ||= record.progress.accepted === true || !!record.progress.remoteTaskId;
|
|
@@ -252,7 +268,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
252
268
|
if (!(error instanceof LocalFileError) || record.task.state !== "completed" || input.executionMode === "async") {
|
|
253
269
|
throw storageContext(error, "final_persist");
|
|
254
270
|
}
|
|
255
|
-
cacheWarning(record.task.taskId);
|
|
271
|
+
await cacheWarning(record.task.taskId);
|
|
256
272
|
}
|
|
257
273
|
return { task: record.task, result, record };
|
|
258
274
|
}
|
|
@@ -286,6 +302,8 @@ export function createTaskUseCases(dependencies) {
|
|
|
286
302
|
if (dispatched && !observationOnly && record.task.state !== "completed")
|
|
287
303
|
await fact(scope, record, "failed", dependencies.now().getTime(), error);
|
|
288
304
|
await stage("task.persist", save).catch(() => undefined);
|
|
305
|
+
if (error instanceof TaskStoreError && error.context)
|
|
306
|
+
error.context.result_state = record.task.state;
|
|
289
307
|
throw error;
|
|
290
308
|
}
|
|
291
309
|
}
|
|
@@ -301,6 +319,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
301
319
|
if (input.executionMode !== "async") {
|
|
302
320
|
pendingOutput = { scope: taskScope(input.state), record: execution.record };
|
|
303
321
|
}
|
|
322
|
+
await usageWarning(execution.task.taskId, execution.record.progress.agentUsageModelMissing === true);
|
|
304
323
|
return execution.result;
|
|
305
324
|
},
|
|
306
325
|
async submit(input) {
|
|
@@ -327,16 +346,24 @@ export function createTaskUseCases(dependencies) {
|
|
|
327
346
|
stored.task = { ...stored.task, state: "unknown", note: text("尚未取得任务结果。", "The task result has not been received.") };
|
|
328
347
|
}));
|
|
329
348
|
}
|
|
349
|
+
record = withoutResourceKeys(record);
|
|
350
|
+
telemetry?.annotate({ diagnostic_summary: {
|
|
351
|
+
...(record.progress.contextId ? { agentContextId: record.progress.contextId } : {}),
|
|
352
|
+
...(record.progress.localMessageId ? { localMessageId: record.progress.localMessageId } : {})
|
|
353
|
+
} });
|
|
330
354
|
telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
|
|
331
355
|
if (record.task.state === "completed" && record.task.result) {
|
|
332
356
|
const result = { ...record.task, result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal)) };
|
|
333
357
|
pendingOutput = { scope, record };
|
|
358
|
+
await usageWarning(id, record.progress.agentUsageModelMissing === true);
|
|
334
359
|
return result;
|
|
335
360
|
}
|
|
336
361
|
const task = summary(record);
|
|
337
362
|
if (task.state === "failed" || (task.state === "running" && !record.progress.detached))
|
|
338
363
|
return task;
|
|
339
|
-
const { failure, ...recovered } = await stage("task.recover", () => dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal));
|
|
364
|
+
const { failure, usageModelMissing, ...recovered } = await stage("task.recover", () => dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal));
|
|
365
|
+
if (usageModelMissing)
|
|
366
|
+
record.progress.agentUsageModelMissing = true;
|
|
340
367
|
const { note: _note, ...metadata } = task;
|
|
341
368
|
const result = { ...metadata, ...recovered };
|
|
342
369
|
if (result.state === "unknown" && task.note) {
|
|
@@ -360,11 +387,13 @@ export function createTaskUseCases(dependencies) {
|
|
|
360
387
|
catch (error) {
|
|
361
388
|
if (!(error instanceof LocalFileError) || result.state !== "completed" || !result.result)
|
|
362
389
|
throw error;
|
|
363
|
-
cacheWarning(id);
|
|
390
|
+
await cacheWarning(id);
|
|
364
391
|
}
|
|
365
392
|
}
|
|
366
393
|
if (result.state === "completed" && result.result)
|
|
367
394
|
pendingOutput = { scope, record };
|
|
395
|
+
if (result.result ?? result.partialResult)
|
|
396
|
+
await usageWarning(id, record.progress.agentUsageModelMissing === true);
|
|
368
397
|
return result;
|
|
369
398
|
},
|
|
370
399
|
async outputCompleted() {
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Product copy only. Executable constraints stay in the shared formal Schema.
|
|
2
|
+
const copy = {
|
|
3
|
+
"image-edit-standard": ["Standard image edit", "White mask pixels are processed; black pixels are protected. Supply an opaque binary PNG matching the auto-oriented source. The CLI converts service-specific mask polarity and requests source dimensions."],
|
|
4
|
+
"image-edit-smart": ["Smart image edit", "Generative editing can change details. An optional mask is rendered as a cyan outline on the target image; referenceImages are references, never a mask. Inspect changes outside the selection."],
|
|
5
|
+
"image-matting-standard": ["Standard background removal", "Preserves visible source pixels without reconstructing occluded parts. Returns a real alpha PNG at source dimensions unless cropToSubject is enabled."],
|
|
6
|
+
"image-matting-smart": ["Smart subject extraction", "Redraws the requested subject, then segments the redraw into a transparent PNG. Hidden details are generated guesses. An optional mask is a visual boundary cue. Transparent postprocessing is included; do not pay for another standard matting call."],
|
|
7
|
+
"image-remove-standard": ["Standard object removal", "Remove within white mask pixels; black pixels are protected. The opaque binary PNG mask must match the auto-oriented source. Source dimensions are requested from the service."],
|
|
8
|
+
"image-remove-smart": ["Smart object removal", "Remove objects from one target image using instructions. An optional mask is rendered as a cyan outline, not sent as another reference image. Inspect changes outside the selection."],
|
|
9
|
+
"image-enhance-standard": ["Standard image upscale", "targetLongEdge specifies the output's longest edge in pixels while retaining aspect ratio. Bounds and steps come from the current catalog."],
|
|
10
|
+
"image-enhance-smart": ["Smart image restoration", "Generative restoration may reconstruct textures, text, faces or product details. Check the user's permitted changes against the actual result."],
|
|
11
|
+
"image-expand-standard": ["Standard image expansion", "canvas and placement use auto-oriented source pixels. Origin is top-left; x goes right and y down. The original must fit without scaling. The target canvas dimensions are requested from the service."],
|
|
12
|
+
"image-expand-smart": ["Smart image expansion", "Place the source at natural size and expand its surroundings. Output uses the target aspect ratio; pixel dimensions follow the live resolution setting. Source details can change."],
|
|
13
|
+
"image-text-edit": ["Image text replacement", "replacements match complete original text. An empty to deletes it. Repeated text cannot be targeted by occurrence. Verify all unchanged text."],
|
|
14
|
+
"image-ocr": ["Image text recognition", "Returns an embedded application/json resource: image{uri,width,height}, blocks[{bbox:[left,top,right,bottom],category,text?}]. Coordinates use the returned recognition image's top-left origin in pixels."],
|
|
15
|
+
"image-layers-layout": ["Layout decomposition", "Fits the source within 3000×3000 pixels without enlargement. Returns native template JSON and actual element counts, not PSD. Editability depends on the returned layers; fonts may be substituted. Use a discovered Editor import capability to open the template."],
|
|
16
|
+
"image-layers-smart": ["Smart layer decomposition", "Fits the source within 3000×3000 pixels without enlargement; the prepared image must have at least 512×512 total pixels. Returns native template JSON and layer counts, not PSD or word-by-word OCR. maxLayers is an upper bound. Pricing uses current remote metered components."],
|
|
17
|
+
"image-vectorize": ["Image to SVG", "Returns an SVG resource. The caller inspects actual vector contents, reconstructed shapes, colors and details."],
|
|
18
|
+
"video-edit-smart": ["Smart video edit", "Duration and ratio come from the actual source. Reference videos including the source total at most 15 seconds. audioEnabled controls audio presence, not preservation of the original sound."],
|
|
19
|
+
"video-enhance-standard": ["Standard video upscale", "Uses ceil(actual seconds) for billing and requests preservation of the source video. The caller inspects actual duration, visuals and soundtrack preservation."],
|
|
20
|
+
"video-enhance-smart": ["Smart video restoration", "Generative restoration requests the source duration rounded to 2–30 seconds and may change details. The caller inspects actual duration, sound content and synchronization."]
|
|
21
|
+
};
|
|
22
|
+
export function englishCanvasCopy(model, schema) {
|
|
23
|
+
const descriptions = {
|
|
24
|
+
image: "One HTTP(S) or CLI file:// source image URI.",
|
|
25
|
+
video: "One HTTP(S) or CLI file:// source video URI.",
|
|
26
|
+
mask: "Fully opaque PNG containing only pure black and white, matching the auto-oriented source. White processes, black protects. White must be nonempty; all-white selects the entire image.",
|
|
27
|
+
cropToSubject: "Crop to the nonzero alpha subject bounds. Default keeps the final source dimensions.",
|
|
28
|
+
canvas: "Target canvas width and height in natural source pixels.",
|
|
29
|
+
placement: "Source top-left position in canvas pixels: x right, y down. No source scaling.",
|
|
30
|
+
referenceImages: "Additional image references, separate from the target image and mask.",
|
|
31
|
+
referenceVideos: "Additional reference videos. The source video remains first.",
|
|
32
|
+
referenceAudios: "Additional audio references.",
|
|
33
|
+
replacements: "Complete original/new text pairs. Empty to means delete; duplicate from entries are rejected.",
|
|
34
|
+
from: "The complete original text to replace, including punctuation and spaces.",
|
|
35
|
+
to: "Replacement text. An empty string deletes the matched original text.",
|
|
36
|
+
targetLongEdge: "Output's longest edge in pixels; aspect ratio is retained.",
|
|
37
|
+
maxLayers: "Requested layer count upper bound, not an exact output count."
|
|
38
|
+
};
|
|
39
|
+
for (const [name, property] of Object.entries(schema.properties)) {
|
|
40
|
+
if (descriptions[name])
|
|
41
|
+
property.description = descriptions[name];
|
|
42
|
+
if (property.items?.format === "uri")
|
|
43
|
+
property.items.description = "HTTP(S) or CLI file:// asset URI.";
|
|
44
|
+
for (const [child, field] of Object.entries(property.items?.properties ?? {})) {
|
|
45
|
+
if (descriptions[child])
|
|
46
|
+
field.description = descriptions[child];
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (model.endsWith("-smart") && schema.properties.mask) {
|
|
50
|
+
schema.properties.mask.description = "Fully opaque PNG containing only pure black and white, matching the auto-oriented source. Nonempty white pixels identify the target; all-white selects the entire image. The CLI converts this to a visual boundary cue, which cannot guarantee unchanged pixels outside the selection.";
|
|
51
|
+
}
|
|
52
|
+
if (model === "video-edit-smart") {
|
|
53
|
+
schema.properties.video.description = "Source video to edit, referenced as 视频1 in the prompt. HTTP(S) or CLI file:// URI.";
|
|
54
|
+
schema.properties.prompt.description = "The user's prompt is kept verbatim; the CLI only prefixes media bindings. Reference the source as 视频1, referenceVideos from 视频2, referenceImages from 图1, and referenceAudios from 音频1, each in array order. The CLI adds original filename-to-label bindings before uploading changes filenames.";
|
|
55
|
+
schema.properties.referenceImages.description = "Reference images, numbered 图1, 图2, etc. in array order.";
|
|
56
|
+
schema.properties.referenceVideos.description = "Reference videos, numbered 视频2, 视频3, etc.; 视频1 is always the source. The source and all reference videos combined must not exceed 15 seconds.";
|
|
57
|
+
schema.properties.referenceAudios.description = "Reference audio, numbered 音频1, 音频2, etc. in array order.";
|
|
58
|
+
}
|
|
59
|
+
const [title, usageDescription] = copy[model];
|
|
60
|
+
return { title, usageDescription };
|
|
61
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { readFile, mkdtemp, writeFile, rm } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { inspectUploadFile, LocalFileInputError } from "../../platform/safe-upload-file.js";
|
|
6
|
+
import { uriShape } from "../../platform/input-uri.js";
|
|
7
|
+
import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
|
|
8
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
9
|
+
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
10
|
+
import { ToolInputError } from "./catalog.js";
|
|
11
|
+
function responseDiagnostics(url, redirectCount, headers) {
|
|
12
|
+
const requestId = ["x-request-id", "x-gd-request-id", "request-id"]
|
|
13
|
+
.map(name => headers?.get(name)).find((value) => typeof value === "string" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value));
|
|
14
|
+
return {
|
|
15
|
+
...(url.hostname.length <= 253 ? { mediaHost: url.hostname } : {}),
|
|
16
|
+
redirectCount, mediaBytesRead: 0, ...(requestId ? { requestId } : {})
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function mediaFailure(phase, summary, status, cause) {
|
|
20
|
+
return new RemoteRequestError(status, false, {}, cause, `MEDIA_${phase.toUpperCase()}_FAILED`, { ...summary, mediaPhase: phase });
|
|
21
|
+
}
|
|
22
|
+
export function createCanvasMedia(dependencies) {
|
|
23
|
+
async function readWithEvidence(uri, signal, limit = 64 * 1024 * 1024) {
|
|
24
|
+
signal.throwIfAborted();
|
|
25
|
+
if (uri.startsWith("file:")) {
|
|
26
|
+
const file = await inspectUploadFile({ url: uri, signal });
|
|
27
|
+
if (file.size > limit)
|
|
28
|
+
throw new ToolInputError("media_too_large", "/arguments");
|
|
29
|
+
try {
|
|
30
|
+
const bytes = await readFile(file.filePath, { signal });
|
|
31
|
+
return { bytes, summary: { ...uriShape(uri), mediaPhase: "read", mediaBytesRead: bytes.length } };
|
|
32
|
+
}
|
|
33
|
+
catch (cause) {
|
|
34
|
+
if (signal.aborted)
|
|
35
|
+
throw signal.reason;
|
|
36
|
+
throw new LocalFileInputError(cause, "file_read_failed", { ...uriShape(uri), mediaPhase: "read" });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
let url = parseSafeRemoteAssetUrl(uri);
|
|
40
|
+
for (let redirects = 0; redirects <= 5; redirects++) {
|
|
41
|
+
let response;
|
|
42
|
+
try {
|
|
43
|
+
response = await dependencies.fetch(url, { redirect: "manual", signal });
|
|
44
|
+
}
|
|
45
|
+
catch (cause) {
|
|
46
|
+
if (signal.aborted)
|
|
47
|
+
throw signal.reason;
|
|
48
|
+
throw mediaFailure("request", responseDiagnostics(url, redirects), undefined, cause);
|
|
49
|
+
}
|
|
50
|
+
signal.throwIfAborted();
|
|
51
|
+
const summary = responseDiagnostics(url, redirects, response.headers);
|
|
52
|
+
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
53
|
+
const location = response.headers.get("location");
|
|
54
|
+
await response.body?.cancel().catch(() => undefined);
|
|
55
|
+
if (!location || redirects === 5)
|
|
56
|
+
throw mediaFailure("redirect", summary, response.status);
|
|
57
|
+
try {
|
|
58
|
+
url = parseSafeRemoteAssetUrl(new URL(location, url).href);
|
|
59
|
+
}
|
|
60
|
+
catch (cause) {
|
|
61
|
+
throw mediaFailure("redirect", summary, response.status, cause);
|
|
62
|
+
}
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (!response.ok) {
|
|
66
|
+
await response.body?.cancel().catch(() => undefined);
|
|
67
|
+
throw mediaFailure("request", summary, response.status);
|
|
68
|
+
}
|
|
69
|
+
if (!response.body)
|
|
70
|
+
throw mediaFailure("read", summary, response.status);
|
|
71
|
+
if (Number(response.headers.get("content-length")) > limit) {
|
|
72
|
+
await response.body.cancel().catch(() => undefined);
|
|
73
|
+
throw Object.assign(new ToolInputError("media_too_large", "/arguments"), { diagnosticSummary: { ...summary, mediaPhase: "read" } });
|
|
74
|
+
}
|
|
75
|
+
const chunks = [];
|
|
76
|
+
let size = 0;
|
|
77
|
+
try {
|
|
78
|
+
const reader = response.body.getReader();
|
|
79
|
+
try {
|
|
80
|
+
while (true) {
|
|
81
|
+
const { value, done } = await reader.read();
|
|
82
|
+
if (done)
|
|
83
|
+
break;
|
|
84
|
+
size += value.byteLength;
|
|
85
|
+
if (size > limit)
|
|
86
|
+
throw new ToolInputError("media_too_large", "/arguments");
|
|
87
|
+
chunks.push(Buffer.from(value));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
await reader.cancel().catch(() => undefined);
|
|
92
|
+
reader.releaseLock();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
catch (cause) {
|
|
96
|
+
if (signal.aborted)
|
|
97
|
+
throw signal.reason;
|
|
98
|
+
const evidence = { ...summary, mediaPhase: "read", mediaBytesRead: Math.min(size, 64 * 1024 * 1024) };
|
|
99
|
+
if (cause instanceof ToolInputError)
|
|
100
|
+
throw Object.assign(cause, { diagnosticSummary: evidence });
|
|
101
|
+
throw mediaFailure("read", evidence, response.status, cause);
|
|
102
|
+
}
|
|
103
|
+
return { bytes: Buffer.concat(chunks), summary: { ...summary, mediaPhase: "read", mediaBytesRead: size }, status: response.status };
|
|
104
|
+
}
|
|
105
|
+
throw mediaFailure("redirect", responseDiagnostics(url, 5));
|
|
106
|
+
}
|
|
107
|
+
async function read(uri, signal, limit) {
|
|
108
|
+
return (await readWithEvidence(uri, signal, limit)).bytes;
|
|
109
|
+
}
|
|
110
|
+
async function image(uri, signal) {
|
|
111
|
+
const { bytes: raw, summary, status } = await readWithEvidence(uri, signal);
|
|
112
|
+
try {
|
|
113
|
+
const { default: sharp } = await import("sharp");
|
|
114
|
+
const metadata = await sharp(raw, { limitInputPixels: 64 * 1024 * 1024 }).metadata();
|
|
115
|
+
if ((metadata.pages ?? 1) !== 1)
|
|
116
|
+
throw new ToolInputError("animated_image_not_supported", "/arguments/image");
|
|
117
|
+
const { data, info } = await sharp(raw).autoOrient().png().toBuffer({ resolveWithObject: true });
|
|
118
|
+
return { bytes: data, width: info.width, height: info.height };
|
|
119
|
+
}
|
|
120
|
+
catch (cause) {
|
|
121
|
+
if (signal.aborted)
|
|
122
|
+
throw signal.reason;
|
|
123
|
+
if (cause instanceof ToolInputError)
|
|
124
|
+
throw cause;
|
|
125
|
+
throw Object.assign(new ToolInputError("image_decode_failed", "/arguments/image", [], cause), {
|
|
126
|
+
...(status === undefined ? {} : { status }), diagnosticSummary: { ...summary, mediaPhase: "decode" }
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async function upload(bytes, extension, access, signal) {
|
|
131
|
+
const directory = await mkdtemp(join(tmpdir(), "gd-cli-media-"));
|
|
132
|
+
try {
|
|
133
|
+
const path = join(directory, `asset.${extension}`);
|
|
134
|
+
await writeFile(path, bytes, { mode: 0o600, signal });
|
|
135
|
+
return (await dependencies.uploader.upload({ url: pathToFileURL(path).href }, access, signal)).url;
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
await rm(directory, { recursive: true, force: true });
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async function mask(uri, source, signal) {
|
|
142
|
+
const { default: sharp } = await import("sharp");
|
|
143
|
+
const bytes = await read(uri, signal);
|
|
144
|
+
const metadata = await sharp(bytes).metadata();
|
|
145
|
+
if (metadata.format !== "png" || metadata.width !== source.width || metadata.height !== source.height
|
|
146
|
+
|| (metadata.orientation !== undefined && metadata.orientation !== 1)) {
|
|
147
|
+
throw new ToolInputError("mask_geometry_or_format", "/arguments/mask");
|
|
148
|
+
}
|
|
149
|
+
const { data, info } = await sharp(bytes).toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
150
|
+
const mono = Buffer.alloc(info.width * info.height);
|
|
151
|
+
let selected = false;
|
|
152
|
+
for (let i = 0; i < mono.length; i++) {
|
|
153
|
+
const offset = i * 4;
|
|
154
|
+
const value = data[offset];
|
|
155
|
+
if ((value !== 0 && value !== 255) || data[offset + 1] !== value || data[offset + 2] !== value || data[offset + 3] !== 255) {
|
|
156
|
+
throw new ToolInputError("mask_requires_opaque_binary_png", "/arguments/mask");
|
|
157
|
+
}
|
|
158
|
+
mono[i] = value;
|
|
159
|
+
selected ||= value === 255;
|
|
160
|
+
}
|
|
161
|
+
if (!selected)
|
|
162
|
+
throw new ToolInputError("mask_empty_selection", "/arguments/mask");
|
|
163
|
+
return mono;
|
|
164
|
+
}
|
|
165
|
+
async function uploadFile(uri, access, signal) {
|
|
166
|
+
// Keep the actual input extension/MIME for audio references instead of renaming every file .mp3.
|
|
167
|
+
await read(uri, signal);
|
|
168
|
+
return (await dependencies.uploader.upload({ url: uri }, access, signal)).url;
|
|
169
|
+
}
|
|
170
|
+
return { read, image, upload, uploadFile, mask };
|
|
171
|
+
}
|
|
172
|
+
export async function maskPng(mask, width, height, invert = false) {
|
|
173
|
+
const { default: sharp } = await import("sharp");
|
|
174
|
+
return sharp(invert ? Buffer.from(mask.map(value => 255 - value)) : mask, { raw: { width, height, channels: 1 } }).png().toBuffer();
|
|
175
|
+
}
|
|
176
|
+
export async function outlineImage(source, mask) {
|
|
177
|
+
const { default: sharp } = await import("sharp");
|
|
178
|
+
const { width, height } = source;
|
|
179
|
+
const { data } = await sharp(source.bytes).toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
180
|
+
const radius = Math.max(1, Math.round(Math.max(width, height) / 600));
|
|
181
|
+
for (let y = 0; y < height; y++)
|
|
182
|
+
for (let x = 0; x < width; x++) {
|
|
183
|
+
const index = y * width + x;
|
|
184
|
+
if (mask[index] !== 255)
|
|
185
|
+
continue;
|
|
186
|
+
let boundary = false;
|
|
187
|
+
for (const [dx, dy] of [[-radius, 0], [radius, 0], [0, -radius], [0, radius]]) {
|
|
188
|
+
const nx = x + dx;
|
|
189
|
+
const ny = y + dy;
|
|
190
|
+
if (nx < 0 || nx >= width || ny < 0 || ny >= height || mask[ny * width + nx] !== 255) {
|
|
191
|
+
boundary = true;
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (boundary) {
|
|
196
|
+
const offset = index * 4;
|
|
197
|
+
data[offset] = 0;
|
|
198
|
+
data[offset + 1] = 255;
|
|
199
|
+
data[offset + 2] = 255;
|
|
200
|
+
data[offset + 3] = 255;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return sharp(data, { raw: { width, height, channels: 4 } }).png().toBuffer();
|
|
204
|
+
}
|
|
205
|
+
export function expansionGeometry(source, canvas, placement) {
|
|
206
|
+
const { width, height } = canvas;
|
|
207
|
+
const { x, y } = placement;
|
|
208
|
+
if (width > 4096 || height > 4096 || width * height > 16 * 1024 * 1024
|
|
209
|
+
|| x + source.width > width || y + source.height > height
|
|
210
|
+
|| (width === source.width && height === source.height)) {
|
|
211
|
+
throw new ToolInputError("expansion_geometry", "/arguments/canvas");
|
|
212
|
+
}
|
|
213
|
+
return { outer: [width, height], corners: [[x, y], [x + source.width, y], [x + source.width, y + source.height], [x, y + source.height]] };
|
|
214
|
+
}
|
|
215
|
+
export async function expansionImage(source, canvas, placement) {
|
|
216
|
+
const { default: sharp } = await import("sharp");
|
|
217
|
+
expansionGeometry(source, canvas, placement);
|
|
218
|
+
const flattened = await sharp(source.bytes).flatten({ background: "white" }).png().toBuffer();
|
|
219
|
+
return sharp({ create: { ...canvas, channels: 3, background: { r: 0, g: 255, b: 0 } } })
|
|
220
|
+
.composite([{ input: flattened, left: placement.x, top: placement.y }]).png().toBuffer();
|
|
221
|
+
}
|
|
222
|
+
export async function composeMatting(source, segmentation, channel, crop) {
|
|
223
|
+
const { default: sharp } = await import("sharp");
|
|
224
|
+
const metadata = await sharp(segmentation).metadata();
|
|
225
|
+
if (channel === "alpha" && metadata.hasAlpha !== true)
|
|
226
|
+
throw new RemoteProtocolError({}, undefined, "MATTING_ALPHA_MISSING");
|
|
227
|
+
const alpha = await sharp(segmentation).autoOrient().resize(source.width, source.height, { fit: "fill" })
|
|
228
|
+
.ensureAlpha().extractChannel(channel === "alpha" ? 3 : 0).raw().toBuffer();
|
|
229
|
+
const { data } = await sharp(source.bytes).toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
230
|
+
let left = source.width, top = source.height, right = -1, bottom = -1;
|
|
231
|
+
for (let i = 0; i < alpha.length; i++) {
|
|
232
|
+
const value = Math.round(alpha[i] * data[i * 4 + 3] / 255);
|
|
233
|
+
data[i * 4 + 3] = value;
|
|
234
|
+
if (value > 0) {
|
|
235
|
+
const x = i % source.width;
|
|
236
|
+
const y = Math.floor(i / source.width);
|
|
237
|
+
left = Math.min(left, x);
|
|
238
|
+
top = Math.min(top, y);
|
|
239
|
+
right = Math.max(right, x);
|
|
240
|
+
bottom = Math.max(bottom, y);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
let pipeline = sharp(data, { raw: { width: source.width, height: source.height, channels: 4 } });
|
|
244
|
+
// An empty segmentation has no subject bounds; preserve its full transparent canvas.
|
|
245
|
+
if (crop && right >= 0)
|
|
246
|
+
pipeline = pipeline.extract({ left, top, width: right - left + 1, height: bottom - top + 1 });
|
|
247
|
+
return pipeline.png().toBuffer();
|
|
248
|
+
}
|