@gaoding/cli 1.1.0 → 1.3.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 (65) hide show
  1. package/contracts/operations/task.get/input.schema.json +14 -0
  2. package/contracts/operations/task.get/output.schema.json +103 -0
  3. package/contracts/operations/task.list/input.schema.json +18 -0
  4. package/contracts/operations/task.list/output.schema.json +53 -0
  5. package/dist/bin/agent-worker.js +41 -0
  6. package/dist/bin/gd-cli.js +2 -1
  7. package/dist/bin/insmind-cli.js +60 -0
  8. package/dist/bin/postinstall.js +1 -1
  9. package/dist/src/bootstrap/create-cli.js +16 -4
  10. package/dist/src/bootstrap/create-runtime.js +190 -33
  11. package/dist/src/bootstrap/run-agent-worker.js +37 -0
  12. package/dist/src/bootstrap/validators.js +17 -5
  13. package/dist/src/cli/agent-commands.js +40 -14
  14. package/dist/src/cli/auth-commands.js +13 -10
  15. package/dist/src/cli/credits-command.js +23 -0
  16. package/dist/src/cli/dam-commands.js +70 -69
  17. package/dist/src/cli/editor-commands.js +12 -11
  18. package/dist/src/cli/errors.js +60 -9
  19. package/dist/src/cli/model-commands.js +6 -5
  20. package/dist/src/cli/presenter.js +24 -6
  21. package/dist/src/cli/task-commands.js +48 -0
  22. package/dist/src/cli/tool-commands.js +38 -14
  23. package/dist/src/cli/update-command.js +4 -3
  24. package/dist/src/features/agent/creative-agent-adapter.js +9 -3
  25. package/dist/src/features/agent/creative-protocol.js +5 -16
  26. package/dist/src/features/agent/creative-stream.js +12 -1
  27. package/dist/src/features/agent/filems-resource-auth-key-provider.js +23 -0
  28. package/dist/src/features/agent/resource-authorizer.js +47 -0
  29. package/dist/src/features/agent/result-reader.js +30 -0
  30. package/dist/src/features/agent/use-cases.js +98 -95
  31. package/dist/src/features/auth/credential-store.js +1 -1
  32. package/dist/src/features/auth/sso-service.js +3 -1
  33. package/dist/src/features/auth/use-cases.js +38 -12
  34. package/dist/src/features/credits/use-cases.js +52 -0
  35. package/dist/src/features/dam/storage-upload.js +1 -1
  36. package/dist/src/features/editor/bridge-process.js +11 -4
  37. package/dist/src/features/editor/session-state.js +1 -1
  38. package/dist/src/features/editor/session.js +14 -8
  39. package/dist/src/features/org/use-cases.js +7 -0
  40. package/dist/src/features/skill/bundled-skills.js +13 -5
  41. package/dist/src/features/task/agent-background.js +63 -0
  42. package/dist/src/features/task/store.js +97 -0
  43. package/dist/src/features/task/types.js +1 -0
  44. package/dist/src/features/task/use-cases.js +139 -0
  45. package/dist/src/features/tool/catalog.js +13 -13
  46. package/dist/src/features/tool/tool-api-adapter.js +53 -36
  47. package/dist/src/features/tool/use-cases.js +111 -108
  48. package/dist/src/features/update/latest-version.js +2 -2
  49. package/dist/src/features/update/update-notification.js +10 -3
  50. package/dist/src/features/update/update-service.js +57 -23
  51. package/dist/src/platform/resource-auth-key.js +1 -0
  52. package/dist/src/platform/signed-http-transport.js +1 -0
  53. package/dist/src/platform/task-observer.js +1 -0
  54. package/dist/src/product/billing.js +47 -0
  55. package/dist/src/product/config.js +85 -0
  56. package/dist/src/product/locale.js +38 -0
  57. package/dist/src/product/text.js +3 -0
  58. package/dist/src/telemetry/sls-sink.js +1 -2
  59. package/package.json +5 -5
  60. package/skills/gd-cli/SKILL.md +1 -1
  61. package/skills/gd-cli/references/agent.md +34 -0
  62. package/skills/gd-cli/references/creation.md +5 -73
  63. package/skills/gd-cli/references/errors.md +18 -2
  64. package/skills/gd-cli/references/generation-constraints.md +36 -0
  65. package/skills/gd-cli/references/tool.md +31 -0
@@ -1,5 +1,11 @@
1
+ import { homedir } from "node:os";
2
+ import { createAgentBackgroundLauncher } from "../features/task/agent-background.js";
3
+ import { createTaskStore } from "../features/task/store.js";
4
+ import { createTaskUseCases } from "../features/task/use-cases.js";
5
+ import { readAgentResult } from "../features/agent/result-reader.js";
6
+ import { queryToolResult, ToolTaskFailedError } from "../features/tool/tool-api-adapter.js";
1
7
  import { randomBytes, randomUUID } from "node:crypto";
