@gaoding/cli 1.9.1 → 2.1.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/README.md +5 -0
- package/contracts/operations/credits.get/input.schema.json +9 -0
- package/contracts/operations/credits.get/output.schema.json +107 -0
- package/contracts/operations/credits.usage.get/input.schema.json +18 -0
- package/contracts/operations/credits.usage.get/output.schema.json +53 -0
- package/contracts/operations/credits.usage.list/input.schema.json +32 -0
- package/contracts/operations/credits.usage.list/output.schema.json +144 -0
- package/dist/bin/gd-cli.js +2 -2
- package/dist/bin/insmind-cli.js +2 -2
- package/dist/src/bootstrap/create-cli.js +28 -24
- package/dist/src/bootstrap/create-runtime.js +31 -18
- package/dist/src/bootstrap/run-task-worker.js +2 -1
- package/dist/src/bootstrap/validators.js +7 -2
- package/dist/src/cli/action-binding.js +42 -13
- package/dist/src/cli/agent-commands.js +8 -12
- package/dist/src/cli/credits-command.js +127 -16
- package/dist/src/cli/dam-commands.js +3 -2
- package/dist/src/cli/editor-commands.js +10 -5
- package/dist/src/cli/host-input.js +34 -0
- package/dist/src/cli/model-commands.js +4 -3
- package/dist/src/cli/presenter.js +4 -0
- package/dist/src/cli/tool-commands.js +7 -9
- package/dist/src/cli/update-command.js +24 -1
- package/dist/src/contracts/creation-input.js +20 -0
- package/dist/src/features/agent/creative-protocol.js +12 -14
- 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/sso-service.js +6 -4
- package/dist/src/features/auth/use-cases.js +2 -1
- 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 +174 -31
- package/dist/src/features/dam/file-downloader.js +2 -1
- package/dist/src/features/dam/use-cases.js +7 -7
- 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 +26 -12
- package/dist/src/features/task/use-cases.js +97 -82
- 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 +29 -64
- 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 +2 -2
- package/dist/src/features/tool/use-cases.js +24 -35
- 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/platform/json-input.js +1 -1
- package/dist/src/platform/safe-upload-file.js +6 -0
- package/dist/src/platform/signature.js +3 -1
- package/dist/src/platform/signed-http-transport.js +34 -32
- package/dist/src/telemetry/host-diagnostics.js +2 -2
- package/dist/src/telemetry/invocation.js +87 -24
- package/dist/src/telemetry/process-errors.js +36 -3
- package/dist/src/telemetry/sls-sink.js +7 -10
- package/package.json +4 -4
- package/skills/gd-cli/SKILL.md +2 -0
- package/skills/gd-cli/references/editor.md +1 -1
- package/skills/gd-cli/references/generation-constraints.md +3 -1
- package/skills/gd-cli/references/tool.md +2 -3
- package/skills/gd-cli/references/update.md +6 -0
|
@@ -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`);
|
|
@@ -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 () => {
|
|
@@ -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
|
+
];
|
|
@@ -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);
|
|
@@ -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) {
|
|
@@ -12,7 +12,6 @@ export class AuthExpiredError extends Error {
|
|
|
12
12
|
this.name = "AuthExpiredError";
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
-
const REFRESH_WINDOW_MS = 5 * 60 * 1000;
|
|
16
15
|
const organizationRefreshes = new Map();
|
|
17
16
|
export function createAccessPolicies(dependencies) {
|
|
18
17
|
async function readValidState(signal) {
|
|
@@ -102,8 +101,7 @@ export function createAccessPolicies(dependencies) {
|
|
|
102
101
|
};
|
|
103
102
|
}
|
|
104
103
|
function bindingNeedsRefresh(organization, now) {
|
|
105
|
-
return organization.bindExpiresAt
|
|
106
|
-
|| Date.parse(organization.bindExpiresAt) <= now.getTime() + REFRESH_WINDOW_MS;
|
|
104
|
+
return organization.bindExpiresAt !== undefined && Date.parse(organization.bindExpiresAt) <= now.getTime();
|
|
107
105
|
}
|
|
108
106
|
function sameOrganization(current, expected) {
|
|
109
107
|
return current?.credential.accessKey === expected.credential.accessKey
|
|
@@ -122,11 +122,11 @@ export function createSsoService(options) {
|
|
|
122
122
|
const deviceCode = nonEmptyString(body.device_code);
|
|
123
123
|
const expiresInSeconds = positiveNumber(body.expires_in);
|
|
124
124
|
const intervalSeconds = positiveNumber(body.interval);
|
|
125
|
-
if (!authorizeCode || !deviceCode || !
|
|
125
|
+
if (!authorizeCode || !deviceCode || !intervalSeconds) {
|
|
126
126
|
throw invalidFields(response, "authorize", { authorize_code: authorizeCode, device_code: deviceCode,
|
|
127
|
-
|
|
127
|
+
interval: intervalSeconds });
|
|
128
128
|
}
|
|
129
|
-
return { authorizeCode, deviceCode, expiresInSeconds, intervalSeconds };
|
|
129
|
+
return { authorizeCode, deviceCode, ...(expiresInSeconds ? { expiresInSeconds } : {}), intervalSeconds };
|
|
130
130
|
},
|
|
131
131
|
async pollDeviceToken(deviceCode, signal) {
|
|
132
132
|
const query = new URLSearchParams({
|
|
@@ -254,7 +254,9 @@ function positiveNumber(value) {
|
|
|
254
254
|
}
|
|
255
255
|
function dateString(value) {
|
|
256
256
|
const text = nonEmptyString(value);
|
|
257
|
-
|
|
257
|
+
if (!text || !Number.isFinite(Date.parse(text)))
|
|
258
|
+
return undefined;
|
|
259
|
+
return /^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/iu.test(text) ? text : new Date(text).toISOString();
|
|
258
260
|
}
|
|
259
261
|
function identifier(value) {
|
|
260
262
|
if (typeof value === "number" && Number.isFinite(value))
|
|
@@ -120,7 +120,8 @@ export function createAuthUseCases(dependencies) {
|
|
|
120
120
|
const authorization = await dependencies.telemetry.stage("authorize", async () => {
|
|
121
121
|
try {
|
|
122
122
|
const authorization = await withinAuthorization(() => dependencies.sso.startDeviceAuthorization(authorizationSignal));
|
|
123
|
-
|
|
123
|
+
if (authorization.expiresInSeconds !== undefined)
|
|
124
|
+
dependencies.telemetry.annotate({ auth_server_expires_in_s: authorization.expiresInSeconds });
|
|
124
125
|
const authorizationUrl = new URL("/cli/device-authorization", dependencies.authPageOrigin);
|
|
125
126
|
authorizationUrl.searchParams.set("code", authorization.authorizeCode);
|
|
126
127
|
await withinAuthorization(() => input.interaction.showAuthorization(authorizationUrl));
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
|
+
const maximum = BigInt(Number.MAX_SAFE_INTEGER);
|
|
3
|
+
/** Keep service decimals exact until arithmetic and range checks are complete. */
|
|
4
|
+
export function readCreditAmount(value) {
|
|
5
|
+
if (typeof value !== "number" && typeof value !== "string")
|
|
6
|
+
throw new RemoteProtocolError();
|
|
7
|
+
const text = String(value).trim();
|
|
8
|
+
const match = /^([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:e([+-]?\d+))?$/i.exec(text);
|
|
9
|
+
if (!match)
|
|
10
|
+
throw new RemoteProtocolError();
|
|
11
|
+
const fraction = match[3] ?? match[4] ?? "";
|
|
12
|
+
const digits = `${match[2] ?? ""}${fraction}`.replace(/^0+/, "");
|
|
13
|
+
if (digits === "")
|
|
14
|
+
return { coefficient: 0n, scale: 0 };
|
|
15
|
+
const numeric = Number(text);
|
|
16
|
+
// Reject nonzero underflow before constructing powers for an extreme exponent.
|
|
17
|
+
if (match[1] === "-" || !Number.isFinite(numeric) || numeric === 0 || numeric > Number.MAX_SAFE_INTEGER) {
|
|
18
|
+
throw new RemoteProtocolError();
|
|
19
|
+
}
|
|
20
|
+
let coefficient = BigInt(digits);
|
|
21
|
+
let scale = fraction.length - Number(match[5] ?? 0);
|
|
22
|
+
if (scale < 0) {
|
|
23
|
+
coefficient *= 10n ** BigInt(-scale);
|
|
24
|
+
scale = 0;
|
|
25
|
+
}
|
|
26
|
+
return checked({ coefficient, scale });
|
|
27
|
+
}
|
|
28
|
+
export function sumCreditAmounts(values) {
|
|
29
|
+
const scale = values.reduce((largest, value) => Math.max(largest, value.scale), 0);
|
|
30
|
+
const coefficient = values.reduce((sum, value) => sum + scaled(value, scale), 0n);
|
|
31
|
+
return checked({ coefficient, scale });
|
|
32
|
+
}
|
|
33
|
+
export function availableCreditAmount(total, used) {
|
|
34
|
+
const scale = Math.max(total.scale, used.scale);
|
|
35
|
+
const difference = scaled(total, scale) - scaled(used, scale);
|
|
36
|
+
return { coefficient: difference > 0n ? difference : 0n, scale };
|
|
37
|
+
}
|
|
38
|
+
export function creditAmountNumber(value) {
|
|
39
|
+
const numeric = Number(`${value.coefficient}e-${value.scale}`);
|
|
40
|
+
if (value.coefficient !== 0n && numeric === 0)
|
|
41
|
+
throw new RemoteProtocolError();
|
|
42
|
+
return numeric;
|
|
43
|
+
}
|
|
44
|
+
function scaled(value, scale) {
|
|
45
|
+
return value.coefficient * 10n ** BigInt(scale - value.scale);
|
|
46
|
+
}
|
|
47
|
+
function checked(value) {
|
|
48
|
+
if (value.coefficient > maximum * 10n ** BigInt(value.scale))
|
|
49
|
+
throw new RemoteProtocolError();
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const amountFields = new Set(["total", "used", "wait", "member_period_limit", "usage"]);
|
|
2
|
+
/** Preserve amount tokens before JSON.parse can round them; other fields keep their JSON types. */
|
|
3
|
+
export function parseCreditsResponse(text) {
|
|
4
|
+
const preserved = text.replace(/("(?:\\.|[^"\\])*")(?:(\s*:\s*)(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?))?/g, (token, key, separator, value) => {
|
|
5
|
+
// Consume every complete string token, including descriptions with escaped quotes.
|
|
6
|
+
if (value === undefined || !amountFields.has(JSON.parse(key)))
|
|
7
|
+
return token;
|
|
8
|
+
return `${key}${separator}${JSON.stringify(value)}`;
|
|
9
|
+
});
|
|
10
|
+
return JSON.parse(preserved);
|
|
11
|
+
}
|
|
@@ -1,53 +1,196 @@
|
|
|
1
|
+
import { withResponseDiagnostics } from "../../platform/signed-http-transport.js";
|
|
1
2
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
3
|
+
import { availableCreditAmount, creditAmountNumber, readCreditAmount, sumCreditAmounts } from "./amount.js";
|
|
4
|
+
import { parseCreditsResponse } from "./response.js";
|
|
2
5
|
export function createCreditsUseCases(options) {
|
|
3
6
|
return {
|
|
4
7
|
async get(input) {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
return withResponseDiagnostics(async (onResponse) => {
|
|
9
|
+
const body = await options.transport.getJson({
|
|
10
|
+
path: "/trade/rights-overview",
|
|
11
|
+
query: { goods_type_enums: "GAODOU" },
|
|
12
|
+
...input,
|
|
13
|
+
onResponse,
|
|
14
|
+
sensitiveResponse: true,
|
|
15
|
+
parseJson: parseCreditsResponse
|
|
16
|
+
});
|
|
17
|
+
const rows = findCreditsRecords(body).map(source => {
|
|
18
|
+
const total = readCreditAmount(source.total);
|
|
19
|
+
const used = readCreditAmount(source.used);
|
|
20
|
+
const pending = readCreditAmount(source.wait);
|
|
21
|
+
const identifier = optionalString(source.identifier);
|
|
22
|
+
const memberPeriodLimit = source.member_period_limit == null ? undefined : amount(source.member_period_limit);
|
|
23
|
+
return { ...(identifier === undefined ? {} : { identifier }), total, used, pending,
|
|
24
|
+
...(memberPeriodLimit === undefined ? {} : { memberPeriodLimit }) };
|
|
25
|
+
});
|
|
26
|
+
const total = sumCreditAmounts(rows.map(row => row.total));
|
|
27
|
+
const used = sumCreditAmounts(rows.map(row => row.used));
|
|
28
|
+
const pending = sumCreditAmounts(rows.map(row => row.pending));
|
|
29
|
+
const balances = rows.map(({ total, used, pending, ...metadata }) => ({
|
|
30
|
+
...metadata, total: creditAmountNumber(total), used: creditAmountNumber(used), pending: creditAmountNumber(pending),
|
|
31
|
+
available: creditAmountNumber(availableCreditAmount(total, used))
|
|
32
|
+
}));
|
|
33
|
+
return {
|
|
34
|
+
credits: { unit: options.billingUnit, total: creditAmountNumber(total), used: creditAmountNumber(used),
|
|
35
|
+
pending: creditAmountNumber(pending), available: creditAmountNumber(availableCreditAmount(total, used)) },
|
|
36
|
+
...(balances.length > 1 || balances.some(row => row.memberPeriodLimit !== undefined) ? { balances } : {})
|
|
37
|
+
};
|
|
11
38
|
});
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
39
|
+
},
|
|
40
|
+
async listUsage({ input, ...access }) {
|
|
41
|
+
return withResponseDiagnostics(async (onResponse) => {
|
|
42
|
+
const normalized = normalizeCreditsUsageListInput(input, options.now?.());
|
|
43
|
+
const body = await options.transport.getJson({
|
|
44
|
+
path: "/trade/gaodou-rights/usage-records",
|
|
45
|
+
query: { recordAtGte: normalized.from, recordAtLte: normalized.to, pageSize: String(normalized.limit),
|
|
46
|
+
...(normalized.cursor === undefined ? {} : { cursor: normalized.cursor }) },
|
|
47
|
+
...access,
|
|
48
|
+
onResponse,
|
|
49
|
+
sensitiveResponse: true,
|
|
50
|
+
parseJson: parseCreditsResponse
|
|
51
|
+
});
|
|
52
|
+
if (!isRecord(body) || !Array.isArray(body.items) || typeof body.has_more !== "boolean")
|
|
53
|
+
throw new RemoteProtocolError();
|
|
54
|
+
const cursor = optionalString(body.next_cursor);
|
|
55
|
+
if (body.has_more && (cursor === undefined || cursor.trim() === ""))
|
|
56
|
+
throw new RemoteProtocolError();
|
|
57
|
+
return {
|
|
21
58
|
unit: options.billingUnit,
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
}
|
|
27
|
-
};
|
|
59
|
+
range: { from: normalized.from, to: normalized.to },
|
|
60
|
+
items: body.items.map(readUsageRecord),
|
|
61
|
+
hasMore: body.has_more,
|
|
62
|
+
nextCursor: body.has_more ? cursor : null
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
},
|
|
66
|
+
async getUsage({ input, ...access }) {
|
|
67
|
+
return withResponseDiagnostics(async (onResponse) => {
|
|
68
|
+
const body = await options.transport.getJson({
|
|
69
|
+
path: `/trade/gaodou-rights/usage-records/${encodeURIComponent(input.id)}`,
|
|
70
|
+
...access,
|
|
71
|
+
onResponse,
|
|
72
|
+
sensitiveResponse: true,
|
|
73
|
+
parseJson: parseCreditsResponse
|
|
74
|
+
});
|
|
75
|
+
if (!isRecord(body) || !Array.isArray(body.usage_logs))
|
|
76
|
+
throw new RemoteProtocolError();
|
|
77
|
+
return {
|
|
78
|
+
id: input.id,
|
|
79
|
+
unit: options.billingUnit,
|
|
80
|
+
breakdown: body.usage_logs.map(value => {
|
|
81
|
+
if (!isRecord(value))
|
|
82
|
+
throw new RemoteProtocolError();
|
|
83
|
+
const usageType = optionalNumber(value.usage_type);
|
|
84
|
+
const sourceType = optionalString(value.source_type);
|
|
85
|
+
return { amount: amount(value.usage), ...(usageType === undefined ? {} : { usageType }),
|
|
86
|
+
...(sourceType === undefined ? {} : { sourceType }) };
|
|
87
|
+
})
|
|
88
|
+
};
|
|
89
|
+
});
|
|
28
90
|
}
|
|
29
91
|
};
|
|
30
92
|
}
|
|
31
|
-
|
|
93
|
+
/** UTC defaults and timezone conversion are CLI-owned, unlike service business limits. */
|
|
94
|
+
export function normalizeCreditsUsageListInput(input, now = new Date()) {
|
|
95
|
+
const from = input.from === undefined
|
|
96
|
+
? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString() : timestamp(input.from);
|
|
97
|
+
const to = input.to === undefined
|
|
98
|
+
? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1) - 1).toISOString() : timestamp(input.to);
|
|
99
|
+
const limit = input.limit ?? 20;
|
|
100
|
+
if (timestampAfter(from, to) || !Number.isSafeInteger(limit) || limit < 1)
|
|
101
|
+
throw new RangeError("Invalid credits time range or page size.");
|
|
102
|
+
if (input.cursor !== undefined && input.cursor.trim() === "")
|
|
103
|
+
throw new RangeError("Empty credits cursor.");
|
|
104
|
+
return { from, to, limit, ...(input.cursor === undefined ? {} : { cursor: input.cursor }) };
|
|
105
|
+
}
|
|
106
|
+
function findCreditsRecords(value) {
|
|
32
107
|
if (Array.isArray(value)) {
|
|
33
|
-
const
|
|
34
|
-
if (!
|
|
108
|
+
const records = value.filter((candidate) => (isRecord(candidate) && candidate.goods_type_enum === "GAODOU"));
|
|
109
|
+
if (!records.length)
|
|
35
110
|
throw new RemoteProtocolError();
|
|
36
|
-
return
|
|
111
|
+
return records;
|
|
37
112
|
}
|
|
38
113
|
if (!isRecord(value))
|
|
39
114
|
throw new RemoteProtocolError();
|
|
40
|
-
const candidates = [value.GAODOU,
|
|
115
|
+
const candidates = [value.GAODOU, isRecord(value.data) ? value.data.GAODOU : undefined, value.data];
|
|
41
116
|
const record = candidates.find(isRecord);
|
|
42
117
|
if (!record)
|
|
43
118
|
throw new RemoteProtocolError();
|
|
44
|
-
return record;
|
|
119
|
+
return [record];
|
|
120
|
+
}
|
|
121
|
+
function readUsageRecord(value) {
|
|
122
|
+
if (!isRecord(value))
|
|
123
|
+
throw new RemoteProtocolError();
|
|
124
|
+
let recordedAt;
|
|
125
|
+
try {
|
|
126
|
+
recordedAt = timestamp(requiredString(value.record_at));
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
throw new RemoteProtocolError();
|
|
130
|
+
}
|
|
131
|
+
const recordMode = optionalString(value.record_mode);
|
|
132
|
+
const description = optionalString(value.consume_desc);
|
|
133
|
+
const scene = optionalNumber(value.consume_scene);
|
|
134
|
+
const referenceId = optionalString(value.reference_id);
|
|
135
|
+
const userId = optionalString(value.uc_id);
|
|
136
|
+
const userName = optionalString(value.user_name);
|
|
137
|
+
return {
|
|
138
|
+
id: requiredString(value.record_id), changeType: requiredString(value.change_type),
|
|
139
|
+
amount: amount(value.usage), recordedAt,
|
|
140
|
+
...(recordMode === undefined ? {} : { recordMode }), ...(description === undefined ? {} : { description }),
|
|
141
|
+
...(scene === undefined ? {} : { scene }), ...(referenceId === undefined ? {} : { referenceId }),
|
|
142
|
+
...(userId === undefined && userName === undefined ? {} : { user: {
|
|
143
|
+
...(userId === undefined ? {} : { id: userId }), ...(userName === undefined ? {} : { name: userName })
|
|
144
|
+
} })
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function amount(value) {
|
|
148
|
+
return creditAmountNumber(readCreditAmount(value));
|
|
149
|
+
}
|
|
150
|
+
function requiredString(value) {
|
|
151
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
152
|
+
throw new RemoteProtocolError();
|
|
153
|
+
return value;
|
|
45
154
|
}
|
|
46
|
-
function
|
|
47
|
-
if (
|
|
155
|
+
function optionalString(value) {
|
|
156
|
+
if (value == null)
|
|
48
157
|
return undefined;
|
|
49
|
-
|
|
50
|
-
|
|
158
|
+
if (typeof value !== "string")
|
|
159
|
+
throw new RemoteProtocolError();
|
|
160
|
+
return value;
|
|
161
|
+
}
|
|
162
|
+
function optionalNumber(value) {
|
|
163
|
+
if (value == null)
|
|
164
|
+
return undefined;
|
|
165
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
166
|
+
throw new RemoteProtocolError();
|
|
167
|
+
return value;
|
|
168
|
+
}
|
|
169
|
+
function timestamp(value) {
|
|
170
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|[+-]\d{2}:\d{2})$/i.exec(value);
|
|
171
|
+
const parsed = Date.parse(value);
|
|
172
|
+
if (!match || !Number.isFinite(parsed))
|
|
173
|
+
throw new RangeError("A timestamp with an explicit timezone is required.");
|
|
174
|
+
const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
|
|
175
|
+
const monthDays = [31, year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
176
|
+
if (month < 1 || month > 12 || day < 1 || day > monthDays[month - 1] || Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59) {
|
|
177
|
+
throw new RangeError("Invalid calendar timestamp.");
|
|
178
|
+
}
|
|
179
|
+
const normalized = new Date(parsed).toISOString();
|
|
180
|
+
// Date normalizes the offset but retains only milliseconds; preserve any finer digits.
|
|
181
|
+
return `${normalized.slice(0, -1)}${match[7]?.slice(3) ?? ""}Z`;
|
|
182
|
+
}
|
|
183
|
+
function timestampAfter(from, to) {
|
|
184
|
+
const fromPoint = from.indexOf(".");
|
|
185
|
+
const toPoint = to.indexOf(".");
|
|
186
|
+
const fromSeconds = Date.parse(`${from.slice(0, fromPoint)}Z`);
|
|
187
|
+
const toSeconds = Date.parse(`${to.slice(0, toPoint)}Z`);
|
|
188
|
+
if (fromSeconds !== toSeconds)
|
|
189
|
+
return fromSeconds > toSeconds;
|
|
190
|
+
const fromFraction = from.slice(fromPoint + 1, -1);
|
|
191
|
+
const toFraction = to.slice(toPoint + 1, -1);
|
|
192
|
+
const precision = Math.max(fromFraction.length, toFraction.length);
|
|
193
|
+
return fromFraction.padEnd(precision, "0") > toFraction.padEnd(precision, "0");
|
|
51
194
|
}
|
|
52
195
|
function isRecord(value) {
|
|
53
196
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -98,7 +98,8 @@ function withIndex(filename, index, total) {
|
|
|
98
98
|
return filename;
|
|
99
99
|
const extension = extname(filename);
|
|
100
100
|
const stem = extension === "" ? filename : filename.slice(0, -extension.length);
|
|
101
|
-
|
|
101
|
+
const suffix = `-${index + 1}${extension}`;
|
|
102
|
+
return stem.slice(0, maximumFilenameLength - suffix.length) + suffix;
|
|
102
103
|
}
|
|
103
104
|
async function fetchDownload(initial, fetch, signal) {
|
|
104
105
|
let url = safeDownloadUrl(initial);
|
|
@@ -117,11 +117,11 @@ export function createDamUseCases(dependencies) {
|
|
|
117
117
|
access: input.access,
|
|
118
118
|
signal: input.signal
|
|
119
119
|
};
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
120
|
+
if (input.operation === "move") {
|
|
121
|
+
const current = await dependencies.telemetry.stage("resolve", () => entryLocation(locationRequest));
|
|
122
|
+
if (current.repositoryId === targetRepositoryId && current.folderId === input.request.targetFolderId)
|
|
123
|
+
invalid("already_in_target", "targetFolderId");
|
|
124
|
+
}
|
|
125
125
|
const execution = await dependencies.telemetry.stage("wait", () => (dependencies.operations.execute({
|
|
126
126
|
operation: input.operation,
|
|
127
127
|
context: { entry_id: input.request.entry_id, repository_id: targetRepositoryId, folder_id: input.request.targetFolderId },
|
|
@@ -316,8 +316,8 @@ export function createDamUseCases(dependencies) {
|
|
|
316
316
|
input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
|
|
317
317
|
if (input.kind !== "asset" && input.kind !== "folder")
|
|
318
318
|
invalid("asset_or_folder", "kind");
|
|
319
|
-
if (!nonblank(input.title)
|
|
320
|
-
invalid("
|
|
319
|
+
if (!nonblank(input.title))
|
|
320
|
+
invalid("nonblank", "title");
|
|
321
321
|
const [repository] = await dependencies.telemetry.stage("repository", () => (resolveRepositories({
|
|
322
322
|
...(input.repositoryId === undefined ? {} : { repositoryId: input.repositoryId })
|
|
323
323
|
}, access, signal)));
|
|
@@ -34,7 +34,7 @@ export function createEditorBridgeClient(options) {
|
|
|
34
34
|
async rpc(method, payload, signal) {
|
|
35
35
|
const value = await request("/rpc", "POST", { method, ...(payload === undefined ? {} : { payload }) }, signal);
|
|
36
36
|
if (!isRecord(value) ||
|
|
37
|
-
(!hasExactKeys(value, []) && !
|
|
37
|
+
(!hasExactKeys(value, []) && (!Object.hasOwn(value, "result") || Object.hasOwn(value, "error")))) {
|
|
38
38
|
throw invalidResponse();
|
|
39
39
|
}
|
|
40
40
|
return value.result;
|
|
@@ -22,7 +22,9 @@ export function createEditorUseCases(dependencies) {
|
|
|
22
22
|
return result;
|
|
23
23
|
},
|
|
24
24
|
async snapshot({ signal }) {
|
|
25
|
-
const
|
|
25
|
+
const raw = await dependencies.session.rpc("snapshot", undefined, signal);
|
|
26
|
+
const result = raw && typeof raw === "object" && "elements" in raw && "selectedIds" in raw
|
|
27
|
+
? { elements: raw.elements, selectedIds: raw.selectedIds } : raw;
|
|
26
28
|
validate.snapshot(result);
|
|
27
29
|
return result;
|
|
28
30
|
},
|
|
@@ -50,14 +52,10 @@ export function createEditorUseCases(dependencies) {
|
|
|
50
52
|
},
|
|
51
53
|
async save({ signal }) {
|
|
52
54
|
const raw = await dependencies.session.rpc("save", undefined, signal);
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const result = {
|
|
56
|
-
...raw,
|
|
57
|
-
url: toPublicEditorUrl(url).href
|
|
58
|
-
};
|
|
55
|
+
const result = raw && typeof raw === "object" && "workId" in raw && "url" in raw
|
|
56
|
+
? { workId: raw.workId, url: raw.url } : raw;
|
|
59
57
|
validate.save(result);
|
|
60
|
-
return result;
|
|
58
|
+
return { workId: result.workId, url: toPublicEditorUrl(safeEditorResultUrl(result.url)).href };
|
|
61
59
|
}
|
|
62
60
|
};
|
|
63
61
|
}
|