@insmind/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.
Files changed (66) hide show
  1. package/README.md +5 -0
  2. package/contracts/operations/credits.get/input.schema.json +8 -0
  3. package/contracts/operations/credits.get/output.schema.json +92 -0
  4. package/contracts/operations/credits.usage.get/input.schema.json +17 -0
  5. package/contracts/operations/credits.usage.get/output.schema.json +46 -0
  6. package/contracts/operations/credits.usage.list/input.schema.json +27 -0
  7. package/contracts/operations/credits.usage.list/output.schema.json +135 -0
  8. package/dist/bin/insmind-cli.js +2 -2
  9. package/dist/src/bootstrap/create-cli.js +28 -24
  10. package/dist/src/bootstrap/create-runtime.js +31 -18
  11. package/dist/src/bootstrap/run-task-worker.js +2 -1
  12. package/dist/src/bootstrap/validators.js +7 -2
  13. package/dist/src/cli/action-binding.js +42 -13
  14. package/dist/src/cli/agent-commands.js +8 -12
  15. package/dist/src/cli/credits-command.js +127 -16
  16. package/dist/src/cli/dam-commands.js +3 -2
  17. package/dist/src/cli/editor-commands.js +10 -5
  18. package/dist/src/cli/host-input.js +34 -0
  19. package/dist/src/cli/model-commands.js +4 -3
  20. package/dist/src/cli/presenter.js +4 -0
  21. package/dist/src/cli/tool-commands.js +7 -9
  22. package/dist/src/cli/update-command.js +24 -1
  23. package/dist/src/contracts/creation-input.js +20 -0
  24. package/dist/src/features/agent/creative-protocol.js +12 -14
  25. package/dist/src/features/agent/use-cases.js +6 -31
  26. package/dist/src/features/auth/access-policy.js +1 -3
  27. package/dist/src/features/auth/sso-service.js +6 -4
  28. package/dist/src/features/auth/use-cases.js +2 -1
  29. package/dist/src/features/credits/amount.js +51 -0
  30. package/dist/src/features/credits/response.js +11 -0
  31. package/dist/src/features/credits/use-cases.js +174 -31
  32. package/dist/src/features/dam/file-downloader.js +2 -1
  33. package/dist/src/features/dam/use-cases.js +7 -7
  34. package/dist/src/features/editor/bridge-client.js +1 -1
  35. package/dist/src/features/editor/use-cases.js +6 -8
  36. package/dist/src/features/org/use-cases.js +3 -3
  37. package/dist/src/features/skill/installer.js +24 -22
  38. package/dist/src/features/task/store.js +26 -12
  39. package/dist/src/features/task/use-cases.js +97 -82
  40. package/dist/src/features/tool/canvas-models.js +21 -4
  41. package/dist/src/features/tool/canvas-tool-adapter.js +29 -20
  42. package/dist/src/features/tool/canvas-video.js +2 -4
  43. package/dist/src/features/tool/dynamic-schema.js +29 -64
  44. package/dist/src/features/tool/mns-catalog-adapter.js +9 -2
  45. package/dist/src/features/tool/scene-catalog-adapter.js +0 -1
  46. package/dist/src/features/tool/tool-api-adapter.js +2 -2
  47. package/dist/src/features/tool/use-cases.js +24 -35
  48. package/dist/src/features/update/check-schema.js +17 -0
  49. package/dist/src/features/update/host-receipt.js +30 -0
  50. package/dist/src/features/update/notice-output.js +30 -0
  51. package/dist/src/features/update/update-lock.js +80 -0
  52. package/dist/src/features/update/update-notification.js +129 -240
  53. package/dist/src/platform/json-input.js +1 -1
  54. package/dist/src/platform/safe-upload-file.js +6 -0
  55. package/dist/src/platform/signature.js +3 -1
  56. package/dist/src/platform/signed-http-transport.js +34 -32
  57. package/dist/src/telemetry/host-diagnostics.js +2 -2
  58. package/dist/src/telemetry/invocation.js +87 -24
  59. package/dist/src/telemetry/process-errors.js +36 -3
  60. package/dist/src/telemetry/sls-sink.js +7 -10
  61. package/package.json +4 -4
  62. package/skills/insmind-cli/SKILL.md +2 -0
  63. package/skills/insmind-cli/references/editor.md +1 -1
  64. package/skills/insmind-cli/references/generation-constraints.md +3 -1
  65. package/skills/insmind-cli/references/tool.md +2 -3
  66. package/skills/insmind-cli/references/update.md +2 -0
