@gaoding/cli 1.8.0 → 1.9.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 (95) hide show
  1. package/contracts/operations/agent.send/input.schema.json +1 -1
  2. package/contracts/operations/agent.send/output.schema.json +1 -1
  3. package/contracts/operations/model.get/input.schema.json +6 -0
  4. package/contracts/operations/model.get/output.schema.json +10 -1
  5. package/contracts/operations/tool.call/canvas-input.schema.json +60 -0
  6. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +42 -0
  7. package/contracts/operations/tool.call/models/image-edit-standard.schema.json +33 -0
  8. package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +27 -0
  9. package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +27 -0
  10. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +76 -0
  11. package/contracts/operations/tool.call/models/image-expand-standard.schema.json +61 -0
  12. package/contracts/operations/tool.call/models/image-layers-layout.schema.json +21 -0
  13. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +28 -0
  14. package/contracts/operations/tool.call/models/image-matting-smart.schema.json +37 -0
  15. package/contracts/operations/tool.call/models/image-matting-standard.schema.json +26 -0
  16. package/contracts/operations/tool.call/models/image-ocr.schema.json +21 -0
  17. package/contracts/operations/tool.call/models/image-remove-smart.schema.json +32 -0
  18. package/contracts/operations/tool.call/models/image-remove-standard.schema.json +27 -0
  19. package/contracts/operations/tool.call/models/image-text-edit.schema.json +46 -0
  20. package/contracts/operations/tool.call/models/image-vectorize.schema.json +21 -0
  21. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +76 -0
  22. package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +33 -0
  23. package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +27 -0
  24. package/contracts/operations/tool.call/ocr-payload.schema.json +66 -0
  25. package/contracts/operations/tool.call/output.schema.json +38 -0
  26. package/contracts/operations/tool.call/template-payload.schema.json +96 -0
  27. package/dist/bin/gd-cli.js +31 -24
  28. package/dist/bin/insmind-cli.js +31 -24
  29. package/dist/bin/task-worker.js +4 -1
  30. package/dist/src/analytics/device.js +2 -2
  31. package/dist/src/bootstrap/create-cli.js +7 -0
  32. package/dist/src/bootstrap/create-runtime.js +53 -30
  33. package/dist/src/bootstrap/run-task-worker.js +5 -1
  34. package/dist/src/bootstrap/validators.js +11 -4
  35. package/dist/src/cli/agent-commands.js +1 -0
  36. package/dist/src/cli/dam-commands.js +3 -3
  37. package/dist/src/cli/errors.js +63 -15
  38. package/dist/src/cli/model-commands.js +6 -3
  39. package/dist/src/cli/observed-errors.js +3 -1
  40. package/dist/src/cli/tool-commands.js +2 -0
  41. package/dist/src/contracts/schema.js +4 -1
  42. package/dist/src/features/agent/creative-agent-adapter.js +37 -11
  43. package/dist/src/features/agent/creative-protocol.js +31 -10
  44. package/dist/src/features/agent/creative-stream.js +54 -6
  45. package/dist/src/features/agent/resource-authorizer.js +1 -0
  46. package/dist/src/features/agent/result-reader.js +3 -1
  47. package/dist/src/features/agent/use-cases.js +15 -5
  48. package/dist/src/features/auth/credential-store.js +6 -10
  49. package/dist/src/features/auth/sso-service.js +22 -6
  50. package/dist/src/features/auth/state.js +6 -0
  51. package/dist/src/features/auth/use-cases.js +90 -32
  52. package/dist/src/features/dam/asset-projection.js +10 -1
  53. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  54. package/dist/src/features/dam/input.js +23 -0
  55. package/dist/src/features/dam/use-cases.js +32 -22
  56. package/dist/src/features/task/store.js +5 -5
  57. package/dist/src/features/task/task-background.js +67 -19
  58. package/dist/src/features/task/use-cases.js +38 -9
  59. package/dist/src/features/tool/canvas-copy.js +61 -0
  60. package/dist/src/features/tool/canvas-media.js +248 -0
  61. package/dist/src/features/tool/canvas-models.js +109 -0
  62. package/dist/src/features/tool/canvas-pricing.js +81 -0
  63. package/dist/src/features/tool/canvas-recovery.js +68 -0
  64. package/dist/src/features/tool/canvas-results.js +144 -0
  65. package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
  66. package/dist/src/features/tool/canvas-video.js +84 -0
  67. package/dist/src/features/tool/catalog.js +35 -13
  68. package/dist/src/features/tool/dynamic-schema.js +55 -25
  69. package/dist/src/features/tool/matting-billing.js +115 -0
  70. package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
  71. package/dist/src/features/tool/resource-authorizer.js +34 -0
  72. package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
  73. package/dist/src/features/tool/tool-api-adapter.js +29 -17
  74. package/dist/src/features/tool/use-cases.js +28 -3
  75. package/dist/src/platform/file-lock.js +58 -15
  76. package/dist/src/platform/input-uri.js +105 -0
  77. package/dist/src/platform/local-json-file.js +7 -4
  78. package/dist/src/platform/remote-error-evidence.js +23 -1
  79. package/dist/src/platform/safe-upload-file.js +18 -4
  80. package/dist/src/platform/schema-issues.js +18 -0
  81. package/dist/src/platform/signed-http-transport.js +77 -16
  82. package/dist/src/platform/text-output.js +55 -13
  83. package/dist/src/product/config.js +12 -1
  84. package/dist/src/telemetry/failure-summary.js +53 -2
  85. package/dist/src/telemetry/host-diagnostics.js +95 -0
  86. package/dist/src/telemetry/invocation.js +24 -3
  87. package/dist/src/telemetry/process-errors.js +2 -1
  88. package/dist/src/telemetry/sls-sink.js +66 -18
  89. package/package.json +5 -4
  90. package/skills/gd-cli/SKILL.md +2 -0
  91. package/skills/gd-cli/references/creation.md +2 -0
  92. package/skills/gd-cli/references/generation-constraints.md +3 -1
  93. package/skills/gd-cli/references/matting.md +29 -0
  94. package/skills/gd-cli/references/media-tools.md +40 -0
  95. package/skills/gd-cli/references/tool.md +4 -4
