@insmind/cli 2.0.0 → 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.
@@ -1,23 +1,134 @@
1
- import { bindAction } from "./action-binding.js";
1
+ import { normalizeCreditsUsageListInput } from "../features/credits/use-cases.js";
2
+ import { contractSchema } from "../contracts/schema.js";
3
+ import { productText as text } from "../product/text.js";
4
+ import { bindPreparedAction } from "./action-binding.js";
5
+ import { CliUsageError } from "./errors.js";
2
6
  export function registerCreditsCommand(program, runtime) {
7
+ const product = runtime.product;
3
8
  const credits = program.command("credits")
4
- .description("Show the current insMind credits balance")
5
- .option("--json", "output JSON")
6
- .allowExcessArguments(false);
7
- bindAction(credits, "organization", async (context, signal) => {
9
+ .description(text(product, "查看当前身份与组织的稿豆余额及变动流水", "Show the current credits balance and usage records"))
10
+ .helpCommand(false);
11
+ presentationOptions(credits, runtime);
12
+ credits.addHelpText("after", text(product, "\n只读当前 CLI 身份和组织的权益概览;不提供跨组织钱包或任意用户查询。available=max(0,total-used),成员周期限额单独展示,不能将权益池余额视为成员实际可用额度。pending 保留服务端 wait,不承诺待生效或冻结。\n流水见 credits usage --help;数量是稿豆,不折算货币。\n", "\nRead-only overview for the current CLI identity and organization context. available=max(0,total-used); member period limits are shown separately and may restrict spendable credits. pending preserves service wait without assuming activation or reservation semantics.\nDiscover records with credits usage --help. Credits are not currency.\n"));
13
+ bindPreparedAction(credits, "organization", async () => {
14
+ if (await showSchemas(credits, runtime, "credits.get"))
15
+ return { handled: true };
16
+ return { handled: false, input: undefined };
17
+ }, async (context, _input, signal) => {
8
18
  const result = await runtime.telemetry.stage("request", () => runtime.credits.get({
9
- credential: context.state.credential,
10
- organizationId: context.state.organization.id,
11
- signal
19
+ credential: context.state.credential, organizationId: context.state.organization.id, signal
20
+ }));
21
+ await runtime.telemetry.stage("output", async () => {
22
+ runtime.validators.creditsOutput(result);
23
+ runtime.presenter.result(result, { json: credits.optsWithGlobals().json === true, view: value => balanceView(value, runtime) });
24
+ });
25
+ }, { operation: "credits.get", mode: () => credits.optsWithGlobals().schema === true ? "schema" : "execute" });
26
+ const usage = credits.command("usage")
27
+ .description(text(product, "查询消费、归还、回收和过期流水", "Query consumption, restoration, recycling and expiry records"))
28
+ .helpCommand(false);
29
+ const list = usage.command("list")
30
+ .description(text(product, "读取指定时间区间的一页流水", "Read one page of records in a time range"))
31
+ .option("--from <timestamp>", text(product, "含起始时刻,带时区 ISO 8601;默认 UTC 本月月首", "inclusive ISO 8601 start with timezone; defaults to current UTC month start"))
32
+ .option("--to <timestamp>", text(product, "含结束时刻,带时区 ISO 8601;默认 UTC 本月月末", "inclusive ISO 8601 end with timezone; defaults to current UTC month end"))
33
+ .option("--limit <number>", text(product, "每页条数,默认 20", "page size, default 20"))
34
+ .option("--cursor <cursor>", text(product, "原样使用上一页 nextCursor,并保持查询区间", "reuse nextCursor unchanged with the same time range"));
35
+ presentationOptions(list, runtime);
36
+ list.addHelpText("after", text(product, "\n只读一页服务端账本,输出实际 UTC 区间、items、hasMore 和 nextCursor。没有总条数或完整区间消费合计;不能把消费、归还、回收和过期数量相加称为消费。RESTORE 为归还稿豆,不代表现金退款;未知类型保留原值,不推断方向。\n首次查询可省略日期,翻页时固定首次返回的 range 和 --limit。单条来源拆分见 credits usage get --help。\n", "\nReads one page of the service ledger, returning its actual UTC range, items, hasMore and nextCursor. No ledger total or range spending total is inferred. Consumption, restoration, recycling and expiry are distinct; RESTORE is a credit restoration, not a cash refund. Unknown types retain their value without an assumed direction.\nDates may be omitted on the first page. Continue with the returned range and the same --limit. Discover source breakdown with credits usage get --help.\n"));
37
+ bindPreparedAction(list, "organization", async () => {
38
+ if (await showSchemas(list, runtime, "credits.usage.list"))
39
+ return { handled: true };
40
+ const options = list.opts();
41
+ try {
42
+ const input = normalizeCreditsUsageListInput({
43
+ ...(options.from === undefined ? {} : { from: options.from }),
44
+ ...(options.to === undefined ? {} : { to: options.to }),
45
+ ...(options.limit === undefined ? {} : { limit: Number(options.limit) }),
46
+ ...(options.cursor === undefined ? {} : { cursor: options.cursor })
47
+ }, runtime.now());
48
+ return { handled: false, input };
49
+ }
50
+ catch (error) {
51
+ if (error instanceof RangeError)
52
+ throw new CliUsageError();
53
+ throw error;
54
+ }
55
+ }, async (context, input, signal) => {
56
+ const result = await runtime.telemetry.stage("request", () => runtime.credits.listUsage({
57
+ input, credential: context.state.credential, organizationId: context.state.organization.id, signal
58
+ }));
59
+ await runtime.telemetry.stage("output", async () => {
60
+ runtime.validators.creditsUsageListOutput(result);
61
+ runtime.presenter.result(result, { json: list.optsWithGlobals().json === true, view: value => usageListView(value, input.limit, runtime) });
62
+ });
63
+ }, { operation: "credits.usage.list", mode: () => list.optsWithGlobals().schema === true ? "schema" : "execute" });
64
+ const get = usage.command("get")
65
+ .description(text(product, "按流水 ID 读取来源拆分", "Read source breakdown by record ID"))
66
+ .argument("[record-id]", text(product, "流水 ID;执行查询时必填", "record ID, required for execution"));
67
+ presentationOptions(get, runtime);
68
+ get.addHelpText("after", text(product, "\n直接查询服务端单条来源拆分,不重新扫描流水。旧记录或某些变动类型可能没有来源拆分;空 breakdown 不表示该记录消费为零。usageType=1 为消费、2 为归还,其他值不推断方向。\n", "\nQueries one record directly without rescanning the ledger. Legacy records or some change types may have no source breakdown; an empty breakdown does not mean zero consumption. usageType=1 means consumption, 2 restoration; other values have no assumed direction.\n"));
69
+ bindPreparedAction(get, "organization", async () => {
70
+ if (await showSchemas(get, runtime, "credits.usage.get"))
71
+ return { handled: true };
72
+ const id = get.processedArgs[0];
73
+ if (typeof id !== "string" || id.trim() === "" || id === "." || id === "..")
74
+ throw new CliUsageError();
75
+ return { handled: false, input: { id } };
76
+ }, async (context, input, signal) => {
77
+ const result = await runtime.telemetry.stage("request", () => runtime.credits.getUsage({
78
+ input, credential: context.state.credential, organizationId: context.state.organization.id, signal
12
79
  }));
13
80
  await runtime.telemetry.stage("output", async () => {
14
- runtime.presenter.result(result, {
15
- json: credits.opts().json === true,
16
- view: (value) => {
17
- const balance = value;
18
- return `${balance.credits.available} insMind credits available`;
19
- }
20
- });
81
+ runtime.validators.creditsUsageGetOutput(result);
82
+ runtime.presenter.result(result, { json: get.optsWithGlobals().json === true, view: value => usageGetView(value, runtime) });
21
83
  });
22
- }, { operation: "credits.get" });
84
+ }, { operation: "credits.usage.get", mode: () => get.optsWithGlobals().schema === true ? "schema" : "execute" });
85
+ }
86
+ function presentationOptions(command, runtime) {
87
+ command.option("--json", text(runtime.product, "输出 JSON", "output JSON"))
88
+ .option("--schema", text(runtime.product, "输出本地 inputSchema 与 outputSchema,无需登录,不执行查询", "output local inputSchema and outputSchema without login or execution"))
89
+ .allowExcessArguments(false);
90
+ }
91
+ async function showSchemas(command, runtime, operation) {
92
+ if (command.optsWithGlobals().schema !== true)
93
+ return false;
94
+ await runtime.telemetry.stage("output", async () => {
95
+ runtime.io.writeOut(`${JSON.stringify({ inputSchema: contractSchema(operation, "input"), outputSchema: contractSchema(operation, "output") })}\n`);
96
+ });
97
+ return true;
98
+ }
99
+ function balanceView(result, runtime) {
100
+ const english = runtime.product.id === "insmind";
101
+ const unit = english ? "credits" : "稿豆";
102
+ const balance = result.credits;
103
+ return [english ? `${balance.available} ${unit} available in the overview` : `概览余额:${balance.available} ${unit}`,
104
+ `total=${balance.total}, used=${balance.used}, pending(wait)=${balance.pending}`,
105
+ ...(result.balances ?? []).map(row => [row.identifier ?? "—", `total=${row.total}`, `used=${row.used}`, `pending(wait)=${row.pending}`, `available=${row.available}`,
106
+ ...(row.memberPeriodLimit === undefined ? [] : [english ? `member period limit=${row.memberPeriodLimit}` : `成员周期限额=${row.memberPeriodLimit}`])].join(" · ")),
107
+ ...(result.balances?.some(row => row.memberPeriodLimit !== undefined) ? [english
108
+ ? "Member limits are separate; the overview balance does not guarantee spendable credits."
109
+ : "成员限额单独生效,概览余额不保证当前成员可用数量。"] : [])
110
+ ].join("\n");
111
+ }
112
+ function usageListView(result, limit, runtime) {
113
+ const product = runtime.product;
114
+ const unit = product.id === "gaoding" ? "稿豆" : "credits";
115
+ const more = result.hasMore ? `${product.commandName} credits usage list --from ${quote(result.range.from)} --to ${quote(result.range.to)} --limit ${limit} --cursor ${quote(result.nextCursor)} --json`
116
+ : text(product, "已到末页", "End of records");
117
+ return [`${result.range.from} → ${result.range.to} (UTC)`,
118
+ ...result.items.map(row => `${row.recordedAt} · ${row.id} · ${row.changeType} · ${signedAmount(row.amount, row.changeType)} ${unit}${row.description ? ` · ${row.description}` : ""}`),
119
+ ...(result.items.length ? [] : [text(product, "本页无记录", "No records on this page")]),
120
+ `${text(product, "本页条数", "Page count")}: ${result.items.length}; hasMore=${result.hasMore}`,
121
+ more, text(product, "本页不是区间消费总计;完整字段见 --json。", "This page is not a range spending total. Use --json for all fields.")].join("\n");
122
+ }
123
+ function usageGetView(result, runtime) {
124
+ const product = runtime.product;
125
+ const unit = product.id === "gaoding" ? "稿豆" : "credits";
126
+ return [result.id, ...result.breakdown.map(row => `${row.sourceType ?? text(product, "来源未知", "Unknown source")} · usageType=${row.usageType ?? "?"} · ${row.usageType === 2 ? "+" : row.usageType === 1 ? "-" : ""}${row.amount} ${unit}`),
127
+ ...(result.breakdown.length ? [] : [text(product, "服务端未提供拆分,不代表消耗为零。", "No breakdown returned; this does not mean zero consumption.")])].join("\n");
128
+ }
129
+ function signedAmount(amount, type) {
130
+ if (amount === 0)
131
+ return "0";
132
+ return `${type === "RESTORE" ? "+" : ["CONSUME", "RECYCLE", "EXPIRE"].includes(type) ? "-" : ""}${amount}`;
23
133
  }
