@insmind/cli 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 (153) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -0
  3. package/contracts/operations/agent.send/input.schema.json +335 -0
  4. package/contracts/operations/agent.send/output.schema.json +248 -0
  5. package/contracts/operations/auth.status/input.schema.json +7 -0
  6. package/contracts/operations/auth.status/output.schema.json +119 -0
  7. package/contracts/operations/dam.copy/input.schema.json +42 -0
  8. package/contracts/operations/dam.copy/output.schema.json +43 -0
  9. package/contracts/operations/dam.delete/input.schema.json +24 -0
  10. package/contracts/operations/dam.delete/output.schema.json +5 -0
  11. package/contracts/operations/dam.download/input.schema.json +28 -0
  12. package/contracts/operations/dam.download/output.schema.json +51 -0
  13. package/contracts/operations/dam.folder.list/input.schema.json +36 -0
  14. package/contracts/operations/dam.folder.list/output.schema.json +104 -0
  15. package/contracts/operations/dam.get/input.schema.json +16 -0
  16. package/contracts/operations/dam.get/output.schema.json +107 -0
  17. package/contracts/operations/dam.list/input.schema.json +73 -0
  18. package/contracts/operations/dam.list/output.schema.json +145 -0
  19. package/contracts/operations/dam.move/input.schema.json +42 -0
  20. package/contracts/operations/dam.move/output.schema.json +40 -0
  21. package/contracts/operations/dam.rename/input.schema.json +42 -0
  22. package/contracts/operations/dam.rename/output.schema.json +43 -0
  23. package/contracts/operations/dam.repository.list/input.schema.json +7 -0
  24. package/contracts/operations/dam.repository.list/output.schema.json +65 -0
  25. package/contracts/operations/dam.search/input.schema.json +79 -0
  26. package/contracts/operations/dam.search/output.schema.json +145 -0
  27. package/contracts/operations/dam.tag.list/input.schema.json +21 -0
  28. package/contracts/operations/dam.tag.list/output.schema.json +52 -0
  29. package/contracts/operations/dam.upload/input.schema.json +43 -0
  30. package/contracts/operations/dam.upload/output.schema.json +107 -0
  31. package/contracts/operations/editor.apply/input.schema.json +177 -0
  32. package/contracts/operations/editor.apply/output.schema.json +15 -0
  33. package/contracts/operations/editor.connect/input.schema.json +13 -0
  34. package/contracts/operations/editor.connect/output.schema.json +17 -0
  35. package/contracts/operations/editor.disconnect/input.schema.json +7 -0
  36. package/contracts/operations/editor.disconnect/output.schema.json +14 -0
  37. package/contracts/operations/editor.save/input.schema.json +7 -0
  38. package/contracts/operations/editor.save/output.schema.json +23 -0
  39. package/contracts/operations/editor.screenshot/input.schema.json +7 -0
  40. package/contracts/operations/editor.screenshot/output.schema.json +16 -0
  41. package/contracts/operations/editor.snapshot/input.schema.json +7 -0
  42. package/contracts/operations/editor.snapshot/output.schema.json +148 -0
  43. package/contracts/operations/model.get/input.schema.json +16 -0
  44. package/contracts/operations/model.get/output.schema.json +167 -0
  45. package/contracts/operations/model.list/input.schema.json +13 -0
  46. package/contracts/operations/model.list/output.schema.json +97 -0
  47. package/contracts/operations/task.get/input.schema.json +14 -0
  48. package/contracts/operations/task.get/output.schema.json +103 -0
  49. package/contracts/operations/task.list/input.schema.json +18 -0
  50. package/contracts/operations/task.list/output.schema.json +53 -0
  51. package/contracts/operations/tool.call/input.schema.json +31 -0
  52. package/contracts/operations/tool.call/output.schema.json +115 -0
  53. package/contracts/operations/tool.list/input.schema.json +6 -0
  54. package/contracts/operations/tool.list/output.schema.json +40 -0
  55. package/dist/bin/agent-worker.js +41 -0
  56. package/dist/bin/insmind-cli.js +60 -0
  57. package/dist/bin/postinstall.js +69 -0
  58. package/dist/src/bootstrap/create-cli.js +124 -0
  59. package/dist/src/bootstrap/create-runtime.js +451 -0
  60. package/dist/src/bootstrap/run-agent-worker.js +37 -0
  61. package/dist/src/bootstrap/validators.js +169 -0
  62. package/dist/src/cli/action-binding.js +109 -0
  63. package/dist/src/cli/agent-commands.js +75 -0
  64. package/dist/src/cli/auth-commands.js +58 -0
  65. package/dist/src/cli/credits-command.js +23 -0
  66. package/dist/src/cli/dam-commands.js +470 -0
  67. package/dist/src/cli/editor-commands.js +74 -0
  68. package/dist/src/cli/errors.js +208 -0
  69. package/dist/src/cli/model-commands.js +62 -0
  70. package/dist/src/cli/org-commands.js +58 -0
  71. package/dist/src/cli/presenter.js +123 -0
  72. package/dist/src/cli/prompt.js +30 -0
  73. package/dist/src/cli/task-commands.js +48 -0
  74. package/dist/src/cli/tool-commands.js +101 -0
  75. package/dist/src/cli/update-command.js +15 -0
  76. package/dist/src/contracts/schema.js +4 -0
  77. package/dist/src/features/agent/creative-agent-adapter.js +42 -0
  78. package/dist/src/features/agent/creative-protocol.js +421 -0
  79. package/dist/src/features/agent/creative-stream.js +138 -0
  80. package/dist/src/features/agent/filems-resource-auth-key-provider.js +23 -0
  81. package/dist/src/features/agent/resource-authorizer.js +47 -0
  82. package/dist/src/features/agent/result-reader.js +30 -0
  83. package/dist/src/features/agent/use-cases.js +153 -0
  84. package/dist/src/features/auth/access-policy.js +101 -0
  85. package/dist/src/features/auth/credential-store.js +62 -0
  86. package/dist/src/features/auth/sso-service.js +196 -0
  87. package/dist/src/features/auth/state.js +129 -0
  88. package/dist/src/features/auth/use-cases.js +162 -0
  89. package/dist/src/features/credits/use-cases.js +52 -0
  90. package/dist/src/features/dam/asset-projection.js +278 -0
  91. package/dist/src/features/dam/dam-api-adapter.js +562 -0
  92. package/dist/src/features/dam/file-downloader.js +242 -0
  93. package/dist/src/features/dam/object-storage.js +193 -0
  94. package/dist/src/features/dam/operation-executor.js +72 -0
  95. package/dist/src/features/dam/registered-uploader.js +247 -0
  96. package/dist/src/features/dam/repository-catalog.js +127 -0
  97. package/dist/src/features/dam/storage-upload.js +141 -0
  98. package/dist/src/features/dam/transient-uploader.js +17 -0
  99. package/dist/src/features/dam/use-cases.js +470 -0
  100. package/dist/src/features/editor/bridge-client.js +109 -0
  101. package/dist/src/features/editor/bridge-process.js +229 -0
  102. package/dist/src/features/editor/bridge-server.js +337 -0
  103. package/dist/src/features/editor/protocol.js +1 -0
  104. package/dist/src/features/editor/public-url.js +36 -0
  105. package/dist/src/features/editor/session-state.js +78 -0
  106. package/dist/src/features/editor/session.js +213 -0
  107. package/dist/src/features/editor/use-cases.js +88 -0
  108. package/dist/src/features/org/org-service.js +76 -0
  109. package/dist/src/features/org/use-cases.js +163 -0
  110. package/dist/src/features/skill/bundled-skills.js +63 -0
  111. package/dist/src/features/skill/installer.js +271 -0
  112. package/dist/src/features/task/agent-background.js +63 -0
  113. package/dist/src/features/task/store.js +97 -0
  114. package/dist/src/features/task/types.js +1 -0
  115. package/dist/src/features/task/use-cases.js +139 -0
  116. package/dist/src/features/tool/catalog.js +83 -0
  117. package/dist/src/features/tool/dynamic-schema.js +128 -0
  118. package/dist/src/features/tool/mns-catalog-adapter.js +265 -0
  119. package/dist/src/features/tool/tool-api-adapter.js +369 -0
  120. package/dist/src/features/tool/use-cases.js +180 -0
  121. package/dist/src/features/update/latest-version.js +37 -0
  122. package/dist/src/features/update/update-notification.js +271 -0
  123. package/dist/src/features/update/update-service.js +226 -0
  124. package/dist/src/platform/installation-owner.js +81 -0
  125. package/dist/src/platform/json-input.js +67 -0
  126. package/dist/src/platform/local-json-file.js +59 -0
  127. package/dist/src/platform/open-browser.js +8 -0
  128. package/dist/src/platform/redact.js +80 -0
  129. package/dist/src/platform/remote-error-evidence.js +80 -0
  130. package/dist/src/platform/remote-protocol.js +10 -0
  131. package/dist/src/platform/resource-auth-key.js +1 -0
  132. package/dist/src/platform/safe-upload-file.js +146 -0
  133. package/dist/src/platform/signature.js +20 -0
  134. package/dist/src/platform/signed-http-transport.js +144 -0
  135. package/dist/src/platform/task-observer.js +1 -0
  136. package/dist/src/platform/url-safety.js +100 -0
  137. package/dist/src/product/billing.js +47 -0
  138. package/dist/src/product/config.js +85 -0
  139. package/dist/src/product/locale.js +38 -0
  140. package/dist/src/product/text.js +3 -0
  141. package/dist/src/telemetry/invocation.js +156 -0
  142. package/dist/src/telemetry/sls-sink.js +30 -0
  143. package/package.json +53 -0
  144. package/skills/insmind-cli/SKILL.md +15 -0
  145. package/skills/insmind-cli/references/agent.md +34 -0
  146. package/skills/insmind-cli/references/auth.md +8 -0
  147. package/skills/insmind-cli/references/creation.md +40 -0
  148. package/skills/insmind-cli/references/dam.md +51 -0
  149. package/skills/insmind-cli/references/editor.md +184 -0
  150. package/skills/insmind-cli/references/errors.md +29 -0
  151. package/skills/insmind-cli/references/generation-constraints.md +36 -0
  152. package/skills/insmind-cli/references/tool.md +31 -0
  153. package/skills/insmind-cli/references/update.md +11 -0