2
- import { dirname } from "node:path";
8
+ import { dirname, join } from "node:path";
3
9
  import { setTimeout as delay } from "node:timers/promises";
4
10
  import { fileURLToPath } from "node:url";
5
11
  import { createAccessPolicies } from "../features/auth/access-policy.js";
@@ -7,6 +13,8 @@ import { createLocalCredentialStore } from "../features/auth/credential-store.js
7
13
  import { createAuthUseCases } from "../features/auth/use-cases.js";
8
14
  import { createSsoService } from "../features/auth/sso-service.js";
9
15
  import { createCreativeAgentAdapter } from "../features/agent/creative-agent-adapter.js";
16
+ import { createAgentResourceAuthorizer } from "../features/agent/resource-authorizer.js";
17
+ import { createFilemsResourceAuthKeyProvider } from "../features/agent/filems-resource-auth-key-provider.js";
10
18
  import { createDamApiAdapter } from "../features/dam/dam-api-adapter.js";
11
19
  import { createDamFileDownloader } from "../features/dam/file-downloader.js";
12
20
  import { createDamOperationExecutor } from "../features/dam/operation-executor.js";
@@ -25,8 +33,9 @@ import { createToolApiAdapter } from "../features/tool/tool-api-adapter.js";
25
33
  import { createToolUseCases } from "../features/tool/use-cases.js";
26
34
  import { createOrgUseCases } from "../features/org/use-cases.js";
27
35
  import { createOrgService } from "../features/org/org-service.js";
36
+ import { createCreditsUseCases } from "../features/credits/use-cases.js";
28
37
  import { createBrowserOpener } from "../platform/open-browser.js";
29
- import { createSignedHttpTransport } from "../platform/signed-http-transport.js";
38
+ import { createSignedHttpTransport, RemoteRequestError } from "../platform/signed-http-transport.js";
30
39
  import { createJsonInputReader } from "../platform/json-input.js";
31
40
  import { createOrganizationPrompt } from "../cli/prompt.js";
32
41
  import { createPresenter } from "../cli/presenter.js";
@@ -34,28 +43,41 @@ import { createContractValidators } from "./validators.js";
34
43
  import { loadBundledSkills } from "../features/skill/bundled-skills.js";
35
44
  import { createUpdateService } from "../features/update/update-service.js";
36
45
  import { createUpdateNotificationService } from "../features/update/update-notification.js";
37
- import { classifyTelemetryError } from "../cli/errors.js";
46
+ import { classifyTelemetryError, mapCliError } from "../cli/errors.js";
38
47
  import { createTelemetryInvocation } from "../telemetry/invocation.js";
39
48
  import { createSlsTelemetrySink } from "../telemetry/sls-sink.js";
49
+ import { gaodingProduct } from "../product/config.js";
50
+ import { resolveProductLocale, systemLocale } from "../product/locale.js";
51
+ import { productText } from "../product/text.js";
52
+ import { agentOutputWithBillingUnit, toolOutputWithBillingUnit, withAgentBillingUnit, withToolBillingUnit } from "../product/billing.js";
40
53
  import { readInstallationOwner } from "../platform/installation-owner.js";
41
- const productionEndpoints = {
42
- orgApi: new URL("https://gdcli.gaoding.com/api"),
43
- agentApi: new URL("https://gdcli.gaoding.com/api"),
44
- mnsApi: new URL("https://gdcli.gaoding.com/api"),
45
- toolApi: new URL("https://gdcli.gaoding.com/api"),
46
- damApi: new URL("https://gdcli.gaoding.com/api"),
47
- ssoApi: new URL("https://www.gaoding.com/api/sso"),
48
- authPageOrigin: new URL("https://www.gaoding.art")
49
- };
50
54
  export function createProductionRuntime(options = {}) {
55
+ const product = options.product ?? gaodingProduct;
56
+ const text = (chinese, english) => productText(product, chinese, english);
51
57
  const bundledSkills = loadBundledSkills(fileURLToPath(import.meta.url));
52
- const primarySkill = bundledSkills.find((skill) => skill.skill === "gd-cli");
58
+ const primarySkill = bundledSkills.find((skill) => skill.skill === product.skillName);
53
59
  if (!primarySkill)
54
- throw new Error("Bundled gd-cli Skill is missing.");
60
+ throw new Error(`Bundled ${product.skillName} Skill is missing.`);
55
61
  const packageRoot = dirname(dirname(primarySkill.sourceDirectory));
56
62
  const installationOwner = readInstallationOwner(packageRoot);
57
- const endpoints = options.endpoints ?? productionEndpoints;
63
+ const endpoints = options.endpoints ?? product.endpoints;
58
64
  const fetch = options.fetch ?? globalThis.fetch;
65
+ const env = options.env ?? process.env;
66
+ const environmentLocale = product.localeEnvironmentVariable
67
+ ? env[product.localeEnvironmentVariable]
68
+ : undefined;
69
+ const localSystemLocale = systemLocale();
70
+ const locale = resolveProductLocale({
71
+ ...(options.locale === undefined ? {} : { explicit: options.locale }),
72
+ ...(environmentLocale === undefined ? {} : { environment: environmentLocale }),
73
+ ...(localSystemLocale === undefined ? {} : { system: localSystemLocale })
74
+ });
75
+ const businessHeaders = product.id === "insmind" ? {
76
+ "X-Locale": locale.locale,
77
+ "X-Language": locale.language,
78
+ "X-Market": locale.market,
79
+ "X-Legal-Region": locale.legalRegion
80
+ } : undefined;
59
81
  const now = options.now ?? (() => new Date());
60
82
  const telemetry = createTelemetryInvocation({
61
83
  cliVersion: primarySkill.version,
@@ -69,7 +91,10 @@ export function createProductionRuntime(options = {}) {
69
91
  },
70
92
  classifyError: classifyTelemetryError
71
93
  });
72
- const telemetrySink = createSlsTelemetrySink({ fetch });
94
+ const telemetrySink = createSlsTelemetrySink({
95
+ fetch,
96
+ trackingUrl: product.telemetryUrl
97
+ });
73
98
  const rawIo = options.io ?? {
74
99
  input: process.stdin,
75
100
  stdout: process.stdout,
@@ -84,41 +109,55 @@ export function createProductionRuntime(options = {}) {
84
109
  stderrTerminal: rawIo.stderrTerminal ?? hasTerminal(rawIo.stderr)
85
110
  };
86
111
  const store = createLocalCredentialStore({
87
- ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {})
112
+ ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {}),
113
+ stateDirectory: product.stateDirectory
88
114
  });
