@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 * as fileSystem from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { gt, valid } from "semver";
6
+ import { createLocalJsonFile } from "../../platform/local-json-file.js";
7
+ import { fetchLatestVersion } from "./latest-version.js";
8
+ const SUCCESS_CHECK_INTERVAL_MS = 60 * 60 * 1_000;
9
+ const FAILED_CHECK_INTERVAL_MS = 15 * 60 * 1_000;
10
+ const REGISTRY_TIMEOUT_MS = 2_000;
11
+ const STALE_LOCK_MS = 30_000;
12
+ export function createUpdateNotificationService(options) {
13
+ const fetchPackage = options.fetch ?? globalThis.fetch;
14
+ const now = options.now ?? (() => new Date());
15
+ const env = options.env ?? process.env;
16
+ const stateDirectory = join(options.homeDirectory ?? homedir(), options.stateDirectoryName ?? ".gd");
17
+ const stateFile = options.stateFile ?? createLocalJsonFile({
18
+ directory: stateDirectory,
19
+ filename: "update-check.json"
20
+ });
21
+ const lock = options.lock ?? createLocalUpdateNotificationLock({
22
+ directory: stateDirectory,
23
+ now: () => new Date()
24
+ });
25
+ return {
26
+ async check(signal) {
27
+ if ((options.installationOwner ?? "user") !== "user")
28
+ return;
29
+ if (env.CI === "true")
30
+ return;
31
+ let release = null;
32
+ try {
33
+ signal.throwIfAborted();
34
+ release = await lock.acquire();
35
+ if (release === null)
36
+ return;
37
+ const checkedAt = now();
38
+ const today = localDate(checkedAt);
39
+ const state = await readState(stateFile);
40
+ if (isNewer(state.latest_version, options.currentVersion)
41
+ && state.last_notified_on !== today) {
42
+ const reminded = withReminder(state, today, state.latest_version);
43
+ await writeState(stateFile, reminded);
44
+ notify(options, state.latest_version);
45
+ return;
46
+ }
47
+ if (!isDue(state.next_check_at, checkedAt))
48
+ return;
49
+ let latestResult;
50
+ const timeout = signalWithTimeout(signal, REGISTRY_TIMEOUT_MS);
51
+ try {
52
+ latestResult = await fetchLatestVersion({
53
+ fetch: fetchPackage,
54
+ signal: timeout.signal,
55
+ ...(options.registryUrl ? { registryUrl: options.registryUrl } : {}),
56
+ ...(state.etag ? { etag: state.etag } : {})
57
+ });
58
+ }
59
+ catch {
60
+ if (signal.aborted)
61
+ return;
62
+ await writeState(stateFile, {
63
+ ...state,
64
+ schema_version: 1,
65
+ next_check_at: addMilliseconds(checkedAt, FAILED_CHECK_INTERVAL_MS)
66
+ });
67
+ return;
68
+ }
69
+ finally {
70
+ timeout.dispose();
71
+ }
72
+ const latest = latestResult.status === "not_modified"
73
+ ? state.latest_version
74
+ : latestResult.version;
75
+ if (latest === undefined || valid(latest) === null) {
76
+ await writeState(stateFile, {
77
+ ...state,
78
+ schema_version: 1,
79
+ next_check_at: addMilliseconds(checkedAt, FAILED_CHECK_INTERVAL_MS)
80
+ });
81
+ return;
82
+ }
83
+ let nextState = {
84
+ ...state,
85
+ schema_version: 1,
86
+ last_success_check_at: checkedAt.toISOString(),
87
+ next_check_at: addMilliseconds(checkedAt, SUCCESS_CHECK_INTERVAL_MS),
88
+ latest_version: latest,
89
+ ...(latestResult.status === "modified" && latestResult.etag
90
+ ? { etag: latestResult.etag }
91
+ : {})
92
+ };
93
+ if (latestResult.status === "modified" && latestResult.etag === undefined) {
94
+ delete nextState.etag;
95
+ }
96
+ const shouldNotify = gt(latest, options.currentVersion)
97
+ && nextState.last_notified_on !== today;
98
+ if (shouldNotify)
99
+ nextState = withReminder(nextState, today, latest);
100
+ await writeState(stateFile, nextState);
101
+ if (shouldNotify)
102
+ notify(options, latest);
103
+ }
104
+ catch {
105
+ // Availability checks are best-effort and never change command behavior.
106
+ }
107
+ finally {
108
+ await release?.().catch(() => undefined);
109
+ }
110
+ }
111
+ };
112
+ }
113
+ function signalWithTimeout(parent, milliseconds) {
114
+ const controller = new AbortController();
115
+ const forwardAbort = () => { controller.abort(parent.reason); };
116
+ if (parent.aborted)
117
+ forwardAbort();
118
+ else
119
+ parent.addEventListener("abort", forwardAbort, { once: true });
120
+ const timer = setTimeout(() => {
121
+ controller.abort(new Error("Registry request timed out."));
122
+ }, milliseconds);
123
+ timer.unref();
124
+ return {
125
+ signal: controller.signal,
126
+ dispose() {
127
+ clearTimeout(timer);
128
+ parent.removeEventListener("abort", forwardAbort);
129
+ }
130
+ };
131
+ }
132
+ function createLocalUpdateNotificationLock(options) {
133
+ const path = join(options.directory, "update-check.lock");
134
+ return {
135
+ async acquire() {
136
+ await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
137
+ await fileSystem.chmod(options.directory, 0o700);
138
+ const first = await tryCreateLock(path);
139
+ if (first)
140
+ return releaseLock(path, first);
141
+ if (!await isStaleLock(path, options.now()))
142
+ return null;
143
+ await fileSystem.unlink(path).catch((error) => {
144
+ if (!isMissing(error))
145
+ throw error;
146
+ });
147
+ const recovered = await tryCreateLock(path);
148
+ return recovered ? releaseLock(path, recovered) : null;
149
+ }
150
+ };
151
+ }
152
+ async function tryCreateLock(path) {
153
+ const token = randomUUID();
154
+ let handle;
155
+ try {
156
+ handle = await fileSystem.open(path, "wx", 0o600);
157
+ await handle.writeFile(token, "utf8");
158
+ await handle.sync();
159
+ await handle.close();
160
+ return token;
161
+ }
162
+ catch (error) {
163
+ await handle?.close().catch(() => undefined);
164
+ if (isExists(error))
165
+ return null;
166
+ throw error;
167
+ }
168
+ }
169
+ function releaseLock(path, token) {
170
+ return async () => {
171
+ let current;
172
+ try {
173
+ current = await fileSystem.readFile(path, "utf8");
174
+ }
175
+ catch (error) {
176
+ if (isMissing(error))
177
+ return;
178
+ throw error;
179
+ }
180
+ if (current === token)
181
+ await fileSystem.unlink(path);
182
+ };
183
+ }
184
+ async function isStaleLock(path, now) {
185
+ try {
186
+ const stats = await fileSystem.stat(path);
187
+ return stats.mtimeMs + STALE_LOCK_MS <= now.getTime();
188
+ }
189
+ catch (error) {
190
+ if (isMissing(error))
191
+ return true;
192
+ throw error;
193
+ }
194
+ }
195
+ async function readState(file) {
196
+ const text = await file.readText();
197
+ if (text === null)
198
+ return { schema_version: 1 };
199
+ try {
200
+ const value = JSON.parse(text);
201
+ return parseState(value) ?? { schema_version: 1 };
202
+ }
203
+ catch {
204
+ return { schema_version: 1 };
205
+ }
206
+ }
207
+ function parseState(value) {
208
+ if (!isRecord(value) || value.schema_version !== 1)
209
+ return null;
210
+ for (const key of [
211
+ "last_success_check_at",
212
+ "next_check_at",
213
+ "latest_version",
214
+ "last_notified_on",
215
+ "last_notified_version",
216
+ "etag"
217
+ ]) {
218
+ if (value[key] !== undefined && typeof value[key] !== "string")
219
+ return null;
220
+ }
221
+ return value;
222
+ }
223
+ async function writeState(file, state) {
224
+ await file.writeTextAtomically(`${JSON.stringify(state, null, 2)}\n`);
225
+ }
226
+ function withReminder(state, today, version) {
227
+ return {
228
+ ...state,
229
+ schema_version: 1,
230
+ last_notified_on: today,
231
+ last_notified_version: version
232
+ };
233
+ }
234
+ function notify(options, latest) {
235
+ if (options.commandName && options.commandName !== "gd-cli") {
236
+ options.notify(`${options.commandName} ${latest} is available; current version is ` +
237
+ `${options.currentVersion}. Run ${options.commandName} update to update.`);
238
+ }
239
+ else {
240
+ options.notify(`gd-cli 有新版本 ${latest},当前版本为 ${options.currentVersion}。` +
241
+ "运行 gd-cli update 即可更新。");
242
+ }
243
+ }
244
+ function isNewer(version, currentVersion) {
245
+ return version !== undefined && valid(version) !== null && gt(version, currentVersion);
246
+ }
247
+ function isDue(nextCheckAt, now) {
248
+ if (nextCheckAt === undefined)
249
+ return true;
250
+ const timestamp = Date.parse(nextCheckAt);
251
+ return !Number.isFinite(timestamp) || timestamp <= now.getTime();
252
+ }
253
+ function addMilliseconds(value, milliseconds) {
254
+ return new Date(value.getTime() + milliseconds).toISOString();
255
+ }
256
+ function localDate(value) {
257
+ return [
258
+ String(value.getFullYear()).padStart(4, "0"),
259
+ String(value.getMonth() + 1).padStart(2, "0"),
260
+ String(value.getDate()).padStart(2, "0")
261
+ ].join("-");
262
+ }
263
+ function isRecord(value) {
264
+ return typeof value === "object" && value !== null && !Array.isArray(value);
265
+ }
266
+ function isMissing(error) {
267
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
268
+ }
269
+ function isExists(error) {
270
+ return error instanceof Error && "code" in error && error.code === "EEXIST";
271
+ }
@@ -0,0 +1,226 @@
1
+ import { spawn } from "node:child_process";
2
+ import { realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { gt } from "semver";
5
+ import { syncBundledSkills, verifyBundledSkills } from "../skill/installer.js";
6
+ import { fetchLatestVersion } from "./latest-version.js";
7
+ import { readInstallationOwner } from "../../platform/installation-owner.js";
8
+ export class UpdateError extends Error {
9
+ code;
10
+ nextSteps;
11
+ constructor(code, message, nextSteps) {
12
+ super(message);
13
+ this.code = code;
14
+ this.nextSteps = nextSteps;
15
+ this.name = "UpdateError";
16
+ }
17
+ }
18
+ export function detectInstallSource(input) {
19
+ const binaryPath = normalizePath(input.binaryPath);
20
+ const realBinaryPath = normalizePath(input.realBinaryPath);
21
+ const packageRoot = normalizePath(input.packageRoot);
22
+ const cwd = normalizePath(resolve(input.cwd));
23
+ const userAgent = input.env.npm_config_user_agent ?? "";
24
+ const npmExecPath = normalizePath(input.env.npm_execpath ?? "");
25
+ const packageName = input.packageName ?? "@gaoding/cli";
26
+ const encodedPackage = packageName.replace("/", "+").replace("@", "@");
27
+ if (userAgent.startsWith("yarn/") || npmExecPath.includes("/yarn/")) {
28
+ return unsupported("Yarn 安装不支持自动更新");
29
+ }
30
+ if (containsTemporaryRunner(binaryPath) || containsTemporaryRunner(packageRoot)) {
31
+ return unsupported("临时运行方式不支持自动更新");
32
+ }
33
+ if (binaryPath.includes("/node_modules/.bin/")
34
+ || packageRoot.startsWith(`${cwd}/node_modules/`)) {
35
+ return unsupported("项目依赖不支持自动更新");
36
+ }
37
+ if (!isWithin(realBinaryPath, packageRoot)) {
38
+ return unsupported("CLI binary 与 package 不匹配");
39
+ }
40
+ if (packageRoot.includes(`/global/`) && packageRoot.includes(`/.pnpm/${encodedPackage}@`)
41
+ || packageRoot.includes(`/node_modules/${packageName}`)
42
+ && /\/v\d+\/[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16}\//u.test(packageRoot)
43
+ || binaryPath.includes(`/node_modules/${packageName}/dist/bin/${input.binaryName ?? "gd-cli"}.js`)
44
+ && /\/v\d+\/[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16}\//u.test(binaryPath)) {
45
+ return { kind: "global", manager: "pnpm", packageRoot: input.packageRoot };
46
+ }
47
+ if (packageRoot.endsWith(`/lib/node_modules/${packageName}`)
48
+ || packageRoot.endsWith(`/npm/node_modules/${packageName}`)) {
49
+ return { kind: "global", manager: "npm", packageRoot: input.packageRoot };
50
+ }
51
+ return unsupported("无法确认 npm 或 pnpm 全局安装");
52
+ }
53
+ export function createUpdateService(options) {
54
+ const fetchPackage = options.fetch ?? globalThis.fetch;
55
+ const runProcess = options.runProcess ?? spawnProcess;
56
+ const syncSkills = options.syncSkills ?? syncBundledSkills;
57
+ const verifySkills = options.verifySkills ?? verifyBundledSkills;
58
+ const env = options.env ?? process.env;
59
+ const packageName = options.packageName ?? "@gaoding/cli";
60
+ const commandName = options.commandName ?? "gd-cli";
61
+ const insmind = packageName === "@insmind/cli";
62
+ return {
63
+ async run(signal) {
64
+ signal.throwIfAborted();
65
+ const owner = options.installationOwner
66
+ ?? readInstallationOwner(options.packageRoot);
67
+ if (owner === "workbuddy") {
68
+ throw new UpdateError("UPDATE_FAILED", insmind
69
+ ? "This insMind CLI installation is managed by WorkBuddy."
70
+ : "此 gd-cli 由 WorkBuddy 连接器管理。", [insmind
71
+ ? "Update the insMind connector in WorkBuddy."
72
+ : "请在 WorkBuddy 中更新「稿定」连接器。"]);
73
+ }
74
+ if (owner === "invalid") {
75
+ throw new UpdateError("UPDATE_FAILED", insmind
76
+ ? "The current installation ownership metadata is invalid."
77
+ : "无法确认当前安装的托管信息。", [insmind
78
+ ? "Reinstall insmind-cli through its original installation channel."
79
+ : "请通过原安装渠道重新安装 gd-cli。"]);
80
+ }
81
+ const latest = await options.telemetry.stage("registry", async () => {
82
+ try {
83
+ const result = await fetchLatestVersion({
84
+ fetch: fetchPackage,
85
+ signal,
86
+ ...(options.registryUrl ? { registryUrl: options.registryUrl } : {})
87
+ });
88
+ if (result.status !== "modified")
89
+ throw new Error("Registry response not modified");
90
+ return result.version;
91
+ }
92
+ catch (error) {
93
+ rethrowAbort(signal);
94
+ throw new UpdateError("UPDATE_FAILED", options.commandName === undefined
95
+ ? "无法获取 @gaoding/cli 最新版本。"
96
+ : `Unable to get the latest ${packageName} version.`, [options.commandName === undefined
97
+ ? "请稍后重新执行 gd-cli update。"
98
+ : `Run ${commandName} update again later.`]);
99
+ }
100
+ });
101
+ signal.throwIfAborted();
102
+ const skillOptions = {
103
+ env,
104
+ ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {})
105
+ };
106
+ if (!gt(latest, options.currentVersion)) {
107
+ await options.telemetry.stage("sync", async () => {
108
+ try {
109
+ await syncSkills(options.bundledSkills, skillOptions);
110
+ }
111
+ catch (error) {
112
+ rethrowAbort(signal);
113
+ throw new UpdateError("UPDATE_FAILED", insmind
114
+ ? `${commandName} ${options.currentVersion} is current, but Agent Skill synchronization failed.`
115
+ : `gd-cli ${options.currentVersion} 无需更新,但 Agent Skill 同步失败。`, [insmind
116
+ ? `Resolve the conflict and run ${commandName} update again.`
117
+ : "请解决冲突后重新执行 gd-cli update。"]);
118
+ }
119
+ });
120
+ return { version: options.currentVersion, updated: false };
121
+ }
122
+ const binaryPath = options.binaryPath ?? process.argv[1] ?? "";
123
+ const source = detectInstallSource({
124
+ binaryPath,
125
+ realBinaryPath: safeRealpath(binaryPath),
126
+ packageRoot: options.packageRoot,
127
+ cwd: options.cwd ?? process.cwd(),
128
+ env,
129
+ packageName,
130
+ binaryName: commandName
131
+ });
132
+ const nextSteps = manualCommands(latest, packageName);
133
+ if (source.kind === "unsupported") {
134
+ throw new UpdateError("UPDATE_FAILED", insmind
135
+ ? "The current installation method does not support automatic updates."
136
+ : `当前安装方式不支持自动更新:${source.reason}。`, nextSteps);
137
+ }
138
+ const command = source.manager;
139
+ const args = source.manager === "npm"
140
+ ? ["install", "--global", `--allow-scripts=${packageName}`, `${packageName}@${latest}`]
141
+ : ["add", "--global", `--allow-build=${packageName}`, `${packageName}@${latest}`];
142
+ await options.telemetry.stage("install", async () => {
143
+ try {
144
+ await runProcess(command, args, signal);
145
+ }
146
+ catch (error) {
147
+ rethrowAbort(signal);
148
+ throw new UpdateError("UPDATE_FAILED", insmind
149
+ ? `Failed to update ${commandName} to ${latest}.`
150
+ : `gd-cli 更新到 ${latest} 失败。`, nextSteps);
151
+ }
152
+ });
153
+ signal.throwIfAborted();
154
+ const targetSkills = options.bundledSkills.map((skill) => ({
155
+ ...skill,
156
+ version: latest
157
+ }));
158
+ await options.telemetry.stage("verify", async () => {
159
+ try {
160
+ await verifySkills(targetSkills, skillOptions);
161
+ }
162
+ catch (error) {
163
+ rethrowAbort(signal);
164
+ throw new UpdateError("UPDATE_PARTIAL", insmind
165
+ ? `${commandName} was updated to ${latest}, but Agent Skill verification failed.`
166
+ : `gd-cli 已更新到 ${latest},但 Agent Skill 验收失败。`, [insmind
167
+ ? `Run ${commandName} update again.`
168
+ : "请重新执行 gd-cli update。"]);
169
+ }
170
+ });
171
+ return { version: latest, updated: true };
172
+ }
173
+ };
174
+ }
175
+ function spawnProcess(command, args, signal) {
176
+ return new Promise((resolvePromise, reject) => {
177
+ const child = spawn(command, args, {
178
+ stdio: "inherit",
179
+ shell: false,
180
+ signal
181
+ });
182
+ child.once("error", reject);
183
+ child.once("exit", (code, exitSignal) => {
184
+ if (code === 0) {
185
+ resolvePromise();
186
+ }
187
+ else {
188
+ reject(new Error(code === null
189
+ ? `package manager terminated by ${exitSignal ?? "unknown signal"}`
190
+ : `package manager exited with ${code}`));
191
+ }
192
+ });
193
+ });
194
+ }
195
+ function manualCommands(version, packageName = "@gaoding/cli") {
196
+ return [
197
+ `npm install --global --allow-scripts=${packageName} ${packageName}@${version}`,
198
+ `pnpm add --global --allow-build=${packageName} ${packageName}@${version}`
199
+ ];
200
+ }
201
+ function containsTemporaryRunner(path) {
202
+ return path.includes("/.npm/_npx/")
203
+ || path.includes("/pnpm/dlx/")
204
+ || path.includes("/.pnpm/dlx/");
205
+ }
206
+ function isWithin(path, directory) {
207
+ return path === directory || path.startsWith(`${directory}/`);
208
+ }
209
+ function normalizePath(path) {
210
+ return path.replace(/\\/gu, "/").replace(/\/+$/u, "");
211
+ }
212
+ function safeRealpath(path) {
213
+ try {
214
+ return realpathSync(path);
215
+ }
216
+ catch {
217
+ return path;
218
+ }
219
+ }
220
+ function unsupported(reason) {
221
+ return { kind: "unsupported", reason };
222
+ }
223
+ function rethrowAbort(signal) {
224
+ if (signal.aborted)
225
+ signal.throwIfAborted();
226
+ }
@@ -0,0 +1,81 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { closeSync, linkSync, lstatSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ const markerFilename = ".gd-cli-installation.json";
5
+ export function readInstallationOwner(packageRoot) {
6
+ const path = join(packageRoot, markerFilename);
7
+ try {
8
+ if (!lstatSync(path).isFile())
9
+ return "invalid";
10
+ const value = JSON.parse(readFileSync(path, "utf8"));
11
+ if (!isRecord(value))
12
+ return "invalid";
13
+ const keys = Object.keys(value);
14
+ return keys.length === 1 && keys[0] === "owner" && value.owner === "workbuddy"
15
+ ? "workbuddy"
16
+ : "invalid";
17
+ }
18
+ catch (error) {
19
+ return isMissing(error) ? "user" : "invalid";
20
+ }
21
+ }
22
+ export function markWorkBuddyInstallation(packageRoot) {
23
+ const packageMetadata = parsePackageMetadata(packageRoot);
24
+ if (packageMetadata.name !== "@gaoding/cli") {
25
+ throw new Error("无法确认当前安装的 package。");
26
+ }
27
+ const markerPath = join(packageRoot, markerFilename);
28
+ const current = readInstallationOwner(packageRoot);
29
+ if (current === "workbuddy")
30
+ return;
31
+ if (current === "invalid")
32
+ throw new Error("无法确认当前安装的托管信息。");
33
+ const temporaryPath = join(packageRoot, `.${markerFilename}.${randomUUID()}.tmp`);
34
+ let descriptor;
35
+ try {
36
+ descriptor = openSync(temporaryPath, "wx", 0o600);
37
+ writeFileSync(descriptor, `${JSON.stringify({ owner: "workbuddy" }, null, 2)}\n`, "utf8");
38
+ closeSync(descriptor);
39
+ descriptor = undefined;
40
+ linkSync(temporaryPath, markerPath);
41
+ unlinkSync(temporaryPath);
42
+ }
43
+ catch (error) {
44
+ if (descriptor !== undefined) {
45
+ try {
46
+ closeSync(descriptor);
47
+ }
48
+ catch { /* best effort */ }
49
+ }
50
+ try {
51
+ unlinkSync(temporaryPath);
52
+ }
53
+ catch { /* best effort */ }
54
+ if (isExists(error)) {
55
+ if (readInstallationOwner(packageRoot) === "workbuddy")
56
+ return;
57
+ throw new Error("无法确认当前安装的托管信息。");
58
+ }
59
+ throw error;
60
+ }
61
+ }
62
+ function parsePackageMetadata(packageRoot) {
63
+ try {
64
+ const value = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
65
+ if (!isRecord(value))
66
+ throw new Error("invalid package metadata");
67
+ return value;
68
+ }
69
+ catch {
70
+ throw new Error("无法确认当前安装的 package。");
71
+ }
72
+ }
73
+ function isRecord(value) {
74
+ return typeof value === "object" && value !== null && !Array.isArray(value);
75
+ }
76
+ function isMissing(error) {
77
+ return isRecord(error) && error.code === "ENOENT";
78
+ }
79
+ function isExists(error) {
80
+ return isRecord(error) && error.code === "EEXIST";
81
+ }
@@ -0,0 +1,67 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ export class JsonInputError extends Error {
4
+ constructor() {
5
+ super("无法读取有效的 JSON。");
6
+ this.name = "JsonInputError";
7
+ }
8
+ }
9
+ export function createJsonInputReader(options) {
10
+ return {
11
+ async read(source, signal) {
12
+ signal.throwIfAborted();
13
+ let text;
14
+ try {
15
+ text = source === "-"
16
+ ? await readStream(options.stdin, signal)
17
+ : await readFile(resolve(options.cwd, source), { encoding: "utf8", signal });
18
+ }
19
+ catch {
20
+ if (signal.aborted)
21
+ throw signal.reason;
22
+ throw new JsonInputError();
23
+ }
24
+ try {
25
+ return JSON.parse(text);
26
+ }
27
+ catch {
28
+ throw new JsonInputError();
29
+ }
30
+ }
31
+ };
32
+ }
33
+ function readStream(stream, signal) {
34
+ return new Promise((resolve, reject) => {
35
+ const chunks = [];
36
+ const onData = (chunk) => {
37
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
38
+ };
39
+ const cleanup = () => {
40
+ stream.removeListener("data", onData);
41
+ stream.removeListener("end", onEnd);
42
+ stream.removeListener("error", onError);
43
+ signal.removeEventListener("abort", onAbort);
44
+ };
45
+ const onEnd = () => {
46
+ cleanup();
47
+ resolve(Buffer.concat(chunks).toString("utf8"));
48
+ };
49
+ const onError = () => {
50
+ cleanup();
51
+ reject(new JsonInputError());
52
+ };
53
+ const onAbort = () => {
54
+ cleanup();
55
+ const destroy = stream.destroy;
56
+ if (typeof destroy === "function")
57
+ destroy.call(stream);
58
+ reject(signal.reason);
59
+ };
60
+ stream.on("data", onData);
61
+ stream.once("end", onEnd);
62
+ stream.once("error", onError);
63
+ signal.addEventListener("abort", onAbort, { once: true });
64
+ if (signal.aborted)
65
+ onAbort();
66
+ });
67
+ }