@insmind/cli 2.0.0 → 2.1.1

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 (113) hide show
  1. package/README.md +5 -0
  2. package/contracts/operations/agent.send/input.schema.json +1 -77
  3. package/contracts/operations/credits.get/input.schema.json +8 -0
  4. package/contracts/operations/credits.get/output.schema.json +92 -0
  5. package/contracts/operations/credits.usage.get/input.schema.json +17 -0
  6. package/contracts/operations/credits.usage.get/output.schema.json +46 -0
  7. package/contracts/operations/credits.usage.list/input.schema.json +27 -0
  8. package/contracts/operations/credits.usage.list/output.schema.json +135 -0
  9. package/contracts/operations/dam.folder.list/input.schema.json +0 -1
  10. package/contracts/operations/dam.folder.list/output.schema.json +1 -2
  11. package/contracts/operations/dam.list/input.schema.json +3 -6
  12. package/contracts/operations/dam.list/output.schema.json +1 -2
  13. package/contracts/operations/dam.search/input.schema.json +3 -6
  14. package/contracts/operations/dam.search/output.schema.json +1 -2
  15. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
  16. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
  17. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
  18. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
  19. package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
  20. package/dist/bin/postinstall.js +22 -6
  21. package/dist/bin/task-worker.js +2 -2
  22. package/dist/src/bootstrap/create-cli.js +31 -15
  23. package/dist/src/bootstrap/create-runtime.js +103 -30
  24. package/dist/src/bootstrap/run-task-worker.js +6 -2
  25. package/dist/src/bootstrap/validators.js +4 -1
  26. package/dist/src/cli/action-binding.js +17 -50
  27. package/dist/src/cli/agent-commands.js +11 -11
  28. package/dist/src/cli/auth-commands.js +2 -1
  29. package/dist/src/cli/creation-help.js +9 -0
  30. package/dist/src/cli/credits-command.js +127 -16
  31. package/dist/src/cli/dam-commands.js +10 -14
  32. package/dist/src/cli/editor-commands.js +7 -5
  33. package/dist/src/cli/errors.js +81 -22
  34. package/dist/src/cli/host-input.js +64 -5
  35. package/dist/src/cli/model-commands.js +9 -3
  36. package/dist/src/cli/observed-errors.js +7 -3
  37. package/dist/src/cli/org-commands.js +3 -1
  38. package/dist/src/cli/presenter.js +4 -0
  39. package/dist/src/cli/task-commands.js +6 -2
  40. package/dist/src/cli/tool-commands.js +12 -11
  41. package/dist/src/cli/update-command.js +24 -1
  42. package/dist/src/features/agent/creative-agent-adapter.js +6 -2
  43. package/dist/src/features/agent/creative-protocol.js +8 -29
  44. package/dist/src/features/agent/resource-authorizer.js +25 -17
  45. package/dist/src/features/agent/result-reader.js +31 -14
  46. package/dist/src/features/agent/use-cases.js +6 -31
  47. package/dist/src/features/credits/amount.js +51 -0
  48. package/dist/src/features/credits/response.js +11 -0
  49. package/dist/src/features/credits/use-cases.js +200 -30
  50. package/dist/src/features/dam/asset-projection.js +3 -6
  51. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  52. package/dist/src/features/dam/repository-catalog.js +30 -21
  53. package/dist/src/features/dam/use-cases.js +12 -7
  54. package/dist/src/features/editor/bridge-client.js +0 -2
  55. package/dist/src/features/editor/public-url.js +1 -36
  56. package/dist/src/features/editor/session.js +3 -2
  57. package/dist/src/features/editor/use-cases.js +27 -2
  58. package/dist/src/features/org/org-service.js +10 -1
  59. package/dist/src/features/org/use-cases.js +18 -4
  60. package/dist/src/features/task/process-owner.js +54 -0
  61. package/dist/src/features/task/store.js +37 -10
  62. package/dist/src/features/task/task-background.js +5 -2
  63. package/dist/src/features/task/use-cases.js +184 -84
  64. package/dist/src/features/tool/argument-paths.js +14 -0
  65. package/dist/src/features/tool/canvas-copy.js +28 -15
  66. package/dist/src/features/tool/canvas-matting.js +123 -0
  67. package/dist/src/features/tool/canvas-media.js +100 -52
  68. package/dist/src/features/tool/canvas-models.js +66 -33
  69. package/dist/src/features/tool/canvas-pricing.js +12 -0
  70. package/dist/src/features/tool/canvas-recovery.js +13 -30
  71. package/dist/src/features/tool/canvas-results.js +79 -87
  72. package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
  73. package/dist/src/features/tool/canvas-video.js +44 -37
  74. package/dist/src/features/tool/dynamic-schema.js +39 -40
  75. package/dist/src/features/tool/ffprobe-executable.js +21 -0
  76. package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
  77. package/dist/src/features/tool/resource-authorizer.js +11 -3
  78. package/dist/src/features/tool/tool-api-adapter.js +73 -82
  79. package/dist/src/features/tool/tool-errors.js +25 -0
  80. package/dist/src/features/tool/tool-output.js +15 -0
  81. package/dist/src/features/tool/use-cases.js +74 -98
  82. package/dist/src/features/update/check-schema.js +17 -0
  83. package/dist/src/features/update/host-receipt.js +30 -0
  84. package/dist/src/features/update/notice-output.js +30 -0
  85. package/dist/src/features/update/update-lock.js +80 -0
  86. package/dist/src/features/update/update-notification.js +129 -240
  87. package/dist/src/features/update/update-service.js +95 -21
  88. package/dist/src/platform/media-type.js +46 -0
  89. package/dist/src/platform/public-url.js +35 -0
  90. package/dist/src/platform/remote-error-evidence.js +33 -6
  91. package/dist/src/platform/resource-auth-key.js +35 -1
  92. package/dist/src/platform/safe-upload-file.js +36 -41
  93. package/dist/src/platform/signature.js +3 -1
  94. package/dist/src/platform/signed-http-transport.js +14 -6
  95. package/dist/src/platform/url-safety.js +6 -1
  96. package/dist/src/platform/webm-header.js +41 -0
  97. package/dist/src/telemetry/command-route.js +38 -0
  98. package/dist/src/telemetry/command-routes.json +1 -0
  99. package/dist/src/telemetry/failure-summary.js +1 -1
  100. package/dist/src/telemetry/invocation.js +1 -2
  101. package/dist/src/telemetry/process-errors.js +17 -33
  102. package/dist/src/telemetry/sanitize.js +19 -4
  103. package/dist/src/telemetry/sls-sink.js +8 -0
  104. package/package.json +4 -4
  105. package/skills/insmind-cli/SKILL.md +19 -5
  106. package/skills/insmind-cli/references/agent.md +9 -4
  107. package/skills/insmind-cli/references/creation.md +3 -1
  108. package/skills/insmind-cli/references/editor.md +7 -5
  109. package/skills/insmind-cli/references/errors.md +20 -9
  110. package/skills/insmind-cli/references/matting.md +3 -5
  111. package/skills/insmind-cli/references/media-tools.md +10 -4
  112. package/skills/insmind-cli/references/tool.md +9 -15
  113. package/skills/insmind-cli/references/update.md +2 -0
