@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,271 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { cp, lstat, mkdir, mkdtemp, readFile, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, relative, resolve } from "node:path";
5
+ export class SkillSyncError extends Error {
6
+ results;
7
+ constructor(message, results) {
8
+ super(message);
9
+ this.results = results;
10
+ this.name = "SkillSyncError";
11
+ }
12
+ }
13
+ export async function syncBundledSkills(skills, options = {}) {
14
+ const homeDirectory = options.homeDirectory ?? homedir();
15
+ const platform = options.platform ?? process.platform;
16
+ const results = [];
17
+ for (const skill of skills) {
18
+ assertDescriptor(skill, results);
19
+ const targets = await skillTargets(skill.skill, homeDirectory, options.env ?? {});
20
+ const targetResults = [];
21
+ try {
22
+ const canonical = targets[0];
23
+ let current = await inspectTarget(canonical, skill, canonical.path, platform);
24
+ if (current.status === "conflict" || current.status === "broken") {
25
+ targetResults.push(current);
26
+ throw new Error(current.reason ?? "canonical Skill conflict");
27
+ }
28
+ if (current.status === "missing" || current.status === "outdated") {
29
+ await replaceManagedDirectory(skill, canonical.path, current.status === "outdated");
30
+ current = installed(canonical, "canonical", true);
31
+ }
32
+ targetResults.push(current);
33
+ for (const target of targets.slice(1)) {
34
+ current = await inspectTarget(target, skill, canonical.path, platform);
35
+ if (current.status === "conflict" || current.status === "broken") {
36
+ targetResults.push(current);
37
+ throw new Error(current.reason ?? "Agent host Skill conflict");
38
+ }
39
+ if (current.status === "missing") {
40
+ current = await createLinkOrCopy(skill, target, canonical.path, {
41
+ platform,
42
+ createLink: options.createLink ?? symlink
43
+ });
44
+ }
45
+ else if (current.status === "outdated") {
46
+ await replaceManagedDirectory(skill, target.path, true);
47
+ current = installed(target, "copy", true);
48
+ }
49
+ targetResults.push(current);
50
+ }
51
+ results.push(syncResult(skill, targetResults));
52
+ }
53
+ catch (error) {
54
+ const active = targets[targetResults.length];
55
+ if (active && !targetResults.some((target) => target.host === active.host)) {
56
+ targetResults.push({
57
+ host: active.host,
58
+ path: active.path,
59
+ status: "conflict",
60
+ changed: false,
61
+ reason: message(error)
62
+ });
63
+ }
64
+ results.push(syncResult(skill, targetResults));
65
+ throw new SkillSyncError(`Agent Skill ${skill.skill} 同步失败${active ? ` (${active.path})` : ""}: ${message(error)}`, results);
66
+ }
67
+ }
68
+ return results;
69
+ }
70
+ export async function verifyBundledSkills(skills, options = {}) {
71
+ const homeDirectory = options.homeDirectory ?? homedir();
72
+ const platform = options.platform ?? process.platform;
73
+ const results = [];
74
+ for (const skill of skills) {
75
+ assertDescriptor(skill, results);
76
+ const targets = await skillTargets(skill.skill, homeDirectory, options.env ?? {});
77
+ const canonical = targets[0];
78
+ const inspected = await Promise.all(targets.map((target) => inspectTarget(target, skill, canonical.path, platform)));
79
+ results.push(syncResult(skill, inspected));
80
+ }
81
+ const invalid = results.flatMap((result) => result.targets)
82
+ .find((target) => target.status !== "installed");
83
+ if (invalid) {
84
+ throw new SkillSyncError(`Agent Skill 验收失败 (${invalid.path}): ${invalid.reason ?? invalid.status}`, results);
85
+ }
86
+ return results;
87
+ }
88
+ async function skillTargets(skill, homeDirectory, env) {
89
+ const roots = [
90
+ { host: "claude-code", root: env.CLAUDE_HOME ?? join(homeDirectory, ".claude") },
91
+ { host: "codex", root: env.CODEX_HOME ?? join(homeDirectory, ".codex") },
92
+ { host: "cursor", root: env.CURSOR_HOME ?? join(homeDirectory, ".cursor") },
93
+ { host: "opencode", root: env.OPENCODE_HOME ?? join(homeDirectory, ".config", "opencode") },
94
+ { host: "openclaw", root: env.OPENCLAW_HOME ?? join(homeDirectory, ".openclaw") },
95
+ { host: "workbuddy", root: join(homeDirectory, ".workbuddy") }
96
+ ];
97
+ const detected = await Promise.all(roots.map(async (target) => ({
98
+ ...target,
99
+ detected: Boolean(await lstatMaybe(target.root))
100
+ })));
101
+ return [
102
+ { host: "canonical", path: join(homeDirectory, ".agents", "skills", skill) },
103
+ ...detected
104
+ .filter((target) => target.detected)
105
+ .map((target) => ({ host: target.host, path: join(target.root, "skills", skill) }))
106
+ ];
107
+ }
108
+ async function inspectTarget(target, skill, canonical, platform) {
109
+ const stat = await lstatMaybe(target.path);
110
+ if (!stat)
111
+ return targetResult(target, "missing");
112
+ if (target.host === "canonical") {
113
+ if (stat.isSymbolicLink()) {
114
+ return targetResult(target, "conflict", undefined, "canonical 不能是链接");
115
+ }
116
+ if (!stat.isDirectory()) {
117
+ return targetResult(target, "conflict", undefined, "canonical 路径不是目录");
118
+ }
119
+ const marker = await readMarker(target.path, skill.skill);
120
+ if (!marker || marker.skill !== skill.skill) {
121
+ return targetResult(target, "conflict", undefined, "canonical 缺少合法 marker");
122
+ }
123
+ return targetResult(target, marker.legacy || marker.version !== skill.version ? "outdated" : "installed", "canonical");
124
+ }
125
+ if (stat.isSymbolicLink()) {
126
+ let resolved;
127
+ try {
128
+ resolved = resolve(dirname(target.path), await readlink(target.path));
129
+ }
130
+ catch (error) {
131
+ return targetResult(target, "conflict", linkMode(platform), message(error));
132
+ }
133
+ if (!samePath(resolved, canonical, platform)) {
134
+ return targetResult(target, "conflict", linkMode(platform), "链接未指向 canonical Skill");
135
+ }
136
+ if (!await lstatMaybe(canonical)) {
137
+ return targetResult(target, "broken", linkMode(platform), "canonical Skill 不存在");
138
+ }
139
+ return targetResult(target, "installed", linkMode(platform));
140
+ }
141
+ if (!stat.isDirectory()) {
142
+ return targetResult(target, "conflict", undefined, "宿主路径不是目录或链接");
143
+ }
144
+ const marker = await readMarker(target.path, skill.skill);
145
+ if (!marker || marker.skill !== skill.skill) {
146
+ return targetResult(target, "conflict", undefined, "宿主目录缺少合法 marker");
147
+ }
148
+ return targetResult(target, marker.legacy || marker.version !== skill.version ? "outdated" : "installed", "copy");
149
+ }
150
+ async function createLinkOrCopy(skill, target, canonical, options) {
151
+ await mkdir(dirname(target.path), { recursive: true });
152
+ try {
153
+ if (options.platform === "win32") {
154
+ await options.createLink(canonical, target.path, "junction");
155
+ return installed(target, "junction", true);
156
+ }
157
+ await options.createLink(relative(dirname(target.path), canonical), target.path);
158
+ return installed(target, "symlink", true);
159
+ }
160
+ catch (error) {
161
+ if (await lstatMaybe(target.path))
162
+ throw error;
163
+ await replaceManagedDirectory(skill, target.path, false);
164
+ return installed(target, "copy", true);
165
+ }
166
+ }
167
+ async function replaceManagedDirectory(skill, destination, replace) {
168
+ const parent = dirname(destination);
169
+ await mkdir(parent, { recursive: true });
170
+ const stagingRoot = await mkdtemp(join(parent, ".gd-cli-stage-"));
171
+ const staged = join(stagingRoot, skill.skill);
172
+ let backup;
173
+ try {
174
+ await cp(skill.sourceDirectory, staged, { recursive: true });
175
+ await writeFile(join(staged, ".gd-cli.json"), `${JSON.stringify({ skill: skill.skill, version: skill.version })}\n`);
176
+ if (replace) {
177
+ backup = join(parent, `.gd-cli-backup-${randomUUID()}`);
178
+ await rename(destination, backup);
179
+ }
180
+ try {
181
+ await rename(staged, destination);
182
+ }
183
+ catch (error) {
184
+ if (backup)
185
+ await rename(backup, destination);
186
+ throw error;
187
+ }
188
+ if (backup)
189
+ await rm(backup, { recursive: true, force: false });
190
+ }
191
+ finally {
192
+ await rm(stagingRoot, { recursive: true, force: true });
193
+ }
194
+ }
195
+ async function readMarker(directory, expectedSkill) {
196
+ try {
197
+ const parsed = JSON.parse(await readFile(join(directory, ".gd-cli.json"), "utf8"));
198
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
199
+ return undefined;
200
+ const marker = parsed;
201
+ const keys = Object.keys(marker).sort().join(",");
202
+ if (keys === "version" && expectedSkill === "gd-cli") {
203
+ if (typeof marker.version !== "string" || !marker.version.trim())
204
+ return undefined;
205
+ return { skill: expectedSkill, version: marker.version, legacy: true };
206
+ }
207
+ if (keys !== "skill,version")
208
+ return undefined;
209
+ if (typeof marker.skill !== "string" || !marker.skill.trim())
210
+ return undefined;
211
+ if (typeof marker.version !== "string" || !marker.version.trim())
212
+ return undefined;
213
+ return { skill: marker.skill, version: marker.version, legacy: false };
214
+ }
215
+ catch (error) {
216
+ const code = error.code;
217
+ if (code === "ENOENT" || error instanceof SyntaxError)
218
+ return undefined;
219
+ throw error;
220
+ }
221
+ }
222
+ async function lstatMaybe(path) {
223
+ try {
224
+ return await lstat(path);
225
+ }
226
+ catch (error) {
227
+ const code = error.code;
228
+ if (code === "ENOENT" || code === "ENOTDIR")
229
+ return undefined;
230
+ throw error;
231
+ }
232
+ }
233
+ function assertDescriptor(skill, results) {
234
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(skill.skill) || !skill.version.trim()) {
235
+ throw new SkillSyncError(`Agent Skill descriptor 无效: ${skill.skill}`, results);
236
+ }
237
+ }
238
+ function installed(target, mode, changed) {
239
+ return { host: target.host, path: target.path, status: "installed", mode, changed };
240
+ }
241
+ function targetResult(target, status, mode, reason) {
242
+ return {
243
+ host: target.host,
244
+ path: target.path,
245
+ status,
246
+ ...(mode ? { mode } : {}),
247
+ changed: false,
248
+ ...(reason ? { reason } : {})
249
+ };
250
+ }
251
+ function syncResult(skill, targets) {
252
+ return {
253
+ skill: skill.skill,
254
+ version: skill.version,
255
+ changed: targets.some((target) => target.changed),
256
+ targets
257
+ };
258
+ }
259
+ function linkMode(platform) {
260
+ return platform === "win32" ? "junction" : "symlink";
261
+ }
262
+ function samePath(left, right, platform) {
263
+ const normalizedLeft = resolve(left);
264
+ const normalizedRight = resolve(right);
265
+ return platform === "win32"
266
+ ? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
267
+ : normalizedLeft === normalizedRight;
268
+ }
269
+ function message(error) {
270
+ return error instanceof Error ? error.message : String(error);
271
+ }
@@ -0,0 +1,63 @@
1
+ import { fork } from "node:child_process";
2
+ export class AgentBackgroundError extends Error {
3
+ failure;
4
+ exitCode;
5
+ constructor(failure, exitCode = 1) {
6
+ super(failure.message);
7
+ this.failure = failure;
8
+ this.exitCode = exitCode;
9
+ }
10
+ }
11
+ export function createAgentBackgroundLauncher(options) {
12
+ return {
13
+ submit(job, signal, started) {
14
+ signal.throwIfAborted();
15
+ return new Promise((resolve, reject) => {
16
+ const child = fork(options.workerPath, [], {
17
+ detached: true,
18
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
19
+ execArgv: [],
20
+ env: { ...process.env, ...options.env }
21
+ });
22
+ let settled = false;
23
+ const finish = (result) => {
24
+ if (settled)
25
+ return;
26
+ settled = true;
27
+ signal.removeEventListener("abort", aborted);
28
+ // The one-task worker owns the request after handoff, including when
29
+ // the caller is interrupted or loses the receipt.
30
+ if (child.connected)
31
+ child.disconnect();
32
+ child.unref();
33
+ if (result instanceof Error)
34
+ reject(result);
35
+ else
36
+ resolve(result);
37
+ };
38
+ const unavailable = () => finish(new AgentBackgroundError({
39
+ code: "TASK_WORKER_UNAVAILABLE",
40
+ message: job.product === "insmind"
41
+ ? "The background process did not return a receipt. Check task list/get before submitting again."
42
+ : "后台进程未返回受理回执。请先用 task list/get 查询,勿重复提交。"
43
+ }));
44
+ const aborted = () => finish(signal.reason instanceof Error ? signal.reason : new Error("SIGINT"));
45
+ child.on("error", unavailable);
46
+ child.once("exit", unavailable);
47
+ child.on("message", (message) => {
48
+ if (settled)
49
+ return;
50
+ if (message.type === "started")
51
+ started(message.task);
52
+ else if (message.type === "accepted")
53
+ finish(message.task);
54
+ else if (message.type === "error")
55
+ finish(new AgentBackgroundError(message.failure, message.exitCode));
56
+ });
57
+ signal.addEventListener("abort", aborted, { once: true });
58
+ child.send(job, error => { if (error)
59
+ unavailable(); });
60
+ });
61
+ }
62
+ };
63
+ }
@@ -0,0 +1,97 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readdir, lstat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { createLocalJsonFile, LocalFileError } from "../../platform/local-json-file.js";
6
+ export class TaskStoreError extends LocalFileError {
7
+ }
8
+ export const validTaskId = (id) => /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/iu.test(id);
9
+ export function taskScope(state) {
10
+ return createHash("sha256").update(JSON.stringify([
11
+ state.account ? ["account", state.account.id] : ["credential", state.credential.accessKey],
12
+ state.organization?.id
13
+ ])).digest("hex");
14
+ }
15
+ export function createTaskStore(options) {
16
+ const root = join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd", "tasks");
17
+ function file(scope, id) {
18
+ if (!/^[a-f0-9]{64}$/u.test(scope) || !validTaskId(id))
19
+ throw new LocalFileError(undefined);
20
+ return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json` });
21
+ }
22
+ const store = {
23
+ async read(scope, id) {
24
+ const stateFile = file(scope, id);
25
+ try {
26
+ const stat = await lstat(join(root, scope, `${id}.json`));
27
+ if (!stat.isFile() || stat.isSymbolicLink())
28
+ throw new LocalFileError(undefined);
29
+ }
30
+ catch (error) {
31
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
32
+ return null;
33
+ throw error;
34
+ }
35
+ const text = await stateFile.readText();
36
+ if (text === null)
37
+ return null;
38
+ try {
39
+ const record = JSON.parse(text);
40
+ if (record.version !== 1 || record.task.taskId !== id || !record.progress
41
+ || typeof record.progress !== "object" || Array.isArray(record.progress))
42
+ throw new Error();
43
+ options.validate(record.task);
44
+ for (const key of ["contextId", "localMessageId", "remoteTaskId"]) {
45
+ if (record.progress[key] !== undefined && typeof record.progress[key] !== "string")
46
+ throw new Error();
47
+ }
48
+ for (const key of ["submissionStarted", "detached", "accepted"]) {
49
+ if (record.progress[key] !== undefined && typeof record.progress[key] !== "boolean")
50
+ throw new Error();
51
+ }
52
+ return record;
53
+ }
54
+ catch (cause) {
55
+ throw new LocalFileError(cause);
56
+ }
57
+ },
58
+ async write(scope, record) {
59
+ options.validate(record.task);
60
+ await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
61
+ },
62
+ async list(scope) {
63
+ let names;
64
+ try {
65
+ names = await readdir(join(root, scope));
66
+ }
67
+ catch (error) {
68
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
69
+ return [];
70
+ throw new LocalFileError(error);
71
+ }
72
+ const records = [];
73
+ for (const name of names) {
74
+ if (!name.endsWith(".json") || !validTaskId(name.slice(0, -5)))
75
+ continue;
76
+ const record = await store.read(scope, name.slice(0, -5));
77
+ if (record)
78
+ records.push(record);
79
+ }
80
+ return records.sort((a, b) => b.task.createdAt.localeCompare(a.task.createdAt)
81
+ || a.task.taskId.localeCompare(b.task.taskId));
82
+ }
83
+ };
84
+ async function access(operation) {
85
+ try {
86
+ return await operation();
87
+ }
88
+ catch (cause) {
89
+ throw new TaskStoreError(cause);
90
+ }
91
+ }
92
+ return {
93
+ read: (scope, id) => access(() => store.read(scope, id)),
94
+ write: (scope, record) => access(() => store.write(scope, record)),
95
+ list: scope => access(() => store.list(scope))
96
+ };
97
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,139 @@
1
+ import { redactSensitiveText } from "../../platform/redact.js";
2
+ import { taskScope } from "./store.js";
3
+ export class TaskNotFoundError extends Error {
4
+ constructor(message) { super(message); }
5
+ }
6
+ // Cached results are private output data, but expiring resource credentials are
7
+ // removed. Query delivery uses the existing authorization adapter again.
8
+ export function withoutResourceKeys(value) {
9
+ function clean(item) {
10
+ if (typeof item === "string") {
11
+ return item.replace(/https?:\/\/[^\s<>"`\]\)]+/gu, raw => {
12
+ try {
13
+ const url = new URL(raw);
14
+ if (!url.searchParams.has("auth_key"))
15
+ return raw;
16
+ url.searchParams.delete("auth_key");
17
+ return url.href;
18
+ }
19
+ catch {
20
+ return raw;
21
+ }
22
+ });
23
+ }
24
+ if (Array.isArray(item))
25
+ return item.map(clean);
26
+ if (item && typeof item === "object")
27
+ return Object.fromEntries(Object.entries(item)
28
+ .filter(([key]) => key.toLowerCase().replaceAll("_", "") !== "authkey")
29
+ .map(([key, nested]) => [key, clean(nested)]));
30
+ return item;
31
+ }
32
+ return clean(value);
33
+ }
34
+ const HEARTBEAT_MS = 5_000;
35
+ const LEASE_MS = 15_000;
36
+ export function createTaskUseCases(dependencies) {
37
+ const { text, commandName } = dependencies;
38
+ function summary(record) {
39
+ const { result: _result, partialResult: _partial, ...task } = record.task;
40
+ if (!record.progress.detached && task.state === "running"
41
+ && dependencies.now().getTime() - Date.parse(task.updatedAt) >= LEASE_MS) {
42
+ return { ...task, state: "unknown", note: text("原 CLI 未继续更新记录;使用 task get 查询,不能据此重新生成。", "The original CLI stopped updating this task. Use task get to check; do not submit again.") };
43
+ }
44
+ return task;
45
+ }
46
+ async function execute(input, finish) {
47
+ const scope = taskScope(input.state);
48
+ const timestamp = dependencies.now().toISOString();
49
+ const record = {
50
+ version: 1, progress: {},
51
+ task: { taskId: dependencies.idFactory(), operation: input.operation,
52
+ label: redactSensitiveText(input.label).slice(0, 200),
53
+ createdAt: timestamp, updatedAt: timestamp, state: "running" }
54
+ };
55
+ await dependencies.store.write(scope, record);
56
+ input.onUpdate?.(structuredClone(record.task), { ...record.progress });
57
+ dependencies.notice(text(`任务 ID: ${record.task.taskId};结果未收到时执行 ${commandName} task get ${record.task.taskId}`, `Task ID: ${record.task.taskId}; retrieve missing output with ${commandName} task get ${record.task.taskId}`));
58
+ let writes = Promise.resolve();
59
+ const save = () => {
60
+ record.task.updatedAt = dependencies.now().toISOString();
61
+ const snapshot = structuredClone(record);
62
+ writes = writes.catch(() => undefined).then(() => dependencies.store.write(scope, snapshot));
63
+ return writes;
64
+ };
65
+ const timer = setInterval(() => { void save().catch(() => undefined); }, HEARTBEAT_MS);
66
+ timer.unref();
67
+ try {
68
+ const result = await input.run(async (progress) => {
69
+ Object.assign(record.progress, progress);
70
+ if (progress.contextId)
71
+ record.task.contextId = progress.contextId;
72
+ await save();
73
+ input.onUpdate?.(structuredClone(record.task), { ...record.progress });
74
+ });
75
+ clearInterval(timer);
76
+ finish(record, result);
77
+ await save();
78
+ return { task: record.task, result };
79
+ }
80
+ catch (error) {
81
+ clearInterval(timer);
82
+ if (record.task.state !== "completed") {
83
+ record.task.state = record.progress.submissionStarted ? "unknown" : "failed";
84
+ record.task.note = record.progress.submissionStarted
85
+ ? text("CLI 未取得完整回执或结果;远端可能仍在执行。查询原任务,不自动重新生成。", "The CLI did not receive a complete receipt or result; the service may still be running. Query this task instead of submitting again.")
86
+ : text("CLI 在提交创作前结束;具体错误见原命令。", "The CLI stopped before submitting the creation. See the original command for the error.");
87
+ }
88
+ const detail = dependencies.failureNote?.(error);
89
+ if (detail)
90
+ record.task.note = `${record.task.note} ${redactSensitiveText(detail)}`;
91
+ await save().catch(() => undefined);
92
+ throw error;
93
+ }
94
+ }
95
+ return {
96
+ async track(input) {
97
+ return (await execute(input, (record, result) => {
98
+ record.task.state = "completed";
99
+ record.task.result = withoutResourceKeys(result);
100
+ if ("message" in result)
101
+ record.task.contextId = result.message.contextId;
102
+ })).result;
103
+ },
104
+ async submit(input) {
105
+ return (await execute(input, record => { record.progress.detached = true; })).task;
106
+ },
107
+ async list({ state, limit, operation }) {
108
+ const records = await dependencies.store.list(taskScope(state));
109
+ return { tasks: records.filter(r => !operation || r.task.operation === operation).slice(0, limit).map(summary) };
110
+ },
111
+ async get({ state, id, signal }) {
112
+ signal.throwIfAborted();
113
+ const scope = taskScope(state);
114
+ const record = await dependencies.store.read(scope, id);
115
+ if (!record)
116
+ throw new TaskNotFoundError(text(`当前身份中没有该任务。请执行 ${commandName} task list 查找。`, `No task was found in the current identity context. Use ${commandName} task list to find it.`));
117
+ if (record.task.state === "completed" && record.task.result) {
118
+ return { ...record.task, result: await dependencies.recovery.authorize(record.task.result, state, signal) };
119
+ }
120
+ const task = summary(record);
121
+ if (task.state === "failed" || (task.state === "running" && !record.progress.detached))
122
+ return task;
123
+ const recovered = await dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal);
124
+ const { note: _note, ...metadata } = task;
125
+ const result = { ...metadata, ...recovered };
126
+ if (result.state === "unknown" && task.note) {
127
+ result.note = [task.note, recovered.note].filter(Boolean).join(" ");
128
+ }
129
+ // Only detached tasks have no original writer. Cache terminal results before
130
+ // delivery, without saving expiring resource authorization credentials.
131
+ if (record.progress.detached && (result.state === "completed" || result.state === "failed")) {
132
+ result.updatedAt = dependencies.now().toISOString();
133
+ record.task = withoutResourceKeys(result);
134
+ await dependencies.store.write(scope, record);
135
+ }
136
+ return result;
137
+ }
138
+ };
139
+ }
@@ -0,0 +1,83 @@
1
+ export const defaultToolDefinitions = [
2
+ {
3
+ name: "image.generate",
4
+ title: "图片生成与编辑",
5
+ description: "使用已发布的图片模型,根据文本和可选参考图片生成或编辑图片。"
6
+ },
7
+ {
8
+ name: "video.generate",
9
+ title: "视频生成",
10
+ description: "使用已发布的视频模型,根据文本及可选图片、视频或音频生成视频。"
11
+ },
12
+ {
13
+ name: "text.generate",
14
+ title: "文本生成",
15
+ description: "使用已发布的文本模型,根据文本和可选图片生成文本。"
16
+ }
17
+ ];
18
+ export class ToolInputError extends Error {
19
+ constructor() {
20
+ super("Tool 输入不可用。");
21
+ this.name = "ToolInputError";
22
+ }
23
+ }
24
+ function toolIndex(tool, tools) {
25
+ return tools.findIndex((candidate) => candidate.name === tool);
26
+ }
27
+ function compareModels(left, right, tools) {
28
+ return toolIndex(left.tool, tools) - toolIndex(right.tool, tools)
29
+ || left.sceneSort - right.sceneSort
30
+ || left.modelSort - right.modelSort
31
+ || (left.model < right.model ? -1 : left.model > right.model ? 1 : 0);
32
+ }
33
+ function summary(model) {
34
+ return {
35
+ tool: model.tool,
36
+ model: model.model,
37
+ title: model.title,
38
+ ...(model.description === undefined ? {} : { description: model.description }),
39
+ ...(model.cost === undefined ? {} : { cost: model.cost }),
40
+ ...(model.estimatedTime === undefined ? {} : { estimatedTime: model.estimatedTime })
41
+ };
42
+ }
43
+ export function projectToolList(catalog, tools = defaultToolDefinitions) {
44
+ return {
45
+ tools: tools.filter((tool) => catalog.models.some((model) => model.tool === tool.name))
46
+ };
47
+ }
48
+ export function projectModelList(catalog, tool, tools = defaultToolDefinitions) {
49
+ if (tool !== undefined && !catalog.models.some((model) => model.tool === tool)) {
50
+ throw new ToolInputError();
51
+ }
52
+ return {
53
+ models: catalog.models
54
+ .filter((model) => tool === undefined || model.tool === tool)
55
+ .toSorted((left, right) => compareModels(left, right, tools))
56
+ .map(summary)
57
+ };
58
+ }
59
+ export function findModel(catalog, model) {
60
+ const found = catalog.models.find((candidate) => candidate.model === model);
61
+ if (found === undefined)
62
+ throw new ToolInputError();
63
+ return found;
64
+ }
65
+ export function projectModelDetail(catalog, model) {
66
+ const found = findModel(catalog, model);
67
+ return {
68
+ ...summary(found),
69
+ ...(found.usageDescription === undefined
70
+ ? {}
71
+ : { usageDescription: found.usageDescription }),
72
+ ...(found.outputMediaTypes === undefined
73
+ ? {}
74
+ : { outputMediaTypes: found.outputMediaTypes }),
75
+ parameters: found.parameters
76
+ };
77
+ }
78
+ export function findToolModel(catalog, tool, model) {
79
+ const found = findModel(catalog, model);
80
+ if (found.tool !== tool)
81
+ throw new ToolInputError();
82
+ return found;
83
+ }