@insmind/cli 1.9.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/bin/insmind-cli.js +2 -2
  2. package/dist/src/bootstrap/create-cli.js +9 -14
  3. package/dist/src/bootstrap/create-runtime.js +26 -16
  4. package/dist/src/bootstrap/run-task-worker.js +2 -1
  5. package/dist/src/bootstrap/validators.js +4 -2
  6. package/dist/src/cli/action-binding.js +39 -0
  7. package/dist/src/cli/agent-commands.js +8 -12
  8. package/dist/src/cli/dam-commands.js +3 -2
  9. package/dist/src/cli/editor-commands.js +10 -5
  10. package/dist/src/cli/host-input.js +34 -0
  11. package/dist/src/cli/model-commands.js +4 -3
  12. package/dist/src/cli/tool-commands.js +7 -9
  13. package/dist/src/contracts/creation-input.js +20 -0
  14. package/dist/src/features/agent/creative-protocol.js +12 -14
  15. package/dist/src/features/agent/use-cases.js +6 -31
  16. package/dist/src/features/auth/access-policy.js +1 -3
  17. package/dist/src/features/auth/sso-service.js +6 -4
  18. package/dist/src/features/auth/use-cases.js +2 -1
  19. package/dist/src/features/credits/use-cases.js +1 -1
  20. package/dist/src/features/dam/file-downloader.js +2 -1
  21. package/dist/src/features/dam/use-cases.js +7 -7
  22. package/dist/src/features/editor/bridge-client.js +1 -1
  23. package/dist/src/features/editor/use-cases.js +6 -8
  24. package/dist/src/features/org/use-cases.js +3 -3
  25. package/dist/src/features/skill/installer.js +24 -22
  26. package/dist/src/features/task/store.js +26 -12
  27. package/dist/src/features/task/use-cases.js +97 -82
  28. package/dist/src/features/tool/canvas-models.js +21 -4
  29. package/dist/src/features/tool/canvas-tool-adapter.js +29 -20
  30. package/dist/src/features/tool/canvas-video.js +2 -4
  31. package/dist/src/features/tool/dynamic-schema.js +29 -64
  32. package/dist/src/features/tool/mns-catalog-adapter.js +9 -2
  33. package/dist/src/features/tool/scene-catalog-adapter.js +0 -1
  34. package/dist/src/features/tool/tool-api-adapter.js +2 -2
  35. package/dist/src/features/tool/use-cases.js +24 -35
  36. package/dist/src/platform/json-input.js +1 -1
  37. package/dist/src/platform/safe-upload-file.js +6 -0
  38. package/dist/src/platform/signed-http-transport.js +24 -27
  39. package/dist/src/telemetry/host-diagnostics.js +2 -2
  40. package/dist/src/telemetry/invocation.js +87 -24
  41. package/dist/src/telemetry/process-errors.js +36 -3
  42. package/dist/src/telemetry/sls-sink.js +7 -10
  43. package/package.json +4 -4
  44. package/skills/insmind-cli/SKILL.md +1 -0
  45. package/skills/insmind-cli/references/editor.md +1 -1
  46. package/skills/insmind-cli/references/generation-constraints.md +3 -1
  47. package/skills/insmind-cli/references/tool.md +2 -3
