@gaoding/cli 1.2.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 (37) 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/src/bootstrap/create-cli.js +2 -0
  7. package/dist/src/bootstrap/create-runtime.js +103 -4
  8. package/dist/src/bootstrap/run-agent-worker.js +37 -0
  9. package/dist/src/bootstrap/validators.js +8 -0
  10. package/dist/src/cli/agent-commands.js +36 -11
  11. package/dist/src/cli/errors.js +11 -0
  12. package/dist/src/cli/task-commands.js +48 -0
  13. package/dist/src/cli/tool-commands.js +31 -8
  14. package/dist/src/features/agent/creative-agent-adapter.js +9 -3
  15. package/dist/src/features/agent/creative-protocol.js +5 -16
  16. package/dist/src/features/agent/creative-stream.js +12 -1
  17. package/dist/src/features/agent/filems-resource-auth-key-provider.js +23 -0
  18. package/dist/src/features/agent/resource-authorizer.js +47 -0
  19. package/dist/src/features/agent/result-reader.js +30 -0
  20. package/dist/src/features/agent/use-cases.js +98 -95
  21. package/dist/src/features/task/agent-background.js +63 -0
  22. package/dist/src/features/task/store.js +97 -0
  23. package/dist/src/features/task/types.js +1 -0
  24. package/dist/src/features/task/use-cases.js +139 -0
  25. package/dist/src/features/tool/tool-api-adapter.js +53 -36
  26. package/dist/src/features/tool/use-cases.js +108 -105
  27. package/dist/src/platform/resource-auth-key.js +1 -0
  28. package/dist/src/platform/task-observer.js +1 -0
  29. package/dist/src/product/billing.js +21 -19
  30. package/dist/src/product/config.js +2 -0
  31. package/package.json +4 -4
  32. package/skills/gd-cli/SKILL.md +1 -1
  33. package/skills/gd-cli/references/agent.md +34 -0
  34. package/skills/gd-cli/references/creation.md +5 -73
  35. package/skills/gd-cli/references/errors.md +18 -2
  36. package/skills/gd-cli/references/generation-constraints.md +36 -0
  37. package/skills/gd-cli/references/tool.md +31 -0