@@ -2,13 +2,45 @@ import { isInterruption } from "./interruption.js";
2
2
  import { remoteErrorEvidence } from "./remote-error-evidence.js";
3
3
  import { RemoteProtocolError } from "./remote-protocol.js";
4
4
  import { canonicalizeQuery, signRequest } from "./signature.js";
5
+ /** Bind adapter interpretation errors to this response, never to a later request. */
6
+ export async function withResponseDiagnostics(run, correlation = {}) {
7
+ let receipt;
8
+ try {
9
+ return await run((status, summary) => { receipt = { status, ...(summary ? { summary } : {}) }; });
10
+ }
11
+ catch (error) {
12
+ try {
13
+ if ((receipt || Object.keys(correlation).length) && error instanceof Error && Object.isExtensible(error)) {
14
+ const previous = error;
15
+ let nestedResponse = false;
16
+ const seen = new Set();
17
+ for (let cause = error.cause; cause instanceof Error && seen.size < 10 && !seen.has(cause); cause = cause.cause) {
18
+ seen.add(cause);
19
+ if ("status" in cause && typeof cause.status === "number") {
20
+ nestedResponse = true;
21
+ break;
22
+ }
23
+ }
24
+ const related = !nestedResponse && (previous.status === undefined || previous.status === receipt?.status)
25
+ && (!previous.diagnosticSummary?.requestId || !receipt?.summary?.requestId || previous.diagnosticSummary.requestId === receipt.summary.requestId);
26
+ const response = related ? receipt : undefined;
27
+ // Existing evidence belongs to the primary failure (e.g. a nested request).
28
+ Object.assign(error, { ...(response ? { status: previous.status ?? response.status } : {}),
29
+ diagnosticSummary: { ...correlation, ...response?.summary, ...previous.diagnosticSummary } });
30
+ }
31
+ }
32
+ catch { /* Diagnostics cannot replace the original failure. */ }
33
+ throw error;
34
+ }
35
+ }
5
36
  export class RemoteRequestError extends Error {
6
37
  status;
7
38
  transient;
8
39
  remoteCode;
9
40
  remoteBody;
10
41
  diagnosticReason;
11
- constructor(status, transient = false, evidence = {}, cause, diagnosticReason) {
42
+ diagnosticSummary;
43
+ constructor(status, transient = false, evidence = {}, cause, diagnosticReason, diagnosticSummary) {
12
44
  super(status === undefined ? "无法连接稿定服务。" : `稿定服务请求失败(HTTP ${status})。`, { cause });
13
45
  this.name = "RemoteRequestError";
14
46
  this.status = status;
@@ -16,7 +48,16 @@ export class RemoteRequestError extends Error {
16
48
  this.remoteCode = evidence.remoteCode;
17
49
  this.remoteBody = evidence.remoteBody;
18
50
  this.diagnosticReason = diagnosticReason ?? evidence.diagnosticReason;
51
+ this.diagnosticSummary = diagnosticSummary;
52
+ }
53
+ }
54
+ function responseDiagnostics(response) {
55
+ for (const header of ["x-request-id", "x-gd-request-id", "request-id"]) {
56
+ const requestId = response.headers.get(header);
57
+ if (requestId && /^[A-Za-z0-9._:-]{1,128}$/u.test(requestId))
58
+ return { requestId };
19
59
  }
60
+ return undefined;
20
61
  }
21
62
  const TRANSIENT_NETWORK_CODES = new Set([
22
63
  "ECONNRESET",
@@ -75,13 +116,18 @@ export function createSignedHttpTransport(options) {
75
116
  headers["Content-Type"] = "application/json";
76
117
  if (request.organizationId !== undefined)
77
118
  headers["X-Org-Id"] = request.organizationId;
78
- const signal = timeout
79
- ? AbortSignal.any([
80
- request.signal,
81
- AbortSignal.timeout(options.timeoutMs ?? 30_000)
82
- ])
119
+ const requestTimeoutMs = timeout ? options.timeoutMs ?? 30_000 : undefined;
120
+ const timeoutSignal = requestTimeoutMs === undefined ? undefined : AbortSignal.timeout(requestTimeoutMs);
121
+ const signal = timeoutSignal
122
+ ? AbortSignal.any([request.signal, timeoutSignal])
83
123
  : request.signal;
84
124
  signal.throwIfAborted();
125
+ const startedAt = Date.now();
126
+ const diagnostics = () => ({
127
+ requestDurationMs: Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, Date.now() - startedAt)),
128
+ ...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),
129
+ abortSource: request.signal.aborted ? "caller" : timeoutSignal?.aborted ? "request_timeout" : "none"
130
+ });
85
131
  let dispatched;
86
132
  try {
87
133
  // Invoke fetch at this boundary; diagnostic persistence never gates dispatch.
@@ -98,9 +144,14 @@ export function createSignedHttpTransport(options) {
98
144
  response,
99
145
  bodyUsedAtReceipt: response.bodyUsed,
100
146
  bodyLockedAtReceipt: response.body?.locked ?? false,
101
- reusedResponse: seenResponses.has(response)
147
+ reusedResponse: seenResponses.has(response),
148
+ diagnostics: () => ({ ...diagnostics(), ...responseDiagnostics(response) })
102
149
  };
103
150
  seenResponses.add(response);
151
+ try {
152
+ request.onResponse?.(response.status, received.diagnostics());
153
+ }
154
+ catch { /* Receipt diagnostics only. */ }
104
155
  return received;
105
156
  });
106
157
  }