@@ -1,122 +1,151 @@
1
- import { randomUUID } from "node:crypto";
2
- import * as fileSystem from "node:fs/promises";
3
1
  import { homedir } from "node:os";
4
2
  import { join } from "node:path";
5
3
  import { gt, valid } from "semver";
6
4
  import { createLocalJsonFile } from "../../platform/local-json-file.js";
7
5
  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;
6
+ import { createLocalUpdateNotificationLock } from "./update-lock.js";
7
+ const HOUR = 60 * 60 * 1_000;
8
+ const RETRY = 15 * 60 * 1_000;
12
9
  export function createUpdateNotificationService(options) {
13
- const fetchPackage = options.fetch ?? globalThis.fetch;
10
+ const { currentVersion } = options;
11
+ const command = options.commandName ?? "gd-cli";
14
12
  const now = options.now ?? (() => new Date());
15
13
  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
- });
14
+ const directory = join(options.homeDirectory ?? homedir(), options.stateDirectoryName ?? ".gd");
15
+ const file = options.stateFile ?? createLocalJsonFile({ directory, filename: "update-check.json" });
16
+ const lock = options.lock ?? createLocalUpdateNotificationLock({ directory, now: () => new Date() });
17
+ const host = env.CLI_HOST_APPLICATION?.toLowerCase();
18
+ const surface = host && /^[a-z0-9_-]{1,48}$/.test(host) ? host : "terminal";
19
+ const unknown = { status: "unknown", currentVersion };
20
+ async function refresh(state, time, signal) {
21
+ if (Date.parse(state.next_check_at ?? "") > time.getTime())
22
+ return state;
23
+ const timeout = signalWithTimeout(signal, 2_000);
24
+ try {
25
+ const fetchLatest = () => fetchLatestVersion({
26
+ fetch: options.fetch ?? globalThis.fetch, signal: timeout.signal,
27
+ ...(options.registryUrl ? { registryUrl: options.registryUrl } : {}),
28
+ ...(state.etag ? { etag: state.etag } : {})
29
+ });
30
+ const result = options.telemetry ? await options.telemetry.stage("update_check.registry", fetchLatest) : await fetchLatest();
31
+ const latest = result.status === "modified" ? result.version : state.latest_version;
32
+ if (!latest || !valid(latest))
33
+ throw new Error("Missing cached Registry version");
34
+ const next = { ...state, latest_version: latest, last_success_check_at: time.toISOString(),
35
+ next_check_at: new Date(time.getTime() + HOUR).toISOString() };
36
+ if (result.status === "modified") {
37
+ if (result.etag)
38
+ next.etag = result.etag;
39
+ else
40
+ delete next.etag;
41
+ }
42
+ return next;
43
+ }
44
+ catch {
45
+ signal.throwIfAborted();
46
+ // A failed refresh cannot establish what the latest version is.
47
+ const { latest_version, etag, ...prior } = state;
48
+ return { ...prior, next_check_at: new Date(time.getTime() + RETRY).toISOString() };
49
+ }
50
+ finally {
51
+ timeout.dispose();
52
+ }
53
+ }
54
+ async function report(signal, channel, deliver, remember = true) {
55
+ if (options.installationOwner === "workbuddy")
56
+ return deliver({ status: "managed", currentVersion });
57
+ if (options.installationOwner === "invalid" || env.CI === "true")
58
+ return deliver(unknown);
59
+ const release = await lock.acquire().catch(() => null);
60
+ if (!release)
61
+ return deliver(unknown);
62
+ try {
63
+ let state;
64
+ try {
65
+ signal.throwIfAborted();
66
+ const prior = await readState(file);
67
+ state = await refresh(prior, now(), signal);
68
+ if (state !== prior)
69
+ await save(file, state);
70
+ }
71
+ catch {
72
+ signal.throwIfAborted();
73
+ return await deliver(unknown);
74
+ }
75
+ const latest = valid(state.latest_version);
76
+ if (!latest)
77
+ return await deliver(unknown);
78
+ if (!gt(latest, currentVersion))
79
+ return await deliver({ status: "current", currentVersion, latestVersion: latest });
80
+ const available = { status: "available", currentVersion, latestVersion: latest, updateCommand: command + " update" };
81
+ const windowStart = now().getTime() - HOUR;
82
+ const recent = Object.fromEntries(Object.entries(state.notified_at ?? {}).filter(([, at]) => at > windowStart));
83
+ if (!channel || Object.hasOwn(recent, channel))
84
+ return await deliver(available);
85
+ const notice = command === "gd-cli"
86
+ ? `gd-cli 有新版本 ${latest},当前版本为 ${currentVersion}。运行 gd-cli update 即可更新。`
87
+ : `${command} ${latest} is available; current version is ${currentVersion}. Run ${command} update to update.`;
88
+ await deliver({ ...available, notice });
89
+ if (remember)
90
+ await save(file, { ...state, notified_at: { ...recent, [channel]: now().getTime() } }).catch(() => undefined);
91
+ }
92
+ finally {
93
+ await release().catch(() => undefined);
94
+ }
95
+ }
25
96
  return {
26
- async check(signal) {
27
- if ((options.installationOwner ?? "user") !== "user")
97
+ async check(signal, output = "machine") {
98
+ if (env.CI === "true" || env.CLI_INVOCATION_PURPOSE === "auth_status" || env.CLI_INVOCATION_PURPOSE === "version_check")
28
99
  return;
29
- if (env.CI === "true")
30
- return;
31
- const lease = { release: null };
100
+ // An unobserved stderr pipe must not spend the next visible text/Skill reminder.
101
+ const channel = output === "machine" && options.diagnosticOnly ? "stderr:" + surface : "display:" + surface;
102
+ const run = () => report(signal, channel, async (result) => {
103
+ if (result.status === "available" && result.notice)
104
+ await options.notify(result.notice, output);
105
+ }, env.CLI_UPDATE_NOTICE_FORMAT !== "offer");
32
106
  try {
33
- const run = async () => {
34
- signal.throwIfAborted();
35
- lease.release = await lock.acquire();
36
- if (lease.release === null)
37
- return;
38
- const checkedAt = now();
39
- const today = localDate(checkedAt);
40
- const state = await readState(stateFile);
41
- if (isNewer(state.latest_version, options.currentVersion)
42
- && state.last_notified_on !== today) {
43
- const reminded = withReminder(state, today, state.latest_version);
44
- await writeState(stateFile, reminded);
45
- notify(options, state.latest_version);
46
- return;
47
- }
48
- if (!isDue(state.next_check_at, checkedAt))
49
- return;
50
- let latestResult;
51
- const timeout = signalWithTimeout(signal, REGISTRY_TIMEOUT_MS);
52
- try {
53
- const fetchLatest = () => fetchLatestVersion({
54
- fetch: fetchPackage,
55
- signal: timeout.signal,
56
- ...(options.registryUrl ? { registryUrl: options.registryUrl } : {}),
57
- ...(state.etag ? { etag: state.etag } : {})
58
- });
59
- latestResult = options.telemetry ? await options.telemetry.stage("update_check.registry", fetchLatest) : await fetchLatest();
60
- }
61
- catch (error) {
62
- if (signal.aborted)
63
- return;
64
- await writeState(stateFile, {
65
- ...state,
66
- schema_version: 1,
67
- next_check_at: addMilliseconds(checkedAt, FAILED_CHECK_INTERVAL_MS)
68
- });
69
- return;
70
- }
71
- finally {
72
- timeout.dispose();
73
- }
74
- const latest = latestResult.status === "not_modified"
75
- ? state.latest_version
76
- : latestResult.version;
77
- if (latest === undefined || valid(latest) === null) {
78
- await writeState(stateFile, {
79
- ...state,
80
- schema_version: 1,
81
- next_check_at: addMilliseconds(checkedAt, FAILED_CHECK_INTERVAL_MS)
82
- });
83
- return;
84
- }
85
- let nextState = {
86
- ...state,
87
- schema_version: 1,
88
- last_success_check_at: checkedAt.toISOString(),
89
- next_check_at: addMilliseconds(checkedAt, SUCCESS_CHECK_INTERVAL_MS),
90
- latest_version: latest,
91
- ...(latestResult.status === "modified" && latestResult.etag
92
- ? { etag: latestResult.etag }
93
- : {})
94
- };
95
- if (latestResult.status === "modified" && latestResult.etag === undefined) {
96
- delete nextState.etag;
97
- }
98
- const shouldNotify = gt(latest, options.currentVersion)
99
- && nextState.last_notified_on !== today;
100
- if (shouldNotify)
101
- nextState = withReminder(nextState, today, latest);
102
- await writeState(stateFile, nextState);
103
- if (shouldNotify)
104
- notify(options, latest);
105
- };
106
107
  if (options.telemetry)
107
108
  await options.telemetry.stage("update_check", run);
108
109
  else
109
110
  await run();
110
111
  }
111
- catch (error) {
112
- // Availability checks are best-effort and never change command behavior.
113
- }
114
- finally {
115
- await lease.release?.().catch(() => undefined);
116
- }
112
+ catch { /* Optional notices never change a business command's result. */ }
113
+ },
114
+ report(signal, forDisplay, deliver) {
115
+ return report(signal, forDisplay ? "display:" + surface : undefined, deliver);
117
116
  }
118
117
  };
119
118
  }