@@ -0,0 +1,14 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "taskId": {
7
+ "type": "string",
8
+ "format": "uuid"
9
+ }
10
+ },
11
+ "required": [
12
+ "taskId"
13
+ ]
14
+ }
@@ -0,0 +1,103 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://gdcli.gaoding.com/contracts/operations/task.get/output.schema.json",
4
+ "title": "TaskResult",
5
+ "allOf": [
6
+ {
7
+ "if": {
8
+ "properties": {
9
+ "state": {
10
+ "const": "completed"
11
+ }
12
+ }
13
+ },
14
+ "then": {
15
+ "properties": {
16
+ "result": {}
17
+ },
18
+ "required": [
19
+ "result"
20
+ ]
21
+ },
22
+ "else": {
23
+ "not": {
24
+ "properties": {
25
+ "result": {}
26
+ },
27
+ "required": [
28
+ "result"
29
+ ]
30
+ }
31
+ }
32
+ }
33
+ ],
34
+ "type": "object",
35
+ "additionalProperties": false,
36
+ "required": [
37
+ "taskId",
38
+ "operation",
39
+ "label",
40
+ "createdAt",
41
+ "updatedAt",
42
+ "state"
43
+ ],
44
+ "properties": {
45
+ "taskId": {
46
+ "type": "string",
47
+ "format": "uuid"
48
+ },
49
+ "operation": {
50
+ "enum": [
51
+ "agent.send",
52
+ "tool.call"
53
+ ]
54
+ },
55
+ "label": {
56
+ "type": "string",
57
+ "maxLength": 200
58
+ },
59
+ "createdAt": {
60
+ "type": "string",
61
+ "format": "date-time"
62
+ },
63
+ "updatedAt": {
64
+ "type": "string",
65
+ "format": "date-time"
66
+ },
67
+ "state": {
68
+ "enum": [
69
+ "running",
70
+ "completed",
71
+ "failed",
72
+ "unknown"
73
+ ]
74
+ },
75
+ "contextId": {
76
+ "type": "string",
77
+ "minLength": 1
78
+ },
79
+ "note": {
80
+ "type": "string"
81
+ },
82
+ "result": {
83
+ "oneOf": [
84
+ {
85
+ "$ref": "../agent.send/output.schema.json"
86
+ },
87
+ {
88
+ "$ref": "../tool.call/output.schema.json"
89
+ }
90
+ ]
91
+ },
92
+ "partialResult": {
93
+ "oneOf": [
94
+ {
95
+ "$ref": "../agent.send/output.schema.json"
96
+ },
97
+ {
98
+ "$ref": "../tool.call/output.schema.json"
99
+ }
100
+ ]
101
+ }
102
+ }
103
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "limit": {
7
+ "type": "integer",
8
+ "minimum": 1,
9
+ "maximum": 100
10
+ },
11
+ "operation": {
12
+ "enum": [
13
+ "agent.send",
14
+ "tool.call"
15
+ ]
16
+ }
17
+ }
18
+ }
@@ -0,0 +1,53 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://gdcli.gaoding.com/contracts/operations/task.list/output.schema.json",
4
+ "title": "TaskListResult",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": [
8
+ "tasks"
9
+ ],
10
+ "properties": {
11
+ "tasks": {
12
+ "type": "array",
13
+ "items": {
14
+ "type": "object",
15
+ "additionalProperties": false,
16
+ "required": [
17
+ "taskId",
18
+ "operation",
19
+ "label",
20
+ "createdAt",
21
+ "updatedAt",
22
+ "state"
23
+ ],
24
+ "properties": {
25
+ "taskId": {
26
+ "$ref": "../task.get/output.schema.json#/properties/taskId"
27
+ },
28
+ "operation": {
29
+ "$ref": "../task.get/output.schema.json#/properties/operation"
30
+ },
31
+ "label": {
32
+ "$ref": "../task.get/output.schema.json#/properties/label"
33
+ },
34
+ "createdAt": {
35
+ "$ref": "../task.get/output.schema.json#/properties/createdAt"
36
+ },
37
+ "updatedAt": {
38
+ "$ref": "../task.get/output.schema.json#/properties/updatedAt"
39
+ },
40
+ "state": {
41
+ "$ref": "../task.get/output.schema.json#/properties/state"
42
+ },
43
+ "contextId": {
44
+ "$ref": "../task.get/output.schema.json#/properties/contextId"
45
+ },
46
+ "note": {
47
+ "$ref": "../task.get/output.schema.json#/properties/note"
48
+ }
49
+ }
50
+ }
51
+ }
52
+ }
53
+ }
@@ -0,0 +1,41 @@
1
+ // Private one-task process; not a public CLI command or a resident service.
2
+ import { once } from "node:events";
3
+ import { Readable } from "node:stream";
4
+ import { gaodingProduct, insmindProduct } from "../src/product/config.js";
5
+ import { createProductionRuntime } from "../src/bootstrap/create-runtime.js";
6
+ import { runAgentWorker } from "../src/bootstrap/run-agent-worker.js";
7
+ if (!process.send) {
8
+ process.exitCode = 2;
9
+ }
10
+ else {
11
+ const controller = new AbortController();
12
+ const interrupt = () => controller.abort(new Error("SIGINT"));
13
+ process.once("SIGINT", interrupt);
14
+ process.once("SIGTERM", interrupt);
15
+ const send = (message) => {
16
+ if (process.connected)
17
+ process.send?.(message, () => undefined);
18
+ };
19
+ try {
20
+ const [job] = await once(process, "message");
21
+ const product = job.product === "insmind" ? insmindProduct : gaodingProduct;
22
+ const endpoints = { ...product.endpoints };
23
+ for (const key of Object.keys(endpoints))
24
+ endpoints[key] = new URL(job.endpoints[key]);
25
+ const runtime = createProductionRuntime({
26
+ product, endpoints, homeDirectory: job.homeDirectory, locale: job.locale,
27
+ io: { input: Readable.from([]), stdout: { write() { } }, stderr: { write() { } } }
28
+ });
29
+ await runAgentWorker({ runtime, job, signal: controller.signal, send });
30
+ }
31
+ catch {
32
+ send({ type: "error", failure: { code: "TASK_WORKER_UNAVAILABLE", message: "The background task could not start. Check task list/get before submitting again." }, exitCode: 1 });
33
+ process.exitCode = 1;
34
+ }
35
+ finally {
36
+ if (process.connected)
37
+ process.disconnect();
38
+ process.removeListener("SIGINT", interrupt);
39
+ process.removeListener("SIGTERM", interrupt);
40
+ }
41
+ }
@@ -1,3 +1,4 @@
1
+ import { registerTaskCommands } from "../cli/task-commands.js";
1
2
  import { Command, CommanderError } from "commander";
