@insmind/cli 1.9.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.
- package/dist/bin/insmind-cli.js +31 -24
- package/dist/bin/task-worker.js +4 -1
- package/dist/src/analytics/device.js +2 -2
- package/dist/src/bootstrap/create-cli.js +7 -0
- package/dist/src/bootstrap/create-runtime.js +3 -7
- package/dist/src/bootstrap/run-task-worker.js +5 -1
- package/dist/src/bootstrap/validators.js +11 -4
- package/dist/src/cli/dam-commands.js +3 -3
- package/dist/src/cli/errors.js +60 -12
- package/dist/src/cli/observed-errors.js +3 -1
- package/dist/src/features/agent/creative-agent-adapter.js +37 -11
- package/dist/src/features/agent/creative-protocol.js +9 -5
- package/dist/src/features/agent/creative-stream.js +54 -6
- package/dist/src/features/agent/result-reader.js +3 -1
- package/dist/src/features/auth/credential-store.js +6 -10
- package/dist/src/features/auth/sso-service.js +22 -6
- package/dist/src/features/auth/state.js +6 -0
- package/dist/src/features/auth/use-cases.js +90 -32
- package/dist/src/features/dam/asset-projection.js +10 -1
- package/dist/src/features/dam/dam-api-adapter.js +30 -15
- package/dist/src/features/dam/input.js +23 -0
- package/dist/src/features/dam/use-cases.js +32 -22
- package/dist/src/features/task/store.js +5 -5
- package/dist/src/features/task/task-background.js +67 -19
- package/dist/src/features/task/use-cases.js +34 -6
- package/dist/src/features/tool/canvas-media.js +82 -27
- package/dist/src/features/tool/dynamic-schema.js +8 -4
- package/dist/src/features/tool/matting-billing.js +38 -26
- package/dist/src/features/tool/tool-api-adapter.js +17 -14
- package/dist/src/platform/file-lock.js +58 -15
- package/dist/src/platform/input-uri.js +105 -0
- package/dist/src/platform/local-json-file.js +7 -4
- package/dist/src/platform/remote-error-evidence.js +23 -1
- package/dist/src/platform/safe-upload-file.js +18 -4
- package/dist/src/platform/schema-issues.js +18 -0
- package/dist/src/platform/signed-http-transport.js +77 -16
- package/dist/src/platform/text-output.js +55 -13
- package/dist/src/telemetry/failure-summary.js +53 -2
- package/dist/src/telemetry/host-diagnostics.js +95 -0
- package/dist/src/telemetry/invocation.js +24 -3
- package/dist/src/telemetry/process-errors.js +2 -1
- package/dist/src/telemetry/sls-sink.js +66 -18
- package/package.json +4 -4
|
@@ -1,36 +1,78 @@
|
|
|
1
1
|
import { Writable } from "node:stream";
|
|
2
2
|
export class OutputStreamError extends Error {
|
|
3
3
|
outputStream;
|
|
4
|
-
|
|
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
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
|
|
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
|
|
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 => {
|
|
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
|
-
|
|
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
|
|
85
|
+
throw failure;
|
|
44
86
|
}
|
|
45
87
|
};
|
|
46
88
|
}
|
|
@@ -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
|
-
...(
|
|
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
|
-
...(
|
|
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 }),
|
|
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { readdir, readFile, unlink, mkdir, chmod } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { cleanDiagnostic } from "./sanitize.js";
|
|
5
|
+
import { safeFailureSummary } from "./failure-summary.js";
|
|
5
6
|
import { createLocalJsonFile } from "../platform/local-json-file.js";
|
|
6
7
|
import { withFileLock } from "../platform/file-lock.js";
|
|
7
8
|
const TTL = 7 * 86_400_000;
|
|
@@ -17,6 +18,13 @@ export function eventKey(event) {
|
|
|
17
18
|
}
|
|
18
19
|
export function wireEvent(event) {
|
|
19
20
|
const safe = cleanDiagnostic(event);
|
|
21
|
+
if ("diagnostic_summary" in safe) {
|
|
22
|
+
const summary = safeFailureSummary(safe.diagnostic_summary);
|
|
23
|
+
if (summary)
|
|
24
|
+
safe.diagnostic_summary = summary;
|
|
25
|
+
else
|
|
26
|
+
delete safe.diagnostic_summary;
|
|
27
|
+
}
|
|
20
28
|
const wire = {};
|
|
21
29
|
for (const [key, value] of Object.entries(safe)) {
|
|
22
30
|
if (value !== undefined)
|
|
@@ -40,8 +48,12 @@ export function wireEvent(event) {
|
|
|
40
48
|
break;
|
|
41
49
|
}
|
|
42
50
|
// Keep the envelope valid even for unexpectedly large identity or adapter fields.
|
|
43
|
-
for (const [key, value] of Object.entries(wire))
|
|
44
|
-
|
|
51
|
+
for (const [key, value] of Object.entries(wire)) {
|
|
52
|
+
// The bounded summary is structured JSON and contains the primary
|
|
53
|
+
// correlation evidence. Slicing it would make every field unreadable.
|
|
54
|
+
if (key !== "diagnostic_summary")
|
|
55
|
+
wire[key] = utf8Prefix(value, 1024);
|
|
56
|
+
}
|
|
45
57
|
}
|
|
46
58
|
return wire;
|
|
47
59
|
}
|
|
@@ -62,10 +74,13 @@ export function createSlsTelemetrySink(options) {
|
|
|
62
74
|
let writes = Promise.resolve();
|
|
63
75
|
let enqueueFailures = 0;
|
|
64
76
|
let lastEnqueueError;
|
|
65
|
-
|
|
77
|
+
let status = { count: 0, delivery_failures: 0 };
|
|
78
|
+
let healthReady = false;
|
|
79
|
+
const statusFile = () => createLocalJsonFile({ directory: options.directory, filename: "delivery-status.json", role: "sls_queue" });
|
|
80
|
+
const file = (id) => createLocalJsonFile({ directory: options.directory, filename: `${id}.json`, role: "sls_queue" });
|
|
66
81
|
let exitDeadline = Infinity;
|
|
67
82
|
const locked = (run, deadline) => options.directory
|
|
68
|
-
? withFileLock(join(options.directory, ".lock"), run, { deadline: Math.min(deadline ?? Infinity, exitDeadline) }) : run();
|
|
83
|
+
? withFileLock(join(options.directory, ".lock"), run, { deadline: Math.min(deadline ?? Infinity, exitDeadline), action: "sls_queue" }) : run();
|
|
69
84
|
function checkBudget(deadline) {
|
|
70
85
|
if (Date.now() >= deadline)
|
|
71
86
|
throw new Error("Telemetry delivery budget exhausted.");
|
|
@@ -76,6 +91,22 @@ export function createSlsTelemetrySink(options) {
|
|
|
76
91
|
entries.clear();
|
|
77
92
|
await mkdir(options.directory, { recursive: true, mode: 0o700 });
|
|
78
93
|
await chmod(options.directory, 0o700);
|
|
94
|
+
let rawStatus;
|
|
95
|
+
try {
|
|
96
|
+
rawStatus = JSON.parse(await statusFile().readText() ?? "{}");
|
|
97
|
+
}
|
|
98
|
+
catch { /* A malformed health file must not prevent replaying intact events. */ }
|
|
99
|
+
if (rawStatus && typeof rawStatus === "object" && !Array.isArray(rawStatus)) {
|
|
100
|
+
const value = rawStatus;
|
|
101
|
+
const count = (key) => typeof value[key] === "number" && Number.isSafeInteger(value[key]) && value[key] >= 0 ? value[key] : 0;
|
|
102
|
+
status = { count: count("count"), delivery_failures: count("delivery_failures"),
|
|
103
|
+
...(["interrupted_write", "corrupt", "expired", "capacity", "http_rejected"].includes(String(value.reason)) ? { reason: value.reason }
|
|
104
|
+
: /^http_4\d\d$/u.test(String(value.reason)) ? { reason: "http_rejected" } : {}),
|
|
105
|
+
...(["accepted", "http_rejected", "http_retryable", "network_error"].includes(String(value.result)) ? { result: value.result } : {}),
|
|
106
|
+
...(typeof value.http_status === "number" && value.http_status >= 100 && value.http_status <= 599 ? { http_status: value.http_status } : {}),
|
|
107
|
+
...(count("first_at_ms") ? { first_at_ms: count("first_at_ms") } : {}),
|
|
108
|
+
...(count("last_at_ms") ? { last_at_ms: count("last_at_ms") } : {}) };
|
|
109
|
+
}
|
|
79
110
|
for (const name of await readdir(options.directory)) {
|
|
80
111
|
checkBudget(deadline);
|
|
81
112
|
// All writers hold the same lock, so remaining atomic-write temporaries are orphaned.
|
|
@@ -99,18 +130,16 @@ export function createSlsTelemetrySink(options) {
|
|
|
99
130
|
await dropped("corrupt", 1);
|
|
100
131
|
}
|
|
101
132
|
}
|
|
133
|
+
healthReady = true;
|
|
134
|
+
}
|
|
135
|
+
async function saveStatus() {
|
|
136
|
+
// Health recording must never stop the original event acknowledgement/backoff path.
|
|
137
|
+
if (options.directory)
|
|
138
|
+
await statusFile().writeTextAtomically(JSON.stringify(status)).catch(() => undefined);
|
|
102
139
|
}
|
|
103
140
|
async function dropped(reason, count) {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const status = createLocalJsonFile({ directory: options.directory, filename: "delivery-status.json" });
|
|
107
|
-
let prior = {};
|
|
108
|
-
try {
|
|
109
|
-
prior = JSON.parse(await status.readText() ?? "{}");
|
|
110
|
-
}
|
|
111
|
-
catch { /* Replace corrupt diagnostic status. */ }
|
|
112
|
-
await status.writeTextAtomically(JSON.stringify({ count: (prior.count ?? 0) + count,
|
|
113
|
-
first_at_ms: prior.first_at_ms ?? now(), last_at_ms: now(), reason }));
|
|
141
|
+
status = { ...status, count: status.count + count, first_at_ms: status.first_at_ms ?? now(), last_at_ms: now(), reason };
|
|
142
|
+
await saveStatus();
|
|
114
143
|
}
|
|
115
144
|
async function remove(id) {
|
|
116
145
|
entries.delete(id);
|
|
@@ -132,7 +161,7 @@ export function createSlsTelemetrySink(options) {
|
|
|
132
161
|
}
|
|
133
162
|
let size = [...entries.values()].reduce((sum, e) => sum + Buffer.byteLength(JSON.stringify(e)), 0);
|
|
134
163
|
const priority = (e) => e.event.event_name === "task_state" || e.event.event_name === "request_sent" || e.event.event_name === "result_ready" ? 2
|
|
135
|
-
: "outcome" in e.event && e.event.outcome !== "success" ? 1 : 0;
|
|
164
|
+
: e.event.event_name === "host_diagnostic" || "outcome" in e.event && e.event.outcome !== "success" ? 1 : 0;
|
|
136
165
|
for (const [id, entry] of [...entries].sort((a, b) => priority(a[1]) - priority(b[1]) || a[1].queuedAt - b[1].queuedAt)) {
|
|
137
166
|
checkBudget(deadline);
|
|
138
167
|
if (size <= (options.maxBytes ?? CAPACITY))
|
|
@@ -208,6 +237,11 @@ export function createSlsTelemetrySink(options) {
|
|
|
208
237
|
return; // Original records remain safe for at-least-once replay.
|
|
209
238
|
await locked(async () => {
|
|
210
239
|
await load(deadline);
|
|
240
|
+
status = { ...status, delivery_failures: status.delivery_failures + (accepted ? 0 : 1),
|
|
241
|
+
result: accepted ? "accepted" : rejected ? "http_rejected" : response ? "http_retryable" : "network_error",
|
|
242
|
+
...(response ? { http_status: response.status } : {}) };
|
|
243
|
+
if (!response)
|
|
244
|
+
delete status.http_status;
|
|
211
245
|
for (const [id, original] of batch) {
|
|
212
246
|
checkBudget(deadline);
|
|
213
247
|
const entry = entries.get(id);
|
|
@@ -220,7 +254,9 @@ export function createSlsTelemetrySink(options) {
|
|
|
220
254
|
nextAttempt: now() + Math.max(retryAfter, attempt === 0 ? 0 : Math.min(60_000, 1000 * 2 ** Math.min(6, original.attempts))) });
|
|
221
255
|
}
|
|
222
256
|
if (rejected)
|
|
223
|
-
await dropped(
|
|
257
|
+
await dropped("http_rejected", batch.length);
|
|
258
|
+
else
|
|
259
|
+
await saveStatus();
|
|
224
260
|
}, deadline);
|
|
225
261
|
if (!accepted && (retryAfter > 0 || rejected))
|
|
226
262
|
return;
|
|
@@ -231,9 +267,21 @@ export function createSlsTelemetrySink(options) {
|
|
|
231
267
|
return sending;
|
|
232
268
|
}
|
|
233
269
|
return { enqueue,
|
|
234
|
-
|
|
270
|
+
async refreshDiagnostics() {
|
|
271
|
+
// Read persisted facts without triggering an extra send or adding business events.
|
|
272
|
+
const deadline = Date.now() + 100;
|
|
273
|
+
await writes;
|
|
274
|
+
await locked(() => load(deadline), deadline).catch(() => undefined);
|
|
275
|
+
},
|
|
276
|
+
// The final flush is observable by a later invocation, never retroactively on this event.
|
|
235
277
|
diagnostics: () => ({ sls_enqueue_failures: enqueueFailures,
|
|
236
|
-
...(lastEnqueueError ? { sls_last_enqueue_error: lastEnqueueError } : {})
|
|
278
|
+
...(lastEnqueueError ? { sls_last_enqueue_error: lastEnqueueError } : {}),
|
|
279
|
+
...(healthReady ? { sls_queue_size: entries.size,
|
|
280
|
+
...(entries.size ? { sls_queue_oldest_age_ms: Math.max(0, now() - Math.min(...[...entries.values()].map(entry => entry.queuedAt))) } : {}),
|
|
281
|
+
sls_delivery_failures: status.delivery_failures, sls_dropped_events: status.count,
|
|
282
|
+
...(status.result ? { sls_last_delivery_result: status.result } : {}),
|
|
283
|
+
...(status.http_status ? { sls_last_delivery_http_status: status.http_status } : {}),
|
|
284
|
+
...(status.reason ? { sls_last_drop_reason: status.reason } : {}) } : {}) }),
|
|
237
285
|
async send(events) {
|
|
238
286
|
const deadline = exitDeadline = Date.now() + BUDGET;
|
|
239
287
|
await enqueue(events, deadline);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@insmind/cli",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.1",
|
|
4
4
|
"description": "insMind command-line interface for agents and people.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -47,8 +47,8 @@
|
|
|
47
47
|
"@gaoding/cli": "workspace:*"
|
|
48
48
|
},
|
|
49
49
|
"gaodingRelease": {
|
|
50
|
-
"sourceCommit": "
|
|
51
|
-
"pipelineId": "
|
|
52
|
-
"pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/
|
|
50
|
+
"sourceCommit": "ad14b59e9789e8e8b7af7b7e38916d920ee0e646",
|
|
51
|
+
"pipelineId": "238371",
|
|
52
|
+
"pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/238371"
|
|
53
53
|
}
|
|
54
54
|
}
|