119
+ async function readState(file) {
120
+ const empty = { schema_version: 1 };
121
+ const content = await file.readText();
122
+ if (!content)
123
+ return empty;
124
+ try {
125
+ const value = JSON.parse(content);
126
+ if (!isRecord(value) || value.schema_version !== 1)
127
+ return empty;
128
+ const state = { ...empty };
129
+ for (const key of ["next_check_at", "latest_version", "etag", "last_success_check_at"]) {
130
+ if (typeof value[key] === "string")
131
+ state[key] = value[key];
132
+ }
133
+ // v1 date-only reminders have no time of day. Start the rolling window on first delivery.
134
+ if (isRecord(value.notified_at)) {
135
+ state.notified_at = Object.fromEntries(Object.entries(value.notified_at).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])));
136
+ }
137
+ return state;
138
+ }
139
+ catch {
140
+ return empty;
141
+ }
142
+ }
143
+ function isRecord(value) {
144
+ return typeof value === "object" && value !== null && !Array.isArray(value);
145
+ }
146
+ function save(file, state) {
147
+ return file.writeTextAtomically(JSON.stringify(state, null, 2) + "\n");
148
+ }
120
149
  function signalWithTimeout(parent, milliseconds) {
121
150
  const controller = new AbortController();
122
151
  const forwardAbort = () => { controller.abort(parent.reason); };
@@ -136,143 +165,3 @@ function signalWithTimeout(parent, milliseconds) {
136
165
  }
137
166
  };
