@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.
Files changed (67) hide show
  1. package/README.md +5 -0
  2. package/contracts/operations/credits.get/input.schema.json +9 -0
  3. package/contracts/operations/credits.get/output.schema.json +107 -0
  4. package/contracts/operations/credits.usage.get/input.schema.json +18 -0
  5. package/contracts/operations/credits.usage.get/output.schema.json +53 -0
  6. package/contracts/operations/credits.usage.list/input.schema.json +32 -0
  7. package/contracts/operations/credits.usage.list/output.schema.json +144 -0
  8. package/dist/bin/gd-cli.js +2 -2
  9. package/dist/bin/insmind-cli.js +2 -2
  10. package/dist/src/bootstrap/create-cli.js +28 -24
  11. package/dist/src/bootstrap/create-runtime.js +31 -18
  12. package/dist/src/bootstrap/run-task-worker.js +2 -1
  13. package/dist/src/bootstrap/validators.js +7 -2
  14. package/dist/src/cli/action-binding.js +42 -13
  15. package/dist/src/cli/agent-commands.js +8 -12
  16. package/dist/src/cli/credits-command.js +127 -16
  17. package/dist/src/cli/dam-commands.js +3 -2
  18. package/dist/src/cli/editor-commands.js +10 -5
  19. package/dist/src/cli/host-input.js +34 -0
  20. package/dist/src/cli/model-commands.js +4 -3
  21. package/dist/src/cli/presenter.js +4 -0
  22. package/dist/src/cli/tool-commands.js +7 -9
  23. package/dist/src/cli/update-command.js +24 -1
  24. package/dist/src/contracts/creation-input.js +20 -0
  25. package/dist/src/features/agent/creative-protocol.js +12 -14
  26. package/dist/src/features/agent/use-cases.js +6 -31
  27. package/dist/src/features/auth/access-policy.js +1 -3
  28. package/dist/src/features/auth/sso-service.js +6 -4
  29. package/dist/src/features/auth/use-cases.js +2 -1
  30. package/dist/src/features/credits/amount.js +51 -0
  31. package/dist/src/features/credits/response.js +11 -0
  32. package/dist/src/features/credits/use-cases.js +174 -31
  33. package/dist/src/features/dam/file-downloader.js +2 -1
  34. package/dist/src/features/dam/use-cases.js +7 -7
  35. package/dist/src/features/editor/bridge-client.js +1 -1
  36. package/dist/src/features/editor/use-cases.js +6 -8
  37. package/dist/src/features/org/use-cases.js +3 -3
  38. package/dist/src/features/skill/installer.js +24 -22
  39. package/dist/src/features/task/store.js +26 -12
  40. package/dist/src/features/task/use-cases.js +97 -82
  41. package/dist/src/features/tool/canvas-models.js +21 -4
  42. package/dist/src/features/tool/canvas-tool-adapter.js +29 -20
  43. package/dist/src/features/tool/canvas-video.js +2 -4
  44. package/dist/src/features/tool/dynamic-schema.js +29 -64
  45. package/dist/src/features/tool/mns-catalog-adapter.js +9 -2
  46. package/dist/src/features/tool/scene-catalog-adapter.js +0 -1
  47. package/dist/src/features/tool/tool-api-adapter.js +2 -2
  48. package/dist/src/features/tool/use-cases.js +24 -35
  49. package/dist/src/features/update/check-schema.js +17 -0
  50. package/dist/src/features/update/host-receipt.js +30 -0
  51. package/dist/src/features/update/notice-output.js +30 -0
  52. package/dist/src/features/update/update-lock.js +80 -0
  53. package/dist/src/features/update/update-notification.js +129 -240
  54. package/dist/src/platform/json-input.js +1 -1
  55. package/dist/src/platform/safe-upload-file.js +6 -0
  56. package/dist/src/platform/signature.js +3 -1
  57. package/dist/src/platform/signed-http-transport.js +34 -32
  58. package/dist/src/telemetry/host-diagnostics.js +2 -2
  59. package/dist/src/telemetry/invocation.js +87 -24
  60. package/dist/src/telemetry/process-errors.js +36 -3
  61. package/dist/src/telemetry/sls-sink.js +7 -10
  62. package/package.json +4 -4
  63. package/skills/gd-cli/SKILL.md +2 -0
  64. package/skills/gd-cli/references/editor.md +1 -1
  65. package/skills/gd-cli/references/generation-constraints.md +3 -1
  66. package/skills/gd-cli/references/tool.md +2 -3
  67. package/skills/gd-cli/references/update.md +6 -0
@@ -1,6 +1,5 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import addFormatsImport, {} from "ajv-formats";
3
- import { canvasControlParameterNames } from "./canvas-models.js";
4
3
  import { inputValidationSummary, validationIssues } from "../../platform/schema-issues.js";
