@insmind/cli 2.1.0 → 2.1.2

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 (122) hide show
  1. package/README.md +30 -0
  2. package/contracts/operations/agent.send/input.schema.json +1 -77
  3. package/contracts/operations/dam.folder.list/input.schema.json +0 -1
  4. package/contracts/operations/dam.folder.list/output.schema.json +1 -2
  5. package/contracts/operations/dam.list/input.schema.json +3 -6
  6. package/contracts/operations/dam.list/output.schema.json +1 -2
  7. package/contracts/operations/dam.search/input.schema.json +3 -6
  8. package/contracts/operations/dam.search/output.schema.json +1 -2
  9. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
  10. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
  11. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
  12. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
  13. package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
  14. package/dist/bin/postinstall.js +22 -6
  15. package/dist/bin/sync-skill.js +33 -0
  16. package/dist/bin/task-worker.js +2 -2
  17. package/dist/src/bootstrap/create-cli.js +13 -6
  18. package/dist/src/bootstrap/create-runtime.js +103 -29
  19. package/dist/src/bootstrap/run-task-worker.js +6 -2
  20. package/dist/src/bootstrap/validators.js +87 -151
  21. package/dist/src/cli/action-binding.js +14 -37
  22. package/dist/src/cli/agent-commands.js +13 -13
  23. package/dist/src/cli/auth-commands.js +2 -1
  24. package/dist/src/cli/creation-help.js +9 -0
  25. package/dist/src/cli/dam-commands.js +10 -14
  26. package/dist/src/cli/editor-commands.js +16 -12
  27. package/dist/src/cli/errors.js +84 -26
  28. package/dist/src/cli/host-input.js +62 -5
  29. package/dist/src/cli/model-commands.js +9 -3
  30. package/dist/src/cli/observed-errors.js +7 -3
  31. package/dist/src/cli/org-commands.js +3 -1
  32. package/dist/src/cli/presenter.js +4 -5
  33. package/dist/src/cli/task-commands.js +6 -2
  34. package/dist/src/cli/tool-commands.js +12 -11
  35. package/dist/src/contracts/creation-input.js +20 -17
  36. package/dist/src/features/agent/creative-agent-adapter.js +6 -2
  37. package/dist/src/features/agent/creative-protocol.js +8 -29
  38. package/dist/src/features/agent/resource-authorizer.js +25 -17
  39. package/dist/src/features/agent/result-reader.js +31 -14
  40. package/dist/src/features/agent/use-cases.js +6 -31
  41. package/dist/src/features/auth/credential-store.js +1 -0
  42. package/dist/src/features/credits/use-cases.js +55 -28
  43. package/dist/src/features/dam/asset-projection.js +3 -6
  44. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  45. package/dist/src/features/dam/object-storage.js +2 -1
  46. package/dist/src/features/dam/repository-catalog.js +30 -21
  47. package/dist/src/features/dam/use-cases.js +14 -9
  48. package/dist/src/features/editor/bridge-client.js +0 -2
  49. package/dist/src/features/editor/bridge-process.js +3 -2
  50. package/dist/src/features/editor/public-url.js +1 -36
  51. package/dist/src/features/editor/session-state.js +1 -0
  52. package/dist/src/features/editor/session.js +3 -2
  53. package/dist/src/features/editor/use-cases.js +27 -2
  54. package/dist/src/features/org/org-service.js +10 -1
  55. package/dist/src/features/org/use-cases.js +18 -4
  56. package/dist/src/features/task/process-owner.js +54 -0
  57. package/dist/src/features/task/store.js +102 -32
  58. package/dist/src/features/task/task-background.js +8 -4
  59. package/dist/src/features/task/use-cases.js +184 -84
  60. package/dist/src/features/tool/argument-paths.js +14 -0
  61. package/dist/src/features/tool/canvas-copy.js +28 -15
  62. package/dist/src/features/tool/canvas-matting.js +123 -0
  63. package/dist/src/features/tool/canvas-media.js +102 -55
  64. package/dist/src/features/tool/canvas-models.js +66 -33
  65. package/dist/src/features/tool/canvas-pricing.js +12 -0
  66. package/dist/src/features/tool/canvas-recovery.js +13 -30
  67. package/dist/src/features/tool/canvas-results.js +92 -93
  68. package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
  69. package/dist/src/features/tool/canvas-video.js +44 -37
  70. package/dist/src/features/tool/catalog.js +2 -23
  71. package/dist/src/features/tool/dynamic-schema.js +42 -46
  72. package/dist/src/features/tool/ffprobe-executable.js +21 -0
  73. package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
  74. package/dist/src/features/tool/resource-authorizer.js +11 -3
  75. package/dist/src/features/tool/tool-api-adapter.js +73 -82
  76. package/dist/src/features/tool/tool-definitions.js +23 -0
  77. package/dist/src/features/tool/tool-errors.js +25 -0
  78. package/dist/src/features/tool/tool-output.js +15 -0
  79. package/dist/src/features/tool/use-cases.js +74 -98
  80. package/dist/src/features/update/package-manager.js +124 -0
  81. package/dist/src/features/update/update-service.js +195 -55
  82. package/dist/src/platform/detached-spawn.js +9 -0
  83. package/dist/src/platform/file-lock.js +12 -4
  84. package/dist/src/platform/input-uri.js +23 -1
  85. package/dist/src/platform/local-json-file.js +97 -15
  86. package/dist/src/platform/media-type.js +46 -0
  87. package/dist/src/platform/open-browser.js +5 -2
  88. package/dist/src/platform/public-url.js +35 -0
  89. package/dist/src/platform/remote-error-evidence.js +33 -6
  90. package/dist/src/platform/resource-auth-key.js +35 -1
  91. package/dist/src/platform/safe-upload-file.js +38 -44
  92. package/dist/src/platform/schema-compiler.js +16 -0
  93. package/dist/src/platform/signature.js +2 -2
  94. package/dist/src/platform/signed-http-transport.js +4 -1
  95. package/dist/src/platform/url-safety.js +6 -1
  96. package/dist/src/platform/webm-header.js +41 -0
  97. package/dist/src/platform/windows-acl/LICENSE-mingw-w64 +43 -0
  98. package/dist/src/platform/windows-acl/arm64.node +0 -0
  99. package/dist/src/platform/windows-acl/ia32.node +0 -0
  100. package/dist/src/platform/windows-acl/x64.node +0 -0
  101. package/dist/src/platform/windows-host-job/arm64.exe +0 -0
  102. package/dist/src/platform/windows-host-job/ia32.exe +0 -0
  103. package/dist/src/platform/windows-host-job/sha256.json +7 -0
  104. package/dist/src/platform/windows-host-job/x64.exe +0 -0
  105. package/dist/src/platform/windows-private-state.js +72 -0
  106. package/dist/src/product/config.js +1 -1
  107. package/dist/src/telemetry/command-route.js +38 -0
  108. package/dist/src/telemetry/command-routes.json +1 -0
  109. package/dist/src/telemetry/failure-summary.js +3 -3
  110. package/dist/src/telemetry/invocation.js +1 -2
  111. package/dist/src/telemetry/process-errors.js +17 -33
  112. package/dist/src/telemetry/sanitize.js +19 -4
  113. package/dist/src/telemetry/sls-sink.js +45 -20
  114. package/package.json +4 -4
  115. package/skills/insmind-cli/SKILL.md +18 -5
  116. package/skills/insmind-cli/references/agent.md +9 -4
  117. package/skills/insmind-cli/references/creation.md +3 -1
  118. package/skills/insmind-cli/references/editor.md +7 -5
  119. package/skills/insmind-cli/references/errors.md +20 -9
  120. package/skills/insmind-cli/references/matting.md +3 -5
  121. package/skills/insmind-cli/references/media-tools.md +10 -4
  122. package/skills/insmind-cli/references/tool.md +9 -15