138
167
  }
139
- function createLocalUpdateNotificationLock(options) {
140
- const path = join(options.directory, "update-check.lock");
141
- return {
142
- async acquire() {
143
- await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
144
- await fileSystem.chmod(options.directory, 0o700);
145
- const first = await tryCreateLock(path);
146
- if (first)
147
- return releaseLock(path, first);
148
- if (!await isStaleLock(path, options.now()))
149
- return null;
150
- await fileSystem.unlink(path).catch((error) => {
151
- if (!isMissing(error))
152
- throw error;
153
- });
154
- const recovered = await tryCreateLock(path);
155
- return recovered ? releaseLock(path, recovered) : null;
156
- }
157
- };
158
- }
159
- async function tryCreateLock(path) {
160
- const token = randomUUID();
161
- let handle;
162
- try {
163
- handle = await fileSystem.open(path, "wx", 0o600);
164
- await handle.writeFile(token, "utf8");
165
- await handle.sync();
166
- await handle.close();
167
- return token;
168
- }
169
- catch (error) {
170
- await handle?.close().catch(() => undefined);
171
- if (isExists(error))
172
- return null;
173
- throw error;
174
- }
175
- }
176
- function releaseLock(path, token) {
177
- return async () => {
178
- let current;
179
- try {
180
- current = await fileSystem.readFile(path, "utf8");
181
- }
182
- catch (error) {
183
- if (isMissing(error))
184
- return;
185
- throw error;
186
- }
187
- if (current === token)
188
- await fileSystem.unlink(path);
189
- };
190
- }
191
- async function isStaleLock(path, now) {
192
- try {
193
- const stats = await fileSystem.stat(path);
194
- return stats.mtimeMs + STALE_LOCK_MS <= now.getTime();
195
- }
196
- catch (error) {
197
- if (isMissing(error))
198
- return true;
199
- throw error;
200
- }
201
- }
202
- async function readState(file) {
203
- const text = await file.readText();
204
- if (text === null)
205
- return { schema_version: 1 };
206
- try {
207
- const value = JSON.parse(text);
208
- return parseState(value) ?? { schema_version: 1 };
209
- }
210
- catch {
211
- return { schema_version: 1 };
212
- }
213
- }
214
- function parseState(value) {
215
- if (!isRecord(value) || value.schema_version !== 1)
216
- return null;
217
- for (const key of [
218
- "last_success_check_at",
219
- "next_check_at",
220
- "latest_version",
221
- "last_notified_on",
222
- "last_notified_version",
223
- "etag"
224
- ]) {
225
- if (value[key] !== undefined && typeof value[key] !== "string")
226
- return null;
227
- }
228
- return value;
229
- }
230
- async function writeState(file, state) {
231
- await file.writeTextAtomically(`${JSON.stringify(state, null, 2)}\n`);
232
- }
233
- function withReminder(state, today, version) {
234
- return {
235
- ...state,
236
- schema_version: 1,
237
- last_notified_on: today,
238
- last_notified_version: version
239
- };
240
- }
241
- function notify(options, latest) {
242
- if (options.commandName && options.commandName !== "gd-cli") {
243
- options.notify(`${options.commandName} ${latest} is available; current version is ` +
244
- `${options.currentVersion}. Run ${options.commandName} update to update.`);
245
- }
246
- else {
247
- options.notify(`gd-cli 有新版本 ${latest},当前版本为 ${options.currentVersion}。` +
248
- "运行 gd-cli update 即可更新。");
249
- }
250
- }
251
- function isNewer(version, currentVersion) {
252
- return version !== undefined && valid(version) !== null && gt(version, currentVersion);
253
- }
254
- function isDue(nextCheckAt, now) {
255
- if (nextCheckAt === undefined)
256
- return true;
257
- const timestamp = Date.parse(nextCheckAt);
258
- return !Number.isFinite(timestamp) || timestamp <= now.getTime();
259
- }
260
- function addMilliseconds(value, milliseconds) {
261
- return new Date(value.getTime() + milliseconds).toISOString();
262
- }
263
- function localDate(value) {
264
- return [
265
- String(value.getFullYear()).padStart(4, "0"),
266
- String(value.getMonth() + 1).padStart(2, "0"),
267
- String(value.getDate()).padStart(2, "0")
268
- ].join("-");
269
- }
270
- function isRecord(value) {
271
- return typeof value === "object" && value !== null && !Array.isArray(value);
272
- }
273
- function isMissing(error) {
274
- return error instanceof Error && "code" in error && error.code === "ENOENT";
275
- }
276
- function isExists(error) {
277
- return error instanceof Error && "code" in error && error.code === "EEXIST";
278
- }
@@ -1,7 +1,9 @@
1
1
  import { isInterruption } from "../../platform/interruption.js";