@@ -114,9 +165,17 @@ export function createSignedHttpTransport(options) {
114
165
  return received;
115
166
  }
116
167
  catch (error) {
117
- if (isInterruption(error, request.signal))
118
- throw request.signal.reason;
119
- throw new RemoteRequestError(undefined, isTransientNetworkFailure(error), {}, error);
168
+ const diagnosticSummary = diagnostics();
169
+ if (isInterruption(error, request.signal)) {
170
+ const reason = request.signal.reason;
171
+ try {
172
+ if (reason instanceof Error && Object.isExtensible(reason))
173
+ Object.assign(reason, { diagnosticSummary });
174
+ }
175
+ catch { /* Preserve the original interruption. */ }
176
+ throw reason;
177
+ }
178
+ throw new RemoteRequestError(undefined, isTransientNetworkFailure(error), {}, error, undefined, diagnosticSummary);
120
179
  }
121
180
  }
122
181
  async function readText(received) {
@@ -136,7 +195,7 @@ export function createSignedHttpTransport(options) {
136
195
  : summary.bodyLockedBeforeRead ? "RESPONSE_BODY_LOCKED" : "RESPONSE_BODY_READ_FAILED";
137
196
  throw new RemoteRequestError(response.status, false, {
138
197
  remoteBody: JSON.stringify(summary)
139
- }, error, diagnosticReason);
198
+ }, error, diagnosticReason, { ...received.diagnostics(), ...summary });
140
199
  }
141
200
  }