89
115
  const orgTransport = createSignedHttpTransport({
90
116
  baseUrl: endpoints.orgApi,
91
117
  fetch,
92
118
  now,
93
- traceparent: () => telemetry.traceparent()
119
+ traceparent: () => telemetry.traceparent(),
120
+ ...(businessHeaders ? { businessHeaders } : {})
121
+ });
122
+ const creditsTransport = createSignedHttpTransport({
123
+ baseUrl: endpoints.creditsApi,
124
+ fetch,
125
+ now,
126
+ traceparent: () => telemetry.traceparent(),
127
+ ...(businessHeaders ? { businessHeaders } : {})
94
128
  });
95
129
  const agentTransport = createSignedHttpTransport({
96
130
  baseUrl: endpoints.agentApi,
97
131
  fetch,
98
132
  now,
99
- traceparent: () => telemetry.traceparent()
133
+ traceparent: () => telemetry.traceparent(),
134
+ ...(businessHeaders ? { businessHeaders } : {})
100
135
  });
101
136
  const mnsTransport = createSignedHttpTransport({
102
137
  baseUrl: endpoints.mnsApi,
103
138
  fetch,
104
139
  now,
105
- traceparent: () => telemetry.traceparent()
140
+ traceparent: () => telemetry.traceparent(),
141
+ ...(businessHeaders ? { businessHeaders } : {})
106
142
  });
107
143
  const toolTransport = createSignedHttpTransport({
108
144
  baseUrl: endpoints.toolApi,
109
145
  fetch,
110
146
  now,
111
- traceparent: () => telemetry.traceparent()
147
+ traceparent: () => telemetry.traceparent(),
148
+ ...(businessHeaders ? { businessHeaders } : {})
112
149
  });
113
150
  const damTransport = createSignedHttpTransport({
114
151
  baseUrl: endpoints.damApi,
115
152
  fetch,
116
153
  now,
117
154
  channelId: "32",
118
- traceparent: () => telemetry.traceparent()
155
+ traceparent: () => telemetry.traceparent(),
156
+ ...(businessHeaders ? { businessHeaders } : {})
119
157
  });
120
158
  const sso = createSsoService({
121
159
  ssoApi: endpoints.ssoApi,
160
+ clientId: product.deviceClientId,
122
161
  fetch,
123
162
  now
124
163
  });
@@ -126,13 +165,18 @@ export function createProductionRuntime(options = {}) {
126
165
  store,
127
166
  org: createOrgService({ transport: orgTransport }),
128
167
  sso,
129
- telemetry
168
+ telemetry,
169
+ ...(product.exposesOrganizations
170
+ ? {}
171
+ : { singleOrganizationName: product.displayName })
130
172
  });
