@insmind/cli 2.0.0 → 2.1.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/README.md +5 -0
- package/contracts/operations/agent.send/input.schema.json +1 -77
- package/contracts/operations/credits.get/input.schema.json +8 -0
- package/contracts/operations/credits.get/output.schema.json +92 -0
- package/contracts/operations/credits.usage.get/input.schema.json +17 -0
- package/contracts/operations/credits.usage.get/output.schema.json +46 -0
- package/contracts/operations/credits.usage.list/input.schema.json +27 -0
- package/contracts/operations/credits.usage.list/output.schema.json +135 -0
- package/contracts/operations/dam.folder.list/input.schema.json +0 -1
- package/contracts/operations/dam.folder.list/output.schema.json +1 -2
- package/contracts/operations/dam.list/input.schema.json +3 -6
- package/contracts/operations/dam.list/output.schema.json +1 -2
- package/contracts/operations/dam.search/input.schema.json +3 -6
- package/contracts/operations/dam.search/output.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
- package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
- package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
- package/dist/bin/postinstall.js +22 -6
- package/dist/bin/task-worker.js +2 -2
- package/dist/src/bootstrap/create-cli.js +31 -15
- package/dist/src/bootstrap/create-runtime.js +103 -30
- package/dist/src/bootstrap/run-task-worker.js +6 -2
- package/dist/src/bootstrap/validators.js +4 -1
- package/dist/src/cli/action-binding.js +17 -50
- package/dist/src/cli/agent-commands.js +11 -11
- package/dist/src/cli/auth-commands.js +2 -1
- package/dist/src/cli/creation-help.js +9 -0
- package/dist/src/cli/credits-command.js +127 -16
- package/dist/src/cli/dam-commands.js +10 -14
- package/dist/src/cli/editor-commands.js +7 -5
- package/dist/src/cli/errors.js +81 -22
- package/dist/src/cli/host-input.js +64 -5
- package/dist/src/cli/model-commands.js +9 -3
- package/dist/src/cli/observed-errors.js +7 -3
- package/dist/src/cli/org-commands.js +3 -1
- package/dist/src/cli/presenter.js +4 -0
- package/dist/src/cli/task-commands.js +6 -2
- package/dist/src/cli/tool-commands.js +12 -11
- package/dist/src/cli/update-command.js +24 -1
- package/dist/src/features/agent/creative-agent-adapter.js +6 -2
- package/dist/src/features/agent/creative-protocol.js +8 -29
- package/dist/src/features/agent/resource-authorizer.js +25 -17
- package/dist/src/features/agent/result-reader.js +31 -14
- package/dist/src/features/agent/use-cases.js +6 -31
- package/dist/src/features/credits/amount.js +51 -0
- package/dist/src/features/credits/response.js +11 -0
- package/dist/src/features/credits/use-cases.js +200 -30
- package/dist/src/features/dam/asset-projection.js +3 -6
- package/dist/src/features/dam/dam-api-adapter.js +30 -15
- package/dist/src/features/dam/repository-catalog.js +30 -21
- package/dist/src/features/dam/use-cases.js +12 -7
- package/dist/src/features/editor/bridge-client.js +0 -2
- package/dist/src/features/editor/public-url.js +1 -36
- package/dist/src/features/editor/session.js +3 -2
- package/dist/src/features/editor/use-cases.js +27 -2
- package/dist/src/features/org/org-service.js +10 -1
- package/dist/src/features/org/use-cases.js +18 -4
- package/dist/src/features/task/process-owner.js +54 -0
- package/dist/src/features/task/store.js +37 -10
- package/dist/src/features/task/task-background.js +5 -2
- package/dist/src/features/task/use-cases.js +184 -84
- package/dist/src/features/tool/argument-paths.js +14 -0
- package/dist/src/features/tool/canvas-copy.js +28 -15
- package/dist/src/features/tool/canvas-matting.js +123 -0
- package/dist/src/features/tool/canvas-media.js +100 -52
- package/dist/src/features/tool/canvas-models.js +66 -33
- package/dist/src/features/tool/canvas-pricing.js +12 -0
- package/dist/src/features/tool/canvas-recovery.js +13 -30
- package/dist/src/features/tool/canvas-results.js +79 -87
- package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
- package/dist/src/features/tool/canvas-video.js +44 -37
- package/dist/src/features/tool/dynamic-schema.js +39 -40
- package/dist/src/features/tool/ffprobe-executable.js +21 -0
- package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
- package/dist/src/features/tool/resource-authorizer.js +11 -3
- package/dist/src/features/tool/tool-api-adapter.js +73 -82
- package/dist/src/features/tool/tool-errors.js +25 -0
- package/dist/src/features/tool/tool-output.js +15 -0
- package/dist/src/features/tool/use-cases.js +74 -98
- package/dist/src/features/update/check-schema.js +17 -0
- package/dist/src/features/update/host-receipt.js +30 -0
- package/dist/src/features/update/notice-output.js +30 -0
- package/dist/src/features/update/update-lock.js +80 -0
- package/dist/src/features/update/update-notification.js +129 -240
- package/dist/src/features/update/update-service.js +95 -21
- package/dist/src/platform/media-type.js +46 -0
- package/dist/src/platform/public-url.js +35 -0
- package/dist/src/platform/remote-error-evidence.js +33 -6
- package/dist/src/platform/resource-auth-key.js +35 -1
- package/dist/src/platform/safe-upload-file.js +36 -41
- package/dist/src/platform/signature.js +3 -1
- package/dist/src/platform/signed-http-transport.js +14 -6
- package/dist/src/platform/url-safety.js +6 -1
- package/dist/src/platform/webm-header.js +41 -0
- package/dist/src/telemetry/command-route.js +38 -0
- package/dist/src/telemetry/command-routes.json +1 -0
- package/dist/src/telemetry/failure-summary.js +1 -1
- package/dist/src/telemetry/invocation.js +1 -2
- package/dist/src/telemetry/process-errors.js +17 -33
- package/dist/src/telemetry/sanitize.js +19 -4
- package/dist/src/telemetry/sls-sink.js +8 -0
- package/package.json +4 -4
- package/skills/insmind-cli/SKILL.md +19 -5
- package/skills/insmind-cli/references/agent.md +9 -4
- package/skills/insmind-cli/references/creation.md +3 -1
- package/skills/insmind-cli/references/editor.md +7 -5
- package/skills/insmind-cli/references/errors.md +20 -9
- package/skills/insmind-cli/references/matting.md +3 -5
- package/skills/insmind-cli/references/media-tools.md +10 -4
- package/skills/insmind-cli/references/tool.md +9 -15
- package/skills/insmind-cli/references/update.md +2 -0
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
2
|
+
import addFormats, {} from "ajv-formats";
|
|
1
3
|
import { InputContractError } from "../bootstrap/validators.js";
|
|
2
4
|
import { productText } from "../product/text.js";
|
|
3
5
|
function object(value) {
|
|
@@ -11,12 +13,69 @@ export function readHostInput(runtime, raw) {
|
|
|
11
13
|
runtime.telemetry.observeHost(host_application);
|
|
12
14
|
return input;
|
|
13
15
|
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
const examples = new Ajv2020({ strict: false, addUsedSchema: false });
|
|
17
|
+
addFormats(examples);
|
|
18
|
+
function toolExample(runtime, source, properties, required, tool) {
|
|
19
|
+
const sample = { host_application: "terminal" };
|
|
20
|
+
const english = runtime.product.id === "insmind";
|
|
21
|
+
const requests = {
|
|
22
|
+
"image-matting-smart": ["把包单独抠出来,补全被遮住的提手。", "Isolate the bag and restore the hidden part of the handle."],
|
|
23
|
+
"image-edit-smart": ["把杯子改成深绿色。", "Change the cup to dark green."],
|
|
24
|
+
"image-remove-smart": ["把桌上的杂物移走。", "Remove the clutter from the table."],
|
|
25
|
+
"image-enhance-smart": ["修复这张照片中模糊的细节。", "Restore the blurred details in this photo."]
|
|
26
|
+
};
|
|
27
|
+
const model = object(properties.model) ? properties.model.const : undefined;
|
|
28
|
+
const request = typeof model === "string" ? requests[model] : undefined;
|
|
29
|
+
const values = { prompt: request?.[english ? 1 : 0] ?? (english ? "A cat at a rainy bus stop." : "一只在雨里等车的猫。"),
|
|
30
|
+
image: "file:///inputs/source.png", video: "file:///inputs/source.mp4", base_video: "file:///inputs/source.mp4", mask: "file:///inputs/selection.png",
|
|
31
|
+
resolution: tool.startsWith("video.") ? "720p" : "2K", quality: "high", audioEnabled: "false",
|
|
32
|
+
targetLongEdge: 2048, maxLayers: 3, canvas: { width: 1200, height: 800 }, placement: { x: 100, y: 50 },
|
|
33
|
+
replacements: [{ from: "2025", to: "2026" }] };
|
|
34
|
+
for (const key of required) {
|
|
35
|
+
if (typeof key !== "string" || key === "host_application")
|
|
36
|
+
continue;
|
|
37
|
+
const property = properties[key];
|
|
38
|
+
if (!object(property))
|
|
39
|
+
return;
|
|
40
|
+
const value = property.const ?? property.default ?? (Array.isArray(property.enum) ? property.enum[0] : undefined)
|
|
41
|
+
?? values[key] ?? (property.format === "uri" ? "file:///inputs/source.png" : undefined)
|
|
42
|
+
?? (object(property.items) && property.items.format === "uri" ? ["file:///inputs/source.png"] : undefined);
|
|
43
|
+
if (value === undefined)
|
|
44
|
+
return;
|
|
45
|
+
sample[key] = value;
|
|
46
|
+
}
|
|
47
|
+
if (object(properties.prompt) && (request || tool === "image.generate" || tool === "video.generate")) {
|
|
48
|
+
sample.prompt ??= values.prompt;
|
|
49
|
+
}
|
|
50
|
+
// Directory extensions can introduce requirements we cannot illustrate faithfully.
|
|
51
|
+
return examples.validate(source, sample) ? sample : undefined;
|
|
52
|
+
}
|
|
53
|
+
export function hostSchema(runtime, schema, tool) {
|
|
54
|
+
const localMedia = productText(runtime.product, "本地附件用 Path(path).resolve().as_uri() 或 pathToFileURL(path).href 生成标准 file URI,转义中文、空格和 #;已有 HTTP(S) URL 原样使用。", "Generate local file URIs with Path(path).resolve().as_uri() or pathToFileURL(path).href to escape Unicode, spaces and #; preserve existing HTTP(S) URLs.");
|
|
55
|
+
const description = productText(runtime.product, "填写实际发起命令的应用名。例如 Codex Agent 通过 shell 执行时填 codex,WorkBuddy 填 workbuddy,其他应用填自己的名称。示例中的 terminal 仅指用户亲自在终端运行。", "Enter the calling application's name. A Codex agent running a shell command uses codex, WorkBuddy uses workbuddy, and other apps use their own names. The example value terminal is for a person running the command directly.");
|
|
56
|
+
const augment = (source) => {
|
|
57
|
+
const properties = { ...(object(source.properties) ? source.properties : {}), host_application: { type: "string", description } };
|
|
58
|
+
for (const [key, property] of Object.entries(properties)) {
|
|
59
|
+
if (object(property) && (property.format === "uri" || (object(property.items) && property.items.format === "uri"))) {
|
|
60
|
+
properties[key] = { ...property, description: [property.description, localMedia].filter(Boolean).join(" ") };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (object(properties.model) && properties.model.description === "要调用的模型机器标识。" && runtime.product.id === "insmind") {
|
|
64
|
+
properties.model = { ...properties.model, description: "Identifier of the selected model." };
|
|
65
|
+
}
|
|
66
|
+
const required = [...new Set([...(Array.isArray(source.required) ? source.required : []), "host_application"])];
|
|
67
|
+
const result = { ...source, properties, required };
|
|
68
|
+
if (!tool || !object(properties.model) || typeof properties.model.const !== "string")
|
|
69
|
+
return result;
|
|
70
|
+
const example = toolExample(runtime, result, properties, required, tool);
|
|
71
|
+
return { ...result,
|
|
72
|
+
...(example ? { examples: [example] } : {}) };
|
|
73
|
+
};
|
|
19
74
|
const result = augment(schema);
|
|
75
|
+
if (tool) {
|
|
76
|
+
const ratio = tool === "image.generate" && productText(runtime.product, "ratio 表示请求的目标宽高比。", "ratio is the requested aspect ratio.");
|
|
77
|
+
result.description = [result.description, localMedia, ratio].filter(Boolean).join(" ");
|
|
78
|
+
}
|
|
20
79
|
if (Array.isArray(schema.allOf)) {
|
|
21
80
|
return { ...result, allOf: schema.allOf.map(branch => object(branch) && object(branch.then) ? { ...branch, then: augment(branch.then) } : branch) };
|
|
22
81
|
}
|
|
@@ -10,6 +10,7 @@ export function registerModelCommands(program, runtime) {
|
|
|
10
10
|
.description(text(runtime.product, "列出当前可用的创作与媒体处理模型(不含独立风格)", "List available creation and media-processing models (excluding standalone styles)"))
|
|
11
11
|
.option("--tool <tool>", text(runtime.product, "按工具筛选", "filter by tool"))
|
|
12
12
|
.allowExcessArguments(false);
|
|
13
|
+
list.addHelpText("after", text(runtime.product, "\n列表只提供模型摘要。选择后用 model get <model> --tool <tool> 读取完整输入、用途与保留范围,再判断是否符合需求;不能仅凭摘要推断整个工具不支持。\n", "\nThis list is a summary. Read model get <model> --tool <tool> for full inputs, purpose and preservation scope before deciding whether it meets the request; the summary alone cannot establish that the whole Tool is unsupported.\n"));
|
|
13
14
|
jsonOutput(list);
|
|
14
15
|
bindAction(list, "organization", async (context, signal) => {
|
|
15
16
|
const selectedTool = list.opts().tool;
|
|
@@ -40,10 +41,13 @@ export function registerModelCommands(program, runtime) {
|
|
|
40
41
|
get.addHelpText("after", [
|
|
41
42
|
"",
|
|
42
43
|
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."),
|
|
44
|
+
text(runtime.product, "cost.minimum/maximum 为目录估价,即使相等也不表示已扣费。计量公式见 usageDescription,未知价格保持未知;实际消费和归还从 credits usage 查询。", "cost.minimum/maximum are catalog estimates, even when equal, and do not indicate a charge. Read usageDescription for metering formulas and leave unknown prices unknown. Query credits usage for actual consumption and restoration."),
|
|
43
45
|
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."),
|
|
44
46
|
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."),
|
|
45
|
-
text(runtime.product, "required
|
|
47
|
+
text(runtime.product, "按 inputSchema.required 提供必填字段。default 是模型声明的默认值;有默认值的字段也可能需要显式提供。model 放在输入顶层。", "Follow inputSchema.required even when a default is documented. Provide model at the top level."),
|
|
48
|
+
text(runtime.product, "required 只属于当前模型,不代表同一工具的其他模型也需要这些字段。前置素材无法准备时,先查看同工具其他模型的要求;遵守用户指定模型及保真等约束,不将单个模型或本地环境的限制说成整个工具不支持。", "required belongs to this model, not every model of the Tool. If a prerequisite cannot be prepared, inspect other models of the same Tool while honoring explicit model and fidelity constraints. A model-specific or local-environment limitation does not establish that the whole Tool is unavailable."),
|
|
46
49
|
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."),
|
|
50
|
+
text(runtime.product, "公开 Schema 指导构参;CLI 仅检查自身读取、转换、授权和交付所必需的条件。服务端决定业务参数是否可接受,返回明确错误时按实际原因处理,不能静默替换用户值。", "The public Schema guides input construction. The CLI checks only what it needs for reading, conversion, authorization and delivery. The service decides business validity; handle its stated error without silently replacing user values."),
|
|
47
51
|
""
|
|
48
52
|
].join("\n"));
|
|
49
53
|
jsonOutput(get);
|
|
@@ -67,8 +71,10 @@ export function registerModelCommands(program, runtime) {
|
|
|
67
71
|
signal
|
|
68
72
|
});
|
|
69
73
|
await runtime.telemetry.stage("output", async () => {
|
|
70
|
-
runtime.
|
|
71
|
-
|
|
74
|
+
const projected = result.inputSchema ? hostSchema(runtime, result.inputSchema, result.tool) : undefined;
|
|
75
|
+
const output = { ...result, ...(projected ? { inputSchema: projected } : {}) };
|
|
76
|
+
runtime.validators.modelGetOutput(output);
|
|
77
|
+
runtime.io.writeOut(JSON.stringify(output) + "\n");
|
|
72
78
|
});
|
|
73
79
|
}, {
|
|
74
80
|
operation: "model.get"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const messages = {
|
|
2
2
|
credits: ["当前可用额度不足,本次生成未能完成。", "There are not enough available credits to complete this creation."],
|
|
3
|
-
review: ["
|
|
3
|
+
review: ["本次创作内容未通过审核,没有可交付结果。", "This creation did not pass content review and has no deliverable result."],
|
|
4
4
|
session_busy: ["这个会话正在使用中,请稍后再试。", "This conversation is in use. Please try again later."],
|
|
5
5
|
service_busy: ["当前服务繁忙,请稍后再试。", "The service is busy. Please try again later."],
|
|
6
6
|
timeout: ["本次操作等待超时。", "This operation timed out."],
|
|
@@ -42,7 +42,7 @@ export function observedErrorCategory(e) {
|
|
|
42
42
|
if (gd && e.operation === "agent.send" && e.httpStatus === 429)
|
|
43
43
|
return "service_busy";
|
|
44
44
|
if (gd && e.operation === "auth.login" && e.httpStatus === 504 || e.code === "EDITOR_RPC_TIMEOUT"
|
|
45
|
-
|| ins && e.operation === "tool.call" && e.remoteCode === "-31994" && e.diagnosticReason === "IMAGE_AUDIT_TIMEOUT")
|
|
45
|
+
|| (gd || ins) && e.operation === "tool.call" && e.remoteCode === "-31994" && e.diagnosticReason === "IMAGE_AUDIT_TIMEOUT")
|
|
46
46
|
return "timeout";
|
|
47
47
|
if (ins && e.operation === "tool.call" && e.remoteCode === "-31993")
|
|
48
48
|
return "settings";
|
|
@@ -100,8 +100,12 @@ export function observedErrorCategory(e) {
|
|
|
100
100
|
}
|
|
101
101
|
export function observedErrorMessage(category, e) {
|
|
102
102
|
const text = (zh, en) => e.product === "insmind" ? en : zh;
|
|
103
|
+
if (e.diagnosticReason === "DAM_DEFAULT_REPOSITORY_UNKNOWN")
|
|
104
|
+
return text("未能确认默认素材库。请从 dam repository list 的可用结果中选择并传入 --repository-id。", "The default repository could not be established. Choose an available repository with dam repository list and pass --repository-id.");
|
|
105
|
+
if (e.diagnosticReason === "CREDITS_NEXT_CURSOR_MISSING")
|
|
106
|
+
return text("已收到本页流水,但服务未返回可用的下一页游标。请查看 details.partial_result,本次无法续页。", "This page was received without a usable cursor. Its records are in details.partial_result; the next page cannot be requested.");
|
|
103
107
|
if (category === "timeout" && e.diagnosticReason === "IMAGE_AUDIT_TIMEOUT")
|
|
104
|
-
return text("
|
|
108
|
+
return text("图片审核处理超时,尚未取得结果。", "The image check did not finish in time.");
|
|
105
109
|
if (category === "login" && e.errorType === "DeviceAuthorizationExpiredError")
|
|
106
110
|
return text("本次登录已超时,请重新登录。", "This sign-in timed out. Please sign in again.");
|
|
107
111
|
if (category === "account" && e.code === "ORG_INVALID")
|
|
@@ -5,6 +5,7 @@ export function registerOrgCommands(program, runtime) {
|
|
|
5
5
|
const org = program.command("org")
|
|
6
6
|
.description("组织选择")
|
|
7
7
|
.helpCommand(false);
|
|
8
|
+
org.addHelpText("after", "\nlist 查询当前账号可用组织;current 只读本机当前选择,不验证远端权限;switch 改变后续 CLI 调用的组织和任务查询范围。资源库不是组织,素材库通过 dam repository list 另行选择。\n");
|
|
8
9
|
const list = leaf(org.command("list"))
|
|
9
10
|
.description("列出可用组织")
|
|
10
11
|
.option("--json", "输出 JSON");
|
|
@@ -33,7 +34,8 @@ export function registerOrgCommands(program, runtime) {
|
|
|
33
34
|
}, { operation: "org.current" });
|
|
34
35
|
const switchCommand = leaf(org.command("switch"))
|
|
35
36
|
.description("切换当前组织")
|
|
36
|
-
.option("--org <org-id>", "
|
|
37
|
+
.option("--org <org-id>", "目标组织 ID;非交互调用必填,可通过 org list 查询")
|
|
38
|
+
.addHelpText("after", "\n使用用户指定的组织 ID,或通过 org list 查找;不要以名称或资源库 ID 代替。切换影响同一本机登录的后续调用,正在执行的创作仍保留提交时的身份和组织。成功输出组织名称与 ID,不提供 --json。\n");
|
|
37
39
|
bindAction(switchCommand, "credential", async (context, signal) => {
|
|
38
40
|
const organizationId = switchCommand.opts().org;
|
|
39
41
|
if (organizationId === undefined && !isInteractive(runtime))
|
|
@@ -5,13 +5,17 @@ export function createPresenter(options) {
|
|
|
5
5
|
type: "terminal",
|
|
6
6
|
small: true
|
|
7
7
|
}));
|
|
8
|
+
let humanResult = false;
|
|
8
9
|
return {
|
|
10
|
+
get humanResult() { return humanResult; },
|
|
9
11
|
result(value, presentation) {
|
|
12
|
+
humanResult = !presentation.json;
|
|
10
13
|
options.writeOut(presentation.json
|
|
11
14
|
? `${JSON.stringify(value)}\n`
|
|
12
15
|
: `${presentation.view(value)}\n`);
|
|
13
16
|
},
|
|
14
17
|
success(message) {
|
|
18
|
+
humanResult = true;
|
|
15
19
|
options.writeOut(`${message}\n`);
|
|
16
20
|
},
|
|
17
21
|
async authorization(input) {
|
|
@@ -10,6 +10,7 @@ export function registerTaskCommands(program, runtime) {
|
|
|
10
10
|
.option("--limit <number>", text("返回 1–100 条,默认 20", "return 1–100 tasks; defaults to 20"), "20")
|
|
11
11
|
.option("--operation <operation>", text("筛选 agent.send 或 tool.call", "filter by agent.send or tool.call"))
|
|
12
12
|
.allowExcessArguments(false);
|
|
13
|
+
list.addHelpText("after", text("\n只读本机当前身份和组织的记录,按创建时间倒序;不查询远端进度,不返回成品或费用。用时间、operation 和 label 定位原调用,再 task get <taskId>。多个候选不明确时先澄清,不自动选最新任务。\n", "\nReads local records for the current identity and organization in reverse creation order, without remote polling, assets or usage. Match time, operation and label, then task get <taskId>. Clarify ambiguous matches rather than choosing the latest automatically.\n"));
|
|
13
14
|
jsonOutput(list);
|
|
14
15
|
bindPreparedAction(list, "local-organization", async () => {
|
|
15
16
|
const options = list.opts();
|
|
@@ -31,12 +32,15 @@ export function registerTaskCommands(program, runtime) {
|
|
|
31
32
|
.allowExcessArguments(false)
|
|
32
33
|
.addHelpText("after", [
|
|
33
34
|
"",
|
|
34
|
-
text("
|
|
35
|
+
text("退出码 0 表示查询成功。现在要结果且 state=running 时隔数秒继续查同一 ID。用户指定稍后取回时,受理后就交接原 taskId 和状态,等用户回来再查。", "Exit 0 means the query succeeded. For delivery now, check the same ID every few seconds while running. For later pickup, hand off the taskId and state upon acceptance and query when the user returns."),
|
|
36
|
+
text("completed 时读取 result。tool.call 返回 content,agent.send 返回 message.parts。重发成品时原样复制本次结果里的完整链接,包括查询参数和签名。若本轮返回文本或补充问题,向用户转述或提问。", "On completed, read result.content for tool.call or result.message.parts for agent.send. When resending an asset, copy the complete link from this result, including its query parameters and signature. Relay text or questions to the user when that is what the turn returned."),
|
|
37
|
+
text("若稿定资源链接已过期,再查原 taskId 可刷新结构化资源的下载授权。第三方链接和正文按原样返回,CLI 不能替第三方续签。", "If a Gaoding file link has expired, query the original taskId for fresh access to structured assets. Third-party URLs and prose are returned unchanged; the CLI cannot renew another provider's signature."),
|
|
38
|
+
text("failed 时向用户说明 note 中的原因。只有错误明确说明尚未派发,才按提示修正并再调用。服务已明确拒绝时,换模型也会发起一次新创作,须有用户补充的需求或另做一次的授权。受理后状态为 unknown 时保留原 ID 核查。", "On failed, relay the cause from note. Correct and retry an input when the error confirms the request was never dispatched. After a definite service refusal, switching models starts another creation and requires a revised request or authorization from the user. On unknown after acceptance, keep and check the original ID."),
|
|
35
39
|
text("unknown 表示无法确认本次执行终态;partialResult 仅是已取得的消息片段,不代表完成。", "unknown means completion cannot be confirmed; partialResult is a message snapshot, not a complete result."),
|
|
36
40
|
text("读取本地状态不请求组织绑定;查询远端进度或获取下载授权仍需联网授权。查询请求失败不代表生成失败,可用原 taskId 重查。", "Local status reads do not bind the organization. Remote progress and download authorization still require network access. A failed query does not mean generation failed; query the same taskId again."),
|
|
37
41
|
text("查询得到完整结果但最终缓存保存失败时仍返回结果和退出码 0;请保留 stderr 警告所指的输出,后续可能无法恢复。", "A complete result is delivered with exit code 0 if only final cache persistence fails; keep the output as warned on stderr because later recovery may be unavailable."),
|
|
38
42
|
text("最终错误为 stderr 中的 JSON error 对象;stderr 也可能有进度和警告,中断不代表远端任务取消。", "The final error is a JSON error object on stderr, which may also contain progress and warnings. Interruption does not mean the remote task was cancelled."),
|
|
39
|
-
text("
|
|
43
|
+
text("查询不重新提交创作。同一任务的 usage 不重复相加;Agent usage.cost.amount 为本轮实扣,Tool minimum/maximum 为目录估价,即使相等也不是实扣。", "Queries never resubmit creation or add usage for repeated reads. Agent usage.cost.amount is this turn's actual charge; Tool minimum/maximum are catalog estimates even when equal."),
|
|
40
44
|
text(`记录仅来自本机执行;保留至用户删除 ~/${runtime.product.stateDirectory}/tasks。切换身份或组织后只显示对应记录。`, `Tasks are local to this machine and identity context; they remain until you remove ~/${runtime.product.stateDirectory}/tasks.`),
|
|
41
45
|
text("Agent 首次回执未取得或原连接中断时可能只能确认未知;不会自动选择最近 Context 或重新生成。", "A missing first Agent receipt or interrupted connection may leave the outcome unknown; the CLI does not select another Context or generate again."),
|
|
42
46
|
""
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
+
import { creationTaskHelp } from "./creation-help.js";
|
|
1
2
|
import { hostSchema, readHostInput } from "./host-input.js";
|
|
2
3
|
import { jsonOutput, bindAction, bindPreparedAction } from "./action-binding.js";
|
|
3
4
|
import { CliUsageError } from "./errors.js";
|
|
4
5
|
import { productText as text } from "../product/text.js";
|
|
5
6
|
export function registerToolCommands(program, runtime) {
|
|
6
7
|
const tool = program.command("tool")
|
|
7
|
-
.description(text(runtime.product, "
|
|
8
|
+
.description(text(runtime.product, "生成及附件图片/视频处理:改字、抠图、分层等", "Generate and process attached images/videos: text, cutouts, layers and more"))
|
|
8
9
|
.helpCommand(false);
|
|
10
|
+
tool.addHelpText("after", text(runtime.product, "\n附件、素材链接或导出图片的处理从 tool list 发现,再用 model list --tool <tool> 和 model get <model> --tool <tool> 选择实现。无需先连接 Editor。模型选择和参数不决定 Agent/Tool 路线;业务策划或持续多轮创作用 agent send。\n", "\nDiscover processing for attachments, asset links and exported images with tool list, then model list --tool <tool> and model get <model> --tool <tool>. No Editor connection is needed. Model choices and controls do not determine Agent/Tool routing; use agent send for planning or multi-turn creation.\n"));
|
|
9
11
|
const list = tool.command("list")
|
|
10
12
|
.description(text(runtime.product, "列出可用工具", "List available tools"))
|
|
11
13
|
.allowExcessArguments(false);
|
|
@@ -32,16 +34,15 @@ export function registerToolCommands(program, runtime) {
|
|
|
32
34
|
.allowExcessArguments(false);
|
|
33
35
|
call.addHelpText("after", [
|
|
34
36
|
"",
|
|
37
|
+
text(runtime.product, "一次调用执行一个工具。输入 JSON 顶层放 model、host_application 和所选模型参数;不要再包一层 arguments。字段、类型与媒体角色见 --schema,当前档位与说明见 model get。", "One call executes one tool. Put model, host_application and the selected model's parameters at the JSON top level, without an arguments wrapper. Read --schema for fields, types and media roles, and model get for current choices and guidance."),
|
|
38
|
+
text(runtime.product, "先保存完整 JSON 文件,再用 --input request.json 执行。命令不交互填参;--input - 必须在同一条 shell 命令中通过管道或重定向送入完整 JSON,单独执行不会再提问。", "Save complete JSON first, then run with --input request.json. Input is not an interactive form: --input - requires piping or redirecting complete JSON in the same shell command and does not prompt for fields."),
|
|
35
39
|
text(runtime.product, "完整结果已校验但最终本地记录保存失败时仍返回结果和退出码 0;stderr 警告 task get 可能无法恢复,请保留输出。", "A validated complete result is delivered with exit code 0 even if its final local record cannot be saved; stderr warns that task get may not recover it. Keep the output."),
|
|
36
40
|
text(runtime.product, "最终错误为 stderr 中的 JSON error 对象;stderr 也可能有进度和警告。中断退出码 130 只表示本地停止等待。", "The final error is a JSON error object on stderr, which may also contain progress and warnings. Exit code 130 means local waiting stopped."),
|
|
37
|
-
|
|
38
|
-
text(runtime.product, "
|
|
39
|
-
text(runtime.product, "
|
|
40
|
-
text(runtime.product, "
|
|
41
|
-
text(runtime.product, "
|
|
42
|
-
text(runtime.product, `结果未收到时用 ${runtime.product.commandName} task list 找到调用,再用 ${runtime.product.commandName} task get <id> 查询,不重复生成。`, `If output is missing, use ${runtime.product.commandName} task list and ${runtime.product.commandName} task get <id> to recover it without generating again.`),
|
|
43
|
-
text(runtime.product, "完整结果为 {content,usage}。content 项为 text、resource_link(uri/name/mimeType)或 resource(resource.uri/mimeType/text);OCR 的 resource.text 是 JSON。分层返回原生模板 JSON 链接,不是 PSD;视频处理需检查实际音轨。", "Complete results are {content,usage}. Content items are text, resource_link (uri/name/mimeType), or resource (resource.uri/mimeType/text); OCR resource.text contains JSON. Layer decomposition returns a native template JSON link, not PSD; verify actual audio after video processing."),
|
|
44
|
-
text(runtime.product, "查询返回同一份 usage;Tool usage.cost 为当次目录预估价格。", "Queries return the same usage; Tool usage.cost is the catalog price estimate for that invocation."),
|
|
41
|
+
...creationTaskHelp(runtime.product),
|
|
42
|
+
text(runtime.product, "媒体 URI 字段支持 HTTP(S) 与本地 file URI;本地路径用 Python Path(path).resolve().as_uri() 或 Node.js pathToFileURL(path).href 生成,正确转义中文、空格和 #。CLI 按调用上传素材;原图、参考和选区分别放入对应字段,数组保留顺序和重复项。", "Media URI fields accept HTTP(S) and local file URIs. Generate local URIs with Python Path(path).resolve().as_uri() or Node.js pathToFileURL(path).href to escape Unicode, spaces and #. The CLI uploads them for the call; keep sources, references and masks in their own fields and preserve array order and duplicates."),
|
|
43
|
+
text(runtime.product, "完整结果为 {content,usage}。content 项为 text、resource_link(uri/name/mimeType)或 resource(resource.uri/mimeType/text);OCR 的 resource.text 是 JSON。分层返回原生模板 JSON 链接,不是 PSD。交付资源链接时原样保留完整 URI 及查询参数,不截断、拼接或去掉授权参数。", "Complete results are {content,usage}. Content items are text, resource_link (uri/name/mimeType), or resource (resource.uri/mimeType/text); OCR resource.text contains JSON. Layer decomposition returns a native template JSON link, not PSD. Preserve each complete delivery URI and its query parameters without truncating, splicing or stripping authorization parameters."),
|
|
44
|
+
text(runtime.product, "Tool usage.cost 的 minimum/maximum 是目录估价,即使相等也不是实际扣费;缺失表示未提供估价,不是免费。实扣须查询可对应的 credits usage 账本;同一 taskId 重复读取不累计费用。", "Tool usage.cost minimum/maximum are catalog estimates even when equal; missing cost means no estimate, not free. Actual charges require matching credits usage ledger records. Repeated reads of one taskId do not add usage."),
|
|
45
|
+
text(runtime.product, "先交付服务返回的已有结果。效果与用户预期有差异时如实说明,后续新创作按用户要求执行;CLI 不按效果阈值判失败或自动重做。本地插值、描图等替代文件不能报告为本工具的服务结果。", "Deliver the existing service result first. Describe any difference from the user's goal and follow the user's instructions for further creation; the CLI does not fail or regenerate based on aesthetic thresholds. Files produced by local interpolation or tracing are not this Tool's service results."),
|
|
45
46
|
""
|
|
46
47
|
].join("\n"));
|
|
47
48
|
jsonOutput(call);
|
|
@@ -74,7 +75,7 @@ export function registerToolCommands(program, runtime) {
|
|
|
74
75
|
});
|
|
75
76
|
runtime.telemetry.annotate({ tool_name: prepared.name });
|
|
76
77
|
await runtime.telemetry.stage("output", async () => {
|
|
77
|
-
runtime.io.writeOut(`${JSON.stringify(hostSchema(runtime, { ...schema }))}\n`);
|
|
78
|
+
runtime.io.writeOut(`${JSON.stringify(hostSchema(runtime, { ...schema }, prepared.name))}\n`);
|
|
78
79
|
});
|
|
79
80
|
return;
|
|
80
81
|
}
|
|
@@ -94,7 +95,7 @@ export function registerToolCommands(program, runtime) {
|
|
|
94
95
|
}
|
|
95
96
|
const run = (observe) => runtime.tool.call({ input: prepared.input, access, signal,
|
|
96
97
|
...(observe ? { observe } : {}) });
|
|
97
|
-
const result = await runtime.tasks.track({ ...task, run });
|
|
98
|
+
const result = await runtime.tasks.track({ ...task, run, signal });
|
|
98
99
|
await runtime.telemetry.stage("output", async () => {
|
|
99
100
|
runtime.io.writeOut(`${JSON.stringify(result)}\n`);
|
|
100
101
|
});
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { waitForHostReceipt } from "../features/update/host-receipt.js";
|
|
2
|
+
import { updateCheckSchema } from "../features/update/check-schema.js";
|
|
3
|
+
import { bindAction, jsonOutput } from "./action-binding.js";
|
|
2
4
|
import { productText as text } from "../product/text.js";
|
|
3
5
|
export function registerUpdateCommand(program, runtime) {
|
|
4
6
|
const update = program.command("update")
|
|
@@ -12,6 +14,27 @@ export function registerUpdateCommand(program, runtime) {
|
|
|
12
14
|
text(runtime.product, "若 CLI 更新成功但 Skill 验收失败,保留已更新版本,按错误中的下一步修复;不支持的安装来源也以命令返回的指引为准。", "If the CLI updates but Skill verification fails, keep the updated version and follow the error's next steps. Unsupported installation sources also receive channel-specific guidance."),
|
|
13
15
|
""
|
|
14
16
|
].join("\n"));
|
|
17
|
+
const check = update.command("check")
|
|
18
|
+
.description(text(runtime.product, "只读查询是否有可用升级,无需登录", "Check for an available update without signing in or installing"))
|
|
19
|
+
.option("--for-display", text(runtime.product, "为当前前台入口交付一次到期提醒,写出成功后开始 60 分钟计时", "Deliver a due notice to the current foreground surface and start its 60-minute window on output"))
|
|
20
|
+
.option("--schema", text(runtime.product, "输出本地查询结果的 Schema,不查询 npm", "Print the local output schema without checking npm"))
|
|
21
|
+
.allowExcessArguments(false);
|
|
22
|
+
jsonOutput(check);
|
|
23
|
+
check.addHelpText("after", text(runtime.product, "\n输出单个 JSON。status 为 available、current、managed 或 unknown;仅 available 提供 updateCommand。普通查询不占提醒次数;--for-display 用于会话展示,仅在到期时返回 notice。使用 CLI_HOST_APPLICATION 指定实际宿主名。复用一小时版本缓存,不安装 CLI 或同步 Skill。\n", "\nOutputs one JSON object with status available, current, managed or unknown. Only available includes updateCommand. Checking spends no reminder slot. --for-display includes notice only when due for the surface named by CLI_HOST_APPLICATION. Reuses the hourly cache without installing the CLI or syncing Skills.\n"));
|
|
24
|
+
bindAction(check, "none", async (_context, signal) => {
|
|
25
|
+
const write = (value) => runtime.telemetry.stage("output", async () => {
|
|
26
|
+
runtime.io.writeOut(JSON.stringify(value) + "\n");
|
|
27
|
+
await runtime.io.flush?.();
|
|
28
|
+
});
|
|
29
|
+
if (check.opts().schema)
|
|
30
|
+
return write({ outputSchema: updateCheckSchema });
|
|
31
|
+
const forDisplay = check.opts().forDisplay === true;
|
|
32
|
+
await runtime.updateNotification.report(signal, forDisplay, async (result) => {
|
|
33
|
+
await write(result);
|
|
34
|
+
if (forDisplay && result.status === "available" && result.notice)
|
|
35
|
+
await waitForHostReceipt(signal, result.notice);
|
|
36
|
+
});
|
|
37
|
+
}, { operation: "update.check", mode: () => check.opts().schema ? "schema" : "execute" });
|
|
15
38
|
bindAction(update, "none", async (_context, signal) => {
|
|
16
39
|
const result = await runtime.update.run(signal);
|
|
17
40
|
await runtime.telemetry.stage("output", async () => {
|
|
@@ -24,6 +24,7 @@ export function createCreativeAgentAdapter(dependencies) {
|
|
|
24
24
|
let httpStatus;
|
|
25
25
|
const stream = await dependencies.transport.postStream({
|
|
26
26
|
path: "/ai-agent/v1/thread/completion",
|
|
27
|
+
sensitiveResponse: true,
|
|
27
28
|
...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
|
|
28
29
|
body: buildCreativeRequest(message, ids),
|
|
29
30
|
accept: "text/event-stream",
|
|
@@ -49,13 +50,16 @@ export function createCreativeAgentAdapter(dependencies) {
|
|
|
49
50
|
const output = await withResponseDiagnostics(async (onResponse) => {
|
|
50
51
|
const messages = await dependencies.transport.getJson({
|
|
51
52
|
path: `/ai-agent/v1/thread/${encodeURIComponent(contextId)}/messages`,
|
|
53
|
+
sensitiveResponse: true,
|
|
52
54
|
credential: access.credential,
|
|
53
55
|
organizationId: access.organizationId,
|
|
54
56
|
onResponse,
|
|
55
57
|
signal
|
|
56
58
|
});
|
|
57
|
-
let usageModelMissing = false;
|
|
58
|
-
const normalized = normalizeCreativeMessages(restoreCreativeResourceUrls(creativeTurnMessages(messages, ids.localMessageId), streamed), () => { usageModelMissing = true; });
|
|
59
|
+
let usageModelMissing = false, usageAmountMissing = false;
|
|
60
|
+
const normalized = normalizeCreativeMessages(restoreCreativeResourceUrls(creativeTurnMessages(messages, ids.localMessageId), streamed), () => { usageModelMissing = true; }, () => { usageAmountMissing = true; });
|
|
61
|
+
if (usageAmountMissing)
|
|
62
|
+
await observe?.({ agentUsageAmountMissing: true });
|
|
59
63
|
if (usageModelMissing)
|
|
60
64
|
await observe?.({ agentUsageModelMissing: true });
|
|
61
65
|
return normalized;
|
|
@@ -375,36 +375,14 @@ function parseQuestionPart(message) {
|
|
|
375
375
|
}
|
|
376
376
|
};
|
|
377
377
|
}
|
|
378
|
-
function
|
|
379
|
-
const texts = new Set();
|
|
380
|
-
const urls = new Set();
|
|
381
|
-
return parts.filter((part) => {
|
|
382
|
-
if ("text" in part) {
|
|
383
|
-
if (texts.has(part.text))
|
|
384
|
-
return false;
|
|
385
|
-
texts.add(part.text);
|
|
386
|
-
return true;
|
|
387
|
-
}
|
|
388
|
-
if ("url" in part) {
|
|
389
|
-
if (urls.has(part.url))
|
|
390
|
-
return false;
|
|
391
|
-
urls.add(part.url);
|
|
392
|
-
}
|
|
393
|
-
return true;
|
|
394
|
-
});
|
|
395
|
-
}
|
|
396
|
-
export function normalizeCreativeMessages(messages, onUsageModelMissing) {
|
|
378
|
+
export function normalizeCreativeMessages(messages, onUsageModelMissing, onUsageAmountMissing) {
|
|
397
379
|
const contextId = creativeContextId(messages);
|
|
398
380
|
const latest = new Map();
|
|
399
|
-
const anonymous = [];
|
|
400
381
|
for (const message of messages) {
|
|
401
382
|
const id = nonEmptyString(message.message_id);
|
|
402
|
-
|
|
403
|
-
anonymous.push(message);
|
|
404
|
-
else
|
|
405
|
-
latest.set(id, message);
|
|
383
|
+
latest.set(id ?? Symbol(), message);
|
|
406
384
|
}
|
|
407
|
-
const normalized = [...latest.values()
|
|
385
|
+
const normalized = [...latest.values()];
|
|
408
386
|
const parts = [];
|
|
409
387
|
for (const message of normalized) {
|
|
410
388
|
if (hasHiddenTransportRole(message))
|
|
@@ -434,7 +412,7 @@ export function normalizeCreativeMessages(messages, onUsageModelMissing) {
|
|
|
434
412
|
return fail();
|
|
435
413
|
parts.push(parseQuestionPart(question));
|
|
436
414
|
}
|
|
437
|
-
const publicParts =
|
|
415
|
+
const publicParts = parts;
|
|
438
416
|
if (publicParts.length === 0)
|
|
439
417
|
return fail("AGENT_RESULT_EMPTY", { messageCount: normalized.length, publicPartCount: 0 });
|
|
440
418
|
const usageItems = [];
|
|
@@ -444,10 +422,11 @@ export function normalizeCreativeMessages(messages, onUsageModelMissing) {
|
|
|
444
422
|
continue;
|
|
445
423
|
const extra = record(message.extra);
|
|
446
424
|
const amount = extra?.deduct_points;
|
|
447
|
-
if (amount
|
|
425
|
+
if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) {
|
|
426
|
+
if (amount !== undefined || (nonEmptyString(extra?.task_id) && nonEmptyString(extra?.scene_code)))
|
|
427
|
+
onUsageAmountMissing?.();
|
|
448
428
|
continue;
|
|
449
|
-
|
|
450
|
-
return fail();
|
|
429
|
+
}
|
|
451
430
|
totalCost += amount;
|
|
452
431
|
const model = nonEmptyString(extra?.scene_code);
|
|
453
432
|
if (model === undefined) {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
|
-
|
|
2
|
+
import { isFilemsResource, withFilemsAuthKey } from "../../platform/resource-auth-key.js";
|
|
3
|
+
function privateResource(value, refreshSigned) {
|
|
3
4
|
let url;
|
|
4
5
|
try {
|
|
5
6
|
url = new URL(value);
|
|
@@ -7,34 +8,41 @@ function unsignedPrivateUrl(value) {
|
|
|
7
8
|
catch {
|
|
8
9
|
throw new RemoteProtocolError();
|
|
9
10
|
}
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
if (
|
|
15
|
-
return
|
|
16
|
-
|
|
17
|
-
if (url.protocol !== "https:" || url.username !== "" || url.password !== ""
|
|
18
|
-
|| url.port !== "")
|
|
19
|
-
throw new RemoteProtocolError();
|
|
20
|
-
return url;
|
|
11
|
+
const signed = !!url.searchParams.get("auth_key")?.trim();
|
|
12
|
+
if (signed && !refreshSigned)
|
|
13
|
+
return;
|
|
14
|
+
// An existing link outside the authorized origin is opaque. Never attach our token.
|
|
15
|
+
if (signed && (url.protocol !== "https:" || url.username || url.password || url.port))
|
|
16
|
+
return;
|
|
17
|
+
return isFilemsResource(url) ? { signed } : undefined;
|
|
21
18
|
}
|
|
22
19
|
export function createAgentResourceAuthorizer(dependencies) {
|
|
23
20
|
return {
|
|
24
|
-
async authorize(output, access, signal) {
|
|
21
|
+
async authorize(output, access, signal, _observe, hasOtherContent) {
|
|
25
22
|
signal.throwIfAborted();
|
|
26
|
-
const urls = output.message.parts.map((part) => ("url" in part ?
|
|
23
|
+
const urls = output.message.parts.map((part) => ("url" in part ? privateResource(part.url, !!dependencies.onSignedRefreshFailure) : undefined));
|
|
27
24
|
if (urls.every((url) => url === undefined))
|
|
28
25
|
return output;
|
|
29
26
|
// One token serves this result only; do not retain it across identities or commands.
|
|
30
|
-
|
|
27
|
+
let authKey;
|
|
28
|
+
try {
|
|
29
|
+
authKey = await dependencies.authKeys.getAuthKey(access, signal);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
signal.throwIfAborted();
|
|
33
|
+
if (urls.every(url => !url || url.signed) && dependencies.onSignedRefreshFailure?.(error))
|
|
34
|
+
return output;
|
|
35
|
+
if (urls.some(url => url && !url.signed) && (hasOtherContent || urls.some(url => !url || url.signed))
|
|
36
|
+
&& dependencies.onPartialResourceFailure?.(error))
|
|
37
|
+
return output;
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
31
40
|
signal.throwIfAborted();
|
|
32
41
|
const parts = output.message.parts.map((part, index) => {
|
|
33
42
|
const url = urls[index];
|
|
34
43
|
if (url === undefined || !("url" in part))
|
|
35
44
|
return part;
|
|
36
|
-
url.
|
|
37
|
-
return { ...part, url: url.href };
|
|
45
|
+
return { ...part, url: withFilemsAuthKey(part.url, authKey) };
|
|
38
46
|
});
|
|
39
47
|
return {
|
|
40
48
|
...output,
|
|
@@ -1,32 +1,49 @@
|
|
|
1
|
+
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
1
2
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
3
|
import { creativeTurnMessages, normalizeCreativeMessages } from "./creative-protocol.js";
|
|
3
4
|
/** History is a snapshot, not proof that this particular invocation finished. */
|
|
4
5
|
export async function readAgentResult(transport, request) {
|
|
5
6
|
const path = `/ai-agent/v1/thread/${encodeURIComponent(request.contextId)}`;
|
|
6
|
-
const access = { credential: request.credential, signal: request.signal,
|
|
7
|
+
const access = { credential: request.credential, signal: request.signal, sensitiveResponse: true,
|
|
7
8
|
...(request.organizationId === undefined ? {} : { organizationId: request.organizationId }) };
|
|
8
9
|
const messages = await transport.getJson({ ...access, path: `${path}/messages` });
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
let connectionState = "unknown";
|
|
11
|
+
let connectionError;
|
|
12
|
+
try {
|
|
13
|
+
const connection = await transport.getJson({ ...access, path: `${path}/connection` });
|
|
14
|
+
if (connection && typeof connection === "object" && "state" in connection && typeof connection.state === "string")
|
|
15
|
+
connectionState = connection.state;
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
request.signal.throwIfAborted();
|
|
19
|
+
if (error instanceof RemoteRequestError && (error.status === 401 || error.status === 403))
|
|
20
|
+
throw error;
|
|
21
|
+
connectionError = error;
|
|
22
|
+
}
|
|
14
23
|
if (!Array.isArray(messages))
|
|
15
24
|
throw new RemoteProtocolError();
|
|
16
25
|
if (!messages.some(m => m && typeof m === "object" && m.local_message_id === request.localMessageId)) {
|
|
17
|
-
|
|
26
|
+
if (connectionError)
|
|
27
|
+
throw connectionError;
|
|
28
|
+
return { connectionState };
|
|
18
29
|
}
|
|
19
30
|
const turn = creativeTurnMessages(messages, request.localMessageId);
|
|
20
|
-
if (!turn.some(m => m.role !== "user" && m.content))
|
|
21
|
-
|
|
31
|
+
if (!turn.some(m => m.role !== "user" && m.content)) {
|
|
32
|
+
if (connectionError)
|
|
33
|
+
throw connectionError;
|
|
34
|
+
return { connectionState };
|
|
35
|
+
}
|
|
22
36
|
try {
|
|
23
|
-
let usageModelMissing = false;
|
|
24
|
-
const partialResult = normalizeCreativeMessages(turn, () => { usageModelMissing = true; });
|
|
25
|
-
return { connectionState
|
|
37
|
+
let usageModelMissing = false, usageAmountMissing = false;
|
|
38
|
+
const partialResult = normalizeCreativeMessages(turn, () => { usageModelMissing = true; }, () => { usageAmountMissing = true; });
|
|
39
|
+
return { connectionState, partialResult, ...(usageModelMissing ? { usageModelMissing: true } : {}), ...(usageAmountMissing ? { usageAmountMissing: true } : {}) };
|
|
26
40
|
}
|
|
27
41
|
catch (error) {
|
|
28
|
-
if (error instanceof RemoteProtocolError)
|
|
29
|
-
|
|
42
|
+
if (error instanceof RemoteProtocolError) {
|
|
43
|
+
if (connectionError)
|
|
44
|
+
throw connectionError;
|
|
45
|
+
return { connectionState };
|
|
46
|
+
}
|
|
30
47
|
throw error;
|
|
31
48
|
}
|
|
32
49
|
}
|