@@ -160,12 +160,21 @@ export function createCanvasToolAdapter(dependencies) {
160
160
  const configuration = model.execution.configuration;
161
161
  async function quote(quantities) {
162
162
  const cost = estimateCanvasCost(model, quantities);
163
- if (!cost)
164
- throw new ToolInputError("component_quote_unavailable", "/model");
165
- await context.observe?.({ toolUsage: { model: id, cost } });
163
+ if (cost)
164
+ await context.observe?.({ toolUsage: { model: id, cost } });
166
165
  }
167
166
  const fields = Array.isArray(configuration.fields) ? configuration.fields.filter(record) : [];
168
167
  const backend = {};
168
+ const extra = Object.entries(args).filter(([key]) => key !== "model" && !model.parameters.some(field => field.name === key));
169
+ // Dedicated adapters translate public fields; generic fields can travel only on an actual service request.
170
+ function serviceArguments() {
171
+ for (const [key] of extra) {
172
+ if (["content_id", "contentid", "async", "model"].includes(key) || (Object.hasOwn(backend, key) && backend[key] !== args[key])) {
173
+ throw new ToolInputError("managed_argument", "/arguments/" + key);
174
+ }
175
+ }
176
+ return { ...Object.fromEntries(extra), ...backend };
177
+ }
169
178
  for (const field of fields)
170
179
  if (["model", "async"].includes(String(field.key)) && field.default_value !== undefined)
171
180
  backend[String(field.key)] = field.default_value;
@@ -181,15 +190,10 @@ export function createCanvasToolAdapter(dependencies) {
181
190
  const sourceUri = args.video;
182
191
  const source = await probe(sourceUri, context.signal);
183
192
  const rounded = Math.round(source.duration);
184
- if (id !== "video-enhance-standard" && (rounded < 2 || rounded > 30)
185
- || id === "video-edit-smart" && source.duration > 15)
186
- throw new ToolInputError("video_duration_unsupported", "/arguments/video");
187
193
  const references = args.referenceVideos ?? [];
188
194
  let total = source.duration;
189
195
  for (const reference of references)
190
196
  total += (await probe(reference, context.signal)).duration;
191
- if (id === "video-edit-smart" && total > 15)
192
- throw new ToolInputError("reference_video_duration_exceeded", "/arguments/referenceVideos");
193
197
  await quote({ time: Math.ceil(source.duration), duration: rounded, video_urls: Math.round(total) });
194
198
  async function remote(uri) {
195
199
  if (!uri.startsWith("file:"))
@@ -220,7 +224,7 @@ export function createCanvasToolAdapter(dependencies) {
220
224
  }
221
225
  backend.content_id = await contentId(context);
222
226
  await pipeline(context, id, "submitted", false, "dify");
223
- const content = await call(code, backend, context);
227
+ const content = await call(code, serviceArguments(), context);
224
228
  const uri = oneResource(content);
225
229
  let output;
226
230
  try {
@@ -243,14 +247,19 @@ export function createCanvasToolAdapter(dependencies) {
243
247
  throw new ToolInputError("matting_billing_contract_unavailable", "/model");
244
248
  if (model.cost === undefined || model.cost.minimum !== model.cost.maximum)
245
249
  throw new ToolInputError("matting_quote_unavailable", "/model");
250
+ if (extra.length)
251
+ throw new ToolInputError("unmapped_argument", "/arguments/" + extra[0][0]);
246
252
  return dependencies.standardMatting(source, context, model.cost.maximum, () => segment(source, context, args.cropToSubject === true));
247
253
  }
248
254
  if (id === "image-text-edit") {
249
255
  const replacements = args.replacements;
250
- if (new Set(replacements.map(item => item.from)).size !== replacements.length || replacements.some(item => item.from === item.to)) {
251
- throw new ToolInputError("text_replacement_conflict_or_noop", "/arguments/replacements");
252
- }
253
- backend.text = JSON.stringify(replacements.map(item => ({ origin: item.from, new: item.to === "" ? "REMOVE_TEXT" : item.to })));
256
+ backend.text = JSON.stringify(replacements.map(({ from, to, ...fields }, index) => {
257
+ for (const key of ["origin", "new"]) {
258
+ if (Object.hasOwn(fields, key))
259
+ throw new ToolInputError("managed_argument", `/arguments/replacements/${index}/${key}`);
260
+ }
261
+ return { ...fields, origin: from, new: to === "" ? "REMOVE_TEXT" : to };
262
+ }));
254
263
  }
255
264
  if (id === "image-ocr" || id === "image-text-edit") {
256
265
  const bytes = await sharp(source.bytes).resize({ width: 3000, height: 3000, fit: "inside", withoutEnlargement: true }).flatten({ background: "white" }).jpeg().toBuffer();
@@ -262,8 +271,6 @@ export function createCanvasToolAdapter(dependencies) {
262
271
  const info = await sharp(bytes).metadata();
263
272
  source = { bytes, width: info.width, height: info.height };
264
273
  }
265
- if (id === "image-layers-smart" && source.width * source.height < 512 * 512)
266
- throw new ToolInputError("layers_input_too_small", "/arguments/image");
267
274
  await quote({ resolution: args.targetLongEdge, max_layers: args.maxLayers });
268
275
  let prepared = source.bytes;
269
276
  if (selection && id.endsWith("-smart"))
@@ -291,14 +298,16 @@ export function createCanvasToolAdapter(dependencies) {
291
298
  backend.url = image;
292
299
  backend.type = id === "image-layers-smart" ? "seedream" : "codia";
293
300
  if (id === "image-layers-smart") {
294
- backend.max_layers = String(args.maxLayers);
301
+ if (args.maxLayers !== undefined)
302
+ backend.max_layers = typeof args.maxLayers === "number" ? String(args.maxLayers) : args.maxLayers;
295
303
  const resolutionField = fields.find(field => field.key === "resolution");
296
304
  const options = resolutionField?.options;
297
305
  const onlyTwoK = resolutionField?.default_value === "2K" && Array.isArray(options)
298
306
  && options.length === 1 && record(options[0]) && options[0].value === "2K";
299
- backend.resolution = onlyTwoK || source.width * source.height > 1280 * 720 ? "2K" : "1K";
307
+ if (args.resolution === undefined)
308
+ backend.resolution = onlyTwoK || source.width * source.height > 1280 * 720 ? "2K" : "1K";
300
309
  const field = fields.find(field => field.key === "seedream_model");
301
- if (field?.default_value !== undefined)
310
+ if (args.seedream_model === undefined && field?.default_value !== undefined)
302
311
  backend.seedream_model = nonblank(field.default_value);
303
312
  }
304
313
  }
@@ -312,7 +321,7 @@ export function createCanvasToolAdapter(dependencies) {
312
321
  backend.prompt = args.prompt;
313
322
  if (selection && id.endsWith("-smart"))
314
323
  backend.prompt = `仅处理青色边界标注的区域,移除青色标记。${backend.prompt ?? ""}`;
315
- if (id === "image-enhance-standard")
324
+ if (id === "image-enhance-standard" && args.targetLongEdge !== undefined)
316
325
  backend.resolution = args.targetLongEdge;
317
326
  if (Array.isArray(args.referenceImages)) {
318
327
  const references = await Promise.all(args.referenceImages.map(async (uri) => {
@@ -328,7 +337,7 @@ export function createCanvasToolAdapter(dependencies) {
328
337
  if (id === "image-remove-standard")
329
338
  backend.contentid = backend.content_id;
330
339
  await pipeline(context, id, "submitted", isMatting, protocol, undefined, id === "image-ocr" ? { ocr: { uri: image, width: source.width, height: source.height } } : undefined);
331
- const content = await call(code, backend, context, protocol);
340
+ const content = await call(code, serviceArguments(), context, protocol);
332
341
  if (id === "image-matting-smart") {
333
342
  await pipeline(context, id, "segmenting", true, "sync", content);
334
343
  const generated = await media.image(oneResource(content), context.signal);
@@ -49,10 +49,8 @@ export function createCanvasVideo(media) {
49
49
  const duration = Number(stream?.duration ?? result.format?.duration);
50
50
  const width = Number(stream?.width);
51
51
  const height = Number(stream?.height);
52
- const [numerator, denominator] = String(stream?.avg_frame_rate).split("/").map(Number);
53
- const frameDuration = denominator / numerator;
54
52
  if (!stream || !Number.isFinite(duration) || duration <= 0 || !Number.isInteger(width) || width <= 0
55
- || !Number.isInteger(height) || height <= 0 || !Number.isFinite(frameDuration) || frameDuration <= 0) {
53
+ || !Number.isInteger(height) || height <= 0) {
56
54
  throw new ToolInputError("video_metadata_invalid", "/arguments/video");
57
55
  }
58
56
  const decoded = await run(probe.path, ["-v", "error", "-protocol_whitelist", "file", "-format_whitelist", "mov,matroska,webm",
@@ -60,7 +58,7 @@ export function createCanvasVideo(media) {
60
58
  const frames = JSON.parse(decoded.stdout);
61
59
  if (!frames.frames?.some(frame => frame.media_type === "video"))
62
60
  throw new ToolInputError("video_decode_failed", "/arguments/video");
63
- return { duration, width, height, frameDuration, hasAudio: result.streams.some(stream => stream.codec_type === "audio"), format };
61
+ return { duration, width, height, hasAudio: result.streams.some(stream => stream.codec_type === "audio"), format };
64
62
  }
65
63
  catch (cause) {
66
64
  if (signal.aborted)
@@ -1,6 +1,5 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import addFormatsImport, {} from "ajv-formats";
3
- import { canvasControlParameterNames } from "./canvas-models.js";
4
3
  import { inputValidationSummary, validationIssues } from "../../platform/schema-issues.js";
5
4
  import { canonicalizeInputFileUris } from "../../platform/input-uri.js";
6
5
  import { ToolInputError } from "./catalog.js";
@@ -89,7 +88,7 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
89
88
  type: "object",
90
89
  properties,
91
90
  required: ["model"],
92
- additionalProperties: false,
91
+ additionalProperties: true,
93
92
  allOf: models.map(model => ({ if: { properties: { model: { const: model.model } }, required: ["model"] },
94
93
  then: buildModelArgumentsSchema(model) }))
95
94
  };
@@ -116,76 +115,42 @@ export function buildModelArgumentsSchema(model) {
116
115
  .filter((parameter) => parameter.required)
117
116
  .map((parameter) => parameter.name)
118
117
  ],
119
- additionalProperties: false
118
+ additionalProperties: true
120
119
  };
121
120
  }
122
121
  const ajv = new Ajv2020({ allErrors: true, strict: true });
123
122
  const addFormats = addFormatsImport;
124
123
  addFormats(ajv);
125
- function validator(model) {
126
- return ajv.compile(buildModelArgumentsSchema(model));
127
- }
128
- function controlArgumentsValidator(model) {
129
- const properties = {};
124
+ /** Enforce structure that the CLI actually reads or transforms. Business controls go to the service. */
125
+ export function assertModelArguments(model, value) {
126
+ const published = buildModelArgumentsSchema(model);
127
+ const properties = { model: published.properties.model };
128
+ const required = ["model"];
130
129
  for (const parameter of model.parameters) {
131
- if (parameter.name === "prompt"
132
- || parameter.type === "uri"
133
- || parameter.type === "uri[]"
134
- || (model.execution?.kind === "canvas" && !canvasControlParameterNames.has(parameter.name)))
135
- continue;
136
- properties[parameter.name] = buildModelArgumentsSchema(model).properties[parameter.name];
130
+ if (parameter.type === "uri" || parameter.type === "uri[]") {
131
+ properties[parameter.name] = parameterSchema(parameter);
132
+ if (model.execution?.kind === "canvas" && ["image", "video"].includes(parameter.name))
133
+ required.push(parameter.name);
134
+ }
137
135
  }
138
- return ajv.compile({
139
- type: "object",
140
- properties,
141
- required: [],
142
- additionalProperties: false
143
- });
144
- }
145
- export function assertModelArguments(model, value) {
146
- const validate = validator(model);
147
- canonicalizeInputFileUris(value, validate.schema);
136
+ if (model.execution?.kind === "canvas") {
137
+ for (const key of ["canvas", "placement", "cropToSubject"]) {
138
+ if (published.properties[key])
139
+ properties[key] = published.properties[key];
140
+ if (published.required.includes(key))
141
+ required.push(key);
142
+ }
143
+ if (model.model === "image-text-edit") {
144
+ properties.replacements = { type: "array", items: { type: "object", required: ["from", "to"],
145
+ properties: { from: { type: "string" }, to: { type: "string" } } } };
146
+ required.push("replacements");
147
+ }
148
+ }
149
+ const schema = { type: "object", properties, required };
150
+ const validate = ajv.compile(schema);
151
+ canonicalizeInputFileUris(value, schema);
148
152
  if (!validate(value)) {
149
- const issues = validationIssues(validate.errors, value, validate.schema);
153
+ const issues = validationIssues(validate.errors, value, schema);
150
154
  throw Object.assign(new ToolInputError("model_parameters", "/arguments", issues), { diagnosticSummary: inputValidationSummary(issues, value, "/arguments") });
151
155
  }
152
- const stepIssues = sliderStepIssues(model, value);
153
- if (stepIssues.length) {
154
- throw Object.assign(new ToolInputError("model_parameters", "/arguments", stepIssues), { diagnosticSummary: inputValidationSummary(stepIssues, value, "/arguments") });
155
- }
156
- }
157
- function sliderStepIssues(model, value) {
158
- const issues = [];
159
- for (const parameter of model.parameters) {
160
- if (parameter.step === undefined || !Object.hasOwn(value, parameter.name))
161
- continue;
162
- const candidate = value[parameter.name];
163
- const minimum = parameter.minimum;
164
- let valid = false;
165
- if (typeof candidate === "number" && minimum !== undefined && parameter.step > 0) {
166
- const steps = (candidate - minimum) / parameter.step;
167
- const nearestStep = Math.round(steps);
168
- const expected = minimum + nearestStep * parameter.step;
169
- const tolerance = Number.EPSILON * Math.max(1, Math.abs(candidate), Math.abs(expected), Math.abs(minimum), Math.abs(nearestStep * parameter.step)) * 2;
170
- valid = Math.abs(candidate - expected) <= tolerance;
171
- }
172
- if (!valid)
173
- issues.push({
174
- field: `/${parameter.name.replace(/~/gu, "~0").replace(/\//gu, "~1")}`.slice(0, 256),
175
- rule: "step",
176
- message: minimum === undefined || parameter.step <= 0
177
- ? "must match the model's slider configuration"
178
- : `must be ${minimum} plus a whole number of steps of ${parameter.step}`
179
- });
180
- if (issues.length === 8)
181
- break;
182
- }
183
- return issues;
184
- }
185
- export function modelControlArgumentsAreValid(model, value) {
186
- return typeof value === "object"
187
- && value !== null
188
- && !Array.isArray(value)
189
- && controlArgumentsValidator(model)(value)
190
- && sliderStepIssues(model, value).length === 0;
191
156
  }
@@ -187,8 +187,15 @@ function normalizeModel(value, scenes, english = false) {
187
187
  .filter((item) => item !== undefined);
188
188
  const description = cleanText(model.description);
189
189
  const usageDescription = cleanText(model.tool_description);
190
- const mimeTypes = typeof model.output_mime_types === "string"
191
- ? JSON.parse(model.output_mime_types) : model.output_mime_types;
190
+ let mimeTypes = model.output_mime_types;
191
+ if (typeof mimeTypes === "string") {
192
+ try {
193
+ mimeTypes = JSON.parse(mimeTypes);
194
+ }
195
+ catch {
196
+ mimeTypes = undefined;
197
+ }
198
+ }
192
199
  const outputMediaTypes = Array.isArray(mimeTypes)
193
200
  ? mimeTypes.map(text).filter((item) => item !== undefined) : [];
194
201
  const costs = activeSkus
@@ -15,7 +15,6 @@ export function createSceneCatalogAdapter(dependencies) {
15
15
  const cost = scene.is_free === true ? 0 : typeof scene.point_rights === "number" && Number.isFinite(scene.point_rights) && scene.point_rights >= 0 ? scene.point_rights : undefined;
16
16
  if (cost === undefined) {
17
17
  catalog.warnings.push(dependencies.english ? `Current pricing is unavailable for ${binding[1]}.` : `${binding[1]} 的当前报价不可用。`);
18
- continue;
19
18
  }
20
19
  const raw = { tool: binding[0], model: code, title: binding[4], sceneSort: 0, modelSort: 0, parameters: [],
21
20
  ...(cost === undefined ? {} : { cost: { unit: "gaodou", minimum: cost, maximum: cost } }),
@@ -109,7 +109,7 @@ export function normalizeToolContent(value) {
109
109
  if (value.type !== "resource" || !isRecord(value.resource)) {
110
110
  return protocolFailure(value);
111
111
  }
112
- if ("blob" in value.resource || "text" in value.resource)
112
+ if ("blob" in value.resource || ("text" in value.resource && value.resource.text !== ""))
113
113
  return protocolFailure(value);
114
114
  if (typeof value.resource.uri !== "string" || value.resource.uri.trim() === "") {
115
115
  return protocolFailure(value);
@@ -327,7 +327,7 @@ export function createToolApiAdapter(dependencies) {
327
327
  }, parseIntent);
328
328
  return {
329
329
  ...intent,
330
- arguments: withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters)
330
+ arguments: { ...withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters), ...invocation.explicitArguments }
331
331
  };
332
332
  });
333
333
  signal.throwIfAborted();
@@ -93,47 +93,35 @@ export function createToolUseCases(dependencies) {
93
93
  return { invocation: { kind: "canvas", model, arguments: input.arguments }, usage };
94
94
  }
95
95
  const prompt = [];
96
- const requestParameters = {};
97
- const directArguments = {};
96
+ if (Object.hasOwn(parameters, "content_id"))
97
+ throw new ToolInputError("managed_argument", "/arguments/content_id");
98
+ const requestParameters = { ...parameters };
99
+ const directArguments = { ...parameters };
98
100
  const prepare = async () => {
101
+ if (typeof parameters.prompt === "string") {
102
+ prompt.push({ type: "text", content: parameters.prompt });
103
+ delete requestParameters.prompt;
104
+ }
99
105
  for (const parameter of model.parameters) {
100
- signal.throwIfAborted();
101
- const value = input.arguments[parameter.name];
102
- if (value === undefined)
103
- continue;
104
- if (parameter.type === "string") {
105
- if (parameter.name === "prompt") {
106
- prompt.push({ type: "text", content: value });
107
- directArguments[parameter.name] = value;
108
- }
109
- else {
110
- requestParameters[parameter.name] = value;
111
- directArguments[parameter.name] = value;
112
- }
106
+ if (parameter.type !== "uri" && parameter.type !== "uri[]")
113
107
  continue;
114
- }
115
- if (parameter.type === "number") {
116
- requestParameters[parameter.name] = value;
117
- directArguments[parameter.name] = value;
108
+ const value = parameters[parameter.name];
109
+ if (value === undefined)
118
110
  continue;
119
- }
120
- const values = parameter.type === "uri[]" ? value : [value];
121
- for (const mediaUrl of values) {
111
+ const urls = [];
112
+ for (const url of (Array.isArray(value) ? value : [value])) {
122
113
  signal.throwIfAborted();
123
- if (mediaUrl.startsWith("file:")) {
124
- const uploaded = await dependencies.uploader.upload({ url: mediaUrl }, access, signal);
125
- signal.throwIfAborted();
126
- prompt.push({
127
- type: "media",
128
- url: uploaded.url,
129
- mime: uploaded.mediaType,
130
- name: parameter.name
131
- });
132
- }
133
- else {
134
- prompt.push(remoteMedia(mediaUrl, parameter.name));
135
- }
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);
136
121
  }
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];
137
125
  }
138
126
  };
139
127
  const hasLocalMedia = model.parameters.some((parameter) => {
@@ -158,6 +146,7 @@ export function createToolUseCases(dependencies) {
158
146
  model: model.model,
159
147
  prompt,
160
148
  parameters: requestParameters,
149
+ explicitArguments: directArguments,
161
150
  optionalMediaParameters: model.parameters
162
151
  .filter((parameter) => ((parameter.type === "uri" || parameter.type === "uri[]")
163
152
  && !parameter.required))
@@ -25,7 +25,7 @@ export function createJsonInputReader(options) {
25
25
  throw new JsonInputError("read", cause);
26
26
  }
27
27
  try {
28
- return JSON.parse(text);
28
+ return JSON.parse(text.replace(/^\uFEFF/u, ""));
29
29
  }
30
30
  catch (cause) {
31
31
  throw new JsonInputError("parse", cause);
@@ -86,6 +86,12 @@ function detectedFormat(header) {
86
86
  return "webp";
87
87
  if (header.length >= 12 && header.subarray(4, 8).toString("ascii") === "ftyp") {
88
88
  const brand = header.subarray(8, 12).toString("ascii");
89
+ if (["isom", "iso2", "iso5", "iso6", "mp41", "mp42", "avc1", "dash"].includes(brand))
90
+ return "mp4";
91
+ if (brand === "qt ")
92
+ return "mov";
93
+ if (brand === "M4V ")
94
+ return "m4v";
89
95
  if (brand === "avif" || brand === "avis")
90
96
  return "avif";
91
97
  if (["heic", "heix", "hevc", "hevx"].includes(brand))
@@ -131,40 +131,37 @@ export function createSignedHttpTransport(options) {
131
131
  let dispatched;
132
132
  try {
133
133
  // Invoke fetch at this boundary; diagnostic persistence never gates dispatch.
134
- let pending;
135
- try {
136
- pending = options.fetch(url, {
137
- method,
138
- headers,
139
- ...(body === undefined ? {} : { body }),
140
- signal
141
- }).then(response => {
142
- // Capture ownership facts before waiting for unrelated dispatch diagnostics.
143
- const received = {
144
- response,
145
- bodyUsedAtReceipt: response.bodyUsed,
146
- bodyLockedAtReceipt: response.body?.locked ?? false,
147
- reusedResponse: seenResponses.has(response),
148
- diagnostics: () => ({ ...diagnostics(), ...responseDiagnostics(response) })
149
- };
150
- seenResponses.add(response);
151
- try {
152
- request.onResponse?.(response.status, received.diagnostics());
153
- }
154
- catch { /* Receipt diagnostics only. */ }
155
- return received;
156
- });
157
- }
158
- finally {
134
+ const pending = options.fetch(url, {
135
+ method,
136
+ headers,
137
+ ...(body === undefined ? {} : { body }),
138
+ signal
139
+ }).then(response => {
140
+ // Capture ownership facts before waiting for unrelated dispatch diagnostics.
141
+ const received = {
142
+ response,
143
+ bodyUsedAtReceipt: response.bodyUsed,
144
+ bodyLockedAtReceipt: response.body?.locked ?? false,
145
+ reusedResponse: seenResponses.has(response),
146
+ diagnostics: () => ({ ...diagnostics(), ...responseDiagnostics(response) })
147
+ };
148
+ seenResponses.add(response);
159
149
  try {
160
- dispatched = request.onDispatch?.(options.now().getTime()).catch(() => undefined);
150
+ request.onResponse?.(response.status, received.diagnostics());
161
151
  }
162
- catch { /* Diagnostic only. */ }
152
+ catch { /* Receipt diagnostics only. */ }
153
+ return received;
154
+ });
155
+ try {
156
+ dispatched = request.onDispatch?.(options.now().getTime()).catch(() => undefined);
163
157
  }
158
+ catch { /* Diagnostic only. */ }
164
159
  const [received] = await Promise.all([pending, dispatched]);
165
160
  return received;
166
161
  }
167
162
  catch (error) {
163
+ // A rejected fetch must not overtake persistence of the dispatch that caused it.
164
+ await dispatched;
168
165
  const diagnosticSummary = diagnostics();
169
166
  if (isInterruption(error, request.signal)) {
170
167
  const reason = request.signal.reason;
@@ -17,7 +17,7 @@ export async function runHostDiagnosticReporter(options) {
17
17
  output.on("error", () => { });
18
18
  const sink = createSlsTelemetrySink({ fetch: options.fetch ?? globalThis.fetch,
19
19
  trackingUrl: options.trackingUrl ?? options.product.telemetryUrl,
20
- directory: join(options.homeDirectory ?? homedir(), options.product.stateDirectory, "telemetry") });
20
+ directory: join(options.homeDirectory ?? homedir(), options.product.stateDirectory, "telemetry", "v6") });
21
21
  const cliVersion = options.cliVersion ?? await packageVersion();
22
22
  // A wrapper may be killed with stdin still open. This helper is always bounded;
23
23
  // queued start evidence survives, and no permanent background process is added.
@@ -55,7 +55,7 @@ export async function runHostDiagnosticReporter(options) {
55
55
  return;
56
56
  if (typeof raw.occurred_at_ms !== "number" || !Number.isSafeInteger(raw.occurred_at_ms) || raw.occurred_at_ms < 0)
57
57
  return;
58
- const event = { ...context, schema_version: "5", cli_name: options.product.commandName,
58
+ const event = { ...context, schema_version: "6", started_at_ms: raw.occurred_at_ms, command_kind: "technical", cli_name: options.product.commandName,
59
59
  cli_version: cliVersion, env: env.CLI_TELEMETRY_ENV === "test" ? "test" : "production",
60
60
  event_name: "host_diagnostic", process_role: "host_connector", trace_id: context.host_invocation_id,
61
61
  record_seq: ++sequence, occurred_at_ms: raw.occurred_at_ms,