142
201
  async function json(received) {
@@ -144,17 +203,19 @@ export function createSignedHttpTransport(options) {
144
203
  const body = await readText(received);
145
204
  const evidence = remoteErrorEvidence(body);
146
205
  if (!response.ok)
147
- throw new RemoteRequestError(response.status, false, evidence);
206
+ throw new RemoteRequestError(response.status, false, evidence, undefined, undefined, received.diagnostics());
148
207
  try {
149
208
  return JSON.parse(body);
150
209
  }
151
210
  catch (error) {
152
- throw new RemoteProtocolError(evidence, error, "RESPONSE_JSON_INVALID");
211
+ throw Object.assign(new RemoteProtocolError(evidence, error, "RESPONSE_JSON_INVALID"), {
212
+ status: response.status, diagnosticSummary: received.diagnostics()
213
+ });
153
214
  }
154
215
  }
155
216
  async function getJsonResponse(request) {
156
217
  const received = await send("GET", request, "application/json", undefined, true);
157
- return { body: await json(received), headers: received.response.headers };
218
+ return { body: await json(received), headers: received.response.headers, status: received.response.status };
158
219
  }
159
220
  return {
160
221
  async getJson(request) {
@@ -172,10 +233,10 @@ export function createSignedHttpTransport(options) {
172
233
  const { response } = received;
173
234
  if (!response.ok) {
174
235
  const body = await readText(received);
175
- throw new RemoteRequestError(response.status, false, remoteErrorEvidence(body));
236
+ throw new RemoteRequestError(response.status, false, remoteErrorEvidence(body), undefined, undefined, received.diagnostics());
176
237
  }
177
238
  if (!response.body)
178
- throw new RemoteRequestError(response.status);
239
+ throw new RemoteRequestError(response.status, false, {}, undefined, "RESPONSE_BODY_MISSING", received.diagnostics());
179
240
  return response.body;
180
241
  }
181
242
  };
@@ -1,36 +1,78 @@
1
1
  import { Writable } from "node:stream";
2
2
  export class OutputStreamError extends Error {
3
3
  outputStream;
4
- constructor(outputStream, cause) {
4
+ diagnosticSummary;
5
+ constructor(outputStream, cause, diagnosticSummary) {
5
6
  super("结果未能完整返回。", { cause });
6
7
  this.outputStream = outputStream;
8
+ this.diagnosticSummary = diagnosticSummary;
7
9
  this.name = "OutputStreamError";
8
10
  }
9
11
  }
10
12
  /** Writes remain synchronous for command presenters; flush acknowledges delivery. */
11
13
  export function createTextOutput(stream, outputStream = "stdout") {
14
+ const startedAt = Date.now();
15
+ let writeCount = 0, attemptedBytes = 0, acknowledgedBytes = 0, pendingWrites = 0;
16
+ let failure;
17
+ function failed(cause, phase) {
18
+ // Snapshot the first failed write; later error presentation/flushes must not
19
+ // replace it with their own write counters or already-destroyed stream state.
20
+ return failure ??= new OutputStreamError(outputStream, cause, {
21
+ outputStream, outputWritePhase: phase, localProcessPid: process.pid, localParentPid: process.ppid,
22
+ runtimeNodeVersion: process.versions.node, outputElapsedMs: Math.max(0, Date.now() - startedAt),
23
+ outputWriteCount: writeCount, outputAttemptedBytes: attemptedBytes,
24
+ outputAcknowledgedBytes: acknowledgedBytes, outputPendingWrites: pendingWrites,
25
+ ...(stream instanceof Writable ? { outputDestroyed: stream.destroyed,
26
+ outputWritableEnded: stream.writableEnded, outputWritableFinished: stream.writableFinished,
27
+ outputBufferedBytes: stream.writableLength } : {}),
28
+ ...("isTTY" in stream && typeof stream.isTTY === "boolean" ? { outputIsTTY: stream.isTTY } : {})
29
+ });
30
+ }
12
31
  if (!(stream instanceof Writable))
13
32
  return {
14
- write: text => { try {
15
- stream.write(text);
16
- }
17
- catch (cause) {
18
- throw new OutputStreamError(outputStream, cause);
19
- } }, flush: async () => { }
33
+ write(text) {
34
+ if (failure)
35
+ throw failure;
36
+ writeCount++;
37
+ attemptedBytes += Buffer.byteLength(text);
38
+ pendingWrites++;
39
+ try {
40
+ stream.write(text);
41
+ acknowledgedBytes += Buffer.byteLength(text);
42
+ }
43
+ catch (cause) {
44
+ throw failed(cause, "write_sync");
45
+ }
46
+ finally {
47
+ pendingWrites--;
48
+ }
49
+ },
50
+ async flush() { if (failure)
51
+ throw failure; }
20
52
  };
21
53
  const pending = new Set();
22
- let failure;
23
- stream.on("error", error => { failure ??= error; });
54
+ stream.on("error", error => { failed(error, "stream_error"); });
24
55
  return {
25
56
  write(text) {
26
57
  if (failure)
27
- throw new OutputStreamError(outputStream, failure);
58
+ throw failure;
59
+ writeCount++;
60
+ attemptedBytes += Buffer.byteLength(text);
61
+ pendingWrites++;
28
62
  const writing = new Promise(resolve => {
29
63
  try {
30
- stream.write(text, error => { failure ??= error ?? undefined; resolve(); });
64
+ stream.write(text, error => {
65
+ if (error)
66
+ failed(error, "write_callback");
67
+ else
68
+ acknowledgedBytes += Buffer.byteLength(text);
69
+ pendingWrites--;
70
+ resolve();
71
+ });
31
72
  }
32
73
  catch (error) {
33
- failure ??= error instanceof Error ? error : new Error(String(error));
74
+ failed(error, "write_sync");
75
+ pendingWrites--;
34
76
  resolve();
35
77
  }
36
78
  });
@@ -40,7 +82,7 @@ export function createTextOutput(stream, outputStream = "stdout") {
40
82
  async flush() {
41
83
  await Promise.all(pending);
42
84
  if (failure)
43
- throw new OutputStreamError(outputStream, failure);
85
+ throw failure;
44
86
  }
45
87
  };
46
88
  }
@@ -75,6 +75,17 @@ export const insmindProduct = freezeProduct({
75
75
  name: "video.generate",
76
76
  title: "Video generation",
77
77
  description: "Generate videos with published video models using text and optional images, video, or audio."
78
- }
78
+ },
79
+ { "name": "image.edit", "title": "Image editing", "description": "Change a selected area or edit an image from instructions." },
80
+ { "name": "image.matting", "title": "Background removal", "description": "Separate original foreground pixels or reconstruct an occluded subject, returning a transparent PNG." },
81
+ { "name": "image.remove", "title": "Object removal", "description": "Remove selected or described content from an image." },
82
+ { "name": "image.enhance", "title": "Image enhancement", "description": "Upscale pixels or restore image details." },
83
+ { "name": "image.expand", "title": "Image expansion", "description": "Extend a canvas with explicit source placement." },
84
+ { "name": "image.text_edit", "title": "Image text editing", "description": "Replace specified text in an image." },
85
+ { "name": "image.ocr", "title": "Text recognition", "description": "Recognize text and its pixel coordinates." },
86
+ { "name": "image.layers", "title": "Image decomposition", "description": "Convert an image to an editable native template." },
87
+ { "name": "image.vectorize", "title": "Image vectorization", "description": "Convert a bitmap to vector SVG." },
88
+ { "name": "video.edit", "title": "Video editing", "description": "Edit a video using instructions and optional references." },
89
+ { "name": "video.enhance", "title": "Video enhancement", "description": "Upscale or restore a video." }
79
90
  ]
80
91
  });
@@ -1,12 +1,39 @@
1
1
  const flags = new Set(["bodyUsedAtReceipt", "bodyLockedAtReceipt", "bodyUsedBeforeRead",
2
- "bodyLockedBeforeRead", "reusedResponse", "contextIdPresent", "streamHadBytes"]);
2
+ "bodyLockedBeforeRead", "reusedResponse", "contextIdPresent", "streamHadBytes", "lockOwnerAlive",
3
+ "uriHasNonAscii", "uriHasWhitespace", "uriHasControlChars", "uriHasBackslash", "uriHasPercentEncoding",
4
+ "uriHasQuery", "uriHasFragment", "uriHasCredentials", "assetSourcePresent",
5
+ "outputDestroyed", "outputWritableEnded", "outputWritableFinished", "outputIsTTY"]);
3
6
  const counts = new Set(["messageCount", "invalidMessageCount", "systemErrorCount", "publicPartCount",
4
7
  "streamPayloadCount", "streamJsonValueCount"]);