2
2
  import { spawn } from "node:child_process";
3
- import { realpathSync } from "node:fs";
4
- import { resolve } from "node:path";
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";
@@ -43,6 +45,15 @@ export function detectInstallSource(input) {
43
45
  if (!isWithin(realBinaryPath, packageRoot)) {
44
46
  return unsupported("CLI binary 与 package 不匹配");
45
47
  }
48
+ // pnpm 12 can link global and project installs to the same store. The hash
49
+ // alone is not ownership evidence: match the actual invocation to its global launcher.
50
+ const command = input.binaryName ?? "gd-cli";
51
+ if (realBinaryPath === `${packageRoot}/dist/bin/${command}.js`
52
+ && pnpmSnapshotDirectory(binaryPath, packageName, command)
53
+ && pnpmLauncherTargets(input.env, command).some(target => target === resolve(input.binaryPath))
54
+ && safeRealpath(input.binaryPath) === input.realBinaryPath) {
55
+ return { kind: "global", manager: "pnpm", packageRoot: input.packageRoot };
56
+ }
46
57
  if (packageRoot.includes(`/global/`) && packageRoot.includes(`/.pnpm/${encodedPackage}@`)
47
58
  || packageRoot.includes(`/node_modules/${packageName}`)
48
59
  && /\/v\d+\/[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16}\//u.test(packageRoot)
@@ -56,6 +67,43 @@ export function detectInstallSource(input) {
56
67
  }
57
68
  return unsupported("无法确认 npm 或 pnpm 全局安装");
58
69
  }
70
+ function pnpmSnapshotDirectory(binaryPath, name, command) {
71
+ const suffix = `/node_modules/${name}/dist/bin/${command}.js`;
72
+ const normalized = normalizePath(binaryPath);
73
+ if (!normalized.endsWith(suffix))
74
+ return;
75
+ const snapshot = normalized.slice(0, -suffix.length);
76
+ if (/\/v\d+\/(?:[a-f0-9]{64}|[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16})$/u.test(snapshot))
77
+ return dirname(dirname(snapshot));
78
+ }
79
+ function pnpmLauncherTargets(env, command) {
80
+ const home = env.HOME || env.USERPROFILE || homedir();
81
+ const pnpmHome = env.PNPM_HOME || (process.platform === "darwin" ? join(home, "Library", "pnpm")
82
+ : process.platform === "win32" ? join(env.LOCALAPPDATA || join(home, "AppData", "Local"), "pnpm")
83
+ : join(env.XDG_DATA_HOME || join(home, ".local", "share"), "pnpm"));
84
+ if (!isAbsolute(pnpmHome))
85
+ return [];
86
+ const targets = [];
87
+ for (const dir of [join(pnpmHome, "bin"), pnpmHome]) {
88
+ for (const ext of process.platform === "win32" ? [".cmd", ".ps1", ""] : [""]) {
89
+ const launcher = join(dir, command + ext);
90
+ try {
91
+ const stat = lstatSync(launcher);
92
+ const target = stat.isSymbolicLink() ? readlinkSync(launcher)
93
+ : stat.isFile() && stat.size < 131072
94
+ ? /^(?:#|::|@?REM)\s+cmd-shim-target=(.+)$/imu.exec(readFileSync(launcher, "utf8"))?.[1]?.trim()
95
+ : undefined;
96
+ if (target) {
97
+ const entry = resolve(dirname(launcher), target);
98
+ realpathSync(entry);
99
+ targets.push(entry);
100
+ }
101
+ }
102
+ catch { /* Another launcher location may exist; ambiguous ownership is never writable. */ }
103
+ }
104
+ }
105
+ return targets;
106
+ }
59
107
  export function createUpdateService(options) {
60
108
  const fetchPackage = options.fetch ?? globalThis.fetch;
61
109
  const runProcess = options.runProcess ?? spawnProcess;
@@ -110,6 +158,22 @@ export function createUpdateService(options) {
110
158
  env,
111
159
  ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {})
112
160
  };
161
+ const binaryPath = options.binaryPath ?? process.argv[1] ?? "";
162
+ const source = detectInstallSource({
163
+ binaryPath,
164
+ realBinaryPath: safeRealpath(binaryPath),
165
+ packageRoot: options.packageRoot,
166
+ cwd: options.cwd ?? process.cwd(),
167
+ env,
168
+ packageName,
169
+ binaryName: commandName
170
+ });
171
+ const nextSteps = [insmind ? "Choose the command for your original package manager:" : "按原安装工具选择下面一条命令执行:", ...manualCommands(latest, packageName)];
172
+ if (source.kind === "unsupported") {
173
+ throw new UpdateError("UPDATE_FAILED", insmind
174
+ ? "The current installation method does not support automatic updates."
175
+ : `当前安装方式不支持自动更新:${source.reason}。`, nextSteps);
176
+ }
113
177
  if (!gt(latest, options.currentVersion)) {
114
178
  await options.telemetry.stage("sync", async () => {
115
179
  try {
@@ -127,26 +191,18 @@ export function createUpdateService(options) {
127
191
  });
128
192
  return { version: options.currentVersion, updated: false };
129
193
  }
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
194
  const command = source.manager;
195
+ const globalDirectory = command === "pnpm" && pnpmLauncherTargets(env, commandName).includes(resolve(binaryPath))
196
+ ? pnpmSnapshotDirectory(binaryPath, packageName, commandName) : undefined;
197
+ const modulesParent = dirname(dirname(dirname(source.packageRoot)));
198
+ // npm puts global modules under <prefix>/lib/node_modules on POSIX and
199
+ // <prefix>/node_modules on Windows. Never let today's config redirect a prior one-off install.
200
+ const npmPrefix = normalizePath(source.packageRoot).endsWith(`/lib/node_modules/${packageName}`)
201
+ ? dirname(modulesParent) : modulesParent;
147
202
  const args = source.manager === "npm"
148
- ? ["install", "--global", `--allow-scripts=${packageName}`, `${packageName}@${latest}`]
149
- : ["add", "--global", `--allow-build=${packageName}`, `${packageName}@${latest}`];
203
+ ? ["install", "--global", "--prefix", npmPrefix, `--allow-scripts=${packageName}`, `${packageName}@${latest}`]
204
+ : ["add", "--global", ...(globalDirectory ? ["--global-dir", globalDirectory] : []),
205
+ `--allow-build=${packageName}`, `${packageName}@${latest}`];
150
206
  await options.telemetry.stage("install", async () => {
151
207
  try {
152
208
  await runProcess(command, args, signal);
@@ -166,7 +222,25 @@ export function createUpdateService(options) {
166
222
  }));
167
223
  await options.telemetry.stage("verify", async () => {
168
224
  try {
169
- await verifySkills(targetSkills, skillOptions);
225
+ try {
226
+ await verifySkills(targetSkills, skillOptions);
227
+ }
228
+ catch (verificationError) {
229
+ if (isInterruption(verificationError, signal) || !globalDirectory)
230
+ throw verificationError;
231
+ // A pnpm store cache hit may skip postinstall. Only use new Skill bytes
232
+ // from the verified replacement launcher in the same global installation.
233
+ const target = pnpmLauncherTargets(env, commandName)
234
+ .find(entry => pnpmSnapshotDirectory(entry, packageName, commandName) === globalDirectory);
235
+ if (!target)
236
+ throw verificationError;
237
+ const actual = loadBundledSkills(realpathSync(target));
238
+ if (!actual.length || actual.some(s => s.skill !== commandName || s.version !== latest)
239
+ || readInstallationOwner(dirname(dirname(actual[0].sourceDirectory))) !== "user")
240
+ throw verificationError;
241
+ await syncSkills(actual, skillOptions);
242
+ await verifySkills(actual, skillOptions);
243
+ }
170
244
  }
171
245
  catch (error) {
172
246
  if (isInterruption(error, signal))
@@ -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
+ }
@@ -0,0 +1,35 @@
1
+ // Exact account or local connection keys, independent of case and snake/kebab spelling.
2
+ // Resource grants (auth_key, signature, project_token, X-Amz-*) belong to the caller.
3
+ const identityKeys = new Set([
4
+ "ak", "sk", "accesskey", "accesskeyid", "accesskeysecret", "secretkey",
5
+ "accesstoken", "refreshtoken", "authorization", "authorizecode", "authorizationcode",
6
+ "devicecode", "bearer", "cookie", "credential", "credentials", "password", "secret",
7
+ "focusededitorport", "focusededitortoken"
8
+ ]);
9
+ function normalizedKey(name) {
10
+ return name.toLowerCase().replace(/[-_]/gu, "");
11
+ }
12
+ function withoutCredentials(fields, keys) {
13
+ return fields.split("&").filter(field => {
14
+ // Decode only the name. Serializing URLSearchParams would change signed bytes.
15
+ const rawName = field.split("=", 1)[0];
16
+ const name = new URLSearchParams("key=" + rawName).get("key");
17
+ return !keys.has(normalizedKey(name));
18
+ }).join("&");
19
+ }
20
+ export function filterUrlParameters(input, privateKeys) {
21
+ const keys = privateKeys ? new Set(Array.from(privateKeys, normalizedKey)) : identityKeys;
22
+ const out = new URL(input.href);
23
+ const rawQuery = out.search.slice(1);
24
+ const query = withoutCredentials(rawQuery, keys);
25
+ if (query !== rawQuery)
26
+ out.search = query;
27
+ const fragment = out.hash.slice(1);
28
+ // A fragment may be a router query or a plain list whose values themselves contain '?'.
29
+ const route = /^(?:!?\/[^?]*|[^?=&]*)\?/u.exec(fragment)?.[0] ?? "";
30
+ const fields = fragment.slice(route.length);
31
+ const kept = withoutCredentials(fields, keys);
32
+ if (kept !== fields)
33
+ out.hash = kept ? route + kept : route.slice(0, -1);
34
+ return out;
35
+ }