@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
@@ -0,0 +1,25 @@
1
+ export class ToolTaskFailedError extends Error {
2
+ remoteCode;
3
+ remoteBody;
4
+ diagnosticReason;
5
+ imagePixelRequirement;
6
+ constructor(evidence = {}) {
7
+ super("稿定工具任务执行失败。");
8
+ this.name = "ToolTaskFailedError";
9
+ this.remoteCode = evidence.remoteCode;
10
+ this.remoteBody = evidence.remoteBody;
11
+ this.imagePixelRequirement = evidence.imagePixelRequirement;
12
+ this.diagnosticReason = evidence.diagnosticReason;
13
+ }
14
+ }
15
+ export class ToolInsufficientCreditsError extends ToolTaskFailedError {
16
+ diagnosticReason = "INSUFFICIENT_CREDITS";
17
+ constructor() {
18
+ super();
19
+ this.name = "ToolInsufficientCreditsError";
20
+ }
21
+ }
22
+ export class ToolTaskCanceledError extends Error {
23
+ diagnosticReason = "TASK_CANCELED";
24
+ constructor() { super("用户已取消生成任务。"); this.name = "ToolTaskCanceledError"; }
25
+ }
@@ -0,0 +1,15 @@
1
+ import { concreteMediaType, mediaTypeFromFilename } from "../../platform/media-type.js";
2
+ import { authorizeToolResources } from "./resource-authorizer.js";
3
+ /** Metadata can explain what was returned. Delivering a URL never requires opening it here. */
4
+ export function presentToolContent(content, kind, onMissingMedia) {
5
+ if (!content.some(part => part.type === "resource_link" &&
6
+ (concreteMediaType(part.mimeType) ?? mediaTypeFromFilename(part.name))?.startsWith(kind + "/")))
7
+ onMissingMedia?.(kind);
8
+ return content;
9
+ }
10
+ export function createToolOutputVerifier(authorizer, onMissingMedia) {
11
+ return async (content, kind, { access, signal }) => {
12
+ const authorized = await authorizeToolResources({ content, usage: { model: "" } }, authorizer, access, signal);
13
+ return presentToolContent(authorized.content, kind, onMissingMedia);
14
+ };
15
+ }
@@ -1,51 +1,52 @@
1
- import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
1
+ import { parseHttpAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
2
2
  import { findToolModel, defaultToolDefinitions, projectModelDetail, projectModelList, projectToolList, ToolInputError } from "./catalog.js";
3
3
  import { assertModelArguments, buildToolArgumentsSchema } from "./dynamic-schema.js";
4
+ import { mediaFilename, mediaTypeFromFilename } from "../../platform/media-type.js";
5
+ import { assertNoLocalAssetPaths } from "./argument-paths.js";
4
6
  import { hasCanvasMetering } from "./canvas-pricing.js";
5
- const mediaTypes = {
6
- avif: "image/avif",
7
- gif: "image/gif",
8
- heic: "image/heic",
9
- jpeg: "image/jpeg",
10
- jpg: "image/jpeg",
11
- mov: "video/quicktime",
12
- mp3: "audio/mpeg",
13
- mp4: "video/mp4",
14
- png: "image/png",
15
- wav: "audio/wav",
16
- webm: "video/webm",
17
- webp: "image/webp"
18
- };
19
- function inferRemoteMediaType(url) {
20
- const segment = url.pathname.split("/").filter(Boolean).at(-1) ?? "";
21
- let filename = segment;
7
+ function remoteMedia(value, name, path = name) {
22
8
  try {
23
- filename = decodeURIComponent(segment);
24
- }
25
- catch {
26
- // The extension remains usable when the path contains malformed escapes.
27
- }
28
- const extension = filename.split(".").at(-1)?.toLowerCase();
29
- return extension === undefined || extension === filename.toLowerCase()
30
- ? "application/octet-stream"
31
- : mediaTypes[extension] ?? "application/octet-stream";
32
- }
33
- function remoteMedia(value, name) {
34
- try {
35
- const url = parseSafeRemoteAssetUrl(value);
9
+ const url = parseHttpAssetUrl(value);
36
10
  return {
37
11
  type: "media",
38
12
  url: value,
39
- mime: inferRemoteMediaType(url),
13
+ mime: mediaTypeFromFilename(mediaFilename(url)) ?? "application/octet-stream",
40
14
  name
41
15
  };
42
16
  }
43
17
  catch (error) {
44
18
  if (error instanceof UrlSafetyError)
45
- throw new ToolInputError("invalid_asset_url", `/arguments/${name}`, [], error);
19
+ throw new ToolInputError("invalid_asset_url", `/arguments/${path}`, [], error);
46
20
  throw error;
47
21
  }
48
22
  }
23
+ function prepareGenerationInput(model, parameters) {
24
+ const prompt = [];
25
+ const controls = Object.create(null);
26
+ const fields = new Map(model.parameters.map(field => [field.name, field]));
27
+ const references = [];
28
+ for (const [name, value] of Object.entries(parameters)) {
29
+ if (name === "prompt") {
30
+ if (typeof value !== "string")
31
+ throw new ToolInputError("prompt_must_be_text", "/arguments/prompt");
32
+ prompt.push({ type: "text", content: value });
33
+ continue;
34
+ }
35
+ const field = fields.get(name);
36
+ if (field?.type === "uri" || field?.type === "uri[]") {
37
+ // assertModelArguments has checked and canonicalized these URI fields.
38
+ const uris = field.type === "uri[]" ? value : [value];
39
+ for (const [index, uri] of uris.entries()) {
40
+ const path = field.type === "uri[]" ? `${name}/${index}` : name;
41
+ references.push(uri.startsWith("file:") ? { type: "local", name, url: uri } : remoteMedia(uri, name, path));
42
+ }
43
+ continue;
44
+ }
45
+ assertNoLocalAssetPaths(value, `/arguments/${name}`, field?.type);
46
+ controls[name] = value;
47
+ }
48
+ return { prompt, controls, references };
49
+ }
49
50
  export function createToolUseCases(dependencies) {
50
51
  async function load(access, signal) {
51
52
  signal.throwIfAborted();
@@ -61,12 +62,13 @@ export function createToolUseCases(dependencies) {
61
62
  dependencies.telemetry.annotate({ tool_name: input.name,
62
63
  ...(typeof input.arguments.model === "string" ? { model_id: input.arguments.model } : {}) });
63
64
  const catalog = await load(access, signal);
64
- const model = await dependencies.telemetry.stage("input", () => {
65
+ const { model, parameters, generationInput } = await dependencies.telemetry.stage("input", () => {
65
66
  const modelName = input.arguments.model;
66
67
  if (typeof modelName !== "string")
67
68
  throw new ToolInputError("model_required", "/arguments/model");
68
69
  const selected = findToolModel(catalog, input.name, modelName);
69
70
  assertModelArguments(selected, input.arguments);
71
+ const { model: _id, ...parameters } = input.arguments;
70
72
  if (selected.execution?.kind === "canvas") {
71
73
  for (const parameter of selected.parameters) {
72
74
  const value = input.arguments[parameter.name];
@@ -77,86 +79,60 @@ export function createToolUseCases(dependencies) {
77
79
  remoteMedia(uri, parameter.type === "uri[]" ? `${parameter.name}/${index}` : parameter.name);
78
80
  }
79
81
  }
82
+ return { model: selected, parameters };
80
83
  }
81
- return selected;
84
+ return { model: selected, parameters, generationInput: prepareGenerationInput(selected, parameters) };
82
85
  });
83
- const { model: ignoredModel, ...parameters } = input.arguments;
84
- void ignoredModel;
85
86
  dependencies.telemetry.annotate({
86
87
  tool_name: model.tool,
87
88
  model_id: model.model,
88
89
  parameters
89
90
  });
90
- if (model.execution?.kind === "canvas") {
91
+ if (!generationInput) {
91
92
  const usage = { model: model.model, ...(model.cost === undefined || hasCanvasMetering(model) ? {} : { cost: model.cost }) };
92
93
  await observe?.({ toolUsage: usage, generation: { tool: model.tool, model: model.model } });
93
94
  return { invocation: { kind: "canvas", model, arguments: input.arguments }, usage };
94
95
  }
95
- const prompt = [];
96
- if (Object.hasOwn(parameters, "content_id"))
97
- throw new ToolInputError("managed_argument", "/arguments/content_id");
98
- const requestParameters = { ...parameters };
99
- const directArguments = { ...parameters };
100
- const prepare = async () => {
101
- if (typeof parameters.prompt === "string") {
102
- prompt.push({ type: "text", content: parameters.prompt });
103
- delete requestParameters.prompt;
104
- }
105
- for (const parameter of model.parameters) {
106
- if (parameter.type !== "uri" && parameter.type !== "uri[]")
107
- continue;
108
- const value = parameters[parameter.name];
109
- if (value === undefined)
110
- continue;
111
- const urls = [];
112
- for (const url of (Array.isArray(value) ? value : [value])) {
113
- signal.throwIfAborted();
114
- const media = url.startsWith("file:")
115
- ? await dependencies.uploader.upload({ url }, access, signal).then(upload => ({
116
- type: "media", url: upload.url, mime: upload.mediaType, name: parameter.name
117
- }))
118
- : remoteMedia(url, parameter.name);
119
- prompt.push(media);
120
- urls.push(media.url);
96
+ const { prompt, controls, references } = generationInput;
97
+ const explicitArguments = { ...parameters };
98
+ // Empty media lists remain explicit values, even though they add no prompt items.
99
+ for (const field of model.parameters) {
100
+ if (field.type === "uri[]" && Object.hasOwn(parameters, field.name))
101
+ explicitArguments[field.name] = [];
102
+ }
103
+ const prepareMedia = async () => {
104
+ const uploaded = new Map();
105
+ for (const ref of references) {
106
+ signal.throwIfAborted();
107
+ let media;
108
+ if (ref.type === "media")
109
+ media = ref;
110
+ else {
111
+ let asset = uploaded.get(ref.url);
112
+ if (!asset) {
113
+ asset = await dependencies.uploader.upload({ url: ref.url }, access, signal);
114
+ uploaded.set(ref.url, asset);
115
+ }
116
+ media = { type: "media", url: asset.url, mime: asset.mediaType, name: ref.name };
121
117
  }
122
- // Preserve scalar/array semantics after converting local files to service URLs.
123
- directArguments[parameter.name] = parameter.type === "uri[]" ? urls : urls[0];
124
- delete requestParameters[parameter.name];
118
+ prompt.push(media);
119
+ if (Array.isArray(explicitArguments[ref.name]))
120
+ explicitArguments[ref.name].push(media.url);
121
+ else
122
+ explicitArguments[ref.name] = media.url;
125
123
  }
126
124
  };
127
- const hasLocalMedia = model.parameters.some((parameter) => {
128
- const value = input.arguments[parameter.name];
129
- return parameter.type === "uri"
130
- ? typeof value === "string" && value.startsWith("file:")
131
- : parameter.type === "uri[]"
132
- && Array.isArray(value) && value.some((url) => url.startsWith("file:"));
133
- });
134
- if (hasLocalMedia) {
135
- await dependencies.telemetry.stage("upload", prepare);
136
- }
137
- else {
138
- await prepare();
139
- }
125
+ if (references.some(ref => ref.type === "local"))
126
+ await dependencies.telemetry.stage("upload", prepareMedia);
127
+ else
128
+ await prepareMedia();
140
129
  signal.throwIfAborted();
141
- const requiresIntent = prompt.some((item) => item.type === "media")
142
- || Object.values(requestParameters).some((value) => value === "");
130
+ const mediaKind = model.tool === "video.generate" ? "video" : "image";
131
+ const requiresIntent = references.length > 0 || Object.values(controls).some(value => value === "");
143
132
  const invocation = requiresIntent
144
- ? {
145
- kind: "intent",
146
- model: model.model,
147
- prompt,
148
- parameters: requestParameters,
149
- explicitArguments: directArguments,
150
- optionalMediaParameters: model.parameters
151
- .filter((parameter) => ((parameter.type === "uri" || parameter.type === "uri[]")
152
- && !parameter.required))
153
- .map((parameter) => parameter.name)
154
- }
155
- : {
156
- kind: "direct",
157
- name: model.model,
158
- arguments: directArguments
159
- };
133
+ ? { kind: "intent", model: model.model, mediaKind, prompt, parameters: controls, explicitArguments,
134
+ optionalMediaParameters: model.parameters.filter(field => !field.required && (field.type === "uri" || field.type === "uri[]")).map(field => field.name) }
135
+ : { kind: "direct", name: model.model, mediaKind, arguments: explicitArguments };
160
136
  const usage = {
161
137
  model: model.model,
162
138
  ...(model.cost === undefined ? {} : { cost: model.cost })
@@ -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
+ }