5
8
  const localFileSteps = new Set(["directory_create", "directory_permissions", "directory_read", "stat", "parse", "validate", "open", "file_permissions", "read", "write", "sync", "close", "rename", "unlink"]);
6
9
  const inputReasons = new Set(["path_restricted", "not_regular_file", "format_missing", "media_type_mismatch", "file_read_failed",
7
10
  "json_read", "json_parse", "schema_validation", "invalid_task_id", "command_arguments", "model_required", "model_not_found",
8
11
  "model_tool_mismatch", "model_parameters", "tool_not_found", "invalid_asset_url", "commander.unknownOption",
9
- "commander.unknownCommand", "commander.missingArgument", "commander.excessArguments", "commander.help"]);
12
+ "commander.unknownCommand", "commander.missingArgument", "commander.excessArguments", "commander.help",
13
+ "invalid_file_uri", "identifier_control_character", "image_decode_failed", "image_request_failed", "image_redirect_failed", "image_read_failed"]);
14
+ const enums = Object.fromEntries(Object.entries({
15
+ inputRule: ["type", "format", "required", "additionalProperties", "enum", "const", "anyOf", "oneOf", "allOf", "not", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "minLength", "maxLength", "pattern", "minItems", "maxItems", "uniqueItems", "minProperties", "maxProperties", "contains", "if", "dependentRequired"],
16
+ inputValueType: ["null", "array", "object", "string", "number", "boolean", "undefined"],
17
+ uriScheme: ["file", "http", "https", "other", "none"], uriWindowsDrive: ["valid", "missing_colon", "none"],
18
+ uriIssue: ["control_character", "invalid_percent_encoding", "missing_scheme", "backslash", "whitespace", "non_ascii", "missing_host", "invalid_host", "file_authority_drive", "file_drive_separator", "file_uri_components", "other_format"],
19
+ downloadPhase: ["url_lookup"], assetType: ["image", "video", "audio", "font", "template", "file", "unknown"],
20
+ mediaPhase: ["request", "redirect", "read", "decode"], streamTerminalReason: ["eof", "error", "canceled"],
21
+ abortSource: ["caller", "request_timeout", "none"],
22
+ lockWaitScope: ["same_process", "cross_process"], lockWaitPhase: ["local_queue", "owner_files"],
23
+ lockOwnerAction: ["task_write", "task_update", "sls_queue", "analytics_device"],
24
+ lockContenderAction: ["task_write", "task_update", "sls_queue", "analytics_device"],
25
+ localFileRole: ["credentials", "task", "sls_queue", "analytics_device"],
26
+ workerPhase: ["spawn", "bootstrap", "before_started", "before_accepted", "ipc_send", "ipc_disconnect"],
27
+ quotaDecisionSource: ["cli_precheck"], quotaUnit: ["gaodou"], quotaLimitScope: ["account", "member_period"],
28
+ outputWritePhase: ["write_sync", "write_callback", "stream_error"],
29
+ hostPhase: ["started", "finished"],
30
+ hostReason: ["authenticated", "unauthenticated", "version", "timeout", "output_limit", "host_signal", "stdout_closed", "spawn_failure", "cli_exit", "invalid_response"]
31
+ }).map(([key, values]) => [key, new Set(values)]));
32
+ const nonnegativeIntegers = new Set(["streamFirstByteMs", "streamReceivedBytes", "lockWaitMs", "lockOwnerCount",
33
+ "lockOwnerPid", "lockContenderPid", "lockOwnerStartedAtMs", "lockOwnerAgeMs", "lockOwnerAcquiredAtMs", "lockOwnerHeldMs", "localProcessPid", "localParentPid", "workerPid", "downloadUrlCount", "mediaBytesRead", "requestTimeoutMs", "requestDurationMs",
34
+ "outputElapsedMs", "outputWriteCount", "outputAttemptedBytes", "outputAcknowledgedBytes", "outputPendingWrites", "outputBufferedBytes",
35
+ "hostElapsedMs", "hostTimeoutMs", "hostStartedAtMs", "hostProcessPid", "hostParentPid", "hostChildPid", "hostStdoutBytes", "hostStderrBytes"]);
36
+ const quotaNumbers = new Set(["quotaTotal", "quotaUsed", "quotaPending", "quotaMemberLimit", "quotaMemberUsed", "quotaAvailable", "quotaRequired"]);
10
37
  /** Fixed diagnostic facts, never arbitrary response fields or error messages. */
