@insmind/cli 2.1.1 → 2.1.3

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 (46) hide show
  1. package/README.md +30 -0
  2. package/dist/bin/sync-skill.js +33 -0
  3. package/dist/src/bootstrap/create-runtime.js +5 -1
  4. package/dist/src/bootstrap/validators.js +88 -152
  5. package/dist/src/cli/agent-commands.js +2 -2
  6. package/dist/src/cli/editor-commands.js +9 -7
  7. package/dist/src/cli/errors.js +4 -5
  8. package/dist/src/cli/host-input.js +3 -5
  9. package/dist/src/cli/observed-errors.js +7 -3
  10. package/dist/src/cli/presenter.js +4 -5
  11. package/dist/src/contracts/creation-input.js +20 -17
  12. package/dist/src/features/auth/credential-store.js +1 -0
  13. package/dist/src/features/dam/object-storage.js +2 -1
  14. package/dist/src/features/dam/use-cases.js +2 -2
  15. package/dist/src/features/editor/bridge-process.js +3 -2
  16. package/dist/src/features/editor/session-state.js +1 -0
  17. package/dist/src/features/task/creation-refusal.js +3 -1
  18. package/dist/src/features/task/store.js +65 -22
  19. package/dist/src/features/task/task-background.js +3 -2
  20. package/dist/src/features/tool/canvas-media.js +2 -3
  21. package/dist/src/features/tool/canvas-results.js +13 -6
  22. package/dist/src/features/tool/catalog.js +2 -23
  23. package/dist/src/features/tool/dynamic-schema.js +3 -6
  24. package/dist/src/features/tool/tool-definitions.js +23 -0
  25. package/dist/src/features/update/package-manager.js +124 -0
  26. package/dist/src/features/update/update-service.js +133 -67
  27. package/dist/src/platform/detached-spawn.js +9 -0
  28. package/dist/src/platform/file-lock.js +12 -4
  29. package/dist/src/platform/input-uri.js +23 -1
  30. package/dist/src/platform/local-json-file.js +97 -15
  31. package/dist/src/platform/open-browser.js +5 -2
  32. package/dist/src/platform/safe-upload-file.js +2 -3
  33. package/dist/src/platform/schema-compiler.js +16 -0
  34. package/dist/src/platform/windows-acl/LICENSE-mingw-w64 +43 -0
  35. package/dist/src/platform/windows-acl/arm64.node +0 -0
  36. package/dist/src/platform/windows-acl/ia32.node +0 -0
  37. package/dist/src/platform/windows-acl/x64.node +0 -0
  38. package/dist/src/platform/windows-host-job/arm64.exe +0 -0
  39. package/dist/src/platform/windows-host-job/ia32.exe +0 -0
  40. package/dist/src/platform/windows-host-job/sha256.json +7 -0
  41. package/dist/src/platform/windows-host-job/x64.exe +0 -0
  42. package/dist/src/platform/windows-private-state.js +72 -0
  43. package/dist/src/product/config.js +1 -1
  44. package/dist/src/telemetry/failure-summary.js +2 -2
  45. package/dist/src/telemetry/sls-sink.js +48 -29
  46. package/package.json +4 -4
@@ -1,5 +1,5 @@
1
1
  import { resolve } from "node:path";
2
- import { pathToFileURL } from "node:url";
2
+ import { fileUriFromLocalPath } from "../../platform/input-uri.js";
3
3
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
4
4
  import { DamAssetNotDownloadableError } from "./dam-api-adapter.js";
5
5
  import { DamInputError, normalizeDamAssetId } from "./input.js";