2
3
  import { assertAllLeafCommandsBound, configureActionEnvironment } from "../cli/action-binding.js";
3
4
  import { registerAgentCommands } from "../cli/agent-commands.js";
@@ -46,6 +47,7 @@ export function createCli(runtime, options) {
46
47
  registerEditorCommands(program, runtime);
47
48
  registerDamCommands(program, runtime);
48
49
  registerUpdateCommand(program, runtime);
50
+ registerTaskCommands(program, runtime);
49
51
  assertAllLeafCommandsBound(program);
50
52
  return program;
51
53
  }
@@ -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";
@@ -27,7 +35,7 @@ import { createOrgUseCases } from "../features/org/use-cases.js";
27
35
  import { createOrgService } from "../features/org/org-service.js";
28
36
  import { createCreditsUseCases } from "../features/credits/use-cases.js";
29
37
  import { createBrowserOpener } from "../platform/open-browser.js";
30
- import { createSignedHttpTransport } from "../platform/signed-http-transport.js";
38
+ import { createSignedHttpTransport, RemoteRequestError } from "../platform/signed-http-transport.js";
31
39
  import { createJsonInputReader } from "../platform/json-input.js";
32
40
  import { createOrganizationPrompt } from "../cli/prompt.js";
33
41
  import { createPresenter } from "../cli/presenter.js";
@@ -35,15 +43,17 @@ import { createContractValidators } from "./validators.js";
35
43
  import { loadBundledSkills } from "../features/skill/bundled-skills.js";
36
44
  import { createUpdateService } from "../features/update/update-service.js";
37
45
  import { createUpdateNotificationService } from "../features/update/update-notification.js";
38
- import { classifyTelemetryError } from "../cli/errors.js";
46
+ import { classifyTelemetryError, mapCliError } from "../cli/errors.js";
39
47
  import { createTelemetryInvocation } from "../telemetry/invocation.js";
40
48
  import { createSlsTelemetrySink } from "../telemetry/sls-sink.js";
41
49
  import { gaodingProduct } from "../product/config.js";
42
50
  import { resolveProductLocale, systemLocale } from "../product/locale.js";
43
- import { withAgentBillingUnit, withToolBillingUnit } from "../product/billing.js";
51
+ import { productText } from "../product/text.js";
52
+ import { agentOutputWithBillingUnit, toolOutputWithBillingUnit, withAgentBillingUnit, withToolBillingUnit } from "../product/billing.js";
44
53
  import { readInstallationOwner } from "../platform/installation-owner.js";