5
4
  import { canonicalizeInputFileUris } from "../../platform/input-uri.js";
6
5
  import { ToolInputError } from "./catalog.js";
@@ -89,7 +88,7 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
89
88
  type: "object",
90
89
  properties,
91
90
  required: ["model"],
92
- additionalProperties: false,
91
+ additionalProperties: true,
93
92
  allOf: models.map(model => ({ if: { properties: { model: { const: model.model } }, required: ["model"] },
94
93
  then: buildModelArgumentsSchema(model) }))
95
94
  };
@@ -116,76 +115,42 @@ export function buildModelArgumentsSchema(model) {
116
115
  .filter((parameter) => parameter.required)
117
116
  .map((parameter) => parameter.name)
118
117
  ],
119
- additionalProperties: false
118
+ additionalProperties: true
120
119
  };
121
120
  }
122
121
  const ajv = new Ajv2020({ allErrors: true, strict: true });
123
122
  const addFormats = addFormatsImport;
124
123
  addFormats(ajv);
125
- function validator(model) {
126
- return ajv.compile(buildModelArgumentsSchema(model));
127
- }
128
- function controlArgumentsValidator(model) {
129
- const properties = {};
124
+ /** Enforce structure that the CLI actually reads or transforms. Business controls go to the service. */
125
+ export function assertModelArguments(model, value) {
126
+ const published = buildModelArgumentsSchema(model);
127
+ const properties = { model: published.properties.model };
128
+ const required = ["model"];
130
129
  for (const parameter of model.parameters) {
131
- if (parameter.name === "prompt"
132
- || parameter.type === "uri"
133
- || parameter.type === "uri[]"
134
- || (model.execution?.kind === "canvas" && !canvasControlParameterNames.has(parameter.name)))
135
- continue;
136
- properties[parameter.name] = buildModelArgumentsSchema(model).properties[parameter.name];
130
+ if (parameter.type === "uri" || parameter.type === "uri[]") {
131
+ properties[parameter.name] = parameterSchema(parameter);
132
+ if (model.execution?.kind === "canvas" && ["image", "video"].includes(parameter.name))
133
+ required.push(parameter.name);
134
+ }
137
135
  }
138
- return ajv.compile({
139
- type: "object",
140
- properties,
141
- required: [],
142
- additionalProperties: false
143
- });
144
- }
145
- export function assertModelArguments(model, value) {
146
- const validate = validator(model);
147
- canonicalizeInputFileUris(value, validate.schema);
136
+ if (model.execution?.kind === "canvas") {
137
+ for (const key of ["canvas", "placement", "cropToSubject"]) {
138
+ if (published.properties[key])
139
+ properties[key] = published.properties[key];
140
+ if (published.required.includes(key))
141
+ required.push(key);
142
+ }
143
+ if (model.model === "image-text-edit") {
144
+ properties.replacements = { type: "array", items: { type: "object", required: ["from", "to"],
145
+ properties: { from: { type: "string" }, to: { type: "string" } } } };
146
+ required.push("replacements");
147
+ }
148
+ }
149
+ const schema = { type: "object", properties, required };
150
+ const validate = ajv.compile(schema);
151
+ canonicalizeInputFileUris(value, schema);
148
152
  if (!validate(value)) {
149
- const issues = validationIssues(validate.errors, value, validate.schema);
153
+ const issues = validationIssues(validate.errors, value, schema);
150
154
  throw Object.assign(new ToolInputError("model_parameters", "/arguments", issues), { diagnosticSummary: inputValidationSummary(issues, value, "/arguments") });
151
155
  }
152
- const stepIssues = sliderStepIssues(model, value);
153
- if (stepIssues.length) {
154
- throw Object.assign(new ToolInputError("model_parameters", "/arguments", stepIssues), { diagnosticSummary: inputValidationSummary(stepIssues, value, "/arguments") });
155
- }
156
- }
157
- function sliderStepIssues(model, value) {
158
- const issues = [];
159
- for (const parameter of model.parameters) {
160
- if (parameter.step === undefined || !Object.hasOwn(value, parameter.name))
161
- continue;
162
- const candidate = value[parameter.name];
163
- const minimum = parameter.minimum;
164
- let valid = false;
165
- if (typeof candidate === "number" && minimum !== undefined && parameter.step > 0) {
166
- const steps = (candidate - minimum) / parameter.step;
167
- const nearestStep = Math.round(steps);
168
- const expected = minimum + nearestStep * parameter.step;
169
- const tolerance = Number.EPSILON * Math.max(1, Math.abs(candidate), Math.abs(expected), Math.abs(minimum), Math.abs(nearestStep * parameter.step)) * 2;
170
- valid = Math.abs(candidate - expected) <= tolerance;
171
- }
172
- if (!valid)
173
- issues.push({
174
- field: `/${parameter.name.replace(/~/gu, "~0").replace(/\//gu, "~1")}`.slice(0, 256),
175
- rule: "step",
176
- message: minimum === undefined || parameter.step <= 0
177
- ? "must match the model's slider configuration"
178
- : `must be ${minimum} plus a whole number of steps of ${parameter.step}`
179
- });
180
- if (issues.length === 8)
181
- break;
182
- }
183
- return issues;
184
- }
185
- export function modelControlArgumentsAreValid(model, value) {
186
- return typeof value === "object"
187
- && value !== null
188
- && !Array.isArray(value)
189
- && controlArgumentsValidator(model)(value)
190
- && sliderStepIssues(model, value).length === 0;
191
156
  }
@@ -187,8 +187,15 @@ function normalizeModel(value, scenes, english = false) {
187
187
  .filter((item) => item !== undefined);
188
188
  const description = cleanText(model.description);
189
189
  const usageDescription = cleanText(model.tool_description);
190
- const mimeTypes = typeof model.output_mime_types === "string"
191
- ? JSON.parse(model.output_mime_types) : model.output_mime_types;
190
+ let mimeTypes = model.output_mime_types;
191
+ if (typeof mimeTypes === "string") {
192
+ try {
193
+ mimeTypes = JSON.parse(mimeTypes);
194
+ }
195
+ catch {
196
+ mimeTypes = undefined;
197
+ }
198
+ }
192
199
  const outputMediaTypes = Array.isArray(mimeTypes)
193
200
  ? mimeTypes.map(text).filter((item) => item !== undefined) : [];
194
201
  const costs = activeSkus
@@ -15,7 +15,6 @@ export function createSceneCatalogAdapter(dependencies) {
15
15
  const cost = scene.is_free === true ? 0 : typeof scene.point_rights === "number" && Number.isFinite(scene.point_rights) && scene.point_rights >= 0 ? scene.point_rights : undefined;
16
16
  if (cost === undefined) {
17
17
  catalog.warnings.push(dependencies.english ? `Current pricing is unavailable for ${binding[1]}.` : `${binding[1]} 的当前报价不可用。`);
18
- continue;
19
18
  }
20
19
  const raw = { tool: binding[0], model: code, title: binding[4], sceneSort: 0, modelSort: 0, parameters: [],
21
20
  ...(cost === undefined ? {} : { cost: { unit: "gaodou", minimum: cost, maximum: cost } }),
@@ -109,7 +109,7 @@ export function normalizeToolContent(value) {
109
109
  if (value.type !== "resource" || !isRecord(value.resource)) {
110
110
  return protocolFailure(value);
111
111
  }
112
- if ("blob" in value.resource || "text" in value.resource)
112
+ if ("blob" in value.resource || ("text" in value.resource && value.resource.text !== ""))
113
113
  return protocolFailure(value);
114
114
  if (typeof value.resource.uri !== "string" || value.resource.uri.trim() === "") {
115
115
  return protocolFailure(value);
@@ -327,7 +327,7 @@ export function createToolApiAdapter(dependencies) {
327
327
  }, parseIntent);
328
328
  return {
329
329
  ...intent,
330
- arguments: withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters)
330
+ arguments: { ...withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters), ...invocation.explicitArguments }
331
331
  };
332
332
  });
333
333
  signal.throwIfAborted();
@@ -93,47 +93,35 @@ export function createToolUseCases(dependencies) {
93
93
  return { invocation: { kind: "canvas", model, arguments: input.arguments }, usage };
94
94
  }
95
95
  const prompt = [];
96
- const requestParameters = {};
97
- const directArguments = {};
96
+ if (Object.hasOwn(parameters, "content_id"))
97
+ throw new ToolInputError("managed_argument", "/arguments/content_id");
98
+ const requestParameters = { ...parameters };
99
+ const directArguments = { ...parameters };
98
100
  const prepare = async () => {
101
+ if (typeof parameters.prompt === "string") {
102
+ prompt.push({ type: "text", content: parameters.prompt });
103
+ delete requestParameters.prompt;
104
+ }
99
105
  for (const parameter of model.parameters) {
100
- signal.throwIfAborted();
101
- const value = input.arguments[parameter.name];
102
- if (value === undefined)
103
- continue;
104
- if (parameter.type === "string") {
105
- if (parameter.name === "prompt") {
106
- prompt.push({ type: "text", content: value });
107
- directArguments[parameter.name] = value;
108
- }
109
- else {
110
- requestParameters[parameter.name] = value;
111
- directArguments[parameter.name] = value;
112
- }
106
+ if (parameter.type !== "uri" && parameter.type !== "uri[]")
113
107
  continue;
114
- }
115
- if (parameter.type === "number") {
116
- requestParameters[parameter.name] = value;
117
- directArguments[parameter.name] = value;
108
+ const value = parameters[parameter.name];
109
+ if (value === undefined)
118
110
  continue;
119
- }
120
- const values = parameter.type === "uri[]" ? value : [value];
121
- for (const mediaUrl of values) {
111
+ const urls = [];
112
+ for (const url of (Array.isArray(value) ? value : [value])) {
122
113
  signal.throwIfAborted();
123
- if (mediaUrl.startsWith("file:")) {
124
- const uploaded = await dependencies.uploader.upload({ url: mediaUrl }, access, signal);
125
- signal.throwIfAborted();
126
- prompt.push({
127
- type: "media",
128
- url: uploaded.url,
129
- mime: uploaded.mediaType,
130
- name: parameter.name
131
- });
132
- }
133
- else {
134
- prompt.push(remoteMedia(mediaUrl, parameter.name));
135
- }
114
+ const media = url.startsWith("file:")
115
+ ? await dependencies.uploader.upload({ url }, access, signal).then(upload => ({
116
+ type: "media", url: upload.url, mime: upload.mediaType, name: parameter.name
117
+ }))
118
+ : remoteMedia(url, parameter.name);
119
+ prompt.push(media);
120
+ urls.push(media.url);
136
121
  }
122
+ // Preserve scalar/array semantics after converting local files to service URLs.
123
+ directArguments[parameter.name] = parameter.type === "uri[]" ? urls : urls[0];
124
+ delete requestParameters[parameter.name];
137
125
  }
138
126
  };
139
127
  const hasLocalMedia = model.parameters.some((parameter) => {
@@ -158,6 +146,7 @@ export function createToolUseCases(dependencies) {
158
146
  model: model.model,
159
147
  prompt,
160
148
  parameters: requestParameters,
149
+ explicitArguments: directArguments,
161
150
  optionalMediaParameters: model.parameters
162
151
  .filter((parameter) => ((parameter.type === "uri" || parameter.type === "uri[]")
163
152
  && !parameter.required))
@@ -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
+ }
@@ -0,0 +1,80 @@
1
+ import { withFileLock } from "../../platform/file-lock.js";
2
+ import { randomUUID } from "node:crypto";
3
+ import * as fileSystem from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ const STALE_LOCK_MS = 30_000;
6
+ export function createLocalUpdateNotificationLock(options) {
7
+ const path = join(options.directory, "update-check.lock");
8
+ return {
9
+ async acquire() {
10
+ await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
11
+ await fileSystem.chmod(options.directory, 0o700);
12
+ const first = await tryCreateLock(path);
13
+ if (first)
14
+ return releaseLock(path, first);
15
+ if (!await isStaleLock(path, options.now()))
16
+ return null;
17
+ // Two recoverers must not both unlink the lock: the first may already have
18
+ // replaced it with a live owner's file when the second resumes.
19
+ return withFileLock(path + ".recovery", async () => {
20
+ if (!await isStaleLock(path, options.now()))
21
+ return null;
22
+ await fileSystem.unlink(path).catch((error) => {
23
+ if (!isMissing(error))
24
+ throw error;
25
+ });
26
+ const recovered = await tryCreateLock(path);
27
+ return recovered ? releaseLock(path, recovered) : null;
28
+ });
29
+ }
30
+ };
31
+ }
32
+ async function tryCreateLock(path) {
33
+ const token = randomUUID();
34
+ let handle;
35
+ try {
36
+ handle = await fileSystem.open(path, "wx", 0o600);
37
+ await handle.writeFile(token, "utf8");
38
+ await handle.sync();
39
+ await handle.close();
40
+ return token;
41
+ }
42
+ catch (error) {
43
+ await handle?.close().catch(() => undefined);
44
+ if (isExists(error))
45
+ return null;
46
+ throw error;
47
+ }
48
+ }
49
+ function releaseLock(path, token) {
50
+ return async () => {
51
+ let current;
52
+ try {
53
+ current = await fileSystem.readFile(path, "utf8");
54
+ }
55
+ catch (error) {
56
+ if (isMissing(error))
57
+ return;
58
+ throw error;
59
+ }
60
+ if (current === token)
61
+ await fileSystem.unlink(path);
62
+ };
63
+ }
64
+ async function isStaleLock(path, now) {
65
+ try {
66
+ const stats = await fileSystem.stat(path);
67
+ return stats.mtimeMs + STALE_LOCK_MS <= now.getTime();
68
+ }
69
+ catch (error) {
70
+ if (isMissing(error))
71
+ return true;
72
+ throw error;
73
+ }
74
+ }
75
+ function isMissing(error) {
76
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
77
+ }
78
+ function isExists(error) {
79
+ return error instanceof Error && "code" in error && error.code === "EEXIST";
80
+ }