@@ -453,7 +453,7 @@ export function createDamUseCases(dependencies) {
453
453
  if (!nonblank(input.file))
454
454
  invalid("nonblank", "file");
455
455
  const file = await dependencies.telemetry.stage("inspect", () => (dependencies.storage.inspect({
456
- url: pathToFileURL(resolve(process.cwd(), input.file)).href,
456
+ url: fileUriFromLocalPath(resolve(process.cwd(), input.file)),
457
457
  ...(input.allowSensitivePath === undefined
458
458
  ? {}
459
459
  : { allowSensitivePath: input.allowSensitivePath })
@@ -1,3 +1,4 @@
1
+ import { startDetached } from "../../platform/detached-spawn.js";
1
2
  import { reportProcessError } from "../../telemetry/process-errors.js";
2
3
  import { spawn as nodeSpawn } from "node:child_process";
3
4
  import { resolve } from "node:path";
@@ -53,7 +54,7 @@ export function startEditorBridgeProcess(input) {
53
54
  return Promise.reject(abortReason(input.signal));
54
55
  let child;
55
56
  try {
56
- child = (input.spawn ?? nodeSpawn)(process.execPath, [
57
+ child = startDetached(() => (input.spawn ?? nodeSpawn)(process.execPath, [
57
58
  fileURLToPath(new URL("./bridge-process.js", import.meta.url)),
58
59
  input.targetOrigin,
59
60
  ...(input.stateDirectory === undefined
@@ -62,7 +63,7 @@ export function startEditorBridgeProcess(input) {
62
63
  ], {
63
64
  detached: true,
64
65
  stdio: ["ignore", "ignore", "ignore", "ipc"]
65
- });
66
+ }));
66
67
  }
67
68
  catch (cause) {
68
69
  return Promise.reject(cause);
@@ -4,6 +4,7 @@ import { createLocalJsonFile, LocalFileError } from "../../platform/local-json-f
4
4
  export function createEditorSessionStateStore(options = {}) {
5
5
  const file = options.file ?? createLocalJsonFile({
6
6
  directory: join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd"),
7
+ protectWindowsAcl: true,
7
8
  filename: "editor-session.json"
8
9
  });
9
10
  const read = async () => {
@@ -3,12 +3,14 @@ import { ToolTaskFailedError } from "../tool/tool-api-adapter.js";
3
3
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
4
4
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
5
5
  // Scope numeric codes to the product/entry where they have a confirmed meaning.
6
- const CONTENT_REVIEW_CODES = new Set(["12020751", "12020752", "12020757", "12020758", "12020760", "12020790"]);
6
+ const CONTENT_REVIEW_CODES = new Set(["12020751", "12020752", "12020756", "12020757", "12020758", "12020760", "12020790"]);
7
7
  export function isContentReviewRejection(error, context = {}) {
8
8
  if (error instanceof AgentAuditRejectedError)
9
9
  return true;
10
10
  if (!(error instanceof RemoteRequestError || error instanceof RemoteProtocolError || error instanceof ToolTaskFailedError))
11
11
  return false;
12
+ if (error.diagnosticReason === "TASK_QUERY_FAILED")
13
+ return false;
12
14
  if (error.diagnosticReason === "AGENT_INPUT_AUDIT_REJECTED")
13
15
  return true;
14
16
  const toolOrQuery = context.operation === "tool.call" || context.operation === "task.get";
@@ -1,9 +1,10 @@
1
- import { withFileLock } from "../../platform/file-lock.js";
1
+ import { fileLockDirectory, withFileLock } from "../../platform/file-lock.js";
2
2
  import { createHash } from "node:crypto";
3
- import { readdir, lstat } from "node:fs/promises";
3
+ import { readdir, lstat, mkdir } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
- import { createLocalJsonFile, LocalFileError } from "../../platform/local-json-file.js";
6
+ import { confirmMissingPath, createLocalJsonFile, LocalFileError } from "../../platform/local-json-file.js";
7
+ import { pinWindowsStateDirectories, readWindowsPrivateText } from "../../platform/windows-private-state.js";
7
8
  export class TaskStoreError extends LocalFileError {
8
9
  context;
9
10
  constructor(cause) { super(cause); this.name = "TaskStoreError"; }
@@ -29,23 +30,31 @@ export function taskScope(state) {
29
30
  ])).digest("hex");
30
31
  }
31
32
  export function createTaskStore(options) {
32
- const root = join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd", "tasks", "v6");
33
+ const home = options.homeDirectory ?? homedir();
34
+ const stateDirectory = options.stateDirectory ?? ".gd";
35
+ const root = join(home, stateDirectory, "tasks", "v6");
36
+ const lockOptions = process.platform === "win32" ? { readOwner: readWindowsPrivateText } : {};
33
37
  function file(scope, id) {
34
- if (!/^[a-f0-9]{64}$/u.test(scope) || !validTaskId(id))
35
- throw new LocalFileError(undefined);
36
- return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json`, role: "task" });
38
+ return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json`, role: "task", protectWindowsAcl: true });
37
39
  }
38
40
  const store = {
39
41
  async read(scope, id, summaryOnly = false) {
40
42
  const stateFile = file(scope, id);
41
43
  try {
42
44
  const stat = await lstat(join(root, scope, `${id}.json`));
43
- if (!stat.isFile() || stat.isSymbolicLink())
45
+ if (!stat.isFile() || stat.isSymbolicLink() || (process.platform === "win32" && stat.nlink !== 1))
44
46
  throw new LocalFileError(undefined, undefined, "invalid_data", { operation: "read", step: "stat" });
45
47
  }
46
48
  catch (error) {
47
- if (error instanceof Error && "code" in error && error.code === "ENOENT")
48
- return null;
49
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
50
+ try {
51
+ await confirmMissingPath(join(root, scope), error);
52
+ return null;
53
+ }
54
+ catch (cause) {
55
+ throw new LocalFileError(cause, undefined, "io", { operation: "read", step: "stat" });
56
+ }
57
+ }
49
58
  if (error instanceof LocalFileError)
50
59
  throw error;
51
60
  throw new LocalFileError(error, undefined, "io", { operation: "read", step: "stat" });
@@ -95,7 +104,6 @@ export function createTaskStore(options) {
95
104
  }
96
105
  },
97
106
  async write(scope, record) {
98
- file(scope, record.task.taskId);
99
107
  await withFileLock(join(root, scope, `${record.task.taskId}.lock`), async () => {
100
108
  const previous = await store.read(scope, record.task.taskId);
101
109
  if (previous) {
@@ -116,10 +124,9 @@ export function createTaskStore(options) {
116
124
  }
117
125
  options.validate(record.task);
118
126
  await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
119
- }, { action: "task_write" });
127
+ }, { ...lockOptions, action: "task_write" });
120
128
  },
121
129
  async update(scope, id, change) {
122
- file(scope, id);
123
130
  return withFileLock(join(root, scope, `${id}.lock`), async () => {
124
131
  const record = await store.read(scope, id);
125
132
  if (!record)
@@ -128,7 +135,7 @@ export function createTaskStore(options) {
128
135
  options.validate(record.task);
129
136
  await file(scope, id).writeTextAtomically(`${JSON.stringify(record)}\n`);
130
137
  return record;
131
- }, { action: "task_update" });
138
+ }, { ...lockOptions, action: "task_update" });
132
139
  },
133
140
  async list(scope) {
134
141
  let names;
@@ -136,8 +143,15 @@ export function createTaskStore(options) {
136
143
  names = await readdir(join(root, scope));
137
144
  }
138
145
  catch (error) {
139
- if (error instanceof Error && "code" in error && error.code === "ENOENT")
140
- return [];
146
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
147
+ try {
148
+ await confirmMissingPath(join(root, scope), error);
149
+ return [];
150
+ }
151
+ catch (cause) {
152
+ throw new LocalFileError(cause, undefined, "io", { operation: "list", step: "directory_read" });
153
+ }
154
+ }
141
155
  throw new LocalFileError(error, undefined, "io", { operation: "list", step: "directory_read" });
142
156
  }
143
157
  const records = [];
@@ -165,18 +179,47 @@ export function createTaskStore(options) {
165
179
  || a.task.taskId.localeCompare(b.task.taskId));
166
180
  }
167
181
  };
168
- async function access(operation) {
182
+ async function access(scope, request, run) {
183
+ let release;
169
184
  try {
170
- return await operation();
185
+ if (!/^[a-f0-9]{64}$/u.test(scope) || ("id" in request && !validTaskId(request.id)))
186
+ throw new LocalFileError(undefined);
187
+ if (process.platform === "win32") {
188
+ const components = [stateDirectory, "tasks", "v6", scope];
189
+ try {
190
+ if (request.operation === "write") {
191
+ await mkdir(home, { recursive: true });
192
+ components.push(fileLockDirectory(`${request.id}.lock`));
193
+ }
194
+ release = pinWindowsStateDirectories(home, components, request.operation === "write");
195
+ }
196
+ catch (cause) {
197
+ if (request.operation !== "write" && cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
198
+ try {
199
+ await confirmMissingPath(home, cause);
200
+ return request.missing;
201
+ }
202
+ catch (error) {
203
+ cause = error;
204
+ }
205
+ }
206
+ throw new LocalFileError(cause, undefined, "io", { role: "task", operation: request.operation,
207
+ step: request.operation === "list" ? "directory_read" : "directory_permissions" });
208
+ }
209
+ }
210
+ return await run();
171
211
  }
172
212
  catch (cause) {
173
213
  throw new TaskStoreError(cause);
174
214
  }
215
+ finally {
216
+ release?.();
217
+ }
175
218
  }
176
219
  return {
177
- update: (scope, id, change) => access(() => store.update(scope, id, change)),
178
- read: (scope, id) => access(() => store.read(scope, id)),
179
- write: (scope, record) => access(() => store.write(scope, record)),
180
- list: scope => access(() => store.list(scope))
220
+ update: (scope, id, change) => access(scope, { operation: "write", id }, () => store.update(scope, id, change)),
221
+ read: (scope, id) => access(scope, { operation: "read", id, missing: null }, () => store.read(scope, id)),
222
+ write: (scope, record) => access(scope, { operation: "write", id: record?.task?.taskId }, () => store.write(scope, record)),
223
+ list: scope => access(scope, { operation: "list", missing: [] }, () => store.list(scope))
181
224
  };
182
225
  }
@@ -1,3 +1,4 @@
1
+ import { startDetached } from "../../platform/detached-spawn.js";
1
2
  import { fork } from "node:child_process";
2
3
  import { safeFailureSummary } from "../../telemetry/failure-summary.js";
3
4
  import { validTaskId } from "./store.js";
@@ -94,12 +95,12 @@ export function createTaskBackgroundLauncher(options) {
94
95
  return new Promise((resolve, reject) => {
95
96
  let child;
96
97
  try {
97
- child = (options.fork ?? fork)(options.workerPath, [], {
98
+ child = startDetached(() => (options.fork ?? fork)(options.workerPath, [], {
98
99
  detached: true,
99
100
  stdio: ["ignore", "ignore", "ignore", "ipc"],
100
101
  execArgv: [],
101
102
  env: { ...process.env, ...options.env }
102
- });
103
+ }));
103
104
  }
104
105
  catch (cause) {
105
106
  reject(taskWorkerUnavailableError({ product: job.product, phase: "spawn", cause }));
@@ -1,9 +1,8 @@
1
1
  import { readFile, mkdtemp, writeFile, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
- import { pathToFileURL } from "node:url";
5
4
  import { inspectUploadFile, LocalFileInputError } from "../../platform/safe-upload-file.js";
6
- import { uriShape } from "../../platform/input-uri.js";
5
+ import { fileUriFromLocalPath, uriShape } from "../../platform/input-uri.js";
7
6
  import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
8
7
  import { isFilemsResource, withFilemsAuthKey } from "../../platform/resource-auth-key.js";
9
8
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
@@ -171,7 +170,7 @@ export function createCanvasMedia(dependencies) {
171
170
  try {
172
171
  const path = join(directory, `asset.${extension}`);
173
172
  await writeFile(path, bytes, { mode: 0o600, signal });
174
- return (await dependencies.uploader.upload({ url: pathToFileURL(path).href }, access, signal)).url;
173
+ return (await dependencies.uploader.upload({ url: fileUriFromLocalPath(path) }, access, signal)).url;
175
174
  }
176
175
  finally {
177
176
  await rm(directory, { recursive: true, force: true });
@@ -1,6 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { Ajv2020 } from "ajv/dist/2020.js";
3
- import addFormatsImport, {} from "ajv-formats";
2
+ import { lazySchemaCompiler } from "../../platform/schema-compiler.js";
4
3
  import { contractDocument } from "../../contracts/schema.js";
5
4
  import { parseHttpAssetUrl, parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
6
5
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
@@ -39,10 +38,18 @@ export function oneResource(content) {
39
38
  export function link(uri, name, mimeType) {
40
39
  return [{ type: "resource_link", uri, name, mimeType }];
41
40
  }
42
- const ajv = new Ajv2020({ strict: true, allErrors: true });
43
- addFormatsImport(ajv);
44
- const validateTemplate = ajv.compile(contractDocument("tool.call/template-payload.schema.json"));
45
- const validateOcr = ajv.compile(contractDocument("tool.call/ocr-payload.schema.json"));
41
+ // A version or login-state query also imports this module through the command
42
+ // graph. Compile each media contract only when that actual result needs it.
43
+ const canvasCompiler = lazySchemaCompiler({ strict: true, allErrors: true });
44
+ function canvasContract(file) {
45
+ let validate;
46
+ return (value) => {
47
+ validate ??= canvasCompiler().compile(contractDocument(file));
48
+ return validate(value);
49
+ };
50
+ }
51
+ const validateTemplate = canvasContract("tool.call/template-payload.schema.json");
52
+ const validateOcr = canvasContract("tool.call/ocr-payload.schema.json");
46
53
  function assertOcrPayload(payload) {
47
54
  if (!validateOcr(payload))
48
55
  throw new RemoteProtocolError({}, undefined, "OCR_PAYLOAD_INVALID");
@@ -1,28 +1,7 @@
1
1
  import { buildModelArgumentsSchema } from "./dynamic-schema.js";
2
2
  import { hasCanvasMetering } from "./canvas-pricing.js";
3
- export const defaultToolDefinitions = [
4
- {
5
- name: "image.generate",
6
- title: "图片生成与编辑",
7
- description: "使用已发布的图片模型,根据文本和可选参考图片生成或编辑图片。"
8
- },
9
- {
10
- name: "video.generate",
11
- title: "视频生成",
12
- description: "使用已发布的视频模型,根据文本及可选图片、视频或音频生成视频。"
13
- },
14
- { name: "image.edit", title: "图片改图", description: "修改原图内容;标准模型使用选区,智能模型可按指令修改。" },
15
- { name: "image.matting", title: "图片抠图", description: "标准抠图保留源像素;智能抠图先重绘补全再分割。最终交付透明 PNG。" },
16
- { name: "image.remove", title: "图片消除", description: "移除指定对象并补齐背景。" },
17
- { name: "image.enhance", title: "图片变清晰", description: "标准超分或生成式修复;智能修复可能改变细节。" },
18
- { name: "image.expand", title: "图片扩图", description: "按目标画布和原图位置补绘外围。" },
19
- { name: "image.text_edit", title: "图片改字", description: "按原文替换或删除图片文字,不承诺定位重复原文中的某一次。" },
20
- { name: "image.ocr", title: "图片文字识别", description: "返回实际识别图尺寸、文字、类别和像素坐标。" },
21
- { name: "image.layers", title: "图片图文分层", description: "交付原生稿定模板 JSON,保留图层结构。" },
22
- { name: "image.vectorize", title: "图片转矢量", description: "将位图转换为 SVG。" },
23
- { name: "video.edit", title: "视频修改", description: "按原视频修改内容,时长由真实素材推导。" },
24
- { name: "video.enhance", title: "视频变清晰", description: "标准超分或生成式视频修复。" }
25
- ];
3
+ import { defaultToolDefinitions } from "./tool-definitions.js";
4
+ export { defaultToolDefinitions } from "./tool-definitions.js";
26
5
  export class ToolInputError extends Error {
27
6
  reason;
28
7
  field;
@@ -1,5 +1,4 @@
1
- import { Ajv2020 } from "ajv/dist/2020.js";
2
- import addFormatsImport, {} from "ajv-formats";
1
+ import { lazySchemaCompiler } from "../../platform/schema-compiler.js";
3
2
  import { inputValidationSummary, validationIssues } from "../../platform/schema-issues.js";
4
3
  import { unavailableCanvasMediaRoles } from "./canvas-models.js";
5
4
  import { canonicalizeInputFileUris } from "../../platform/input-uri.js";
@@ -110,9 +109,7 @@ export function buildModelArgumentsSchema(model) {
110
109
  propertyNames: { not: { enum: managed } }
111
110
  };
112
111
  }
113
- const ajv = new Ajv2020({ allErrors: true, strict: true });
114
- const addFormats = addFormatsImport;
115
- addFormats(ajv);
112
+ const compiler = lazySchemaCompiler({ allErrors: true, strict: true });
116
113
  /** Enforce structure that the CLI actually reads or transforms. Business controls go to the service. */
117
114
  export function assertModelArguments(model, value) {
118
115
  const published = buildModelArgumentsSchema(model);
@@ -146,7 +143,7 @@ export function assertModelArguments(model, value) {
146
143
  }
147
144
  }
148
145
  const schema = { type: "object", properties, required };
149
- const validate = ajv.compile(schema);
146
+ const validate = compiler().compile(schema);
150
147
  canonicalizeInputFileUris(value, schema);
151
148
  if (!validate(value)) {
152
149
  const issues = validationIssues(validate.errors, value, schema);
@@ -0,0 +1,23 @@
1
+ export const defaultToolDefinitions = [
2
+ {
3
+ name: "image.generate",
4
+ title: "图片生成与编辑",
5
+ description: "使用已发布的图片模型,根据文本和可选参考图片生成或编辑图片。"
6
+ },
7
+ {
8
+ name: "video.generate",
9
+ title: "视频生成",
10
+ description: "使用已发布的视频模型,根据文本及可选图片、视频或音频生成视频。"
11
+ },
12
+ { name: "image.edit", title: "图片改图", description: "修改原图内容;标准模型使用选区,智能模型可按指令修改。" },
13
+ { name: "image.matting", title: "图片抠图", description: "标准抠图保留源像素;智能抠图先重绘补全再分割。最终交付透明 PNG。" },
14
+ { name: "image.remove", title: "图片消除", description: "移除指定对象并补齐背景。" },
15
+ { name: "image.enhance", title: "图片变清晰", description: "标准超分或生成式修复;智能修复可能改变细节。" },
16
+ { name: "image.expand", title: "图片扩图", description: "按目标画布和原图位置补绘外围。" },
17
+ { name: "image.text_edit", title: "图片改字", description: "按原文替换或删除图片文字,不承诺定位重复原文中的某一次。" },
18
+ { name: "image.ocr", title: "图片文字识别", description: "返回实际识别图尺寸、文字、类别和像素坐标。" },
19
+ { name: "image.layers", title: "图片图文分层", description: "交付原生稿定模板 JSON,保留图层结构。" },
20
+ { name: "image.vectorize", title: "图片转矢量", description: "将位图转换为 SVG。" },
21
+ { name: "video.edit", title: "视频修改", description: "按原视频修改内容,时长由真实素材推导。" },
22
+ { name: "video.enhance", title: "视频变清晰", description: "标准超分或生成式视频修复。" }
23
+ ];
@@ -0,0 +1,124 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { dirname, join, sep } from "node:path";
4
+ export class PackageManagerTerminationError extends Error {
5
+ constructor(cause) {
6
+ super("Unable to confirm that the package manager process tree stopped", { cause });
7
+ this.name = "PackageManagerTerminationError";
8
+ }
9
+ }
10
+ export function windowsShimTarget(text) {
11
+ // Only a command that forwards all of argv can identify the target. Comments,
12
+ // setup steps and similarly named installations do not identify the launcher.
13
+ const lines = text.trim().split(/\r?\n/u);
14
+ const lastLine = lines.at(-1)?.trim() ?? "";
15
+ const entry = (line) => {
16
+ const invocation = line.trim().replace(/^endLocal & goto #_undefined_# 2>NUL \|\| title %COMSPEC% & "%_prog%"\s+/iu, "");
17
+ return /^@?(?:(?:node(?:\.exe)?|"[^"\r\n]+\\node\.exe")\s+)?"%(?:~dp0|dp0%)\\([^"\r\n]+\.(?:cjs|mjs|js))"\s+%\*$/iu.exec(invocation)?.[1];
18
+ };
19
+ // pnpm's normal IF/ELSE chooses a sibling or PATH Node. Both branches
20
+ // must forward to the same entry before we identify this installation.
21
+ if (lastLine === ")") {
22
+ const targets = lines.filter(line => line.trimEnd().endsWith("%*")).map(entry);
23
+ if (targets.length === 2 && targets[0] && targets[0] === targets[1])
24
+ return targets[0].replace(/\\/gu, sep);
25
+ return undefined;
26
+ }
27
+ return entry(lastLine)?.replace(/\\/gu, sep);
28
+ }
29
+ /** Honor the selected executable, JS entry or command script and forward literal arguments. */
30
+ export function windowsManagerInvocation(command, args, env) {
31
+ const pathValue = env.Path ?? env.PATH ?? "";
32
+ for (const dir of pathValue.split(";").filter(Boolean)) {
33
+ for (const suffix of [".exe", ".cmd", ".js"]) {
34
+ const file = join(dir.replace(/^"|"$/gu, ""), command + suffix);
35
+ if (!existsSync(file))
36
+ continue;
37
+ if (suffix === ".exe")
38
+ return { file, args };
39
+ if (suffix === ".js")
40
+ return { file: process.execPath, args: [file, ...args] };
41
+ // A .cmd can select its own Node, npm prefix or environment. Run its
42
+ // actual program, including for stock npm and custom pnpm launchers.
43
+ // Values enter through environment expansion after cmd parses metacharacters.
44
+ // Windows filenames cannot contain quotes; reject unusual arguments rather than
45
+ // permit quote injection into a script-only package manager.
46
+ if ([file, ...args].some(value => /["\r\n\0]/u.test(value)))
47
+ throw new Error("Cannot safely launch package manager script with quoted or multiline arguments");
48
+ const childEnv = { ...env };
49
+ const values = [file, ...args];
50
+ values.forEach((value, index) => { childEnv[`GD_CLI_PM_ARG_${index}`] = value; });
51
+ const line = values.map((_, index) => `"%GD_CLI_PM_ARG_${index}%"`).join(" ");
52
+ return { file: env.ComSpec || env.COMSPEC || "cmd.exe", args: ["/d", "/v:off", "/s", "/c", `"${line}"`], env: childEnv, windowsVerbatimArguments: true };
53
+ }
54
+ }
55
+ throw new Error(`Cannot find ${command} on PATH`);
56
+ }
57
+ export function spawnPackageManager(command, args, signal) {
58
+ return new Promise((resolvePromise, reject) => {
59
+ if (signal.aborted) {
60
+ reject(signal.reason);
61
+ return;
62
+ }
63
+ let invocation;
64
+ try {
65
+ invocation = process.platform === "win32" ? windowsManagerInvocation(command, args, process.env) : { file: command, args };
66
+ }
67
+ catch (error) {
68
+ reject(error);
69
+ return;
70
+ }
71
+ const child = spawn(invocation.file, invocation.args, {
72
+ stdio: [0, 2, 2], shell: false,
73
+ ...(process.platform === "win32" ? {} : { signal }),
74
+ ...(invocation.env ? { env: invocation.env } : {}),
75
+ ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {})
76
+ });
77
+ let interrupted = false;
78
+ let settled = false;
79
+ const finish = (error) => {
80
+ if (settled)
81
+ return;
82
+ settled = true;
83
+ signal.removeEventListener("abort", abort);
84
+ if (error !== undefined)
85
+ reject(error);
86
+ else
87
+ resolvePromise();
88
+ };
89
+ const abort = () => {
90
+ if (process.platform !== "win32" || interrupted || settled)
91
+ return;
92
+ interrupted = true;
93
+ if (!child.pid) {
94
+ finish(signal.reason);
95
+ return;
96
+ }
97
+ // Kill the tree while the parent still exists so its descendants remain
98
+ // discoverable; killing cmd.exe first would orphan the package manager.
99
+ const killer = spawn(process.env.ComSpec ? join(dirname(process.env.ComSpec), "taskkill.exe") : "taskkill.exe", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore", windowsHide: true });
100
+ killer.once("error", error => finish(new PackageManagerTerminationError(error)));
101
+ killer.once("close", code => {
102
+ if (code !== 0) {
103
+ finish(new PackageManagerTerminationError());
104
+ }
105
+ else
106
+ finish(signal.reason);
107
+ });
108
+ };
109
+ if (process.platform === "win32")
110
+ signal.addEventListener("abort", abort, { once: true });
111
+ child.once("error", error => { if (!interrupted)
112
+ finish(error); });
113
+ child.once("close", (code, exitSignal) => {
114
+ if (interrupted)
115
+ return;
116
+ if (code === 0)
117
+ finish();
118
+ else
119
+ finish(new Error(code === null ? `package manager terminated by ${exitSignal ?? "unknown signal"}` : `package manager exited with ${code}`));
120
+ });
121
+ if (signal.aborted)
122
+ abort();
123
+ });
124
+ }