@@ -1,7 +1,9 @@
1
1
  import { isInterruption } from "../../platform/interruption.js";
2
- import { spawn } from "node:child_process";
3
- import { realpathSync } from "node:fs";
4
- import { resolve } from "node:path";
2
+ import { PackageManagerTerminationError, spawnPackageManager, windowsShimTarget } from "./package-manager.js";
3
+ import { lstatSync, readFileSync, readlinkSync, realpathSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, isAbsolute, join, resolve } from "node:path";
6
+ import { loadBundledSkills } from "../skill/bundled-skills.js";
5
7
  import { gt } from "semver";
6
8
  import { syncBundledSkills, SkillSyncError, verifyBundledSkills } from "../skill/installer.js";
7
9
  import { fetchLatestVersion } from "./latest-version.js";
@@ -29,36 +31,138 @@ export function detectInstallSource(input) {
29
31
  const userAgent = input.env.npm_config_user_agent ?? "";
30
32
  const npmExecPath = normalizePath(input.env.npm_execpath ?? "");
31
33
  const packageName = input.packageName ?? "@gaoding/cli";
32
- const encodedPackage = packageName.replace("/", "+").replace("@", "@");
33
34
  if (userAgent.startsWith("yarn/") || npmExecPath.includes("/yarn/")) {
34
35
  return unsupported("Yarn 安装不支持自动更新");
35
36
  }
36
37
  if (containsTemporaryRunner(binaryPath) || containsTemporaryRunner(packageRoot)) {
37
38
  return unsupported("临时运行方式不支持自动更新");
38
39
  }
39
- if (binaryPath.includes("/node_modules/.bin/")
40
- || packageRoot.startsWith(`${cwd}/node_modules/`)) {
40
+ if (binaryPath.includes("/node_modules/.bin/")) {
41
41
  return unsupported("项目依赖不支持自动更新");
42
42
  }
43
43
  if (!isWithin(realBinaryPath, packageRoot)) {
44
44
  return unsupported("CLI binary 与 package 不匹配");
45
45
  }
46
- if (packageRoot.includes(`/global/`) && packageRoot.includes(`/.pnpm/${encodedPackage}@`)
47
- || packageRoot.includes(`/node_modules/${packageName}`)
48
- && /\/v\d+\/[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16}\//u.test(packageRoot)
49
- || binaryPath.includes(`/node_modules/${packageName}/dist/bin/${input.binaryName ?? "gd-cli"}.js`)
50
- && /\/v\d+\/[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16}\//u.test(binaryPath)) {
51
- return { kind: "global", manager: "pnpm", packageRoot: input.packageRoot };
46
+ // pnpm 12 can link global and project installs to the same store. The hash
47
+ // alone is not ownership evidence: match the actual invocation to its global launcher.
48
+ const command = input.binaryName ?? "gd-cli";
49
+ const platform = input.platform ?? process.platform;
50
+ const pnpmDirectory = pnpmSnapshotDirectory(binaryPath, packageName, command);
51
+ const pnpmLauncher = pnpmLaunchers(input.env, command).find(entry => entry.target === resolve(input.binaryPath));
52
+ if (realBinaryPath === `${packageRoot}/dist/bin/${command}.js` && pnpmDirectory && pnpmLauncher
53
+ && safeRealpath(input.binaryPath) === input.realBinaryPath
54
+ && packageManifestMatches(input.packageRoot, packageName)
55
+ && (!binaryPath.includes("/5/.pnpm/") || legacyManifestMatches(pnpmDirectory, packageName))) {
56
+ return { kind: "global", manager: "pnpm", packageRoot: input.packageRoot, directory: pnpmDirectory, launcher: pnpmLauncher.launcher };
52
57
  }
53
- if (packageRoot.endsWith(`/lib/node_modules/${packageName}`)
54
- || packageRoot.endsWith(`/npm/node_modules/${packageName}`)) {
55
- return { kind: "global", manager: "npm", packageRoot: input.packageRoot };
58
+ // Windows npm places packages directly under <prefix>/node_modules. Require
59
+ // the matching npm-generated launcher before treating that layout as global.
60
+ if (platform === "win32" && packageRoot.endsWith(`/node_modules/${packageName}`)
61
+ && realBinaryPath === `${packageRoot}/dist/bin/${command}.js` && packageManifestMatches(input.packageRoot, packageName)) {
62
+ const prefix = dirname(dirname(dirname(input.packageRoot)));
63
+ const launcher = join(prefix, `${command}.cmd`);
64
+ try {
65
+ const shim = readFileSync(launcher, "utf8");
66
+ const target = windowsShimTarget(shim);
67
+ if (target && realpathSync(resolve(prefix, target)) === input.realBinaryPath
68
+ && safeRealpath(input.binaryPath) === input.realBinaryPath) {
69
+ return { kind: "global", manager: "npm", packageRoot: input.packageRoot, directory: prefix, launcher };
70
+ }
71
+ }
72
+ catch { /* no matching launcher */ }
73
+ }
74
+ if (platform !== "win32" && packageRoot.endsWith(`/lib/node_modules/${packageName}`)
75
+ && realBinaryPath === `${packageRoot}/dist/bin/${command}.js` && packageManifestMatches(input.packageRoot, packageName)) {
76
+ const prefix = dirname(dirname(dirname(dirname(input.packageRoot))));
77
+ try {
78
+ const launcher = join(prefix, "bin", command);
79
+ if (lstatSync(launcher).isSymbolicLink() && realpathSync(launcher) === input.realBinaryPath
80
+ && safeRealpath(input.binaryPath) === input.realBinaryPath) {
81
+ return { kind: "global", manager: "npm", packageRoot: input.packageRoot, directory: prefix, launcher };
82
+ }
83
+ }
84
+ catch { /* no matching global launcher */ }
56
85
  }
86
+ if (packageRoot.startsWith(`${cwd}/node_modules/`))
87
+ return unsupported("项目依赖不支持自动更新");
57
88
  return unsupported("无法确认 npm 或 pnpm 全局安装");
58
89
  }
90
+ function pnpmSnapshotDirectory(binaryPath, name, command) {
91
+ const suffix = `/node_modules/${name}/dist/bin/${command}.js`;
92
+ const normalized = normalizePath(binaryPath);
93
+ if (!normalized.endsWith(suffix))
94
+ return;
95
+ const snapshot = normalized.slice(0, -suffix.length);
96
+ if (/\/v\d+\/(?:[a-f0-9]{64}|[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16})$/u.test(snapshot))
97
+ return dirname(dirname(snapshot));
98
+ const marker = `/5/.pnpm/${name.replace("/", "+")}@`;
99
+ const index = snapshot.lastIndexOf(marker);
100
+ if (index > 0 && !snapshot.slice(index + marker.length).includes("/"))
101
+ return resolve(snapshot.slice(0, index));
102
+ }
103
+ function packageManifestMatches(root, name) {
104
+ try {
105
+ return JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name === name;
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ }
111
+ function legacyManifestMatches(directory, name) {
112
+ try {
113
+ return typeof JSON.parse(readFileSync(join(directory, "5", "package.json"), "utf8")).dependencies?.[name] === "string";
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ }
119
+ function launcherTarget(launcher) {
120
+ try {
121
+ const stat = lstatSync(launcher);
122
+ const text = stat.isFile() && stat.size < 131072 ? readFileSync(launcher, "utf8") : undefined;
123
+ // pnpm also emits sh and PowerShell siblings. Identify the forwarded
124
+ // entry from their command, never from a comment naming a different file.
125
+ const shellEntry = text?.startsWith("#!") ? /^\s*exec\s+[^\r\n]*?\s+"([^"\r\n]+\.js)"\s+"\$@"\s*$/mu.exec(text)?.[1]
126
+ ?? /^\s*&\s+[^\r\n]*?\s+"([^"\r\n]+\.js)"\s+\$args\s*$/mu.exec(text)?.[1] : undefined;
127
+ const marker = text && /^#\s*cmd-shim-target=(.+)$/mu.exec(text)?.[1]?.trim();
128
+ const shellTarget = shellEntry?.match(/^\$basedir(?:_win)?\/(.+)$/u)?.[1]
129
+ ?? (marker && shellEntry && resolve(dirname(launcher), marker) === resolve(dirname(launcher), shellEntry) ? shellEntry : undefined);
130
+ const target = stat.isSymbolicLink() ? readlinkSync(launcher) : text
131
+ ? windowsShimTarget(text) ?? shellTarget : undefined;
132
+ if (!target)
133
+ return;
134
+ const entry = resolve(dirname(launcher), target);
135
+ realpathSync(entry);
136
+ return entry;
137
+ }
138
+ catch {
139
+ return;
140
+ }
141
+ }
142
+ function pnpmLaunchers(env, command) {
143
+ const home = env.HOME || env.USERPROFILE || homedir();
144
+ const pnpmHome = env.PNPM_HOME || (process.platform === "darwin" ? join(home, "Library", "pnpm")
145
+ : process.platform === "win32" ? join(env.LOCALAPPDATA || join(home, "AppData", "Local"), "pnpm")
146
+ : join(env.XDG_DATA_HOME || join(home, ".local", "share"), "pnpm"));
147
+ if (!isAbsolute(pnpmHome))
148
+ return [];
149
+ const result = [];
150
+ for (const dir of [join(pnpmHome, "bin"), pnpmHome]) {
151
+ for (const ext of process.platform === "win32" ? [".cmd", ".ps1", ""] : [""]) {
152
+ const launcher = join(dir, command + ext);
153
+ const target = launcherTarget(launcher);
154
+ if (target)
155
+ result.push({ launcher, target });
156
+ }
157
+ }
158
+ return result;
159
+ }
160
+ export function pnpmLauncherTargets(env, command) {
161
+ return pnpmLaunchers(env, command).map(entry => entry.target);
162
+ }
59
163
  export function createUpdateService(options) {
60
164
  const fetchPackage = options.fetch ?? globalThis.fetch;
61
- const runProcess = options.runProcess ?? spawnProcess;
165
+ const runProcess = options.runProcess ?? spawnPackageManager;
62
166
  const syncSkills = options.syncSkills ?? syncBundledSkills;
63
167
  const verifySkills = options.verifySkills ?? verifyBundledSkills;
64
168
  const env = options.env ?? process.env;
@@ -110,6 +214,22 @@ export function createUpdateService(options) {
110
214
  env,
111
215
  ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {})
112
216
  };
217
+ const binaryPath = options.binaryPath ?? process.argv[1] ?? "";
218
+ const source = detectInstallSource({
219
+ binaryPath,
220
+ realBinaryPath: safeRealpath(binaryPath),
221
+ packageRoot: options.packageRoot,
222
+ cwd: options.cwd ?? process.cwd(),
223
+ env,
224
+ packageName,
225
+ binaryName: commandName
226
+ });
227
+ const nextSteps = [insmind ? "Choose the command for your original package manager:" : "按原安装工具选择下面一条命令执行:", ...manualCommands(latest, packageName)];
228
+ if (source.kind === "unsupported") {
229
+ throw new UpdateError("UPDATE_FAILED", insmind
230
+ ? "The current installation method does not support automatic updates."
231
+ : `当前安装方式不支持自动更新:${source.reason}。`, nextSteps);
232
+ }
113
233
  if (!gt(latest, options.currentVersion)) {
114
234
  await options.telemetry.stage("sync", async () => {
115
235
  try {
@@ -127,26 +247,15 @@ export function createUpdateService(options) {
127
247
  });
128
248
  return { version: options.currentVersion, updated: false };
129
249
  }
130
- const binaryPath = options.binaryPath ?? process.argv[1] ?? "";
131
- const source = detectInstallSource({
132
- binaryPath,
133
- realBinaryPath: safeRealpath(binaryPath),
134
- packageRoot: options.packageRoot,
135
- cwd: options.cwd ?? process.cwd(),
136
- env,
137
- packageName,
138
- binaryName: commandName
139
- });
140
- const nextSteps = [insmind ? "Choose the command for your original package manager:" : "按原安装工具选择下面一条命令执行:", ...manualCommands(latest, packageName)];
141
- if (source.kind === "unsupported") {
142
- throw new UpdateError("UPDATE_FAILED", insmind
143
- ? "The current installation method does not support automatic updates."
144
- : `当前安装方式不支持自动更新:${source.reason}。`, nextSteps);
145
- }
146
250
  const command = source.manager;
251
+ const globalDirectory = source.manager === "pnpm" ? source.directory : undefined;
147
252
  const args = source.manager === "npm"
148
- ? ["install", "--global", `--allow-scripts=${packageName}`, `${packageName}@${latest}`]
149
- : ["add", "--global", `--allow-build=${packageName}`, `${packageName}@${latest}`];
253
+ ? ["install", "--global", "--prefix", source.directory, `--allow-scripts=${packageName}`, `${packageName}@${latest}`]
254
+ : ["add", "--global", "--global-dir", source.directory, `--allow-build=${packageName}`, `${packageName}@${latest}`];
255
+ const installNextSteps = [
256
+ insmind ? `Original installation directory: ${source.directory}` : `原安装目录:${source.directory}`,
257
+ insmind ? "Use the original package manager and directory if a manual retry is needed." : "如需手动重试,请使用原包管理器和该目录。"
258
+ ];
150
259
  await options.telemetry.stage("install", async () => {
151
260
  try {
152
261
  await runProcess(command, args, signal);
@@ -154,19 +263,51 @@ export function createUpdateService(options) {
154
263
  catch (error) {
155
264
  if (isInterruption(error, signal))
156
265
  throw signal.reason;
266
+ if (error instanceof PackageManagerTerminationError) {
267
+ throw new UpdateError("UPDATE_FAILED", insmind
268
+ ? "Unable to confirm that the interrupted package manager stopped; it may still be running."
269
+ : "无法确认已中断的包管理器已停止;安装进程可能仍在运行。", [installNextSteps[0], insmind ? "Check the package manager process and original installation before retrying." : "请先检查包管理器进程及原安装状态,再决定是否重试。"], error);
270
+ }
157
271
  throw new UpdateError("UPDATE_FAILED", insmind
158
272
  ? `Failed to update ${commandName} to ${latest}.`
159
- : `gd-cli 更新到 ${latest} 失败。`, nextSteps, error);
273
+ : `gd-cli 更新到 ${latest} 失败。`, installNextSteps, error);
160
274
  }
161
275
  });
162
276
  signal.throwIfAborted();
277
+ try {
278
+ (options.verifyInstallation ?? verifyInstalledVersion)(source, latest, globalDirectory, env, packageName, commandName);
279
+ }
280
+ catch (error) {
281
+ throw new UpdateError("UPDATE_FAILED", insmind
282
+ ? `The package manager finished, but the ${latest} installation could not be confirmed; the installation may have changed.`
283
+ : `包管理器已结束,但无法确认原安装目录已更新到 ${latest};安装状态可能已改变。`, [installNextSteps[0], insmind ? `Check the original installation and run ${commandName} --version.` : "请检查原安装目录并执行 gd-cli --version。"], error);
284
+ }
163
285
  const targetSkills = options.bundledSkills.map((skill) => ({
164
286
  ...skill,
165
287
  version: latest
166
288
  }));
167
289
  await options.telemetry.stage("verify", async () => {
168
290
  try {
169
- await verifySkills(targetSkills, skillOptions);
291
+ try {
292
+ await verifySkills(targetSkills, skillOptions);
293
+ }
294
+ catch (verificationError) {
295
+ if (isInterruption(verificationError, signal) || !globalDirectory)
296
+ throw verificationError;
297
+ // A pnpm store cache hit may skip postinstall. Only use new Skill bytes
298
+ // from the verified replacement launcher in the same global installation.
299
+ const target = launcherTarget(source.launcher);
300
+ if (target && pnpmSnapshotDirectory(target, packageName, commandName) !== globalDirectory)
301
+ throw verificationError;
302
+ if (!target)
303
+ throw verificationError;
304
+ const actual = loadBundledSkills(realpathSync(target));
305
+ if (!actual.length || actual.some(s => s.skill !== commandName || s.version !== latest)
306
+ || readInstallationOwner(dirname(dirname(actual[0].sourceDirectory))) !== "user")
307
+ throw verificationError;
308
+ await syncSkills(actual, skillOptions);
309
+ await verifySkills(actual, skillOptions);
310
+ }
170
311
  }
171
312
  catch (error) {
172
313
  if (isInterruption(error, signal))
@@ -182,25 +323,24 @@ export function createUpdateService(options) {
182
323
  }
183
324
  };
184
325
  }
185
- function spawnProcess(command, args, signal) {
186
- return new Promise((resolvePromise, reject) => {
187
- const child = spawn(command, args, {
188
- stdio: [0, 2, 2],
189
- shell: false,
190
- signal
191
- });
192
- child.once("error", reject);
193
- child.once("exit", (code, exitSignal) => {
194
- if (code === 0) {
195
- resolvePromise();
196
- }
197
- else {
198
- reject(new Error(code === null
199
- ? `package manager terminated by ${exitSignal ?? "unknown signal"}`
200
- : `package manager exited with ${code}`));
201
- }
202
- });
203
- });
326
+ function verifyInstalledVersion(source, version, globalDirectory, env, packageName, command) {
327
+ let root = source.packageRoot;
328
+ if (source.manager === "pnpm") {
329
+ if (!globalDirectory)
330
+ throw new Error("Cannot verify the original pnpm global directory");
331
+ const target = launcherTarget(source.launcher);
332
+ if (!target || pnpmSnapshotDirectory(target, packageName, command) !== globalDirectory)
333
+ throw new Error("Cannot find the replacement launcher in the original global directory");
334
+ root = dirname(dirname(dirname(realpathSync(target))));
335
+ }
336
+ const entry = launcherTarget(source.launcher);
337
+ const expectedEntry = realpathSync(join(root, "dist", "bin", `${command}.js`));
338
+ if (!entry || realpathSync(entry) !== expectedEntry)
339
+ throw new Error("The original launcher no longer reaches the updated installation");
340
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
341
+ if (manifest.name !== packageName || manifest.version !== version || readInstallationOwner(root) !== "user") {
342
+ throw new Error("The original installation does not contain the requested package version");
343
+ }
204
344
  }
205
345
  function manualCommands(version, packageName = "@gaoding/cli") {
206
346
  return [
@@ -0,0 +1,9 @@
1
+ import { createRequire } from "node:module";
2
+ const require = createRequire(import.meta.url);
3
+ let windowsSpawn;
4
+ export function startDetached(spawn) {
5
+ if (process.platform !== "win32")
6
+ return spawn();
7
+ windowsSpawn ??= require(`./windows-acl/${process.arch}.node`).withDetachedPipes;
8
+ return windowsSpawn(spawn);
9
+ }
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import * as nodeFileSystem from "node:fs/promises";
3
3
  import { join, resolve } from "node:path";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
+ export const fileLockDirectory = (lockPath) => `${lockPath}.d`;
5
6
  const localTurns = new Map();
6
7
  const actions = new Set(["task_write", "task_update", "sls_queue", "analytics_device"]);
7
8
  const localOwners = new Map();
@@ -70,7 +71,7 @@ async function acquireFileLock(path, run, options, identity) {
70
71
  const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
71
72
  if (Date.now() >= deadline)
72
73
  throw lockTimeout(identity.startedAt, identity.contenderId, "owner_files", [], options.action);
73
- const directory = `${path}.d`;
74
+ const directory = fileLockDirectory(path);
74
75
  await mkdir(directory, { recursive: true, mode: 0o700 });
75
76
  await chmod(directory, 0o700);
76
77
  const name = `${process.pid}-${identity.contenderId}.json`;
@@ -96,7 +97,8 @@ async function acquireFileLock(path, run, options, identity) {
96
97
  }
97
98
  }
98
99
  try {
99
- const text = await readFile(join(directory, entry), "utf8");
100
+ const ownerPath = join(directory, entry);
101
+ const text = options.readOwner ? await options.readOwner(ownerPath) : await readFile(ownerPath, "utf8");
100
102
  let ticket = null;
101
103
  let action;
102
104
  let startedAtMs;
@@ -115,8 +117,14 @@ async function acquireFileLock(path, run, options, identity) {
115
117
  ...(action ? { action } : {}), ...(startedAtMs === undefined ? {} : { startedAtMs }) });
116
118
  }
117
119
  catch (error) {
118
- if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
119
- throw error;
120
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
121
+ continue;
122
+ // Windows can return ACCESS_DENIED when the previous owner unlinks its
123
+ // ticket between readdir and open. A UUID ticket is never reused.
124
+ if (error instanceof Error && "win32Code" in error && error.win32Code === 5
125
+ && !(await readdir(directory)).includes(entry))
126
+ continue;
127
+ throw error;
120
128
  }
121
129
  }
122
130
  return found;
@@ -1,3 +1,4 @@
1
+ import { fileURLToPath, pathToFileURL } from "node:url";
1
2
  /** Structural evidence for an already rejected URI; never include its value. */
2
3
  export function uriIssue(value) {
3
4
  if (/[\u0000-\u001f\u007f-\u009f]/u.test(value))
@@ -50,6 +51,27 @@ export function uriShape(value) {
50
51
  uriWindowsDrive: windowsDrive
51
52
  };
52
53
  }
54
+ // WHATWG file URLs drop an explicit "localhost" authority. On Windows it can
55
+ // identify an SMB share, so preserve it until the native filesystem boundary.
56
+ const localhostAuthority = /^file:\/\/localhost(?=\/)/iu;
57
+ export function fileUriFromLocalPath(path) {
58
+ const url = pathToFileURL(path);
59
+ return process.platform === "win32" && /^\\\\localhost\\/iu.test(path)
60
+ ? "file://localhost" + url.pathname : url.href;
61
+ }
62
+ export function localPathFromFileUri(uri) {
63
+ try {
64
+ return fileURLToPath(uri);
65
+ }
66
+ catch (cause) {
67
+ if (process.platform !== "win32" || !/^file:\/\/localhost\/[^/]/iu.test(uri))
68
+ throw cause;
69
+ // A trailing DNS dot keeps the authority intact for Node's UNC decoding,
70
+ // including its encoded-separator checks. Only the original name reaches fs.
71
+ const unc = fileURLToPath(uri.replace(localhostAuthority, "file://localhost."));
72
+ return "\\\\localhost" + unc.slice("\\\\localhost.".length);
73
+ }
74
+ }
53
75
  /** Canonicalize explicit file URIs, without repairing paths or losing filename spaces. */
54
76
  export function canonicalFileUri(value) {
55
77
  if (!/^file:\//iu.test(value) || /[\\\u0000-\u001f\u007f-\u009f]/u.test(value)
@@ -61,7 +83,7 @@ export function canonicalFileUri(value) {
61
83
  return undefined;
62
84
  // URL accepts malformed escapes, whereas fileURLToPath cannot read them.
63
85
  decodeURIComponent(url.pathname);
64
- return url.href;
86
+ return process.platform === "win32" && localhostAuthority.test(value) ? "file://localhost" + url.pathname : url.href;
65
87
  }
66
88
  catch {
67
89
  return undefined;
@@ -1,6 +1,31 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { closeSync } from "node:fs";
2
3
  import * as nodeFileSystem from "node:fs/promises";
3
- import { join } from "node:path";
4
+ import { dirname, join } from "node:path";
5
+ import { openWindowsState, openWindowsStateReader, retryWindowsStateRename } from "./windows-private-state.js";
6
+ // Windows can report ENOENT when an ancestor is a regular file. Walk only
7
+ // on the missing path, so normal reads incur no additional filesystem calls.
8
+ export async function confirmMissingPath(directory, cause) {
9
+ if (process.platform !== "win32" || !isMissing(cause))
10
+ return;
11
+ let current = directory;
12
+ for (;;) {
13
+ try {
14
+ const stat = await nodeFileSystem.stat(current);
15
+ if (!stat.isDirectory())
16
+ throw Object.assign(new Error("A local state parent is not a directory."), { code: "ENOTDIR", cause });
17
+ return;
18
+ }
19
+ catch (error) {
20
+ if (!isMissing(error))
21
+ throw error;
22
+ const parent = dirname(current);
23
+ if (parent === current)
24
+ throw error;
25
+ current = parent;
26
+ }
27
+ }
28
+ }
4
29
  export class LocalFileError extends Error {
5
30
  file;
6
31
  reason;
@@ -19,6 +44,7 @@ export class LocalFileError extends Error {
19
44
  export function createLocalJsonFile(options) {
20
45
  const fileSystem = options.fileSystem ?? nodeFileSystem;
21
46
  const path = join(options.directory, options.filename);
47
+ const windowsAcl = process.platform === "win32" && options.protectWindowsAcl;
22
48
  return {
23
49
  async readText() {
24
50
  let handle;
@@ -26,17 +52,37 @@ export function createLocalJsonFile(options) {
26
52
  let primaryError;
27
53
  let step = "directory_permissions";
28
54
  try {
29
- await fileSystem.chmod(options.directory, 0o700);
30
- step = "open";
31
- handle = await fileSystem.open(path, "r");
32
- step = "file_permissions";
33
- await handle.chmod(0o600);
55
+ if (windowsAcl) {
56
+ const directoryFd = openWindowsState(options.directory, "directory");
57
+ try {
58
+ step = "file_permissions";
59
+ handle = openWindowsStateReader(path);
60
+ }
61
+ finally {
62
+ closeSync(directoryFd);
63
+ }
64
+ }
65
+ else {
66
+ await fileSystem.chmod(options.directory, 0o700);
67
+ step = "open";
68
+ const opened = await fileSystem.open(path, "r");
69
+ handle = opened;
70
+ step = "file_permissions";
71
+ await opened.chmod(0o600);
72
+ }
34
73
  step = "read";
35
74
  return await handle.readFile("utf8");
36
75
  }
37
76
  catch (cause) {
38
- if (!handle && isMissing(cause))
39
- return null;
77
+ if (!handle && isMissing(cause)) {
78
+ try {
79
+ await confirmMissingPath(options.directory, cause);
80
+ return null;
81
+ }
82
+ catch (error) {
83
+ cause = error;
84
+ }
85
+ }
40
86
  failed = true;
41
87
  primaryError = cause;
42
88
  throw new LocalFileError(cause, options.filename, "io", { operation: "read", step, ...(options.role ? { role: options.role } : {}) });
@@ -54,14 +100,24 @@ export function createLocalJsonFile(options) {
54
100
  },
55
101
  async writeTextAtomically(value) {
56
102
  const temporaryPath = join(options.directory, `${options.filename}.tmp-${randomUUID()}`);
103
+ let directoryFd;
57
104
  let handle;
105
+ let createdTemporary = false;
58
106
  let step = "directory_create";
59
107
  try {
60
- await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
61
- step = "directory_permissions";
62
- await fileSystem.chmod(options.directory, 0o700);
108
+ if (windowsAcl) {
109
+ await fileSystem.mkdir(dirname(options.directory), { recursive: true });
110
+ step = "directory_permissions";
111
+ directoryFd = openWindowsState(options.directory, "create");
112
+ }
113
+ else {
114
+ await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
115
+ step = "directory_permissions";
116
+ await fileSystem.chmod(options.directory, 0o700);
117
+ }
63
118
  step = "open";
64
119
  handle = await fileSystem.open(temporaryPath, "wx", 0o600);
120
+ createdTemporary = true;
65
121
  step = "file_permissions";
66
122
  await handle.chmod(0o600);
67
123
  step = "write";
@@ -72,21 +128,47 @@ export function createLocalJsonFile(options) {
72
128
  await handle.close();
73
129
  handle = undefined;
74
130
  step = "rename";
75
- await fileSystem.rename(temporaryPath, path);
131
+ const rename = () => fileSystem.rename(temporaryPath, path);
132
+ if (windowsAcl)
133
+ await retryWindowsStateRename(rename);
134
+ else
135
+ await rename();
76
136
  }
77
137
  catch (cause) {
78
138
  await handle?.close().catch(() => undefined);
79
- await fileSystem.unlink(temporaryPath).catch(() => undefined);
139
+ if (createdTemporary)
140
+ await fileSystem.unlink(temporaryPath).catch(() => undefined);
80
141
  throw new LocalFileError(cause, options.filename, "io", { operation: "write", step, ...(options.role ? { role: options.role } : {}) });
81
142
  }
143
+ finally {
144
+ if (directoryFd !== undefined)
145
+ closeSync(directoryFd);
146
+ }
82
147
  },
83
148
  async remove() {
149
+ let directoryFd;
150
+ let step = "directory_permissions";
84
151
  try {
152
+ if (windowsAcl)
153
+ directoryFd = openWindowsState(options.directory, "directory");
154
+ step = "unlink";
85
155
  await fileSystem.unlink(path);
86
156
  }
87
157
  catch (cause) {
88
- if (!isMissing(cause))
89
- throw new LocalFileError(cause, options.filename, "io", { operation: "remove", step: "unlink", ...(options.role ? { role: options.role } : {}) });
158
+ if (isMissing(cause)) {
159
+ try {
160
+ await confirmMissingPath(options.directory, cause);
161
+ return;
162
+ }
163
+ catch (error) {
164
+ cause = error;
165
+ }
166
+ }
167
+ throw new LocalFileError(cause, options.filename, "io", { operation: "remove", step, ...(options.role ? { role: options.role } : {}) });
168
+ }
169
+ finally {
170
+ if (directoryFd !== undefined)
171
+ closeSync(directoryFd);
90
172
  }
91
173
  }
92
174
  };
@@ -0,0 +1,46 @@
1
+ const mediaTypes = {
2
+ avif: "image/avif",
3
+ bmp: "image/bmp",
4
+ gif: "image/gif",
5
+ heic: "image/heic",
6
+ heif: "image/heif",
7
+ jpeg: "image/jpeg",
8
+ jpg: "image/jpeg",
9
+ m4v: "video/x-m4v",
10
+ mkv: "video/x-matroska",
11
+ mov: "video/quicktime",
12
+ mp3: "audio/mpeg",
13
+ mp4: "video/mp4",
14
+ png: "image/png",
15
+ svg: "image/svg+xml",
16
+ wav: "audio/wav",
17
+ webm: "video/webm",
18
+ webp: "image/webp"
19
+ };
20
+ export function mediaFilename(url) {
21
+ const segment = url.pathname.split("/").filter(Boolean).at(-1);
22
+ if (segment === undefined)
23
+ return "creative-media";
24
+ try {
25
+ const name = decodeURIComponent(segment);
26
+ return name.trim() ? name : "creative-media";
27
+ }
28
+ catch {
29
+ return segment;
30
+ }
31
+ }
32
+ export function mediaTypeForFormat(format) {
33
+ return Object.hasOwn(mediaTypes, format) ? mediaTypes[format] : undefined;
34
+ }
35
+ // Only a concrete type can contradict a recognized file. MIME parameters are not part of the type.
36
+ export function concreteMediaType(declaration) {
37
+ const type = declaration?.split(";", 1)[0]?.trim().toLowerCase();
38
+ return type === "application/octet-stream" ? undefined : type;
39
+ }
40
+ export function mediaTypeFromFilename(filename) {
41
+ const dot = filename.lastIndexOf(".");
42
+ if (dot < 0)
43
+ return undefined;
44
+ const extension = filename.slice(dot + 1).toLowerCase();
45
+ return mediaTypeForFormat(extension);
46
+ }
@@ -1,5 +1,8 @@
1
- import open from "open";
2
- export function createBrowserOpener(openUrl = open) {
1
+ async function launchBrowser(url) {
2
+ const { default: open } = await import("open");
3
+ return open(url);
4
+ }
5
+ export function createBrowserOpener(openUrl = launchBrowser) {
3
6
  return {
4
7
  async open(url) {
5
8
  await openUrl(url.href);