@@ -0,0 +1,208 @@
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";
4
+ import { CommanderError } from "commander";
5
+ import { AuthExpiredError, AuthRequiredError } from "../features/auth/access-policy.js";
6
+ import { AuthStateInvalidError } from "../features/auth/state.js";
7
+ import { SsoRequestError } from "../features/auth/sso-service.js";
8
+ import { AuthorizedAccountContextMissingError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
9
+ import { AgentInputError } from "../features/agent/use-cases.js";
10
+ import { ToolInputError } from "../features/tool/catalog.js";
11
+ import { ToolTaskFailedError } from "../features/tool/tool-api-adapter.js";
12
+ import { ObjectStorageUploadError } from "../features/dam/object-storage.js";
13
+ import { DamAssetNotDownloadableError, DamAssetNotFoundError, DamFolderNotFoundError } from "../features/dam/dam-api-adapter.js";
14
+ import { DamDownloadDestinationExistsError } from "../features/dam/file-downloader.js";
15
+ import { DamOperationFailedError } from "../features/dam/operation-executor.js";
16
+ import { DamInputError, DamOperationUnconfirmedError, DamRepositoryNotFoundError } from "../features/dam/use-cases.js";
17
+ import { OrganizationResponseError } from "../features/org/org-service.js";
18
+ import { OrganizationBindFailedError, OrganizationInvalidError, OrgUsageError } from "../features/org/use-cases.js";
19
+ import { RemoteRequestError } from "../platform/signed-http-transport.js";
20
+ import { RemoteProtocolError } from "../platform/remote-protocol.js";
21
+ import { InputContractError, OutputContractError } from "../bootstrap/validators.js";
22
+ import { JsonInputError } from "../platform/json-input.js";
23
+ import { LocalFileInputError } from "../platform/safe-upload-file.js";
24
+ import { EditorBridgeError } from "../features/editor/bridge-client.js";
25
+ import { EditorNotReadyError, EditorSessionNotFoundError, EditorTargetError } from "../features/editor/session.js";
26
+ import { UpdateError } from "../features/update/update-service.js";
27
+ export class CliUsageError extends Error {
28
+ constructor() {
29
+ super("命令或参数无效。");
30
+ this.name = "CliUsageError";
31
+ }
32
+ }
33
+ const INSUFFICIENT_CREDITS_REMOTE_CODE = "12020770";
34
+ const INSUFFICIENT_CREDITS_NEXT_STEPS = [
35
+ "前往 https://www.gaoding.art/pricing 购买稿豆",
36
+ "也可以执行 gd-cli org switch 切换到有可用稿豆的组织",
37
+ "处理后重新发起本次创作"
38
+ ];
39
+ export function isHelpOutcome(error) {
40
+ return error instanceof CommanderError
41
+ && error.exitCode === 0
42
+ && (error.code === "commander.helpDisplayed" || error.code === "commander.version");
43
+ }
44
+ export function mapCliError(error, options) {
45
+ const insmind = options.product?.id === "insmind";
46
+ const command = options.product?.commandName ?? "gd-cli";
47
+ if (options.aborted)
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);
57
+ if (error instanceof AuthRequiredError) {
58
+ if (insmind)
59
+ return failure("AUTH_REQUIRED", `Run ${command} auth login first.`, 1, [`${command} auth login`]);
60
+ return failure("AUTH_REQUIRED", "请先执行 gd-cli auth login", 1, ["gd-cli auth login"]);
61
+ }
62
+ if (error instanceof AuthExpiredError) {
63
+ if (insmind)
64
+ return failure("AUTH_EXPIRED", "Authentication expired. Sign out and sign in again.", 1, [`${command} auth logout`, `${command} auth login`]);
65
+ return failure("AUTH_EXPIRED", "登录已过期,请退出后重新登录。", 1, ["gd-cli auth logout", "gd-cli auth login"]);
66
+ }
67
+ if (error instanceof AuthStateInvalidError) {
68
+ if (insmind)
69
+ return failure("AUTH_STATE_INVALID", "Local authentication state is invalid. Sign out and sign in again.", 1, [`${command} auth logout`, `${command} auth login`]);
70
+ return failure("AUTH_STATE_INVALID", "本地登录状态已失效,请退出后重新登录。", 1, ["gd-cli auth logout", "gd-cli auth login"]);
71
+ }
72
+ if (error instanceof OrganizationInvalidError) {
73
+ if (insmind)
74
+ return failure("AUTH_STATE_INVALID", "The account context is unavailable. Sign out and sign in again.", 1, [`${command} auth logout`, `${command} auth login`]);
75
+ return failure("ORG_INVALID", "所选组织不可用,请重新选择组织。", 1, ["gd-cli org switch"]);
76
+ }
77
+ if (error instanceof UpdateError) {
78
+ return failure(error.code, error.message, 1, error.nextSteps);
79
+ }
80
+ if (error instanceof EditorTargetError) {
81
+ if (insmind)
82
+ return failure(error.code, "Editor target must be a work ID or a complete trusted insMind Editor URL.", 2);
83
+ return failure(error.code, error.message, 2);
84
+ }
85
+ if (error instanceof OrgUsageError
86
+ || error instanceof CliUsageError
87
+ || error instanceof JsonInputError
88
+ || error instanceof InputContractError
89
+ || error instanceof AgentInputError
90
+ || error instanceof ToolInputError
91
+ || error instanceof DamInputError
92
+ || error instanceof LocalFileInputError
93
+ || error instanceof CommanderError) {
94
+ if (insmind)
95
+ return failure("USAGE_ERROR", "Invalid command or arguments. See --help.", 2);
96
+ return failure("USAGE_ERROR", "命令或参数无效,请查看 --help。", 2);
97
+ }
98
+ if (isInsufficientCreditsError(error)) {
99
+ if (insmind)
100
+ return failure("INSUFFICIENT_CREDITS", "There are not enough insMind credits to complete this creation.", 1, [`Buy credits at ${options.product.pricingUrl.href}`, "Retry after adding credits."]);
101
+ return failure("INSUFFICIENT_CREDITS", "当前组织稿豆不足,无法完成本次创作。", 1, INSUFFICIENT_CREDITS_NEXT_STEPS);
102
+ }
103
+ if (error instanceof RemoteProtocolError) {
104
+ if (insmind)
105
+ return failure("REMOTE_PROTOCOL_INCOMPATIBLE", "The insMind service returned a result this CLI cannot safely process; processing stopped to avoid duplicate creation.", 1);
106
+ return failure("REMOTE_PROTOCOL_INCOMPATIBLE", "稿定服务返回了当前 CLI 无法安全处理的结果;为避免重复创作,已停止处理。", 1);
107
+ }
108
+ if (error instanceof ToolTaskFailedError) {
109
+ return failure("TOOL_TASK_FAILED", insmind ? "The Tool task failed." : "稿定工具任务执行失败。", 1);
110
+ }
111
+ if (error instanceof DamAssetNotFoundError) {
112
+ return failure("DAM_ASSET_NOT_FOUND", insmind ? "The requested asset was not found." : "未找到指定的 DAM 素材。", 1);
113
+ }
114
+ if (error instanceof DamFolderNotFoundError) {
115
+ return failure("DAM_FOLDER_NOT_FOUND", insmind ? "The requested folder was not found." : "未找到指定的 DAM 文件夹。", 1);
116
+ }
117
+ if (error instanceof DamAssetNotDownloadableError) {
118
+ if (insmind)
119
+ return failure("DAM_ASSET_NOT_DOWNLOADABLE", "The asset has no downloadable source file. Check its current status first.", 1, [`${command} dam get <asset-id>`]);
120
+ return failure("DAM_ASSET_NOT_DOWNLOADABLE", "该素材当前没有可下载的源文件;请先查看素材状态。", 1, ["gd-cli dam get <asset-id>"]);
121
+ }
122
+ if (error instanceof DamDownloadDestinationExistsError) {
123
+ return failure("DAM_DOWNLOAD_DESTINATION_EXISTS", insmind
124
+ ? "The destination file already exists and was not overwritten. Choose another output directory."
125
+ : "目标文件已存在,未覆盖任何文件;请更换输出目录或移走同名文件。", 1);
126
+ }
127
+ if (error instanceof DamOperationUnconfirmedError) {
128
+ return failure("DAM_OPERATION_UNCONFIRMED", insmind
129
+ ? "The operation was submitted, but its final result could not be confirmed. Check the destination before retrying."
130
+ : "操作已提交,但未能确认最终结果;请先查询目标位置,不要立即重复提交。", 1);
131
+ }
132
+ if (error instanceof DamOperationFailedError) {
133
+ return failure("DAM_OPERATION_FAILED", insmind
134
+ ? "The asset operation failed. Use the diagnostic ID to investigate before retrying."
135
+ : "DAM 操作执行失败;请先按诊断 ID 查询原因,不要立即重复提交。", 1);
136
+ }
137
+ if (error instanceof DamRepositoryNotFoundError) {
138
+ if (insmind)
139
+ return failure("DAM_REPOSITORY_NOT_FOUND", "No accessible asset repository is available for this account.", 1, [`${command} auth logout`, `${command} auth login`]);
140
+ return failure("DAM_REPOSITORY_NOT_FOUND", "当前组织没有可用的 DAM 资源库。", 1, ["gd-cli org list", "gd-cli org switch --org <org-id>"]);
141
+ }
142
+ if (error instanceof RemoteRequestError
143
+ || error instanceof SsoRequestError
144
+ || error instanceof DeviceAuthorizationExpiredError
145
+ || error instanceof OrganizationResponseError
146
+ || error instanceof OrganizationBindFailedError
147
+ || error instanceof ObjectStorageUploadError
148
+ || error instanceof AuthorizedAccountContextMissingError) {
149
+ if (insmind)
150
+ return failure("REMOTE_REQUEST_FAILED", "The insMind service request failed.", 1);
151
+ return failure("REMOTE_REQUEST_FAILED", "稿定服务请求失败。", 1);
152
+ }
153
+ if (error instanceof OutputContractError) {
154
+ if (insmind)
155
+ return failure("INTERNAL_ERROR", "CLI result validation failed.", 1);
156
+ return failure("INTERNAL_ERROR", "CLI 内部结果校验失败。", 1);
157
+ }
158
+ if (error instanceof EditorBridgeError
159
+ || error instanceof EditorSessionNotFoundError
160
+ || error instanceof EditorNotReadyError) {
161
+ if (insmind) {
162
+ if (error instanceof EditorSessionNotFoundError)
163
+ return failure(error.code, `No Editor session is available. Run ${command} editor connect [target] again.`, 1);
164
+ if (error instanceof EditorNotReadyError)
165
+ return failure(error.code, "The Editor page did not become ready in time.", 1);
166
+ return failure(error.code, "The Editor operation failed.", 1);
167
+ }
168
+ return failure(error.code, error.message, 1);
169
+ }
170
+ return failure("INTERNAL_ERROR", insmind ? "The CLI encountered an internal error." : "CLI 发生内部错误。", 1);
171
+ }
172
+ function isInsufficientCreditsError(error) {
173
+ return (error instanceof RemoteRequestError
174
+ || error instanceof RemoteProtocolError
175
+ || error instanceof ToolTaskFailedError) && error.remoteCode === INSUFFICIENT_CREDITS_REMOTE_CODE;
176
+ }
177
+ export function classifyTelemetryError(error) {
178
+ const outcome = mapCliError(error, { aborted: false });
179
+ const remoteError = error instanceof RemoteRequestError
180
+ || error instanceof RemoteProtocolError
181
+ || error instanceof ToolTaskFailedError
182
+ ? error
183
+ : undefined;
184
+ return {
185
+ outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
186
+ ...(outcome.kind === "failure" ? { errorCode: outcome.failure.code } : {}),
187
+ ...(error instanceof RemoteRequestError && error.status !== undefined
188
+ ? { httpStatus: error.status }
189
+ : {}),
190
+ ...(remoteError?.remoteCode === undefined
191
+ ? {}
192
+ : { remoteErrorCode: remoteError.remoteCode }),
193
+ ...(remoteError?.remoteBody === undefined
194
+ ? {}
195
+ : { remoteErrorBody: remoteError.remoteBody })
196
+ };
197
+ }
198
+ function failure(code, message, exitCode, nextSteps) {
199
+ return {
200
+ kind: "failure",
201
+ failure: {
202
+ code,
203
+ message,
204
+ ...(nextSteps ? { details: { next_steps: nextSteps } } : {})
205
+ },
206
+ exitCode
207
+ };
208
+ }
@@ -0,0 +1,62 @@
1
+ import { bindAction } from "./action-binding.js";
2
+ import { CliUsageError } from "./errors.js";
3
+ import { productText as text } from "../product/text.js";
4
+ export function registerModelCommands(program, runtime) {
5
+ const model = program.command("model")
6
+ .description(text(runtime.product, "创作模型", "Creation models"))
7
+ .helpCommand(false);
8
+ const list = model.command("list")
9
+ .description(text(runtime.product, "列出可用模型", "List available models"))
10
+ .option("--tool <tool>", text(runtime.product, "按工具筛选", "filter by tool"))
11
+ .allowExcessArguments(false);
12
+ bindAction(list, "organization", async (context, signal) => {
13
+ const selectedTool = list.opts().tool;
14
+ const input = selectedTool === undefined ? {} : { tool: selectedTool };
15
+ await runtime.telemetry.stage("input", async () => {
16
+ runtime.validators.modelListInput(input);
17
+ });
18
+ const result = await runtime.tool.listModels({
19
+ input,
20
+ access: {
21
+ credential: context.state.credential,
22
+ organizationId: context.state.organization.id
23
+ },
24
+ signal
25
+ });
26
+ if (selectedTool !== undefined)
27
+ runtime.telemetry.annotate({ tool_name: selectedTool });
28
+ await runtime.telemetry.stage("output", async () => {
29
+ runtime.validators.modelListOutput(result);
30
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
31
+ });
32
+ }, { operation: "model.list" });
33
+ const get = model.command("get")
34
+ .description(text(runtime.product, "查看模型完整信息", "Show complete model information"))
35
+ .argument("<model>", text(runtime.product, "模型机器标识", "model machine identifier"))
36
+ .allowExcessArguments(false);
37
+ bindAction(get, "organization", async (context, signal) => {
38
+ const modelName = get.processedArgs[0];
39
+ if (typeof modelName !== "string" || modelName.trim() === "")
40
+ throw new CliUsageError();
41
+ const input = { model: modelName };
42
+ await runtime.telemetry.stage("input", async () => {
43
+ runtime.validators.modelGetInput(input);
44
+ });
45
+ const access = {
46
+ credential: context.state.credential,
47
+ organizationId: context.state.organization.id
48
+ };
49
+ const result = await runtime.tool.getModel({
50
+ input,
51
+ access,
52
+ signal
53
+ });
54
+ runtime.telemetry.annotate({ model_id: modelName });
55
+ await runtime.telemetry.stage("output", async () => {
56
+ runtime.validators.modelGetOutput(result);
57
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
58
+ });
59
+ }, {
60
+ operation: "model.get"
61
+ });
62
+ }
@@ -0,0 +1,58 @@
1
+ import { bindAction } from "./action-binding.js";
2
+ import { OrgUsageError } from "../features/org/use-cases.js";
3
+ import { orgCurrentView, orgListView } from "./presenter.js";
4
+ export function registerOrgCommands(program, runtime) {
5
+ const org = program.command("org")
6
+ .description("组织选择")
7
+ .helpCommand(false);
8
+ const list = leaf(org.command("list"))
9
+ .description("列出可用组织")
10
+ .option("--json", "输出 JSON");
11
+ bindAction(list, "credential", async (context, signal) => {
12
+ const result = await runtime.org.list({ state: context.state, signal });
13
+ await runtime.telemetry.stage("output", async () => {
14
+ runtime.validators.orgList(result);
15
+ runtime.presenter.result(result, {
16
+ json: list.opts().json === true,
17
+ view: orgListView
18
+ });
19
+ });
20
+ }, { operation: "org.list" });
21
+ const current = leaf(org.command("current"))
22
+ .description("查看当前组织")
23
+ .option("--json", "输出 JSON");
24
+ bindAction(current, "none", async () => {
25
+ const result = await runtime.org.current();
26
+ await runtime.telemetry.stage("output", async () => {
27
+ runtime.validators.orgCurrent(result);
28
+ runtime.presenter.result(result, {
29
+ json: current.opts().json === true,
30
+ view: orgCurrentView
31
+ });
32
+ });
33
+ }, { operation: "org.current" });
34
+ const switchCommand = leaf(org.command("switch"))
35
+ .description("切换当前组织")
36
+ .option("--org <org-id>", "指定组织 ID");
37
+ bindAction(switchCommand, "credential", async (context, signal) => {
38
+ const organizationId = switchCommand.opts().org;
39
+ if (organizationId === undefined && !isInteractive(runtime))
40
+ throw new OrgUsageError();
41
+ const record = await runtime.org.switchOrganization({
42
+ state: context.state,
43
+ ...(organizationId === undefined
44
+ ? { select: (records) => runtime.prompt.choose(records, signal) }
45
+ : { organizationId }),
46
+ signal
47
+ });
48
+ await runtime.telemetry.stage("output", async () => {
49
+ runtime.presenter.success(`已切换到${record.publicName} (${record.id})。`);
50
+ });
51
+ }, { operation: "org.switch" });
52
+ }
53
+ function leaf(command) {
54
+ return command.allowExcessArguments(false);
55
+ }
56
+ function isInteractive(runtime) {
57
+ return runtime.io.inputTerminal && runtime.io.stderrTerminal;
58
+ }
@@ -0,0 +1,123 @@
1
+ import * as QRCode from "qrcode";
2
+ export function createPresenter(options) {
3
+ const insmind = options.product?.id === "insmind";
4
+ const qrCode = options.qrCode ?? ((text) => QRCode.toString(text, {
5
+ type: "terminal",
6
+ small: true
7
+ }));
8
+ return {
9
+ result(value, presentation) {
10
+ options.writeOut(presentation.json
11
+ ? `${JSON.stringify(value)}\n`
12
+ : `${presentation.view(value)}\n`);
13
+ },
14
+ success(message) {
15
+ options.writeOut(`${message}\n`);
16
+ },
17
+ async authorization(input) {
18
+ options.writeError(`${insmind ? "Authorization URL" : "授权地址"}: ${input.url.href}\n`);
19
+ if (input.terminal)
20
+ options.writeError(await qrCode(input.url.href));
21
+ },
22
+ notice(message) {
23
+ options.writeError(`${insmind ? "Notice" : "提示"}: ${message}\n`);
24
+ },
25
+ warning(message) {
26
+ options.writeError(`${insmind ? "Warning" : "警告"}: ${message}\n`);
27
+ },
28
+ error(outcome, presentation) {
29
+ if (outcome.kind === "interrupted") {
30
+ options.writeError(insmind ? "Cancelled.\n" : "已取消。\n");
31
+ return;
32
+ }
33
+ if (presentation.json) {
34
+ options.writeError(`${JSON.stringify({
35
+ error: {
36
+ ...outcome.failure,
37
+ ...(presentation.traceId
38
+ ? { trace_id: presentation.traceId }
39
+ : {})
40
+ }
41
+ })}\n`);
42
+ return;
43
+ }
44
+ options.writeError(`${outcome.failure.code}: ${outcome.failure.message}\n`);
45
+ const nextSteps = nextStepsFrom(outcome.failure.details);
46
+ if (nextSteps.length > 0) {
47
+ options.writeError(`${insmind ? "Next steps" : "下一步"}: ${nextSteps.join(insmind ? ", " : ",")}\n`);
48
+ }
49
+ if (presentation.traceId) {
50
+ options.writeError(`${insmind ? "Diagnostic ID" : "诊断 ID"}: ${presentation.traceId}\n`);
51
+ }
52
+ }
53
+ };
54
+ }
55
+ export const authStatusView = (value) => {
56
+ const status = value;
57
+ if (!status.logged_in)
58
+ return lines("未登录", nextStepsLine(status.next_steps));
59
+ return lines("已登录", `账号: ${status.account.name ?? "未记录"}${status.account.user_id ? ` (${status.account.user_id})` : ""}`, status.organization
60
+ ? `组织: ${status.organization.name} (${status.organization.id})`
61
+ : "组织: 未选择", `凭证: ${status.credential.valid ? "有效" : "已过期"},到期 ${status.credential.expires_at}`, status.credential.scope.length > 0
62
+ ? `权限: ${status.credential.scope.join(", ")}`
63
+ : "权限: 未声明", nextStepsLine(status.next_steps));
64
+ };
65
+ export function authStatusViewFor(product) {
66
+ if (product.id !== "insmind")
67
+ return authStatusView;
68
+ return (value) => {
69
+ const status = value;
70
+ if (!status.logged_in)
71
+ return lines("Not signed in", nextStepsLineFor(status.next_steps, true));
72
+ return lines("Signed in", `Account: ${status.account.name ?? "Not recorded"}${status.account.user_id ? ` (${status.account.user_id})` : ""}`, `Credential: ${status.credential.valid ? "valid" : "expired"}; expires ${status.credential.expires_at}`, status.credential.scope.length > 0
73
+ ? `Scopes: ${status.credential.scope.join(", ")}`
74
+ : "Scopes: not declared", nextStepsLineFor(status.next_steps, true));
75
+ };
76
+ }
77
+ export const orgListView = (value) => {
78
+ const result = value;
79
+ if (result.orgs.length === 0)
80
+ return "没有可用组织。";
81
+ return result.orgs.map((organization) => {
82
+ const product = organization.product_name ? ` · ${organization.product_name}` : "";
83
+ const current = organization.id === result.current_org_id ? " [当前]" : "";
84
+ return `${organization.name} (${organization.id})${product}${current}`;
85
+ }).join("\n");
86
+ };
87
+ export const orgCurrentView = (value) => {
88
+ const result = value;
89
+ return result.organization
90
+ ? `当前组织: ${result.organization.name} (${result.organization.id})`
91
+ : lines("尚未选择组织。", nextStepsLine(result.next_steps));
92
+ };
93
+ export const repositoryListView = (value) => {
94
+ const result = value;
95
+ if (result.repositories.length === 0)
96
+ return "没有可用资源库。";
97
+ return result.repositories.map((repository) => {
98
+ const permission = repository.permission_code === undefined
99
+ ? ""
100
+ : ` · ${repository.permission_code}`;
101
+ const defaultMarker = repository.is_default ? " [默认]" : "";
102
+ return `${repository.name} (${repository.repository_id}) · ${repository.type}${permission}${defaultMarker}`;
103
+ }).join("\n");
104
+ };
105
+ function lines(...values) {
106
+ return values.filter((value) => Boolean(value)).join("\n");
107
+ }
108
+ function nextStepsLineFor(nextSteps, english) {
109
+ return nextSteps.length > 0
110
+ ? `${english ? "Next steps" : "下一步"}: ${nextSteps.join(english ? ", " : ",")}`
111
+ : undefined;
112
+ }
113
+ function nextStepsLine(nextSteps) {
114
+ return nextSteps.length > 0 ? `下一步: ${nextSteps.join(",")}` : undefined;
115
+ }
116
+ function nextStepsFrom(details) {
117
+ if (typeof details !== "object" || details === null || Array.isArray(details))
118
+ return [];
119
+ const nextSteps = details.next_steps;
120
+ return Array.isArray(nextSteps) && nextSteps.every((item) => typeof item === "string")
121
+ ? nextSteps
122
+ : [];
123
+ }
@@ -0,0 +1,30 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { OrganizationInvalidError } from "../features/org/use-cases.js";
3
+ export function createOrganizationPrompt(options) {
4
+ return {
5
+ async choose(records, signal) {
6
+ signal.throwIfAborted();
7
+ if (records.length === 0)
8
+ throw new OrganizationInvalidError();
9
+ const readline = createInterface({ input: options.input, output: options.output });
10
+ try {
11
+ options.output.write("请选择组织:\n");
12
+ records.forEach((record, index) => {
13
+ const product = record.productName ? ` · ${record.productName}` : "";
14
+ options.output.write(`${index + 1}. ${record.publicName} (${record.id})${product}\n`);
15
+ });
16
+ while (true) {
17
+ const answer = (await readline.question("输入序号: ", { signal })).trim();
18
+ const index = Number(answer) - 1;
19
+ if (Number.isInteger(index) && index >= 0 && index < records.length) {
20
+ return records[index].id;
21
+ }
22
+ options.output.write("请输入列表中的有效序号。\n");
23
+ }
24
+ }
25
+ finally {
26
+ readline.close();
27
+ }
28
+ }
29
+ };
30
+ }
@@ -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
+ }
@@ -0,0 +1,101 @@
1
+ import { bindAction, bindPreparedAction } from "./action-binding.js";
2
+ import { CliUsageError } from "./errors.js";
3
+ import { productText as text } from "../product/text.js";
4
+ export function registerToolCommands(program, runtime) {
5
+ const tool = program.command("tool")
6
+ .description(text(runtime.product, "创作工具", "Creation tools"))
7
+ .helpCommand(false);
8
+ const list = tool.command("list")
9
+ .description(text(runtime.product, "列出可用工具", "List available tools"))
10
+ .allowExcessArguments(false);
11
+ bindAction(list, "organization", async (context, signal) => {
12
+ const result = await runtime.tool.listTools({
13
+ access: {
14
+ credential: context.state.credential,
15
+ organizationId: context.state.organization.id
16
+ },
17
+ signal
18
+ });
19
+ await runtime.telemetry.stage("output", async () => {
20
+ runtime.validators.toolListOutput(result);
21
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
22
+ });
23
+ }, { operation: "tool.list" });
24
+ const call = tool.command("call")
25
+ .description(text(runtime.product, "调用创作工具", "Call a creation tool"))
26
+ .argument("<tool>", text(runtime.product, "工具机器标识", "tool machine identifier"))
27
+ .option("--schema", text(runtime.product, "输出当前工具所有模型参数并集的输入 Schema", "output the tool-wide input Schema"))
28
+ .option("--input <file|->", text(runtime.product, "从文件或标准输入读取参数 JSON", "read argument JSON from a file or stdin"))
29
+ .option("--async", text(runtime.product, "提交后返回 taskId,通过 task get 查询结果", "return taskId after submission; retrieve results with task get"))
30
+ .allowExcessArguments(false);
31
+ call.addHelpText("after", [
32
+ "",
33
+ text(runtime.product, "--async 在服务端受理后输出包含 taskId 和 state 的 JSON;退出码 0 仅表示受理。", "--async returns JSON with taskId and state after acceptance; exit code 0 means accepted only."),
34
+ 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."),
35
+ text(runtime.product, "默认等待原 Tool 结果;任务 ID 写入 stderr,stdout 保持原 JSON。", "By default, the command waits for the original Tool result; stderr shows the Task ID and stdout keeps the result JSON."),
36
+ text(runtime.product, `结果未收到时用 ${runtime.product.commandName} task list 找到调用,再用 ${runtime.product.commandName} task get <id> 查询,不重复生成。`, `If output is missing, use ${runtime.product.commandName} task list and ${runtime.product.commandName} task get <id> to recover it without generating again.`),
37
+ text(runtime.product, "查询返回同一份 usage;Tool usage.cost 为当次目录预估价格。", "Queries return the same usage; Tool usage.cost is the catalog price estimate for that invocation."),
38
+ ""
39
+ ].join("\n"));
40
+ bindPreparedAction(call, "organization", async (signal) => {
41
+ signal.throwIfAborted();
42
+ const name = call.processedArgs[0];
43
+ if (typeof name !== "string" || name.trim() === "")
44
+ throw new CliUsageError();
45
+ const options = call.opts();
46
+ const modes = Number(options.schema === true) + Number(options.input !== undefined);
47
+ if (modes !== 1 || (options.schema && options.async))
48
+ throw new CliUsageError();
49
+ if (options.schema === true) {
50
+ return { handled: false, input: { mode: "schema", name } };
51
+ }
52
+ const argumentsInput = await runtime.jsonInput.read(options.input, signal);
53
+ const input = { name, arguments: argumentsInput };
54
+ runtime.validators.toolCallInput(input);
55
+ return { handled: false, input: { mode: "call", input, async: options.async === true } };
56
+ }, async (context, prepared, signal) => {
57
+ const access = {
58
+ credential: context.state.credential,
59
+ organizationId: context.state.organization.id
60
+ };
61
+ if (prepared.mode === "schema") {
62
+ const schema = await runtime.tool.getArgumentsSchema({
63
+ name: prepared.name,
64
+ access,
65
+ signal
66
+ });
67
+ runtime.telemetry.annotate({ tool_name: prepared.name });
68
+ await runtime.telemetry.stage("output", async () => {
69
+ runtime.io.writeOut(`${JSON.stringify(schema)}\n`);
70
+ });
71
+ return;
72
+ }
73
+ const task = {
74
+ state: context.state,
75
+ operation: "tool.call",
76
+ label: `${prepared.input.name}: ${String(prepared.input.arguments.prompt ?? prepared.input.arguments.model ?? "")}`
77
+ };
78
+ if (prepared.async) {
79
+ const result = await runtime.tasks.submit({ ...task,
80
+ run: observe => runtime.tool.submit({ input: prepared.input, access, signal, observe }) });
81
+ runtime.validators.taskResult(result);
82
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
83
+ return;
84
+ }
85
+ const run = async (observe) => {
86
+ const result = await runtime.tool.call({ input: prepared.input, access, signal,
87
+ ...(observe ? { observe } : {}) });
88
+ runtime.validators.toolCallOutput(result);
89
+ return result;
90
+ };
91
+ const result = await runtime.tasks.track({ ...task, run });
92
+ await runtime.telemetry.stage("output", async () => {
93
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
94
+ });
95
+ }, {
96
+ operation: "tool.call",
97
+ mode: () => call.opts().schema === true
98
+ ? "schema"
99
+ : "execute"
100
+ });
101
+ }
@@ -0,0 +1,15 @@
1
+ import { bindAction } from "./action-binding.js";
2
+ import { productText as text } from "../product/text.js";
3
+ export function registerUpdateCommand(program, runtime) {
4
+ const update = program.command("update")
5
+ .description(text(runtime.product, "更新 GD CLI 与内置 Agent Skill", "Update insMind CLI and its bundled Agent Skill"))
6
+ .allowExcessArguments(false);
7
+ bindAction(update, "none", async (_context, signal) => {
8
+ const result = await runtime.update.run(signal);
9
+ await runtime.telemetry.stage("output", async () => {
10
+ runtime.presenter.success(result.updated
11
+ ? text(runtime.product, `gd-cli 已更新到 ${result.version},Agent Skill 已同步。`, `insmind-cli updated to ${result.version}; Agent Skill synchronized.`)
12
+ : text(runtime.product, `gd-cli ${result.version} 已是最新版本,Agent Skill 已同步。`, `insmind-cli ${result.version} is current; Agent Skill synchronized.`));
13
+ });
14
+ }, { operation: "update" });
15
+ }
@@ -0,0 +1,4 @@
1
+ import { readFileSync } from "node:fs";
2
+ export function contractSchema(operation, direction) {
3
+ return JSON.parse(readFileSync(new URL(`../../../contracts/operations/${operation}/${direction}.schema.json`, import.meta.url), "utf8"));
4
+ }