131
173
  const auth = createAuthUseCases({
132
174
  store,
133
175
  sso,
134
176
  organizationBinder: org,
135
177
  authPageOrigin: endpoints.authPageOrigin,
178
+ commandName: product.commandName,
179
+ requireOrganization: !product.exposesOrganizations,
136
180
  now,
137
181
  telemetry,
138
182
  sleep: async (milliseconds, signal) => {
@@ -140,6 +184,10 @@ export function createProductionRuntime(options = {}) {
140
184
  }
141
185
  });
142
186
  const storage = options.objectStorage ?? createObjectStorageUploader({ fetch, now });
187
+ const credits = createCreditsUseCases({
188
+ transport: creditsTransport,
189
+ billingUnit: product.billingUnit
190
+ });
143
191
  const storageUpload = createDamStorageUploader({
144
192
  transport: damTransport,
145
193
  storage
@@ -147,10 +195,13 @@ export function createProductionRuntime(options = {}) {
147
195
  const transientUploader = createDamTransientUploader({ storageUpload });
148
196
  const presenter = createPresenter({
149
197
  writeOut: io.writeOut,
150
- writeError: io.writeError
198
+ writeError: io.writeError,
199
+ product
151
200
  });
152
201
  const browser = createBrowserOpener();
153
- const validators = createContractValidators();
202
+ const validators = createContractValidators({
203
+ organizations: product.exposesOrganizations
204
+ });
154
205
  const modelCatalog = createMnsCatalogAdapter({ transport: mnsTransport });
155
206
  const damApi = createDamApiAdapter({ transport: damTransport });
156
207
  const damRepositories = createDamRepositoryCatalog({ transport: damTransport });
@@ -193,34 +244,122 @@ export function createProductionRuntime(options = {}) {
193
244
  },
194
245
  telemetry
195
246
  });
196
- const agent = createAgentUseCases({
247
+ const resourceAuthorizer = createAgentResourceAuthorizer({
248
+ authKeys: options.resourceAuthKeys
249
+ ?? createFilemsResourceAuthKeyProvider({ transport: createSignedHttpTransport({
250
+ baseUrl: endpoints.filemsApi,
251
+ fetch,
252
+ now,
253
+ channelId: "32",
254
+ traceparent: () => telemetry.traceparent(),
255
+ ...(businessHeaders ? { businessHeaders } : {})
256
+ }) })
257
+ });
258
+ const authorizeTaskResult = async (result, state, signal) => {
259
+ const access = { credential: state.credential, organizationId: state.organization.id };
260
+ if ("message" in result)
261
+ return resourceAuthorizer.authorize(result, access, signal);
262
+ const links = result.content.filter(part => part.type === "resource_link");
263
+ if (links.length === 0)
264
+ return result;
265
+ const parts = links.map(part => ({ url: part.uri, mediaType: part.mimeType ?? "application/octet-stream" }));
266
+ const authorized = await resourceAuthorizer.authorize({
267
+ message: { contextId: "resource-authorization", parts: [parts[0], ...parts.slice(1)] },
268
+ usage: { cost: { unit: "gaodou", amount: 0 }, items: [] }
269
+ }, access, signal);
270
+ let index = 0;
271
+ return { ...result, content: result.content.map(part => {
272
+ if (part.type !== "resource_link")
273
+ return part;
274
+ const authorizedPart = authorized.message.parts[index++];
275
+ return authorizedPart && "url" in authorizedPart ? { ...part, uri: authorizedPart.url } : part;
276
+ }) };
277
+ };
278
+ const tasks = createTaskUseCases({
279
+ store: createTaskStore({
280
+ ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {}),
281
+ stateDirectory: product.stateDirectory,
282
+ validate: validators.taskResult
283
+ }),
284
+ idFactory: randomUUID,
285
+ now,
286
+ notice: message => presenter.notice(message),
287
+ commandName: product.commandName,
288
+ text,
289
+ failureNote: error => {
290
+ const outcome = mapCliError(error, { aborted: false, product });
291
+ const status = error instanceof RemoteRequestError && error.status !== undefined ? ` (HTTP ${error.status})` : "";
292
+ return outcome.kind === "failure" ? `${outcome.failure.code}${status}: ${outcome.failure.message}` : "";
293
+ },
294
+ recovery: {
295
+ authorize: authorizeTaskResult,
296
+ async agent(progress, state, signal) {
297
+ if (!progress.contextId || !progress.localMessageId)
298
+ return {
299
+ state: "unknown", note: text("本地记录未取得服务端会话标识;无法确认提交结果,不自动重新生成。", "No service context was recorded. The submission outcome is unknown; do not generate again.")
300
+ };
301
+ const snapshot = await readAgentResult(agentTransport, {
302
+ contextId: progress.contextId, localMessageId: progress.localMessageId,
303
+ credential: state.credential, organizationId: state.organization.id, signal
304
+ });
305
+ return { state: "unknown",
306
+ note: text(`会话连接为 ${snapshot.connectionState};这不是本次调用的完成凭据。已有内容仅作为消息快照。`, `The context connection is ${snapshot.connectionState}; this does not prove that the run completed. Available content is a message snapshot only.`),
307
+ ...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal) } : {})
308
+ };
309
+ },
310
+ async tool(progress, state, signal) {
311
+ if (!progress.remoteTaskId || !progress.toolUsage)
312
+ return {
313
+ state: "unknown", note: text("本地记录未取得可查询的 Tool 回执;不自动重新生成。", "No queryable Tool receipt was recorded; do not generate again.")
314
+ };
315
+ const response = await queryToolResult(toolTransport, {
316
+ taskId: progress.remoteTaskId, credential: state.credential,
317
+ organizationId: state.organization.id, signal
318
+ });
319
+ if (response.state === "pending")
320
+ return { state: "running", note: text("原 Tool 查询尚未返回最终结果。", "The original Tool is still processing.") };
321
+ if (response.state === "failed")
322
+ return { state: "failed", note: text(response.error.message, response.error instanceof ToolTaskFailedError ? "The Tool run failed." : "The Tool service response is incompatible with this CLI.") };
323
+ return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
324
+ content: response.content, usage: progress.toolUsage
325
+ }, product.billingUnit), state, signal) };
326
+ }
327
+ }
328
+ });
329
+ const agent = withAgentBillingUnit(createAgentUseCases({
197
330
  catalog: modelCatalog,
198
331
  uploader: transientUploader,
199
332
  completion: createCreativeAgentAdapter({
200
333
  transport: agentTransport,
334
+ resourceAuthorizer,
201
335
  idFactory: randomUUID,
202
336
  telemetry
203
337
  }),
204
338
  warn: (message) => { presenter.warning(message); },
205
339
  telemetry
206
- });
207
- const tool = createToolUseCases({
340
+ }), product.billingUnit);
341
+ const tool = withToolBillingUnit(createToolUseCases({
208
342
  catalog: modelCatalog,
343
+ tools: product.tools,
209
344
  execution: createToolApiAdapter({ transport: toolTransport, telemetry }),
210
345
  uploader: transientUploader,
211
346
  warn: (message) => { presenter.warning(message); },
212
347
  telemetry
213
- });
348
+ }), product.billingUnit);
214
349
  const editor = createEditorUseCases({
215
350
  session: createEditorSession({
216
351
  store: createEditorSessionStateStore({
217
352
  ...(options.homeDirectory === undefined
218
353
  ? {}
219
- : { homeDirectory: options.homeDirectory })
354
+ : { homeDirectory: options.homeDirectory }),
355
+ stateDirectory: product.stateDirectory
220
356
  }),
221
357
  browser,
222
- defaultCreateUrl: new URL("https://www.gaoding.art/editor/canvas?mode=create&type=board"),
223
- workUrl: new URL("https://www.gaoding.art/editor/canvas"),
358
+ defaultCreateUrl: product.defaultEditorCreateUrl,
359
+ workUrl: product.editorWorkUrl,
360
+ commandName: product.commandName,
361
+ restrictTargets: product.restrictEditorTargets,
362
+ stateDirectory: product.stateDirectory,
224
363
  ...(options.homeDirectory === undefined
225
364
  ? {}
226
365
  : { homeDirectory: options.homeDirectory })
@@ -242,6 +381,11 @@ export function createProductionRuntime(options = {}) {
242
381
  bundledSkills,
243
382
  fetch,
244
383
  telemetry,
384
+ ...(product.id === "insmind" ? {
385
+ packageName: product.npmPackage,
386
+ commandName: product.commandName,
387
+ registryUrl: `https://registry.npmjs.org/${encodeURIComponent(product.npmPackage)}`
388
+ } : {}),
245
389
  installationOwner,
246
390
  ...(process.argv[1] ? { binaryPath: process.argv[1] } : {}),
247
391
  ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {})
@@ -255,9 +399,15 @@ export function createProductionRuntime(options = {}) {
255
399
  installationOwner,
256
400
  ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {}),
257
401
  ...(options.env ? { env: options.env } : {}),
258
- notify: (message) => { presenter.notice(message); }
402
+ notify: (message) => { presenter.notice(message); },
403
+ ...(product.id === "insmind" ? {
404
+ stateDirectoryName: product.stateDirectory,
405
+ registryUrl: `https://registry.npmjs.org/${encodeURIComponent(product.npmPackage)}`,
406
+ commandName: product.commandName
407
+ } : {})
259
408
  });
260
409
  return {
410
+ product,
261
411
  version: primarySkill.version,
262
412
  telemetry,
263
413
  telemetrySink,
@@ -269,9 +419,16 @@ export function createProductionRuntime(options = {}) {
269
419
  auth,
270
420
  org,
271
421
  agent,
422
+ tasks,
423
+ startAgentTask: (input, signal) => (options.agentBackground ?? createAgentBackgroundLauncher({
424
+ workerPath: join(packageRoot, "dist", "bin", "agent-worker.js"), env
425
+ })).submit({ ...input, product: product.id, homeDirectory: options.homeDirectory ?? homedir(),
426
+ locale: locale.locale, endpoints: Object.fromEntries(Object.entries(endpoints).map(([key, value]) => [key, String(value)]))
427
+ }, signal, task => presenter.notice(text(`任务 ID: ${task.taskId};结果未收到时执行 ${product.commandName} task get ${task.taskId}`, `Task ID: ${task.taskId}; retrieve missing output with ${product.commandName} task get ${task.taskId}`))),
272
428
  editor,
273
429
  dam,
274
430
  tool,
431
+ credits,
275
432
  update,
276
433
  updateNotification,
277
434
  jsonInput: createJsonInputReader({
@@ -0,0 +1,37 @@
1
+ import { mapCliError } from "../cli/errors.js";
2
+ import { redact } from "../platform/redact.js";
3
+ export async function runAgentWorker(options) {
4
+ const runtime = options.runtime;
5
+ const { job, signal, send } = options;
6
+ let started = false;
7
+ let accepted = false;
8
+ try {
9
+ runtime.validators.agentSendInput(job.input);
10
+ await runtime.tasks.track({
11
+ state: job.state,
12
+ operation: "agent.send",
13
+ label: job.label,
14
+ onUpdate(task, progress) {
15
+ if (!started) {
16
+ started = true;
17
+ send({ type: "started", task });
18
+ }
19
+ if (progress.accepted && !accepted) {
20
+ accepted = true;
21
+ send({ type: "accepted", task });
22
+ }
23
+ },
24
+ run: async (observe) => {
25
+ const result = await runtime.agent.send({ input: job.input, signal, observe,
26
+ access: { credential: job.state.credential, organizationId: job.state.organization.id } });
27
+ runtime.validators.agentSendOutput(result);
28
+ return result;
29
+ }
30
+ });
31
+ }
32
+ catch (error) {
33
+ const outcome = redact(mapCliError(error, { aborted: signal.aborted, product: runtime.product }));
34
+ if (outcome.kind === "failure")
35
+ send({ type: "error", failure: outcome.failure, exitCode: outcome.exitCode });
36
+ }
37
+ }
@@ -35,8 +35,6 @@ const editorDisconnectOutputSchema = contractSchema("editor.disconnect", "output
35
35
  const editorSaveOutputSchema = contractSchema("editor.save", "output");
36
36
  const editorScreenshotOutputSchema = contractSchema("editor.screenshot", "output");
37
37
  const editorSnapshotOutputSchema = contractSchema("editor.snapshot", "output");
38
- const orgCurrentSchema = contractSchema("org.current", "output");
39
- const orgListSchema = contractSchema("org.list", "output");
40
38
  const modelGetInputSchema = contractSchema("model.get", "input");
41
39
  const modelGetOutputSchema = contractSchema("model.get", "output");
42
40
  const modelListInputSchema = contractSchema("model.list", "input");
@@ -56,7 +54,7 @@ export class OutputContractError extends Error {
56
54
  this.name = "OutputContractError";
57
55
  }
58
56
  }
59
- export function createContractValidators() {
57
+ export function createContractValidators(options = {}) {
60
58
  const ajv = new Ajv2020({ allErrors: true, strict: true });
61
59
  const addFormats = addFormatsImport;
62
60
  addFormats(ajv);
@@ -94,8 +92,13 @@ export function createContractValidators() {
94
92
  const editorApplyOutput = ajv.compile(editorApplyOutputSchema);
95
93
  const editorScreenshotOutput = ajv.compile(editorScreenshotOutputSchema);
96
94
  const editorSaveOutput = ajv.compile(editorSaveOutputSchema);
97
- const orgList = ajv.compile(orgListSchema);
98
- const orgCurrent = ajv.compile(orgCurrentSchema);
95
+ const organizations = options.organizations !== false;
96
+ const orgList = organizations
97
+ ? ajv.compile(contractSchema("org.list", "output"))
98
+ : unavailableValidator;
99
+ const orgCurrent = organizations
100
+ ? ajv.compile(contractSchema("org.current", "output"))
101
+ : unavailableValidator;
99
102
  const toolListOutput = ajv.compile(toolListOutputSchema);
100
103
  const modelListInput = ajv.compile(modelListInputSchema);
101
104
  const modelListOutput = ajv.compile(modelListOutputSchema);
@@ -103,7 +106,15 @@ export function createContractValidators() {
103
106
  const modelGetOutput = ajv.compile(modelGetOutputSchema);
104
107
  const toolCallInput = ajv.compile(toolCallInputSchema);
105
108
  const toolCallOutput = ajv.compile(toolCallOutputSchema);
109
+ const runOutputSchema = contractSchema("task.get", "output");
110
+ const runSchemaId = runOutputSchema.$id;
111
+ ajv.addSchema(agentSendOutputSchema, new URL("../agent.send/output.schema.json", runSchemaId).href);
112
+ ajv.addSchema(toolCallOutputSchema, new URL("../tool.call/output.schema.json", runSchemaId).href);
113
+ const taskResult = ajv.compile(runOutputSchema);
114
+ const taskListResult = ajv.compile(contractSchema("task.list", "output"));
106
115
  return {
116
+ taskResult: assertion(taskResult, OutputContractError),
117
+ taskListResult: assertion(taskListResult, OutputContractError),
107
118
  agentSendInput: assertion(agentSendInput, InputContractError),
108
119
  agentSendOutput: assertion(agentSendOutput, OutputContractError),
109
120
  authStatus: assertion(authStatus, OutputContractError),
@@ -149,6 +160,7 @@ export function createContractValidators() {
149
160
  toolCallOutput: assertion(toolCallOutput, OutputContractError)
150
161
  };
151
162
  }
163
+ const unavailableValidator = Object.assign(() => false, { errors: null, schema: false, schemaEnv: undefined });
152
164
  function assertion(validate, ErrorType) {
153
165
  return (value) => {
154
166
  if (!validate(value))
@@ -1,21 +1,37 @@
1
1
  import { contractSchema } from "../contracts/schema.js";
2
2
  import { bindPreparedAction } from "./action-binding.js";
3
3
  import { CliUsageError } from "./errors.js";
4
+ import { productText as text } from "../product/text.js";
4
5
  const agentSendInputSchema = contractSchema("agent.send", "input");
5
6
  export function registerAgentCommands(program, runtime) {
6
7
  const agent = program.command("agent")
7
- .description("稿定 Agent")
8
+ .description(text(runtime.product, "稿定 Agent", "insMind Agent"))
8
9
  .helpCommand(false);
9
10
  const send = agent.command("send")
10
- .description("发送结构化创作消息")
11
- .option("--schema", "输出输入 Schema")
12
- .option("--input <file|->", "从文件或标准输入读取 JSON")
11
+ .description(text(runtime.product, "发送结构化创作消息并等待最终结果", "Send a structured creation message and wait for its result"))
12
+ .option("--schema", text(runtime.product, "输出输入 Schema", "output the input Schema"))
13
+ .option("--input <file|->", text(runtime.product, "从文件或标准输入读取 JSON", "read JSON from a file or stdin"))
14
+ .option("--async", text(runtime.product, "提交后返回 taskId,通过 task get 查询结果", "return taskId after submission; retrieve results with task get"))
13
15
  .allowExcessArguments(false);
16
+ send.addHelpText("after", [
17
+ "",
18
+ text(runtime.product, "--async 在服务端受理后输出包含 taskId 和 state 的 JSON;退出码 0 仅表示受理。", "--async returns JSON with taskId and state after acceptance; exit code 0 means accepted only."),
19
+ text(runtime.product, "用 task get <taskId> 查询原任务;completed 时 result 为完整结果,running/unknown 或查询超时不应重新提交。", "Query the same taskId with task get; completed includes result. Do not resubmit on running, unknown, or a query timeout."),
20
+ text(runtime.product, "Agent 异步由本机后台进程继续执行;进程终止或关机可能使状态变为 unknown。", "Agent async continues in a local background process; termination or shutdown may leave its state unknown."),
21
+ text(runtime.product, "中断前台等待不会取消已交接的后台任务;仍用原 taskId 查询。", "Interrupting the foreground wait does not cancel a handed-off task; query the same taskId."),
22
+ text(runtime.product, "默认在当前进程等待最终结果,成功后一次输出 JSON。", "By default, the command waits in the current process and returns the final result as one JSON object."),
23
+ text(runtime.product, "运行中请继续等待原进程;已提交但结果未知时,不要重复提交。", "Wait for the original process. Do not resubmit a creation whose outcome is unknown."),
24
+ text(runtime.product, "默认模式在 stderr 提示任务 ID,stdout 保持原结果 JSON。", "In default mode the Task ID is written to stderr; stdout contains only the original result JSON."),
25
+ text(runtime.product, `结果未收到时执行 ${runtime.product.commandName} task list 找到原调用,再执行 ${runtime.product.commandName} task get <id> 查询。`, `If output is missing, find the original run with ${runtime.product.commandName} task list, then query ${runtime.product.commandName} task get <id>.`),
26
+ text(runtime.product, "首次创作省略 JSON 中的 message.contextId;续聊时传入上次结果的 message.contextId。", "Omit message.contextId for the first creation. Continue a conversation using message.contextId from the previous result."),
27
+ text(runtime.product, "usage 仅覆盖本次调用,不包含其他命令调用的消耗。", "usage covers this invocation only, excluding other command invocations."),
28
+ ""
29
+ ].join("\n"));
14
30
  bindPreparedAction(send, "organization", async (signal) => {
15
31
  signal.throwIfAborted();
16
32
  const options = send.opts();
17
33
  const modes = Number(options.schema === true) + Number(options.input !== undefined);
18
- if (modes !== 1)
34
+ if (modes !== 1 || (options.schema && options.async))
19
35
  throw new CliUsageError();
20
36
  if (options.schema === true) {
21
37
  await runtime.telemetry.stage("output", async () => {
@@ -28,16 +44,26 @@ export function registerAgentCommands(program, runtime) {
28
44
  runtime.telemetry.annotate({ parameters: { ...input } });
29
45
  return { handled: false, input };
30
46
  }, async (context, input, signal) => {
31
- const result = await runtime.agent.send({
32
- input,
33
- access: {
34
- credential: context.state.credential,
35
- organizationId: context.state.organization.id
36
- },
37
- signal
38
- });
39
- await runtime.telemetry.stage("output", async () => {
47
+ const task = {
48
+ state: context.state,
49
+ operation: "agent.send",
50
+ label: input.message.parts.map(part => part && typeof part === "object" && "text" in part ? String(part.text) : text(runtime.product, "[素材或结构化输入]", "[asset or structured input]")).join(" ")
51
+ };
52
+ if (send.opts().async) {
53
+ const result = await runtime.startAgentTask({ state: context.state, label: task.label, input }, signal);
54
+ runtime.validators.taskResult(result);
55
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
56
+ return;
57
+ }
58
+ const run = async (observe) => {
59
+ const result = await runtime.agent.send({ input,
60
+ ...(observe ? { observe } : {}),
61
+ access: { credential: context.state.credential, organizationId: context.state.organization.id }, signal });
40
62
  runtime.validators.agentSendOutput(result);
63
+ return result;
64
+ };
65
+ const result = await runtime.tasks.track({ ...task, run });
66
+ await runtime.telemetry.stage("output", async () => {
41
67
  runtime.io.writeOut(`${JSON.stringify(result)}\n`);
42
68
  });
43
69
  }, {
@@ -1,12 +1,13 @@
1
1
  import { bindAction } from "./action-binding.js";
2
- import { authStatusView } from "./presenter.js";
2
+ import { authStatusViewFor } from "./presenter.js";
3
+ import { productText as text } from "../product/text.js";
3
4
  export function registerAuthCommands(program, runtime) {
4
5
  const auth = program.command("auth")
5
- .description("登录与本机凭证")
6
+ .description(text(runtime.product, "登录与本机凭证", "Authentication and local credentials"))
6
7
  .helpCommand(false);
7
8
  const login = leaf(auth.command("login"))
8
- .description("登录稿定")
9
- .option("--no-browser", "不自动打开浏览器");
9
+ .description(text(runtime.product, "登录稿定", "Sign in to insMind"))
10
+ .option("--no-browser", text(runtime.product, "不自动打开浏览器", "do not open a browser automatically"));
10
11
  bindAction(login, "none", async (_context, signal) => {
11
12
  const noBrowser = login.opts().browser === false;
12
13
  runtime.telemetry.annotate({ parameters: { noBrowser } });
@@ -23,30 +24,32 @@ export function registerAuthCommands(program, runtime) {
23
24
  }
24
25
  });
25
26
  await runtime.telemetry.stage("output", async () => {
26
- runtime.presenter.success(result.status === "already_logged_in" ? "已登录。" : "登录成功。");
27
+ runtime.presenter.success(result.status === "already_logged_in"
28
+ ? text(runtime.product, "已登录。", "Already signed in.")
29
+ : text(runtime.product, "登录成功。", "Signed in successfully."));
27
30
  if (result.status === "already_logged_in" && !result.organizationSelected) {
28
31
  runtime.presenter.warning("尚未选择组织,请执行 gd-cli org switch。");
29
32
  }
30
33
  });
31
34
  }, { operation: "auth.login" });
32
35
  const status = leaf(auth.command("status"))
33
- .description("查看登录状态")
34
- .option("--json", "输出 JSON");
36
+ .description(text(runtime.product, "查看登录状态", "Show authentication status"))
37
+ .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
35
38
  bindAction(status, "none", async () => {
36
39
  const result = await runtime.auth.status({ now: runtime.now() });
37
40
  await runtime.telemetry.stage("output", async () => {
38
41
  runtime.validators.authStatus(result);
39
42
  runtime.presenter.result(result, {
40
43
  json: status.opts().json === true,
41
- view: authStatusView
44
+ view: authStatusViewFor(runtime.product)
42
45
  });
43
46
  });
44
47
  }, { operation: "auth.status" });
45
- const logout = leaf(auth.command("logout")).description("退出登录");
48
+ const logout = leaf(auth.command("logout")).description(text(runtime.product, "退出登录", "Sign out"));
46
49
  bindAction(logout, "none", async () => {
47
50
  await runtime.auth.logout();
48
51
  await runtime.telemetry.stage("output", async () => {
49
- runtime.presenter.success("已退出登录。");
52
+ runtime.presenter.success(text(runtime.product, "已退出登录。", "Signed out."));
50
53
  });
51
54
  }, { operation: "auth.logout" });
52
55
  }
@@ -0,0 +1,23 @@
1
+ import { bindAction } from "./action-binding.js";
2
+ export function registerCreditsCommand(program, runtime) {
3
+ 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) => {
8
+ const result = await runtime.credits.get({
9
+ credential: context.state.credential,
10
+ organizationId: context.state.organization.id,
11
+ signal
12
+ });
13
+ 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
+ });
21
+ });
22
+ }, { operation: "credits.get" });
23
+ }