@@ -1,6 +1,4 @@
1
- import { findModel, ToolInputError } from "../tool/catalog.js";
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 catalog = await dependencies.telemetry.stage("catalog", () => (dependencies.catalog.load({ access, signal })));
57
- signal.throwIfAborted();
58
- if (catalog.warnings.length)
59
- dependencies.telemetry.annotate({ warning_codes: ["MODEL_CATALOG_INCOMPLETE"], invalid_model_count: catalog.invalidModelCount });
60
- for (const warning of catalog.warnings)
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 === undefined
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 || !expiresInSeconds || !intervalSeconds) {
125
+ if (!authorizeCode || !deviceCode || !intervalSeconds) {
126
126
  throw invalidFields(response, "authorize", { authorize_code: authorizeCode, device_code: deviceCode,
127
- expires_in: expiresInSeconds, interval: intervalSeconds });
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
- return text && !Number.isNaN(Date.parse(text)) ? text : undefined;
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
- dependencies.telemetry.annotate({ auth_server_expires_in_s: authorization.expiresInSeconds });
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
- 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();
40
- const candidates = [value.GAODOU, value.data, isRecord(value.data) ? value.data.GAODOU : undefined];
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 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);
@@ -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
- return truncateFilename(`${stem}-${index + 1}${extension}`);
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
- const current = await dependencies.telemetry.stage("resolve", () => (entryLocation(locationRequest)));
121
- if (input.operation === "move"
122
- && current.repositoryId === targetRepositoryId
123
- && current.folderId === input.request.targetFolderId)
124
- invalid("already_in_target", "targetFolderId");
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) || input.title.length > 100)
320
- invalid("nonblank_max_100", "title");
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, []) && !hasExactKeys(value, ["result"]))) {
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 result = await dependencies.session.rpc("snapshot", undefined, signal);
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
- validate.save(raw);
54
- const url = safeEditorResultUrl(raw.url);
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
  }
@@ -113,19 +113,19 @@ export function createOrgUseCases(dependencies) {
113
113
  }
114
114
  const records = await dependencies.org.list(input.credential, input.signal);
115
115
  const record = records.find((candidate) => candidate.id === organizationId);
116
- if (!record?.realName)
116
+ if (!record)
117
117
  return null;
118
118
  const bound = await bind(input.credential, record, input.signal);
119
119
  return {
120
120
  id: bound.id,
121
- name: record.realName,
121
+ name: record.realName || record.id,
122
122
  ...(bound.bindExpiresAt ? { bindExpiresAt: bound.bindExpiresAt } : {})
123
123
  };
124
124
  }
125
125
  catch (error) {
126
126
  if (isInterruption(error, input.signal))
127
127
  throw input.signal.reason;
128
- if (isExpectedAuthorizationFailure(error))
128
+ if (dependencies.singleOrganizationName === undefined && isExpectedAuthorizationFailure(error))
129
129
  return null;
130
130
  throw error;
131
131
  }
@@ -31,35 +31,37 @@ export async function syncBundledSkills(skills, options = {}) {
31
31
  }
32
32
  targetResults.push(current);
33
33
  for (const target of targets.slice(1)) {
34
- current = await inspectTarget(target, skill, canonical.path, platform);
35
- if (current.status === "conflict" || current.status === "broken") {
34
+ try {
35
+ current = await inspectTarget(target, skill, canonical.path, platform);
36
+ if (current.status === "conflict" || current.status === "broken") {
37
+ targetResults.push(current);
38
+ continue;
39
+ }
40
+ if (current.status === "missing") {
41
+ current = await createLinkOrCopy(skill, target, canonical.path, {
42
+ platform,
43
+ createLink: options.createLink ?? symlink
44
+ });
45
+ }
46
+ else if (current.status === "outdated") {
47
+ await replaceManagedDirectory(skill, target.path, true);
48
+ current = installed(target, "copy", true);
49
+ }
36
50
  targetResults.push(current);
37
- throw new Error(current.reason ?? "Agent host Skill conflict");
38
51
  }
39
- if (current.status === "missing") {
40
- current = await createLinkOrCopy(skill, target, canonical.path, {
41
- platform,
42
- createLink: options.createLink ?? symlink
43
- });
52
+ catch (error) {
53
+ targetResults.push({ host: target.host, path: target.path, status: "conflict", changed: false, reason: message(error) });
44
54
  }
45
- else if (current.status === "outdated") {
46
- await replaceManagedDirectory(skill, target.path, true);
47
- current = installed(target, "copy", true);
48
- }
49
- targetResults.push(current);
50
55
  }
56
+ const conflict = targetResults.find(target => target.status === "conflict" || target.status === "broken");
57
+ if (conflict)
58
+ throw new Error(conflict.reason ?? conflict.path);
51
59
  results.push(syncResult(skill, targetResults));
52
60
  }
53
61
  catch (error) {
54
- const active = targets[targetResults.length];
55
- if (active && !targetResults.some((target) => target.host === active.host)) {
56
- targetResults.push({
57
- host: active.host,
58
- path: active.path,
59
- status: "conflict",
60
- changed: false,
61
- reason: message(error)
62
- });
62
+ const active = targetResults.find(target => target.status === "conflict" || target.status === "broken") ?? targets[0];
63
+ if (active && !targetResults.some(target => target.host === active.host)) {
64
+ targetResults.push({ host: active.host, path: active.path, status: "conflict", changed: false, reason: message(error) });
63
65
  }
64
66
  results.push(syncResult(skill, targetResults));
65
67
  throw new SkillSyncError(`Agent Skill ${skill.skill} 同步失败${active ? ` (${active.path})` : ""}: ${message(error)}`, results);
@@ -16,14 +16,14 @@ export function taskScope(state) {
16
16
  ])).digest("hex");
17
17
  }