45
54
  export function createProductionRuntime(options = {}) {
46
55
  const product = options.product ?? gaodingProduct;
56
+ const text = (chinese, english) => productText(product, chinese, english);
47
57
  const bundledSkills = loadBundledSkills(fileURLToPath(import.meta.url));
48
58
  const primarySkill = bundledSkills.find((skill) => skill.skill === product.skillName);
49
59
  if (!primarySkill)
@@ -234,11 +244,94 @@ export function createProductionRuntime(options = {}) {
234
244
  },
235
245
  telemetry
236
246
  });
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
+ });
237
329
  const agent = withAgentBillingUnit(createAgentUseCases({
238
330
  catalog: modelCatalog,
239
331
  uploader: transientUploader,
240
332
  completion: createCreativeAgentAdapter({
241
333
  transport: agentTransport,
334
+ resourceAuthorizer,
242
335
  idFactory: randomUUID,
243
336
  telemetry
244
337
  }),
@@ -326,6 +419,12 @@ export function createProductionRuntime(options = {}) {
326
419
  auth,
327
420
  org,
328
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}`))),
329
428
  editor,
330
429
  dam,
331
430
  tool,
@@ -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
+ }
@@ -106,7 +106,15 @@ export function createContractValidators(options = {}) {
106
106
  const modelGetOutput = ajv.compile(modelGetOutputSchema);
107
107
  const toolCallInput = ajv.compile(toolCallInputSchema);
108
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"));
109
115
  return {
116
+ taskResult: assertion(taskResult, OutputContractError),
117
+ taskListResult: assertion(taskListResult, OutputContractError),
110
118
  agentSendInput: assertion(agentSendInput, InputContractError),
111
119
  agentSendOutput: assertion(agentSendOutput, OutputContractError),
112
120
  authStatus: assertion(authStatus, OutputContractError),
@@ -8,15 +8,30 @@ export function registerAgentCommands(program, runtime) {
8
8
  .description(text(runtime.product, "稿定 Agent", "insMind Agent"))
9
9
  .helpCommand(false);
10
10
  const send = agent.command("send")
11
- .description(text(runtime.product, "发送结构化创作消息", "Send a structured creation message"))
11
+ .description(text(runtime.product, "发送结构化创作消息并等待最终结果", "Send a structured creation message and wait for its result"))
12
12
  .option("--schema", text(runtime.product, "输出输入 Schema", "output the input Schema"))
13
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"))
14
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"));
15
30
  bindPreparedAction(send, "organization", async (signal) => {
16
31
  signal.throwIfAborted();
17
32
  const options = send.opts();
18
33
  const modes = Number(options.schema === true) + Number(options.input !== undefined);
19
- if (modes !== 1)
34
+ if (modes !== 1 || (options.schema && options.async))
20
35
  throw new CliUsageError();
21
36
  if (options.schema === true) {
22
37
  await runtime.telemetry.stage("output", async () => {
@@ -29,16 +44,26 @@ export function registerAgentCommands(program, runtime) {
29
44
  runtime.telemetry.annotate({ parameters: { ...input } });
30
45
  return { handled: false, input };
31
46
  }, async (context, input, signal) => {
32
- const result = await runtime.agent.send({
33
- input,
34
- access: {
35
- credential: context.state.credential,
36
- organizationId: context.state.organization.id
37
- },
38
- signal
39
- });
40
- 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 });
41
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 () => {
42
67
  runtime.io.writeOut(`${JSON.stringify(result)}\n`);
43
68
  });
44
69
  }, {
@@ -1,3 +1,6 @@
1
+ import { AgentBackgroundError } from "../features/task/agent-background.js";
2
+ import { TaskNotFoundError } from "../features/task/use-cases.js";
3
+ import { TaskStoreError } from "../features/task/store.js";
1
4
  import { CommanderError } from "commander";
2
5
  import { AuthExpiredError, AuthRequiredError } from "../features/auth/access-policy.js";
3
6
  import { AuthStateInvalidError } from "../features/auth/state.js";
@@ -43,6 +46,14 @@ export function mapCliError(error, options) {
43
46
  const command = options.product?.commandName ?? "gd-cli";
44
47
  if (options.aborted)
45
48
  return { kind: "interrupted", exitCode: 130 };
49
+ if (error instanceof AgentBackgroundError)
50
+ return { kind: "failure", failure: error.failure, exitCode: error.exitCode };
51
+ if (error instanceof TaskNotFoundError)
52
+ return failure("TASK_NOT_FOUND", error.message, 1);
53
+ if (error instanceof TaskStoreError)
54
+ return failure("LOCAL_STATE_ERROR", insmind
55
+ ? "Cannot read or write local task records. Check permissions and file integrity in ~/.insmind/tasks."
56
+ : "无法读写本地执行记录;请检查 ~/.gd/tasks 的权限和文件完整性。", 1);
46
57
  if (error instanceof AuthRequiredError) {
47
58
  if (insmind)
48
59
  return failure("AUTH_REQUIRED", `Run ${command} auth login first.`, 1, [`${command} auth login`]);
@@ -0,0 +1,48 @@
1
+ import { productText } from "../product/text.js";
2
+ import { validTaskId } from "../features/task/store.js";
3
+ import { bindPreparedAction } from "./action-binding.js";
4
+ import { CliUsageError } from "./errors.js";
5
+ export function registerTaskCommands(program, runtime) {
6
+ const tasks = runtime.tasks;
7
+ const text = (chinese, english) => productText(runtime.product, chinese, english);
8
+ const task = program.command("task").description(text("查找本机创作执行记录与结果", "Find local creation tasks and results")).helpCommand(false);
9
+ const list = task.command("list").description(text("列出当前身份和组织的近期创作执行记录", "List recent creation tasks for the current identity context"))
10
+ .option("--limit <number>", text("返回 1–100 条,默认 20", "return 1–100 tasks; defaults to 20"), "20")
11
+ .option("--operation <operation>", text("筛选 agent.send 或 tool.call", "filter by agent.send or tool.call"))
12
+ .allowExcessArguments(false);
13
+ bindPreparedAction(list, "organization", async () => {
14
+ const options = list.opts();
15
+ const limit = Number(options.limit);
16
+ if (!/^\d+$/u.test(options.limit) || !Number.isInteger(limit) || limit < 1 || limit > 100
17
+ || (options.operation !== undefined && !["agent.send", "tool.call"].includes(options.operation)))
18
+ throw new CliUsageError();
19
+ return { handled: false, input: { limit,
20
+ ...(options.operation === undefined ? {} : { operation: options.operation }) } };
21
+ }, async (context, input) => {
22
+ const result = await tasks.list({ ...input, state: context.state });
23
+ runtime.validators.taskListResult(result);
24
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
25
+ }, { operation: "task.list" });
26
+ const get = task.command("get").description(text("查询原执行状态并取回已有结果,不重新生成", "Query a task and retrieve existing results without generating again"))
27
+ .argument("<id>", text("task list 或原命令提示的任务 ID", "Task ID from task list or the original command"))
28
+ .allowExcessArguments(false)
29
+ .addHelpText("after", [
30
+ "",
31
+ text("completed 表示该次执行已有完整结果;running 表示原 CLI 仍在更新记录,或远端任务仍在执行。", "completed means this task has a complete result; running means the original CLI is updating the record or the service is still processing."),
32
+ text("unknown 表示无法确认本次执行终态;partialResult 仅是已取得的消息片段,不代表完成。", "unknown means completion cannot be confirmed; partialResult is a message snapshot, not a complete result."),
33
+ text("查询不重新提交创作;同一执行记录多次读取的 usage 是同一份费用。", "Queries never resubmit a creation. Reading the same task again does not add another usage charge."),
34
+ text(`记录仅来自本机执行;保留至用户删除 ~/${runtime.product.stateDirectory}/tasks。切换身份或组织后只显示对应记录。`, `Tasks are local to this machine and identity context; they remain until you remove ~/${runtime.product.stateDirectory}/tasks.`),
35
+ text("Agent 首次回执未取得或原连接中断时可能只能确认未知;不会自动选择最近 Context 或重新生成。", "A missing first Agent receipt or interrupted connection may leave the outcome unknown; the CLI does not select another Context or generate again."),
36
+ ""
37
+ ].join("\n"));
38
+ bindPreparedAction(get, "organization", async () => {
39
+ const id = get.processedArgs[0];
40
+ if (typeof id !== "string" || !validTaskId(id))
41
+ throw new CliUsageError();
42
+ return { handled: false, input: id.toLowerCase() };
43
+ }, async (context, id, signal) => {
44
+ const result = await tasks.get({ id, state: context.state, signal });
45
+ runtime.validators.taskResult(result);
46
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
47
+ }, { operation: "task.get" });
48
+ }