134
+ function quote(value) { return `'${value.replaceAll("'", "'\\''")}'`; }
@@ -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) {
@@ -1,4 +1,6 @@
1
- import { bindAction } from "./action-binding.js";
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,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,39 +1,114 @@
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
- const body = await options.transport.getJson({
6
- path: "/trade/rights-overview",
7
- query: { goods_type_enums: "GAODOU" },
8
- credential: input.credential,
9
- organizationId: input.organizationId,
10
- signal: input.signal
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
- const source = findCreditsRecord(body);
13
- const total = number(source.total);
14
- const used = number(source.used);
15
- const pending = number(source.wait);
16
- if (total === undefined || used === undefined || pending === undefined) {
17
- throw new RemoteProtocolError();
18
- }
19
- return {
20
- credits: {
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
- total,
23
- used,
24
- pending,
25
- available: Math.max(0, total - used)
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
- function findCreditsRecord(value) {
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 record = value.find((candidate) => (isRecord(candidate) && candidate.goods_type_enum === "GAODOU"));
34
- if (!record)
108
+ const records = value.filter((candidate) => (isRecord(candidate) && candidate.goods_type_enum === "GAODOU"));
109
+ if (!records.length)
35
110
  throw new RemoteProtocolError();
36
- return record;
111
+ return records;
37
112
  }
38
113
  if (!isRecord(value))
39
114
  throw new RemoteProtocolError();
@@ -41,13 +116,81 @@ function findCreditsRecord(value) {
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 number(value) {
47
- if (typeof value !== "number" && (typeof value !== "string" || value.trim() === ""))
155
+ function optionalString(value) {
156
+ if (value == null)
48
157
  return undefined;
49
- const parsed = typeof value === "number" ? value : Number(value);
50
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
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);
@@ -0,0 +1,17 @@
1
+ // Local CLI output contract exposed by `update check --schema`.
2
+ export const updateCheckSchema = {
3
+ $schema: "https://json-schema.org/draft/2020-12/schema",
4
+ type: "object",
5
+ additionalProperties: false,
6
+ required: ["status", "currentVersion"],
7
+ properties: {
8
+ status: { enum: ["available", "current", "managed", "unknown"] },
9
+ currentVersion: { type: "string" }, latestVersion: { type: "string" },
10
+ updateCommand: { type: "string" }, notice: { type: "string" }
11
+ },
12
+ oneOf: [
13
+ { properties: { status: { const: "available" } }, required: ["latestVersion", "updateCommand"] },
14
+ { properties: { status: { const: "current" }, notice: false, updateCommand: false }, required: ["latestVersion"] },
15
+ { properties: { status: { enum: ["managed", "unknown"] }, latestVersion: false, updateCommand: false, notice: false } }
16
+ ]
17
+ };
@@ -0,0 +1,30 @@
1
+ // An IPC-enabled connector confirms that the notice reached its own stdout before the
2
+ // CLI spends its shared display window. Direct CLI / Skill calls use stdout acknowledgement.
3
+ export function waitForHostReceipt(signal, notice) {
4
+ if (!process.send || process.env.CLI_UPDATE_NOTICE_FORMAT !== "receipt")
5
+ return Promise.resolve();
6
+ return new Promise((resolve, reject) => {
7
+ const failed = () => finish(new Error("Host did not deliver the update notice"));
8
+ const received = (value) => { if (value === "CLI_UPDATE_DISPLAYED")
9
+ finish(); };
10
+ const timer = setTimeout(failed, 2_000);
11
+ function finish(error) {
12
+ clearTimeout(timer);
13
+ signal.removeEventListener("abort", failed);
14
+ process.off("disconnect", failed);
15
+ process.off("message", received);
16
+ if (error)
17
+ reject(error);
18
+ else
19
+ resolve();
20
+ }
21
+ process.on("message", received);
22
+ process.once("disconnect", failed);
23
+ signal.addEventListener("abort", failed, { once: true });
24
+ if (!process.connected || signal.aborted)
25
+ failed();
26
+ else
27
+ process.send({ code: "CLI_UPDATE_READY", notice }, error => { if (error)
28
+ failed(); });
29
+ });
30
+ }
@@ -0,0 +1,30 @@
1
+ import { fstatSync } from "node:fs";
2
+ export function sameTerminal(stdout, stderr) {
3
+ if (stdout === stderr)
4
+ return true;
5
+ if (stdout !== process.stdout || stderr !== process.stderr || !process.stdout.isTTY || !process.stderr.isTTY)
6
+ return false;
7
+ try {
8
+ const a = fstatSync(1), b = fstatSync(2);
9
+ return a.rdev !== 0 && a.dev === b.dev && a.rdev === b.rdev && a.ino === b.ino;
10
+ }
11
+ catch {
12
+ return false;
13
+ }
14
+ }
15
+ export function noticeWriter(stdout, stderr, shared, structured, label) {
16
+ return async (message, output) => {
17
+ const text = label + message + "\n";
18
+ const diagnostic = structured ? JSON.stringify({ notice: { code: "CLI_UPDATE_AVAILABLE", message } }) + "\n" : text;
19
+ async function send(sink, line) {
20
+ sink.write(line);
21
+ await sink.flush();
22
+ }
23
+ const writes = [send(stderr, diagnostic)];
24
+ if (output === "text" && !shared && !structured)
25
+ writes.push(send(stdout, text));
26
+ const results = await Promise.allSettled(writes);
27
+ if (results.every(result => result.status === "rejected"))
28
+ throw new Error("Update notice could not be delivered");
29
+ };
30
+ }