11
38
  export function safeFailureSummary(value) {
12
39
  if (!value || typeof value !== "object" || Array.isArray(value))
@@ -17,6 +44,30 @@ export function safeFailureSummary(value) {
17
44
  result[key] = field;
18
45
  if (counts.has(key) && typeof field === "number" && Number.isSafeInteger(field) && field >= 0 && field <= 100_000)
19
46
  result[key] = field;
47
+ if (nonnegativeIntegers.has(key) && typeof field === "number" && Number.isSafeInteger(field) && field >= 0)
48
+ result[key] = field;
49
+ if (key === "workerExitCode" && typeof field === "number" && Number.isSafeInteger(field) && field >= 0 && field <= 255)
50
+ result[key] = field;
51
+ if (key === "hostExitCode" && typeof field === "number" && Number.isSafeInteger(field) && field >= -2147483648 && field <= 4294967295)
52
+ result[key] = field;
53
+ if (key === "runtimeNodeVersion" && typeof field === "string" && /^\d{1,3}\.\d{1,3}\.\d{1,3}$/u.test(field))
54
+ result[key] = field;
55
+ if (key === "redirectCount" && typeof field === "number" && Number.isSafeInteger(field) && field >= 0 && field <= 5)
56
+ result[key] = field;
57
+ if (quotaNumbers.has(key) && typeof field === "number" && Number.isFinite(field) && Math.abs(field) <= Number.MAX_SAFE_INTEGER)
58
+ result[key] = field;
59
+ if (typeof field === "string" && Object.hasOwn(enums, key) && enums[key].has(field))
60
+ result[key] = field;
61
+ if (key === "inputField" && typeof field === "string" && field.length <= 256 && /^(?:\/[A-Za-z0-9_~.-]+)*$/u.test(field))
62
+ result[key] = field;
63
+ if (["assetFormat", "selectedRepositoryId", "actualRepositoryId", "requestId", "agentContextId", "localThreadId", "localMessageId"].includes(key) && typeof field === "string" && /^[A-Za-z0-9_.:-]{1,128}$/u.test(field))
64
+ result[key] = field;
65
+ if (key === "mediaHost" && typeof field === "string" && field.length <= 253 && /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)*[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/u.test(field))
66
+ result[key] = field;
67
+ if (["lockOwnerId", "lockContenderId"].includes(key) && typeof field === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/iu.test(field))
68
+ result[key] = field;
69
+ if (["workerSignal", "hostSignal", "hostChildSignal"].includes(key) && typeof field === "string" && /^(?:SIGABRT|SIGALRM|SIGBUS|SIGCHLD|SIGCONT|SIGFPE|SIGHUP|SIGILL|SIGINT|SIGKILL|SIGPIPE|SIGQUIT|SIGSEGV|SIGSTOP|SIGTERM|SIGTRAP|SIGTSTP|SIGTTIN|SIGTTOU|SIGUSR1|SIGUSR2|SIGWINCH)$/u.test(field))
70
+ result[key] = field;
20
71
  if (key === "inputReason" && typeof field === "string" && inputReasons.has(field))
21
72
  result[key] = field;
22
73
  if (key === "ssoPhase" && (field === "authorize" || field === "token"))
@@ -0,0 +1,95 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { homedir } from "node:os";
4
+ import { fileURLToPath } from "node:url";
5
+ import { hostTelemetryContext } from "./invocation.js";
6
+ import { safeFailureSummary } from "./failure-summary.js";
7
+ import { createSlsTelemetrySink } from "./sls-sink.js";
8
+ /** Private connector entry: no Commander graph, credential reads or business events. */
9
+ export async function runHostDiagnosticReporter(options) {
10
+ const env = options.env ?? process.env;
11
+ const context = hostTelemetryContext(env);
12
+ if (!context.host_invocation_id || !context.host_application || !context.invocation_purpose)
13
+ return;
14
+ const input = options.input ?? process.stdin;
15
+ const output = options.output ?? process.stdout;
16
+ if ("on" in output && typeof output.on === "function")
17
+ output.on("error", () => { });
18
+ const sink = createSlsTelemetrySink({ fetch: options.fetch ?? globalThis.fetch,
19
+ trackingUrl: options.trackingUrl ?? options.product.telemetryUrl,
20
+ directory: join(options.homeDirectory ?? homedir(), options.product.stateDirectory, "telemetry") });
21
+ const cliVersion = options.cliVersion ?? await packageVersion();
22
+ // A wrapper may be killed with stdin still open. This helper is always bounded;
23
+ // queued start evidence survives, and no permanent background process is added.
24
+ const timer = setTimeout(() => input.destroy(), 12_000);
25
+ let buffer = "", receivedBytes = 0, sequence = 0;
26
+ try {
27
+ for await (const chunk of input) {
28
+ receivedBytes += Buffer.byteLength(chunk);
29
+ if (receivedBytes > 16_384)
30
+ break;
31
+ buffer += String(chunk);
32
+ let newline;
33
+ while ((newline = buffer.indexOf("\n")) >= 0) {
34
+ const line = buffer.slice(0, newline);
35
+ buffer = buffer.slice(newline + 1);
36
+ if (Buffer.byteLength(line) > 4096)
37
+ return;
38
+ let value;
39
+ try {
40
+ value = JSON.parse(line);
41
+ }
42
+ catch {
43
+ return;
44
+ }
45
+ if (!value || typeof value !== "object" || Array.isArray(value))
46
+ return;
47
+ const raw = value;
48
+ const summary = raw.diagnostic_summary;
49
+ const facts = safeFailureSummary(summary && typeof summary === "object" && !Array.isArray(summary)
50
+ ? Object.fromEntries(Object.entries(summary).filter(([key]) => key.startsWith("host") || key === "runtimeNodeVersion" || key === "systemCode"))
51
+ : undefined);
52
+ if (facts?.hostPhase !== (sequence === 0 ? "started" : "finished"))
53
+ return;
54
+ if (facts.hostPhase === "finished" && !facts.hostReason)
55
+ return;
56
+ if (typeof raw.occurred_at_ms !== "number" || !Number.isSafeInteger(raw.occurred_at_ms) || raw.occurred_at_ms < 0)
57
+ return;
58
+ const event = { ...context, schema_version: "5", cli_name: options.product.commandName,
59
+ cli_version: cliVersion, env: env.CLI_TELEMETRY_ENV === "test" ? "test" : "production",
60
+ event_name: "host_diagnostic", process_role: "host_connector", trace_id: context.host_invocation_id,
61
+ record_seq: ++sequence, occurred_at_ms: raw.occurred_at_ms,
62
+ operation: context.invocation_purpose === "auth_status" ? "auth.status" : "version",
63
+ os: process.platform, arch: process.arch, node_major: Number(process.versions.node.split(".")[0]),
64
+ diagnostic_summary: facts };
65
+ // Acknowledge only AFTER durable enqueue, before the bounded network flush.
66
+ const accepted = await sink.enqueue([event]);
67
+ try {
68
+ output.write(`${JSON.stringify({ phase: facts.hostPhase, queued: accepted === true })}\n`);
69
+ }
70
+ catch { /* Host stdout can already be gone. */ }
71
+ if (sequence === 2)
72
+ return;
73
+ }
74
+ }
75
+ }
76
+ finally {
77
+ clearTimeout(timer);
78
+ input.destroy();
79
+ // Automated tests inspect their isolated queue; live acceptance unsets NODE_ENV.
80
+ if (env.NODE_ENV !== "test" && !env.VITEST)
81
+ await sink.send([]);
82
+ }
83
+ }
84
+ async function packageVersion() {
85
+ let directory = dirname(fileURLToPath(import.meta.url));
86
+ for (let depth = 0; depth < 5; depth++, directory = dirname(directory)) {
87
+ try {
88
+ const value = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
89
+ if ((value.name === "@gaoding/cli" || value.name === "@insmind/cli") && typeof value.version === "string")
90
+ return value.version;
91
+ }
92
+ catch { /* A broken installation must not alter connector business results. */ }
93
+ }
94
+ return "unknown";
95
+ }
@@ -1,5 +1,18 @@
1
1
  import { cleanDiagnostic, errorEvidence } from "./sanitize.js";
2
2
  import { isInterruption } from "../platform/interruption.js";
3
+ import { safeFailureSummary } from "./failure-summary.js";
4
+ /** Only the connector's explicit fixed metadata identifies a host invocation. */
5
+ export function hostTelemetryContext(env) {
6
+ return {
7
+ ...(["workbuddy", "qwenwork"].includes(env.CLI_HOST_APPLICATION ?? "")
8
+ ? { host_application: env.CLI_HOST_APPLICATION } : {}),
9
+ ...(["auth_status", "version_check"].includes(env.CLI_INVOCATION_PURPOSE ?? "")
10
+ ? { invocation_purpose: env.CLI_INVOCATION_PURPOSE } : {}),
11
+ ...(/^[a-f0-9]{32}$/u.test(env.CLI_HOST_INVOCATION_ID ?? "") ? { host_invocation_id: env.CLI_HOST_INVOCATION_ID } : {}),
12
+ ...(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u.test(env.CLI_HOST_CONNECTOR_VERSION ?? "")
13
+ && env.CLI_HOST_CONNECTOR_VERSION.length <= 32 ? { host_connector_version: env.CLI_HOST_CONNECTOR_VERSION } : {})
14
+ };
15
+ }
3
16
  const detailedStages = {
4
17
  "auth.login": new Set(["authorize", "wait", "identity", "bind"]),
5
18
  "org.switch": new Set(["list", "bind"]),
@@ -33,13 +46,14 @@ export function createTelemetryInvocation(options) {
33
46
  }
34
47
  function errorFields(error) {
35
48
  const c = classify(error);
49
+ const summary = { ...context.diagnostic_summary, ...c.diagnosticSummary };
36
50
  return { ...errorEvidence(error),
37
51
  ...(c.errorType === undefined ? {} : { error_type: c.errorType }),
38
52
  ...(c.errorCode === undefined ? {} : { error_code: c.errorCode }),
39
53
  ...(c.httpStatus === undefined ? {} : { http_status: c.httpStatus }),
40
54
  ...(c.remoteErrorCode === undefined ? {} : { remote_error_code: c.remoteErrorCode }),
41
55
  ...(c.remoteErrorBody === undefined ? {} : { remote_error_body: c.remoteErrorBody }),
42
- ...(c.diagnosticSummary === undefined ? {} : { diagnostic_summary: c.diagnosticSummary }),
56
+ ...(Object.keys(summary).length ? { diagnostic_summary: summary } : {}),
43
57
  ...(c.diagnosticReason === undefined ? {} : { diagnostic_reason: c.diagnosticReason }) };
44
58
  }
45
59
  function failureStage(error) {
@@ -76,6 +90,12 @@ export function createTelemetryInvocation(options) {
76
90
  useSignal(next) { signal = next; },
77
91
  annotate(annotation) {
78
92
  for (const [key, value] of Object.entries(annotation)) {
93
+ if (key === "diagnostic_summary") {
94
+ const safe = safeFailureSummary(value);
95
+ if (safe)
96
+ context.diagnostic_summary = { ...context.diagnostic_summary, ...safe };
97
+ continue;
98
+ }
79
99
  if (key === "warning_codes" && Array.isArray(value)) {
80
100
  context.warning_codes = [...new Set([...(context.warning_codes ?? []), ...value])].slice(0, 20);
81
101
  continue;
@@ -85,18 +105,19 @@ export function createTelemetryInvocation(options) {
85
105
  }
86
106
  },
87
107
  creationContext() {
88
- const { record_seq: _seq, occurred_at_ms: _time, parameters: _parameters, warning_codes: _warnings, invalid_model_count: _invalidModels, task_state_revision: _revision, task_state_write_confirmed: _written, sls_enqueue_failures: _queueFailures, sls_last_enqueue_error: _queueError, content_id: _content, task_id: _task, dify_task_id: _dify, result_state: _state, ...snapshot } = base();
108
+ const { record_seq: _seq, occurred_at_ms: _time, parameters: _parameters, warning_codes: _warnings, invalid_model_count: _invalidModels, diagnostic_summary: _diagnostics, task_state_revision: _revision, task_state_write_confirmed: _written, sls_enqueue_failures: _queueFailures, sls_last_enqueue_error: _queueError, sls_queue_size: _queueSize, sls_queue_oldest_age_ms: _oldestAge, sls_delivery_failures: _deliveryFailures, sls_last_delivery_result: _deliveryResult, sls_last_delivery_http_status: _deliveryStatus, sls_dropped_events: _droppedEvents, sls_last_drop_reason: _dropReason, content_id: _content, task_id: _task, dify_task_id: _dify, result_state: _state, ...snapshot } = base();
89
109
  return cleanDiagnostic({ ...snapshot, mode: "execute" });
90
110
  },
91
111
  async emit(event) { await publish(remember(event)); },
92
112
  taskFailure(error) {
93
113
  const c = classify(error);
114
+ const summary = { ...context.diagnostic_summary, ...c.diagnosticSummary };
94
115
  const failedAt = c.failureStage ?? failureStage(error);
95
116
  return { error_type: c.errorType ?? (error instanceof Error ? error.name : typeof error),
96
117
  ...(c.errorCode === undefined ? {} : { error_code: c.errorCode }),
97
118
  ...(c.httpStatus === undefined ? {} : { http_status: c.httpStatus }),
98
119
  ...(c.remoteErrorCode === undefined ? {} : { remote_error_code: c.remoteErrorCode }),
99
- ...(c.diagnosticSummary === undefined ? {} : { diagnostic_summary: c.diagnosticSummary }),
120
+ ...(Object.keys(summary).length ? { diagnostic_summary: summary } : {}),
100
121
  ...(c.diagnosticReason === undefined && c.outcome !== "interrupted" ? {} : { diagnostic_reason: c.diagnosticReason ?? "LOCAL_WAIT_INTERRUPTED" }),
101
122
  ...(failedAt === undefined ? {} : { failure_stage: failedAt }) };
102
123
  },
@@ -6,7 +6,7 @@ import { dirname, join } from "node:path";
6
6
  import { homedir } from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { gaodingProduct, insmindProduct } from "../product/config.js";
9
- import { createTelemetryInvocation } from "./invocation.js";
9
+ import { createTelemetryInvocation, hostTelemetryContext } from "./invocation.js";
10
10
  import { createSlsTelemetrySink } from "./sls-sink.js";
11
11
  /** Independent fallback for entrypoints which cannot construct the full runtime. */
12
12
  export async function reportProcessError(error, options) {
@@ -35,6 +35,7 @@ export async function reportProcessError(error, options) {
35
35
  runtime: { os: process.platform, arch: process.arch, nodeMajor: Number(process.versions.node.split(".")[0]) },
36
36
  classifyError: () => classification });
37
37
  telemetry.select({ operation: options.operation });
38
+ telemetry.annotate(hostTelemetryContext(process.env));
38
39
  const events = telemetry.finish(mapped.kind === "interrupted" ? { outcome: "interrupted", error } : {
39
40
  outcome: "failure", error, errorCode: mapped.failure.code, errorMessage: mapped.failure.message,
40
41
  ...(classification.httpStatus === undefined ? {} : { httpStatus: classification.httpStatus }),