18
18
  export function createTaskStore(options) {
19
- const root = join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd", "tasks");
19
+ const root = join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd", "tasks", "v6");
20
20
  function file(scope, id) {
21
21
  if (!/^[a-f0-9]{64}$/u.test(scope) || !validTaskId(id))
22
22
  throw new LocalFileError(undefined);
23
23
  return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json`, role: "task" });
24
24
  }
25
25
  const store = {
26
- async read(scope, id) {
26
+ async read(scope, id, summaryOnly = false) {
27
27
  const stateFile = file(scope, id);
28
28
  try {
29
29
  const stat = await lstat(join(root, scope, `${id}.json`));
@@ -47,7 +47,22 @@ export function createTaskStore(options) {
47
47
  if (record.version !== 1 || record.task.taskId !== id || !record.progress
48
48
  || typeof record.progress !== "object" || Array.isArray(record.progress))
49
49
  throw new Error();
50
+ if (summaryOnly && options.validateSummary) {
51
+ const { result, partialResult, ...summary } = record.task;
52
+ options.validateSummary(summary);
53
+ record.task = summary;
54
+ return record;
55
+ }
50
56
  options.validate(record.task);
57
+ if (record.telemetry) {
58
+ const { context, steps } = record.telemetry;
59
+ if (context?.schema_version !== "6" || !context.trace_id || !Array.isArray(steps)
60
+ || steps.some(item => typeof item?.enqueued !== "boolean" || item.event?.event_name !== "command_step"
61
+ || item.event.schema_version !== "6" || item.event.trace_id !== context.trace_id
62
+ || !["request_sent", "result_received", "delivered"].includes(item.event.step))) {
63
+ throw new Error("Invalid task telemetry");
64
+ }
65
+ }
51
66
  for (const key of ["contextId", "localMessageId", "remoteTaskId"]) {
52
67
  if (record.progress[key] !== undefined && typeof record.progress[key] !== "string")
53
68
  throw new Error();
@@ -74,17 +89,16 @@ export function createTaskStore(options) {
74
89
  }
75
90
  if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed"))
76
91
  record.task = previous.task;
77
- if (previous.failureCorrection)
78
- record.failureCorrection = previous.failureCorrection;
79
92
  if (previous.analytics)
80
93
  record.analytics = { ...record.analytics, ...previous.analytics };
81
- if (previous.telemetry)
82
- record.telemetry = {
83
- ...record.telemetry, ...previous.telemetry,
84
- context: previous.telemetry.states?.length || previous.telemetry.request_sent ? previous.telemetry.context : record.telemetry?.context ?? previous.telemetry.context,
85
- states: [...new Map([...(record.telemetry?.states ?? []), ...(previous.telemetry.states ?? [])]
86
- .map(event => [event.task_revision, event])).values()].sort((a, b) => a.task_revision - b.task_revision)
87
- };
94
+ if (previous.telemetry) {
95
+ const steps = [...previous.telemetry.steps];
96
+ for (const item of record.telemetry?.steps ?? []) {
97
+ if (!steps.some(saved => saved.event.step === item.event.step))
98
+ steps.push(item);
99
+ }
100
+ record.telemetry = { ...previous.telemetry, steps };
101
+ }
88
102
  }
89
103
  options.validate(record.task);
90
104
  await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
@@ -116,7 +130,7 @@ export function createTaskStore(options) {
116
130
  for (const name of names) {
117
131
  if (!name.endsWith(".json") || !validTaskId(name.slice(0, -5)))
118
132
  continue;
119
- const record = await store.read(scope, name.slice(0, -5));
133
+ const record = await store.read(scope, name.slice(0, -5), true);
120
134
  if (record)
121
135
  records.push(record);
122
136
  }