@insmind/cli 1.9.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/insmind-cli.js +32 -25
- package/dist/bin/task-worker.js +4 -1
- package/dist/src/analytics/device.js +2 -2
- package/dist/src/bootstrap/create-cli.js +10 -8
- package/dist/src/bootstrap/create-runtime.js +29 -23
- package/dist/src/bootstrap/run-task-worker.js +7 -2
- package/dist/src/bootstrap/validators.js +15 -6
- package/dist/src/cli/action-binding.js +39 -0
- package/dist/src/cli/agent-commands.js +8 -12
- package/dist/src/cli/dam-commands.js +6 -5
- package/dist/src/cli/editor-commands.js +10 -5
- package/dist/src/cli/errors.js +60 -12
- package/dist/src/cli/host-input.js +34 -0
- package/dist/src/cli/model-commands.js +4 -3
- package/dist/src/cli/observed-errors.js +3 -1
- package/dist/src/cli/tool-commands.js +7 -9
- package/dist/src/contracts/creation-input.js +20 -0
- package/dist/src/features/agent/creative-agent-adapter.js +37 -11
- package/dist/src/features/agent/creative-protocol.js +21 -19
- package/dist/src/features/agent/creative-stream.js +54 -6
- package/dist/src/features/agent/result-reader.js +3 -1
- package/dist/src/features/agent/use-cases.js +6 -31
- package/dist/src/features/auth/access-policy.js +1 -3
- package/dist/src/features/auth/credential-store.js +6 -10
- package/dist/src/features/auth/sso-service.js +28 -10
- package/dist/src/features/auth/state.js +6 -0
- package/dist/src/features/auth/use-cases.js +91 -32
- package/dist/src/features/credits/use-cases.js +1 -1
- 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/file-downloader.js +2 -1
- package/dist/src/features/dam/input.js +23 -0
- package/dist/src/features/dam/use-cases.js +39 -29
- package/dist/src/features/editor/bridge-client.js +1 -1
- package/dist/src/features/editor/use-cases.js +6 -8
- package/dist/src/features/org/use-cases.js +3 -3
- package/dist/src/features/skill/installer.js +24 -22
- package/dist/src/features/task/store.js +31 -17
- package/dist/src/features/task/task-background.js +67 -19
- package/dist/src/features/task/use-cases.js +131 -88
- package/dist/src/features/tool/canvas-media.js +82 -27
- package/dist/src/features/tool/canvas-models.js +21 -4
- package/dist/src/features/tool/canvas-tool-adapter.js +29 -20
- package/dist/src/features/tool/canvas-video.js +2 -4
- package/dist/src/features/tool/dynamic-schema.js +32 -63
- package/dist/src/features/tool/matting-billing.js +38 -26
- package/dist/src/features/tool/mns-catalog-adapter.js +9 -2
- package/dist/src/features/tool/scene-catalog-adapter.js +0 -1
- package/dist/src/features/tool/tool-api-adapter.js +19 -16
- package/dist/src/features/tool/use-cases.js +24 -35
- package/dist/src/platform/file-lock.js +58 -15
- package/dist/src/platform/input-uri.js +105 -0
- package/dist/src/platform/json-input.js +1 -1
- 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 +24 -4
- package/dist/src/platform/schema-issues.js +18 -0
- package/dist/src/platform/signed-http-transport.js +95 -37
- package/dist/src/platform/text-output.js +55 -13
- package/dist/src/telemetry/failure-summary.js +53 -2
- package/dist/src/telemetry/host-diagnostics.js +95 -0
- package/dist/src/telemetry/invocation.js +107 -23
- package/dist/src/telemetry/process-errors.js +38 -4
- package/dist/src/telemetry/sls-sink.js +71 -26
- package/package.json +4 -4
- package/skills/insmind-cli/SKILL.md +1 -0
- package/skills/insmind-cli/references/editor.md +1 -1
- package/skills/insmind-cli/references/generation-constraints.md +3 -1
- package/skills/insmind-cli/references/tool.md +2 -3
package/dist/src/cli/errors.js
CHANGED
|
@@ -4,7 +4,7 @@ import { TaskNotFoundError } from "../features/task/use-cases.js";
|
|
|
4
4
|
import { TaskStoreError } from "../features/task/store.js";
|
|
5
5
|
import { CommanderError } from "commander";
|
|
6
6
|
import { AuthExpiredError, AuthRequiredError } from "../features/auth/access-policy.js";
|
|
7
|
-
import { AuthStateInvalidError, UserIdentityMissingError } from "../features/auth/state.js";
|
|
7
|
+
import { AuthStateInvalidError, AuthStateUnavailableError, UserIdentityMissingError } from "../features/auth/state.js";
|
|
8
8
|
import { SsoRequestError } from "../features/auth/sso-service.js";
|
|
9
9
|
import { AuthorizedAccountContextMissingError, BrowserOpenError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
|
|
10
10
|
import { AgentInputError } from "../features/agent/use-cases.js";
|
|
@@ -68,7 +68,7 @@ export function mapCliError(error, options) {
|
|
|
68
68
|
if (!category)
|
|
69
69
|
return outcome;
|
|
70
70
|
// Keep precise input corrections and their fields; general failures have a short user message.
|
|
71
|
-
if (category === "input" && ["USAGE_ERROR", "INVALID_ACTIONS"].includes(outcome.failure.code))
|
|
71
|
+
if ((category === "input" || category === "input_asset") && ["USAGE_ERROR", "INVALID_ACTIONS"].includes(outcome.failure.code))
|
|
72
72
|
return outcome;
|
|
73
73
|
return { ...outcome, failure: { ...outcome.failure, message: observedErrorMessage(category, evidence) } };
|
|
74
74
|
}
|
|
@@ -108,6 +108,8 @@ function mapBaseCliError(error, options) {
|
|
|
108
108
|
return failure("AUTH_EXPIRED", "Authentication expired. Sign out and sign in again.", 1, [`${command} auth logout`, `${command} auth login`]);
|
|
109
109
|
return failure("AUTH_EXPIRED", "登录已过期,请退出后重新登录。", 1, ["gd-cli auth logout", "gd-cli auth login"]);
|
|
110
110
|
}
|
|
111
|
+
if (error instanceof AuthStateUnavailableError)
|
|
112
|
+
return failure("AUTH_STATE_UNAVAILABLE", text("无法读取或保存本地登录信息。", "Local sign-in information could not be read or saved."), 1, [text("请检查文件访问权限后重试。", "Check file access permissions and try again.")], { reason: "local_io", system_code: systemErrorCode(error) });
|
|
111
113
|
if (error instanceof AuthStateInvalidError) {
|
|
112
114
|
if (error.reason === "local_io")
|
|
113
115
|
return failure("AUTH_STATE_INVALID", text("无法读写本地凭证,当前无法判断登录是否有效。", "Cannot access local credentials; authentication validity is unknown."), 1, [text("恢复凭证文件的访问权限或宿主文件访问能力;不要执行 logout 或删除凭证。", "Restore access to the credential file or host file permissions; do not log out or delete credentials.")], { reason: error.reason, system_code: systemErrorCode(error) });
|
|
@@ -147,12 +149,23 @@ function mapBaseCliError(error, options) {
|
|
|
147
149
|
const description = descriptions[error.reason];
|
|
148
150
|
return failure("USAGE_ERROR", description ? text(...description) : text("创作输入不可用,请核对模型与参数。", "Check the model and creation arguments."), 2, [`${command} model list`, text(`使用 ${command} model get <model> 核对模型参数;素材应使用安全的 HTTP(S) URL 或本地 file URL。`, `Use ${command} model get <model> to inspect parameters; assets require safe HTTP(S) URLs or local file URLs.`)], { reason: error.reason, field: error.field, ...(error instanceof ToolInputError ? { issues: error.issues } : {}) });
|
|
149
151
|
}
|
|
150
|
-
if (error instanceof LocalFileInputError)
|
|
151
|
-
|
|
152
|
+
if (error instanceof LocalFileInputError) {
|
|
153
|
+
const message = error.reason === "invalid_file_uri"
|
|
154
|
+
? text("本地文件地址格式不正确。Windows 地址示例:file:///C:/目录/文件。", "Invalid local file URL. Windows example: file:///C:/folder/file.")
|
|
155
|
+
: error.reason === "file_read_failed" && systemErrorCode(error) === "ENOENT"
|
|
156
|
+
? text("找不到指定的本地文件,请核对完整路径。", "The local file was not found. Check its full path.")
|
|
157
|
+
: error.reason === "media_type_mismatch"
|
|
158
|
+
? text("素材类型与文件实际格式不一致,请修正 mediaType 或重新选择文件。", "The mediaType does not match the file format. Correct it or select another file.")
|
|
159
|
+
: text("本地素材文件不可用于上传。", "The local asset file cannot be uploaded.");
|
|
160
|
+
return failure("USAGE_ERROR", message, 2, [text("检查文件访问权限、文件类型和声明的 mediaType;受保护路径不可上传。", "Check file access, type and declared mediaType; protected paths cannot be uploaded.")], { reason: error.reason, system_code: systemErrorCode(error) });
|
|
161
|
+
}
|
|
152
162
|
if (error instanceof CliUsageError && error.reason === "invalid_task_id")
|
|
153
163
|
return failure("USAGE_ERROR", text("任务编号不正确,请使用本机任务列表中的 taskId。", "Invalid Task ID. Use a taskId from the local task list."), 2, [`${command} task list`, `${command} task get <taskId>`], { reason: error.reason });
|
|
154
164
|
if (error instanceof DamInputError)
|
|
155
165
|
return failure("USAGE_ERROR", text("素材管理参数无效,请根据字段和原因核对命令 --help。", "Invalid asset-management argument; check the field and reason against the command's --help."), 2, undefined, { reason: error.reason, field: error.field });
|
|
166
|
+
if (error instanceof CommanderError && error.code === "commander.unknownOption" && options.operation === "dam.download"
|
|
167
|
+
&& /unknown option ['"]--output['"]/u.test(error.message))
|
|
168
|
+
return failure("USAGE_ERROR", text("下载目录请使用 --output-dir <directory>。", "Use --output-dir <directory> to choose the download directory."), 2);
|
|
156
169
|
if (error instanceof OrgUsageError
|
|
157
170
|
|| error instanceof CliUsageError
|
|
158
171
|
|| error instanceof CommanderError) {
|
|
@@ -256,6 +269,8 @@ function mapBaseCliError(error, options) {
|
|
|
256
269
|
}
|
|
257
270
|
return failure(error.code, redactSensitiveText(error.message).slice(0, 1024), 1, ["写入失败时先检查原作品,不直接重复 apply 或 save;按 editor --help 中的对应错误指引处理。"]);
|
|
258
271
|
}
|
|
272
|
+
if (systemErrorCode(error) === "ECONNRESET")
|
|
273
|
+
return failure("REMOTE_REQUEST_FAILED", text("连接中断,未能完整收到结果。", "The connection closed before the full result was received."), 1);
|
|
259
274
|
return failure("INTERNAL_ERROR", insmind ? "The CLI encountered an internal error." : "CLI 发生内部错误。", 1);
|
|
260
275
|
}
|
|
261
276
|
function isInsufficientCreditsError(error) {
|
|
@@ -270,6 +285,13 @@ export function classifyTelemetryError(error, options = {}) {
|
|
|
270
285
|
return { outcome: "failure", errorCode: error.code,
|
|
271
286
|
...(error.status === undefined ? {} : { httpStatus: error.status }) };
|
|
272
287
|
const outcome = mapCliError(error, { ...options, aborted: options.aborted === true });
|
|
288
|
+
if (error instanceof DeviceAuthorizationExpiredError && outcome.kind !== "interrupted")
|
|
289
|
+
return {
|
|
290
|
+
outcome: "failure", errorCode: "REMOTE_REQUEST_FAILED",
|
|
291
|
+
diagnosticReason: error.expirationSource === "server_expired" ? "AUTHORIZATION_SERVER_EXPIRED" : "AUTHORIZATION_WAIT_TIMEOUT",
|
|
292
|
+
...(error.httpStatus === undefined ? {} : { httpStatus: error.httpStatus }),
|
|
293
|
+
...(error.expirationSource === "server_expired" ? { remoteErrorCode: "expired_token" } : {})
|
|
294
|
+
};
|
|
273
295
|
if (error instanceof TaskBackgroundError) {
|
|
274
296
|
const diagnostics = error.diagnostics;
|
|
275
297
|
return { outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
|
|
@@ -290,24 +312,27 @@ export function classifyTelemetryError(error, options = {}) {
|
|
|
290
312
|
}
|
|
291
313
|
catch { /* No safe summary available. */ }
|
|
292
314
|
}
|
|
315
|
+
const inputReason = error instanceof LocalFileInputError ? error.reason
|
|
316
|
+
: error instanceof JsonInputError ? `json_${error.reason}`
|
|
317
|
+
: error instanceof InputContractError ? "schema_validation"
|
|
318
|
+
: error instanceof CliUsageError || error instanceof ToolInputError || error instanceof AgentInputError || error instanceof DamInputError ? error.reason
|
|
319
|
+
: error instanceof CommanderError ? error.code : undefined;
|
|
320
|
+
const systemCode = systemErrorCode(error);
|
|
293
321
|
const diagnosticSummary = safeFailureSummary({
|
|
294
322
|
...localFileSummary(error),
|
|
295
323
|
...(error instanceof OutputStreamError ? { outputStream: error.outputStream } : {}),
|
|
296
324
|
...(remoteError instanceof SsoRequestError ? remoteError.diagnosticSummary : {}),
|
|
297
325
|
...(summary && typeof summary === "object" && !Array.isArray(summary) ? summary : {}),
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
: error instanceof InputContractError ? "schema_validation"
|
|
302
|
-
: error instanceof CliUsageError || error instanceof ToolInputError || error instanceof AgentInputError ? error.reason
|
|
303
|
-
: error instanceof CommanderError ? error.code : undefined
|
|
326
|
+
...nestedDiagnosticSummary(error),
|
|
327
|
+
...(systemCode ? { systemCode } : {}),
|
|
328
|
+
...(inputReason ? { inputReason } : {})
|
|
304
329
|
});
|
|
305
330
|
return {
|
|
306
331
|
outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
|
|
307
332
|
...(diagnosticSummary ? { diagnosticSummary } : {}),
|
|
308
333
|
...(outcome.kind === "failure" ? { errorCode: outcome.failure.code } : {}),
|
|
309
|
-
...((
|
|
310
|
-
? { httpStatus:
|
|
334
|
+
...(httpErrorStatus(error) !== undefined
|
|
335
|
+
? { httpStatus: httpErrorStatus(error) }
|
|
311
336
|
: {}),
|
|
312
337
|
...(remoteError?.remoteCode === undefined
|
|
313
338
|
? {}
|
|
@@ -323,6 +348,29 @@ export function classifyTelemetryError(error, options = {}) {
|
|
|
323
348
|
? { diagnosticReason: remoteError.diagnosticReason } : {})
|
|
324
349
|
};
|
|
325
350
|
}
|
|
351
|
+
function nestedDiagnosticSummary(error) {
|
|
352
|
+
const facts = {};
|
|
353
|
+
const seen = new Set();
|
|
354
|
+
for (let depth = 0; error instanceof Error && depth < 10 && !seen.has(error); depth++, error = error.cause) {
|
|
355
|
+
seen.add(error);
|
|
356
|
+
if (!("diagnosticSummary" in error))
|
|
357
|
+
continue;
|
|
358
|
+
const summary = safeFailureSummary(error.diagnosticSummary);
|
|
359
|
+
for (const [key, value] of Object.entries(summary ?? {}))
|
|
360
|
+
if (!(key in facts))
|
|
361
|
+
facts[key] = value;
|
|
362
|
+
}
|
|
363
|
+
return facts;
|
|
364
|
+
}
|
|
365
|
+
function httpErrorStatus(error) {
|
|
366
|
+
const seen = new Set();
|
|
367
|
+
for (let depth = 0; error instanceof Error && depth < 10 && !seen.has(error); depth++, error = error.cause) {
|
|
368
|
+
seen.add(error);
|
|
369
|
+
if ("status" in error && typeof error.status === "number" && Number.isInteger(error.status) && error.status >= 100 && error.status <= 599)
|
|
370
|
+
return error.status;
|
|
371
|
+
}
|
|
372
|
+
return undefined;
|
|
373
|
+
}
|
|
326
374
|
function failure(code, message, exitCode, nextSteps, details) {
|
|
327
375
|
return {
|
|
328
376
|
kind: "failure",
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { InputContractError } from "../bootstrap/validators.js";
|
|
2
|
+
import { productText } from "../product/text.js";
|
|
3
|
+
function object(value) {
|
|
4
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
/** The host is CLI metadata. Neither the service nor the shared MCP operation receives it. */
|
|
7
|
+
export function readHostInput(runtime, raw) {
|
|
8
|
+
if (!object(raw))
|
|
9
|
+
return raw;
|
|
10
|
+
const { host_application, ...input } = raw;
|
|
11
|
+
runtime.telemetry.observeHost(host_application);
|
|
12
|
+
return input;
|
|
13
|
+
}
|
|
14
|
+
export function hostSchema(runtime, schema) {
|
|
15
|
+
const description = productText(runtime.product, "填写发起本次 CLI 命令的应用名称,例如 workbuddy、qwenwork 或 trae。应用通过终端执行命令时仍填该应用的名称。用户直接在终端执行时填 terminal。其他应用填写其实际名称。", "Name the application invoking this command, for example workbuddy, qwenwork or trae. When an app uses a terminal, name the app. For direct terminal use, enter terminal. For other apps, enter their actual name.");
|
|
16
|
+
const augment = (source) => ({ ...source,
|
|
17
|
+
properties: { ...(object(source.properties) ? source.properties : {}), host_application: { type: "string", description } },
|
|
18
|
+
required: [...new Set([...(Array.isArray(source.required) ? source.required : []), "host_application"])] });
|
|
19
|
+
const result = augment(schema);
|
|
20
|
+
if (Array.isArray(schema.allOf)) {
|
|
21
|
+
return { ...result, allOf: schema.allOf.map(branch => object(branch) && object(branch.then) ? { ...branch, then: augment(branch.then) } : branch) };
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
export function editorActions(raw) {
|
|
26
|
+
if (!object(raw) || !Array.isArray(raw.actions))
|
|
27
|
+
throw new InputContractError([
|
|
28
|
+
{ field: "/actions", rule: "type", message: "expected an array of editor actions" }
|
|
29
|
+
]);
|
|
30
|
+
const extra = Object.keys(raw).find(key => key !== "actions");
|
|
31
|
+
if (extra)
|
|
32
|
+
throw new InputContractError([{ field: "/" + extra, rule: "additionalProperties", message: "editor action fields belong inside actions" }]);
|
|
33
|
+
return raw.actions;
|
|
34
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { hostSchema } from "./host-input.js";
|
|
1
2
|
import { jsonOutput, bindAction } from "./action-binding.js";
|
|
2
3
|
import { CliUsageError } from "./errors.js";
|
|
3
4
|
import { productText as text } from "../product/text.js";
|
|
@@ -41,8 +42,8 @@ export function registerModelCommands(program, runtime) {
|
|
|
41
42
|
text(runtime.product, "只读查询当前身份可用的 Model,输出 JSON;不提交创作。参数、费用和预估耗时来自实时目录。", "Reads a Model available to the current identity as JSON without submitting creation. Parameters, cost and estimated time come from the live catalog."),
|
|
42
43
|
text(runtime.product, "inputSchema 是选定 Tool + Model 的完整 JSON Schema,包含嵌套对象、数组及约束。同一 Model 用于多个 Tool 时请加 --tool;优先按 inputSchema 构造 Tool 输入。", "inputSchema is the complete JSON Schema for the selected Tool + Model, including nested objects, arrays and constraints. Use --tool when a Model supports multiple Tools; construct Tool input from inputSchema."),
|
|
43
44
|
text(runtime.product, "parameters 是结构化元数据,不是 JSON Schema:遵守 required/type、minimum/maximum/step,SELECT 使用 options[].value 而非 label。", "parameters is structured metadata, not JSON Schema: follow required/type, minimum/maximum/step, and use SELECT options[].value rather than label."),
|
|
44
|
-
text(runtime.product, "
|
|
45
|
-
text(runtime.product, "usageDescription 说明跨字段组合规则。tool call <tool> --schema
|
|
45
|
+
text(runtime.product, "required 和 default 说明模型的输入要求和服务默认值。用户未指定有默认值的参数时可以省略;显式值原样发送。model 放在输入顶层。", "required and default describe the model input and service defaults. Omit a defaulted parameter the user did not specify. Explicit values are forwarded. Put model at the top level."),
|
|
46
|
+
text(runtime.product, "usageDescription 说明跨字段组合规则。tool call <tool> --schema 按 model 展示字段、选项和范围;step 及跨字段规则见本 Model 元数据。Agent 只传显式生成约束,不照搬 Tool 的完整必填参数。", "usageDescription explains cross-field combinations. tool call <tool> --schema describes fields, options and ranges per model; follow this Model's metadata for step and cross-field rules. For Agent, pass explicit generation constraints rather than copying every Tool-required parameter."),
|
|
46
47
|
""
|
|
47
48
|
].join("\n"));
|
|
48
49
|
jsonOutput(get);
|
|
@@ -67,7 +68,7 @@ export function registerModelCommands(program, runtime) {
|
|
|
67
68
|
});
|
|
68
69
|
await runtime.telemetry.stage("output", async () => {
|
|
69
70
|
runtime.validators.modelGetOutput(result);
|
|
70
|
-
runtime.io.writeOut(`${JSON.stringify(result)}\n`);
|
|
71
|
+
runtime.io.writeOut(`${JSON.stringify(result.inputSchema ? { ...result, inputSchema: hostSchema(runtime, result.inputSchema) } : result)}\n`);
|
|
71
72
|
});
|
|
72
73
|
}, {
|
|
73
74
|
operation: "model.get"
|
|
@@ -76,7 +76,7 @@ export function observedErrorCategory(e) {
|
|
|
76
76
|
return "unsupported";
|
|
77
77
|
if (e.code === "SAVE_FAILED")
|
|
78
78
|
return "save";
|
|
79
|
-
if (e.code
|
|
79
|
+
if (["LOCAL_STATE_ERROR", "AUTH_STATE_UNAVAILABLE"].includes(e.code))
|
|
80
80
|
return "local";
|
|
81
81
|
if (e.code === "UPDATE_FAILED" && e.diagnosticReason === "UPDATE_MANAGED_BY_HOST")
|
|
82
82
|
return "managed_update";
|
|
@@ -112,6 +112,8 @@ export function observedErrorMessage(category, e) {
|
|
|
112
112
|
return text("素材下载未完成。", "The asset download did not complete.");
|
|
113
113
|
if (category === "local" && e.errorType === "LocalFileError")
|
|
114
114
|
return text("无法读取或保存所需文件。", "A required file could not be read or saved.");
|
|
115
|
+
if (category === "local" && e.code === "AUTH_STATE_UNAVAILABLE")
|
|
116
|
+
return text("无法读取或保存本地登录信息。", "Local sign-in information could not be read or saved.");
|
|
115
117
|
if (category === "request" && e.operation === "task.get")
|
|
116
118
|
return text("本次未能读取任务结果。", "The task result could not be retrieved.");
|
|
117
119
|
return text(messages[category][0], messages[category][1]);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { hostSchema, readHostInput } from "./host-input.js";
|
|
1
2
|
import { jsonOutput, bindAction, bindPreparedAction } from "./action-binding.js";
|
|
2
3
|
import { CliUsageError } from "./errors.js";
|
|
3
4
|
import { productText as text } from "../product/text.js";
|
|
@@ -56,7 +57,7 @@ export function registerToolCommands(program, runtime) {
|
|
|
56
57
|
if (options.schema === true) {
|
|
57
58
|
return { handled: false, input: { mode: "schema", name } };
|
|
58
59
|
}
|
|
59
|
-
const argumentsInput = await runtime.jsonInput.read(options.input, signal);
|
|
60
|
+
const argumentsInput = readHostInput(runtime, await runtime.jsonInput.read(options.input, signal));
|
|
60
61
|
const input = { name, arguments: argumentsInput };
|
|
61
62
|
runtime.validators.toolCallInput(input);
|
|
62
63
|
return { handled: false, input: { mode: "call", input, async: options.async === true } };
|
|
@@ -73,14 +74,15 @@ export function registerToolCommands(program, runtime) {
|
|
|
73
74
|
});
|
|
74
75
|
runtime.telemetry.annotate({ tool_name: prepared.name });
|
|
75
76
|
await runtime.telemetry.stage("output", async () => {
|
|
76
|
-
runtime.io.writeOut(`${JSON.stringify(schema)}\n`);
|
|
77
|
+
runtime.io.writeOut(`${JSON.stringify(hostSchema(runtime, { ...schema }))}\n`);
|
|
77
78
|
});
|
|
78
79
|
return;
|
|
79
80
|
}
|
|
81
|
+
const { prompt, model } = prepared.input.arguments;
|
|
80
82
|
const task = {
|
|
81
83
|
state: context.state,
|
|
82
84
|
operation: "tool.call",
|
|
83
|
-
label: `${prepared.input.name}: ${
|
|
85
|
+
label: `${prepared.input.name}: ${typeof prompt === "string" ? prompt : typeof model === "string" ? model : ""}`
|
|
84
86
|
};
|
|
85
87
|
if (prepared.async) {
|
|
86
88
|
const result = await runtime.startBackgroundTask({ ...task, input: prepared.input }, signal);
|
|
@@ -90,12 +92,8 @@ export function registerToolCommands(program, runtime) {
|
|
|
90
92
|
});
|
|
91
93
|
return;
|
|
92
94
|
}
|
|
93
|
-
const run =
|
|
94
|
-
|
|
95
|
-
...(observe ? { observe } : {}) });
|
|
96
|
-
runtime.validators.toolCallOutput(result);
|
|
97
|
-
return result;
|
|
98
|
-
};
|
|
95
|
+
const run = (observe) => runtime.tool.call({ input: prepared.input, access, signal,
|
|
96
|
+
...(observe ? { observe } : {}) });
|
|
99
97
|
const result = await runtime.tasks.track({ ...task, run });
|
|
100
98
|
await runtime.telemetry.stage("output", async () => {
|
|
101
99
|
runtime.io.writeOut(`${JSON.stringify(result)}\n`);
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { contractSchema } from "./schema.js";
|
|
2
|
+
// Media alone is a prompt. The service has one scene/parameter map and rewrites a
|
|
3
|
+
// question reply into a function response, discarding any accompanying prompt.
|
|
4
|
+
export const agentInputSchema = contractSchema("agent.send", "input");
|
|
5
|
+
const definitions = agentInputSchema.$defs;
|
|
6
|
+
delete definitions.FirstFramePart;
|
|
7
|
+
delete definitions.LastFramePart;
|
|
8
|
+
const generation = definitions.GenerationConstraintsPart.properties.data;
|
|
9
|
+
const model = generation.properties.model;
|
|
10
|
+
if (model.description)
|
|
11
|
+
model.description = "可选创作模型标识;已知编辑模型别名会映射到服务端 code,其余标识原样发送。";
|
|
12
|
+
delete generation.properties.arguments.minProperties;
|
|
13
|
+
const question = { $ref: "#/$defs/QuestionAnswerPart" };
|
|
14
|
+
definitions.UserMessage.allOf = [
|
|
15
|
+
...["GenerationConstraintsPart", "QuestionAnswerPart"].map(part => ({
|
|
16
|
+
properties: { parts: { type: "array", contains: { $ref: "#/$defs/" + part }, minContains: 0, maxContains: 1 } }
|
|
17
|
+
})),
|
|
18
|
+
{ if: { properties: { parts: { type: "array", contains: question } } },
|
|
19
|
+
then: { required: ["contextId"], properties: { contextId: { type: "string" }, parts: { type: "array", maxItems: 1 } } } }
|
|
20
|
+
];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { withResponseDiagnostics } from "../../platform/signed-http-transport.js";
|
|
1
2
|
import { buildCreativeRequest, creativeContextId, creativeTurnMessages, normalizeCreativeMessages, restoreCreativeResourceUrls } from "./creative-protocol.js";
|
|
2
3
|
import { parseCreativeStream } from "./creative-stream.js";
|
|
3
4
|
export function createCreativeAgentAdapter(dependencies) {
|
|
@@ -10,30 +11,55 @@ export function createCreativeAgentAdapter(dependencies) {
|
|
|
10
11
|
localMessageId: dependencies.idFactory()
|
|
11
12
|
}
|
|
12
13
|
: { localMessageId: dependencies.idFactory() };
|
|
14
|
+
const correlation = {
|
|
15
|
+
localMessageId: ids.localMessageId,
|
|
16
|
+
...("localThreadId" in ids ? { localThreadId: ids.localThreadId } : {}),
|
|
17
|
+
...(message.contextId ? { agentContextId: message.contextId } : {})
|
|
18
|
+
};
|
|
19
|
+
dependencies.telemetry.annotate({ diagnostic_summary: correlation });
|
|
13
20
|
await observe?.({ localMessageId: ids.localMessageId, ...(message.contextId ? { contextId: message.contextId } : {}) });
|
|
14
|
-
const { streamed, contextId } = await dependencies.telemetry.stage("execute", async () => {
|
|
21
|
+
const { streamed, contextId } = await dependencies.telemetry.stage("execute", () => withResponseDiagnostics(async (onResponse) => {
|
|
15
22
|
await observe?.({ submissionStarted: true });
|
|
23
|
+
const startedAt = Date.now();
|
|
24
|
+
let httpStatus;
|
|
16
25
|
const stream = await dependencies.transport.postStream({
|
|
17
26
|
path: "/ai-agent/v1/thread/completion",
|
|
18
27
|
...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
|
|
19
28
|
body: buildCreativeRequest(message, ids),
|
|
20
29
|
accept: "text/event-stream",
|
|
30
|
+
onResponse: (status, summary) => { httpStatus = status; onResponse(status, summary); },
|
|
21
31
|
credential: access.credential,
|
|
22
32
|
organizationId: access.organizationId,
|
|
23
33
|
signal
|
|
24
34
|
});
|
|
25
35
|
await observe?.({ accepted: true });
|
|
26
|
-
const streamed = await parseCreativeStream(stream, signal,
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
organizationId: access.organizationId,
|
|
34
|
-
signal
|
|
36
|
+
const streamed = await parseCreativeStream(stream, signal, async (contextId) => {
|
|
37
|
+
correlation.agentContextId = contextId;
|
|
38
|
+
dependencies.telemetry.annotate({ diagnostic_summary: { agentContextId: contextId } });
|
|
39
|
+
await observe?.({ contextId });
|
|
40
|
+
}, {
|
|
41
|
+
startedAt, ...(httpStatus === undefined ? {} : { httpStatus }),
|
|
42
|
+
onDiagnostics: diagnostic_summary => dependencies.telemetry.annotate({ diagnostic_summary })
|
|
35
43
|
});
|
|
36
|
-
const
|
|
44
|
+
const contextId = creativeContextId(streamed);
|
|
45
|
+
dependencies.telemetry.annotate({ diagnostic_summary: { agentContextId: contextId } });
|
|
46
|
+
return { streamed, contextId };
|
|
47
|
+
}, correlation));
|
|
48
|
+
return dependencies.telemetry.stage("result", async () => {
|
|
49
|
+
const output = await withResponseDiagnostics(async (onResponse) => {
|
|
50
|
+
const messages = await dependencies.transport.getJson({
|
|
51
|
+
path: `/ai-agent/v1/thread/${encodeURIComponent(contextId)}/messages`,
|
|
52
|
+
credential: access.credential,
|
|
53
|
+
organizationId: access.organizationId,
|
|
54
|
+
onResponse,
|
|
55
|
+
signal
|
|
56
|
+
});
|
|
57
|
+
let usageModelMissing = false;
|
|
58
|
+
const normalized = normalizeCreativeMessages(restoreCreativeResourceUrls(creativeTurnMessages(messages, ids.localMessageId), streamed), () => { usageModelMissing = true; });
|
|
59
|
+
if (usageModelMissing)
|
|
60
|
+
await observe?.({ agentUsageModelMissing: true });
|
|
61
|
+
return normalized;
|
|
62
|
+
}, correlation);
|
|
37
63
|
return dependencies.resourceAuthorizer
|
|
38
64
|
? dependencies.resourceAuthorizer.authorize(output, access, signal)
|
|
39
65
|
: output;
|
|
@@ -32,7 +32,8 @@ export function buildCreativeRequest(message, ids) {
|
|
|
32
32
|
type: "media",
|
|
33
33
|
url: part.asset.url,
|
|
34
34
|
name: part.asset.filename,
|
|
35
|
-
mime: part.asset.mediaType
|
|
35
|
+
mime: part.asset.mediaType,
|
|
36
|
+
extra: { role: part.role }
|
|
36
37
|
});
|
|
37
38
|
attachments.push({
|
|
38
39
|
uri: part.asset.url,
|
|
@@ -144,27 +145,24 @@ export function creativeTurnMessages(value, localMessageId) {
|
|
|
144
145
|
if (!Array.isArray(value)) {
|
|
145
146
|
return fail("AGENT_MESSAGES_NOT_ARRAY", { valueType: value === null ? "null" : typeof value });
|
|
146
147
|
}
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
}
|
|
151
|
-
const messages = value;
|
|
152
|
-
const start = messages.findIndex((message) => {
|
|
153
|
-
if (message.local_message_id !== localMessageId)
|
|
154
|
-
return false;
|
|
155
|
-
return message.role === "user" || contentOf(message)?.type === "function_response";
|
|
156
|
-
});
|
|
148
|
+
const messages = value.map(message => record(message));
|
|
149
|
+
const start = messages.findIndex(message => message?.local_message_id === localMessageId
|
|
150
|
+
&& (message.role === "user" || contentOf(message)?.type === "function_response"));
|
|
157
151
|
if (start < 0) {
|
|
158
|
-
const matchingLocalMessageCount = messages.filter((message) => message
|
|
152
|
+
const matchingLocalMessageCount = messages.filter((message) => message?.local_message_id === localMessageId).length;
|
|
159
153
|
return fail(matchingLocalMessageCount > 0 ? "AGENT_TURN_ANCHOR_INVALID" : "AGENT_TURN_ANCHOR_MISSING", {
|
|
160
154
|
messageCount: messages.length, matchingLocalMessageCount
|
|
161
155
|
});
|
|
162
156
|
}
|
|
163
|
-
const nextInput = messages.findIndex((message, index) => index > start
|
|
157
|
+
const nextInput = messages.findIndex((message, index) => index > start && message !== undefined
|
|
164
158
|
&& typeof message.local_message_id === "string" && message.local_message_id !== ""
|
|
165
159
|
&& message.local_message_id !== localMessageId
|
|
166
160
|
&& (message.role === "user" || contentOf(message)?.type === "function_response"));
|
|
167
|
-
|
|
161
|
+
const turn = messages.slice(start, nextInput < 0 ? undefined : nextInput);
|
|
162
|
+
const valid = turn.filter(message => message !== undefined);
|
|
163
|
+
if (valid.length !== turn.length)
|
|
164
|
+
return fail("AGENT_MESSAGE_INVALID", { messageCount: turn.length, invalidMessageCount: turn.length - valid.length });
|
|
165
|
+
return valid;
|
|
168
166
|
}
|
|
169
167
|
function contentOf(message) {
|
|
170
168
|
return record(message.content);
|
|
@@ -395,7 +393,7 @@ function dedupeParts(parts) {
|
|
|
395
393
|
return true;
|
|
396
394
|
});
|
|
397
395
|
}
|
|
398
|
-
export function normalizeCreativeMessages(messages) {
|
|
396
|
+
export function normalizeCreativeMessages(messages, onUsageModelMissing) {
|
|
399
397
|
const contextId = creativeContextId(messages);
|
|
400
398
|
const latest = new Map();
|
|
401
399
|
const anonymous = [];
|
|
@@ -440,6 +438,7 @@ export function normalizeCreativeMessages(messages) {
|
|
|
440
438
|
if (publicParts.length === 0)
|
|
441
439
|
return fail("AGENT_RESULT_EMPTY", { messageCount: normalized.length, publicPartCount: 0 });
|
|
442
440
|
const usageItems = [];
|
|
441
|
+
let totalCost = 0;
|
|
443
442
|
for (const message of normalized) {
|
|
444
443
|
if (contentOf(message)?.type !== "function_response")
|
|
445
444
|
continue;
|
|
@@ -449,11 +448,14 @@ export function normalizeCreativeMessages(messages) {
|
|
|
449
448
|
continue;
|
|
450
449
|
if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
|
|
451
450
|
return fail();
|
|
451
|
+
totalCost += amount;
|
|
452
|
+
const model = nonEmptyString(extra?.scene_code);
|
|
453
|
+
if (model === undefined) {
|
|
454
|
+
onUsageModelMissing?.();
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
452
457
|
if (amount === 0)
|
|
453
458
|
continue;
|
|
454
|
-
const model = nonEmptyString(extra?.scene_code);
|
|
455
|
-
if (model === undefined)
|
|
456
|
-
return fail("AGENT_USAGE_MODEL_MISSING", { messageCount: normalized.length, publicPartCount: publicParts.length });
|
|
457
459
|
usageItems.push({ model, cost: { unit: "gaodou", amount } });
|
|
458
460
|
}
|
|
459
461
|
return {
|
|
@@ -465,7 +467,7 @@ export function normalizeCreativeMessages(messages) {
|
|
|
465
467
|
usage: {
|
|
466
468
|
cost: {
|
|
467
469
|
unit: "gaodou",
|
|
468
|
-
amount:
|
|
470
|
+
amount: totalCost
|
|
469
471
|
},
|
|
470
472
|
items: usageItems
|
|
471
473
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
|
+
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
2
3
|
function isMessage(value) {
|
|
3
4
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4
5
|
}
|
|
@@ -87,12 +88,24 @@ function parseSequence(payload) {
|
|
|
87
88
|
}
|
|
88
89
|
return values;
|
|
89
90
|
}
|
|
90
|
-
export async function parseCreativeStream(stream, signal, onContextId) {
|
|
91
|
+
export async function parseCreativeStream(stream, signal, onContextId, diagnostics = {}) {
|
|
91
92
|
signal.throwIfAborted();
|
|
92
93
|
const reader = stream.getReader();
|
|
93
94
|
const decoder = new TextDecoder();
|
|
94
95
|
let raw = "";
|
|
95
96
|
let contextReported = false;
|
|
97
|
+
const now = diagnostics.now ?? Date.now;
|
|
98
|
+
const startedAt = diagnostics.startedAt ?? now();
|
|
99
|
+
let receivedBytes = 0;
|
|
100
|
+
let firstByteMs;
|
|
101
|
+
let terminalReason = "canceled";
|
|
102
|
+
const summary = () => ({
|
|
103
|
+
streamHadBytes: receivedBytes > 0,
|
|
104
|
+
streamReceivedBytes: receivedBytes,
|
|
105
|
+
...(firstByteMs === undefined ? {} : { streamFirstByteMs: firstByteMs }),
|
|
106
|
+
streamTerminalReason: terminalReason,
|
|
107
|
+
abortSource: signal.aborted ? "caller" : "none"
|
|
108
|
+
});
|
|
96
109
|
const onAbort = () => {
|
|
97
110
|
void reader.cancel(signal.reason).catch(() => undefined);
|
|
98
111
|
};
|
|
@@ -100,10 +113,25 @@ export async function parseCreativeStream(stream, signal, onContextId) {
|
|
|
100
113
|
try {
|
|
101
114
|
while (true) {
|
|
102
115
|
signal.throwIfAborted();
|
|
103
|
-
|
|
116
|
+
let result;
|
|
117
|
+
try {
|
|
118
|
+
result = await reader.read();
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (signal.aborted)
|
|
122
|
+
throw signal.reason;
|
|
123
|
+
terminalReason = "error";
|
|
124
|
+
throw new RemoteRequestError(diagnostics.httpStatus, false, {}, error, "AGENT_STREAM_READ_FAILED", summary());
|
|
125
|
+
}
|
|
126
|
+
if (!result.done && result.value.byteLength) {
|
|
127
|
+
receivedBytes = Math.min(Number.MAX_SAFE_INTEGER, receivedBytes + result.value.byteLength);
|
|
128
|
+
firstByteMs ??= Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, now() - startedAt));
|
|
129
|
+
}
|
|
104
130
|
signal.throwIfAborted();
|
|
105
|
-
if (result.done)
|
|
131
|
+
if (result.done) {
|
|
132
|
+
terminalReason = "eof";
|
|
106
133
|
break;
|
|
134
|
+
}
|
|
107
135
|
raw += decoder.decode(result.value, { stream: true });
|
|
108
136
|
if (onContextId && !contextReported) {
|
|
109
137
|
const contextId = messagesFrom(raw).find(message => typeof message.thread_id === "string" && message.thread_id)?.thread_id;
|
|
@@ -115,16 +143,36 @@ export async function parseCreativeStream(stream, signal, onContextId) {
|
|
|
115
143
|
}
|
|
116
144
|
raw += decoder.decode();
|
|
117
145
|
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
try {
|
|
148
|
+
if (error instanceof Error && Object.isExtensible(error)) {
|
|
149
|
+
const previous = error.diagnosticSummary;
|
|
150
|
+
Object.assign(error, { diagnosticSummary: {
|
|
151
|
+
...(previous && typeof previous === "object" && !Array.isArray(previous) ? previous : {}), ...summary()
|
|
152
|
+
} });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
catch { /* Diagnostic attachment cannot replace the original failure. */ }
|
|
156
|
+
if (terminalReason === "canceled")
|
|
157
|
+
void reader.cancel(error).catch(() => undefined);
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
118
160
|
finally {
|
|
119
161
|
signal.removeEventListener("abort", onAbort);
|
|
120
162
|
reader.releaseLock();
|
|
163
|
+
try {
|
|
164
|
+
diagnostics.onDiagnostics?.(summary());
|
|
165
|
+
}
|
|
166
|
+
catch { /* Diagnostics cannot replace a result or primary error. */ }
|
|
121
167
|
}
|
|
122
168
|
const messages = messagesFrom(raw);
|
|
123
169
|
if (messages.length === 0) {
|
|
124
170
|
const payloads = extractPayloads(raw);
|
|
125
|
-
throw new RemoteProtocolError({ remoteBody: JSON.stringify({ messageCount: 0, contextIdPresent: false, systemErrorCount: 0,
|
|
126
|
-
|
|
127
|
-
streamJsonValueCount: Math.min(payloads.reduce((count, payload) => count + parseSequence(payload).length, 0), 100_000) }) }, undefined, "AGENT_CONTEXT_ID_MISSING")
|
|
171
|
+
throw Object.assign(new RemoteProtocolError({ remoteBody: JSON.stringify({ messageCount: 0, contextIdPresent: false, systemErrorCount: 0,
|
|
172
|
+
...summary(), streamPayloadCount: Math.min(payloads.length, 100_000),
|
|
173
|
+
streamJsonValueCount: Math.min(payloads.reduce((count, payload) => count + parseSequence(payload).length, 0), 100_000) }) }, undefined, "AGENT_CONTEXT_ID_MISSING"), {
|
|
174
|
+
...(diagnostics.httpStatus === undefined ? {} : { status: diagnostics.httpStatus }), diagnosticSummary: summary()
|
|
175
|
+
});
|
|
128
176
|
}
|
|
129
177
|
return messages;
|
|
130
178
|
}
|
|
@@ -20,7 +20,9 @@ export async function readAgentResult(transport, request) {
|
|
|
20
20
|
if (!turn.some(m => m.role !== "user" && m.content))
|
|
21
21
|
return { connectionState: connection.state };
|
|
22
22
|
try {
|
|
23
|
-
|
|
23
|
+
let usageModelMissing = false;
|
|
24
|
+
const partialResult = normalizeCreativeMessages(turn, () => { usageModelMissing = true; });
|
|
25
|
+
return { connectionState: connection.state, partialResult, ...(usageModelMissing ? { usageModelMissing: true } : {}) };
|
|
24
26
|
}
|
|
25
27
|
catch (error) {
|
|
26
28
|
if (error instanceof RemoteProtocolError)
|
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { modelControlArgumentsAreValid } from "../tool/dynamic-schema.js";
|
|
3
|
-
import { canvasRemoteControlArguments } from "../tool/canvas-models.js";
|
|
1
|
+
import { canvasModelBindings, canvasRemoteControlArguments } from "../tool/canvas-models.js";
|
|
4
2
|
import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
|
|
5
3
|
export class AgentInputError extends Error {
|
|
6
4
|
reason;
|
|
@@ -51,35 +49,12 @@ export function createAgentUseCases(dependencies) {
|
|
|
51
49
|
}
|
|
52
50
|
}
|
|
53
51
|
if (generation?.model !== undefined) {
|
|
54
|
-
const requested = generation;
|
|
55
52
|
dependencies.telemetry.annotate({ model_id: generation.model });
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
dependencies.warn(warning);
|
|
62
|
-
await dependencies.telemetry.stage("input", async () => {
|
|
63
|
-
let model;
|
|
64
|
-
try {
|
|
65
|
-
model = findModel(catalog, requested.model);
|
|
66
|
-
}
|
|
67
|
-
catch (error) {
|
|
68
|
-
if (error instanceof ToolInputError)
|
|
69
|
-
throw new AgentInputError(error.reason, "/generation/model", error);
|
|
70
|
-
throw error;
|
|
71
|
-
}
|
|
72
|
-
if (!modelControlArgumentsAreValid(model, requested.arguments ?? {}))
|
|
73
|
-
throw new AgentInputError("model_parameters", "/generation/arguments");
|
|
74
|
-
if (model.execution?.kind === "canvas") {
|
|
75
|
-
generation = {
|
|
76
|
-
model: model.execution.code,
|
|
77
|
-
...(requested.arguments === undefined ? {} : {
|
|
78
|
-
arguments: canvasRemoteControlArguments(model.model, requested.arguments)
|
|
79
|
-
})
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
});
|
|
53
|
+
const binding = canvasModelBindings.find(([, alias]) => alias === generation?.model);
|
|
54
|
+
if (binding)
|
|
55
|
+
generation = { model: binding[2], ...(generation.arguments === undefined ? {} : {
|
|
56
|
+
arguments: canvasRemoteControlArguments(binding[1], generation.arguments)
|
|
57
|
+
}) };
|
|
83
58
|
}
|
|
84
59
|
const prepare = async () => {
|
|
85
60
|
for (const part of input.message.parts) {
|