@insmind/cli 1.9.0 → 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.
- package/dist/bin/insmind-cli.js +32 -25
- package/dist/bin/task-worker.js +4 -1
- package/dist/src/analytics/device.js +2 -2
- package/dist/src/bootstrap/create-cli.js +10 -8
- package/dist/src/bootstrap/create-runtime.js +29 -23
- package/dist/src/bootstrap/run-task-worker.js +7 -2
- package/dist/src/bootstrap/validators.js +15 -6
- package/dist/src/cli/action-binding.js +39 -0
- package/dist/src/cli/agent-commands.js +8 -12
- package/dist/src/cli/dam-commands.js +6 -5
- package/dist/src/cli/editor-commands.js +10 -5
- package/dist/src/cli/errors.js +60 -12
- package/dist/src/cli/host-input.js +34 -0
- package/dist/src/cli/model-commands.js +4 -3
- package/dist/src/cli/observed-errors.js +3 -1
- package/dist/src/cli/tool-commands.js +7 -9
- package/dist/src/contracts/creation-input.js +20 -0
- package/dist/src/features/agent/creative-agent-adapter.js +37 -11
- package/dist/src/features/agent/creative-protocol.js +21 -19
- package/dist/src/features/agent/creative-stream.js +54 -6
- package/dist/src/features/agent/result-reader.js +3 -1
- package/dist/src/features/agent/use-cases.js +6 -31
- package/dist/src/features/auth/access-policy.js +1 -3
- package/dist/src/features/auth/credential-store.js +6 -10
- package/dist/src/features/auth/sso-service.js +28 -10
- package/dist/src/features/auth/state.js +6 -0
- package/dist/src/features/auth/use-cases.js +91 -32
- package/dist/src/features/credits/use-cases.js +1 -1
- 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/file-downloader.js +2 -1
- package/dist/src/features/dam/input.js +23 -0
- package/dist/src/features/dam/use-cases.js +39 -29
- package/dist/src/features/editor/bridge-client.js +1 -1
- package/dist/src/features/editor/use-cases.js +6 -8
- package/dist/src/features/org/use-cases.js +3 -3
- package/dist/src/features/skill/installer.js +24 -22
- package/dist/src/features/task/store.js +31 -17
- package/dist/src/features/task/task-background.js +67 -19
- package/dist/src/features/task/use-cases.js +131 -88
- package/dist/src/features/tool/canvas-media.js +82 -27
- package/dist/src/features/tool/canvas-models.js +21 -4
- package/dist/src/features/tool/canvas-tool-adapter.js +29 -20
- package/dist/src/features/tool/canvas-video.js +2 -4
- package/dist/src/features/tool/dynamic-schema.js +32 -63
- package/dist/src/features/tool/matting-billing.js +38 -26
- package/dist/src/features/tool/mns-catalog-adapter.js +9 -2
- package/dist/src/features/tool/scene-catalog-adapter.js +0 -1
- package/dist/src/features/tool/tool-api-adapter.js +19 -16
- package/dist/src/features/tool/use-cases.js +24 -35
- package/dist/src/platform/file-lock.js +58 -15
- package/dist/src/platform/input-uri.js +105 -0
- package/dist/src/platform/json-input.js +1 -1
- 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 +24 -4
- package/dist/src/platform/schema-issues.js +18 -0
- package/dist/src/platform/signed-http-transport.js +95 -37
- 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 +107 -23
- package/dist/src/telemetry/process-errors.js +38 -4
- package/dist/src/telemetry/sls-sink.js +71 -26
- package/package.json +4 -4
- package/skills/insmind-cli/SKILL.md +1 -0
- package/skills/insmind-cli/references/editor.md +1 -1
- package/skills/insmind-cli/references/generation-constraints.md +3 -1
- package/skills/insmind-cli/references/tool.md +2 -3
|
@@ -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", "v6") });
|
|
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: "6", started_at_ms: raw.occurred_at_ms, command_kind: "technical", 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,19 @@
|
|
|
1
1
|
import { cleanDiagnostic, errorEvidence } from "./sanitize.js";
|
|
2
2
|
import { isInterruption } from "../platform/interruption.js";
|
|
3
|
+
import { safeFailureSummary } from "./failure-summary.js";
|
|
4
|
+
export function hostName(value) {
|
|
5
|
+
return typeof value === "string" && value.trim() ? value.trim().slice(0, 128) : undefined;
|
|
6
|
+
}
|
|
7
|
+
export function hostTelemetryContext(env) {
|
|
8
|
+
return {
|
|
9
|
+
host_application: hostName(env.CLI_HOST_APPLICATION) ?? "unknown",
|
|
10
|
+
...(["auth_status", "version_check"].includes(env.CLI_INVOCATION_PURPOSE ?? "")
|
|
11
|
+
? { invocation_purpose: env.CLI_INVOCATION_PURPOSE } : {}),
|
|
12
|
+
...(/^[a-f0-9]{32}$/u.test(env.CLI_HOST_INVOCATION_ID ?? "") ? { host_invocation_id: env.CLI_HOST_INVOCATION_ID } : {}),
|
|
13
|
+
...(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u.test(env.CLI_HOST_CONNECTOR_VERSION ?? "")
|
|
14
|
+
&& env.CLI_HOST_CONNECTOR_VERSION.length <= 32 ? { host_connector_version: env.CLI_HOST_CONNECTOR_VERSION } : {})
|
|
15
|
+
};
|
|
16
|
+
}
|
|
3
17
|
const detailedStages = {
|
|
4
18
|
"auth.login": new Set(["authorize", "wait", "identity", "bind"]),
|
|
5
19
|
"org.switch": new Set(["list", "bind"]),
|
|
@@ -12,34 +26,43 @@ export function createTelemetryInvocation(options) {
|
|
|
12
26
|
const traceId = options.traceIdFactory();
|
|
13
27
|
const startedAt = options.startedAt ?? options.now();
|
|
14
28
|
let definition;
|
|
29
|
+
let issued = false;
|
|
30
|
+
let nextStep = "request_sent";
|
|
15
31
|
let finished = false;
|
|
16
32
|
let signal;
|
|
17
33
|
let sequence = 0;
|
|
18
34
|
const context = {};
|
|
19
35
|
const events = [];
|
|
36
|
+
const steps = new Map();
|
|
20
37
|
const published = new Set();
|
|
21
38
|
const failures = [];
|
|
22
|
-
function
|
|
39
|
+
function identity() {
|
|
23
40
|
const mode = definition?.mode?.();
|
|
24
|
-
|
|
41
|
+
const creation = mode === "execute" && (definition?.operation === "agent.send" || definition?.operation === "tool.call");
|
|
42
|
+
return { host_application: context.host_application ?? "unknown", schema_version: "6", started_at_ms: startedAt, command_kind: creation ? "creation" : "technical", cli_name: options.cliName ?? "gd-cli",
|
|
25
43
|
env: options.env ?? "production", process_role: options.processRole ?? "cli",
|
|
26
|
-
trace_id: traceId,
|
|
44
|
+
trace_id: traceId,
|
|
27
45
|
operation: definition?.operation ?? "unknown", ...(mode ? { mode } : {}),
|
|
28
46
|
cli_version: options.cliVersion, os: options.runtime.os, arch: options.runtime.arch,
|
|
29
47
|
node_major: options.runtime.nodeMajor };
|
|
30
48
|
}
|
|
49
|
+
function base() {
|
|
50
|
+
const { parameters: _input, ...diagnostics } = context;
|
|
51
|
+
return { ...diagnostics, ...identity(), record_seq: ++sequence, occurred_at_ms: options.now() };
|
|
52
|
+
}
|
|
31
53
|
function classify(error) {
|
|
32
54
|
return isInterruption(error, signal) ? { outcome: "interrupted" } : options.classifyError(error);
|
|
33
55
|
}
|
|
34
56
|
function errorFields(error) {
|
|
35
57
|
const c = classify(error);
|
|
58
|
+
const summary = { ...context.diagnostic_summary, ...c.diagnosticSummary };
|
|
36
59
|
return { ...errorEvidence(error),
|
|
37
60
|
...(c.errorType === undefined ? {} : { error_type: c.errorType }),
|
|
38
61
|
...(c.errorCode === undefined ? {} : { error_code: c.errorCode }),
|
|
39
62
|
...(c.httpStatus === undefined ? {} : { http_status: c.httpStatus }),
|
|
40
63
|
...(c.remoteErrorCode === undefined ? {} : { remote_error_code: c.remoteErrorCode }),
|
|
41
64
|
...(c.remoteErrorBody === undefined ? {} : { remote_error_body: c.remoteErrorBody }),
|
|
42
|
-
...(
|
|
65
|
+
...(Object.keys(summary).length ? { diagnostic_summary: summary } : {}),
|
|
43
66
|
...(c.diagnosticReason === undefined ? {} : { diagnostic_reason: c.diagnosticReason }) };
|
|
44
67
|
}
|
|
45
68
|
function failureStage(error) {
|
|
@@ -52,17 +75,35 @@ export function createTelemetryInvocation(options) {
|
|
|
52
75
|
}
|
|
53
76
|
function remember(event) {
|
|
54
77
|
const safe = cleanDiagnostic(event);
|
|
78
|
+
if (safe.event_name === "command_step") {
|
|
79
|
+
const key = `${safe.trace_id}/${safe.step}`;
|
|
80
|
+
const first = steps.get(key);
|
|
81
|
+
if (first)
|
|
82
|
+
return first;
|
|
83
|
+
steps.set(key, safe);
|
|
84
|
+
}
|
|
55
85
|
events.push(safe);
|
|
56
86
|
return safe;
|
|
57
87
|
}
|
|
88
|
+
function observeStep(step) {
|
|
89
|
+
if (step === "request_sent")
|
|
90
|
+
nextStep = "result_received";
|
|
91
|
+
if (step === "result_received")
|
|
92
|
+
nextStep = "delivered";
|
|
93
|
+
if (step === "delivered")
|
|
94
|
+
nextStep = undefined;
|
|
95
|
+
}
|
|
58
96
|
async function publish(event) {
|
|
59
97
|
if (!options.onEvent)
|
|
60
|
-
return;
|
|
98
|
+
return false;
|
|
61
99
|
try {
|
|
62
|
-
if (await options.onEvent(event) !== false)
|
|
100
|
+
if (await options.onEvent(event) !== false) {
|
|
63
101
|
published.add(event);
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
64
104
|
}
|
|
65
105
|
catch { /* Logging cannot fail the operation. */ }
|
|
106
|
+
return false;
|
|
66
107
|
}
|
|
67
108
|
return {
|
|
68
109
|
traceId,
|
|
@@ -72,10 +113,28 @@ export function createTelemetryInvocation(options) {
|
|
|
72
113
|
&& definition.mode?.() === "execute";
|
|
73
114
|
return `00-${traceId}-${options.spanIdFactory()}-${paid ? "01" : "00"}`;
|
|
74
115
|
},
|
|
75
|
-
select(next) {
|
|
116
|
+
select(next) { if (!issued)
|
|
117
|
+
definition = next; },
|
|
118
|
+
async issue(next) {
|
|
119
|
+
if (issued)
|
|
120
|
+
return;
|
|
121
|
+
issued = true;
|
|
122
|
+
definition = next;
|
|
123
|
+
await publish(remember({ ...base(), occurred_at_ms: startedAt, event_name: "command_step", step: "issued", outcome: "success" }));
|
|
124
|
+
},
|
|
125
|
+
observeHost(value) {
|
|
126
|
+
if (!context.host_application || context.host_application === "unknown")
|
|
127
|
+
context.host_application = hostName(value) ?? "unknown";
|
|
128
|
+
},
|
|
76
129
|
useSignal(next) { signal = next; },
|
|
77
130
|
annotate(annotation) {
|
|
78
131
|
for (const [key, value] of Object.entries(annotation)) {
|
|
132
|
+
if (key === "diagnostic_summary") {
|
|
133
|
+
const safe = safeFailureSummary(value);
|
|
134
|
+
if (safe)
|
|
135
|
+
context.diagnostic_summary = { ...context.diagnostic_summary, ...safe };
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
79
138
|
if (key === "warning_codes" && Array.isArray(value)) {
|
|
80
139
|
context.warning_codes = [...new Set([...(context.warning_codes ?? []), ...value])].slice(0, 20);
|
|
81
140
|
continue;
|
|
@@ -85,18 +144,32 @@ export function createTelemetryInvocation(options) {
|
|
|
85
144
|
}
|
|
86
145
|
},
|
|
87
146
|
creationContext() {
|
|
88
|
-
|
|
89
|
-
|
|
147
|
+
// Background work and later queries retain the originating invocation's dimensions.
|
|
148
|
+
const snapshot = identity();
|
|
149
|
+
const keys = ["host_invocation_id", "host_connector_version", "installation_owner", "invocation_purpose",
|
|
150
|
+
"account_id", "organization_id", "tool_name", "model_id", "content_id", "task_id", "dify_task_id",
|
|
151
|
+
"cli_task_id", "execution_mode", "parameters"];
|
|
152
|
+
for (const key of keys) {
|
|
153
|
+
if (context[key] !== undefined)
|
|
154
|
+
Object.assign(snapshot, { [key]: context[key] });
|
|
155
|
+
}
|
|
156
|
+
return cleanDiagnostic(snapshot);
|
|
157
|
+
},
|
|
158
|
+
observeStep,
|
|
159
|
+
async emit(event) {
|
|
160
|
+
if (event.trace_id === traceId || event.trace_id === context.creation_trace_id)
|
|
161
|
+
observeStep(event.step);
|
|
162
|
+
return publish(remember(event));
|
|
90
163
|
},
|
|
91
|
-
async emit(event) { await publish(remember(event)); },
|
|
92
164
|
taskFailure(error) {
|
|
93
165
|
const c = classify(error);
|
|
166
|
+
const summary = { ...context.diagnostic_summary, ...c.diagnosticSummary };
|
|
94
167
|
const failedAt = c.failureStage ?? failureStage(error);
|
|
95
168
|
return { error_type: c.errorType ?? (error instanceof Error ? error.name : typeof error),
|
|
96
169
|
...(c.errorCode === undefined ? {} : { error_code: c.errorCode }),
|
|
97
170
|
...(c.httpStatus === undefined ? {} : { http_status: c.httpStatus }),
|
|
98
171
|
...(c.remoteErrorCode === undefined ? {} : { remote_error_code: c.remoteErrorCode }),
|
|
99
|
-
...(
|
|
172
|
+
...(Object.keys(summary).length ? { diagnostic_summary: summary } : {}),
|
|
100
173
|
...(c.diagnosticReason === undefined && c.outcome !== "interrupted" ? {} : { diagnostic_reason: c.diagnosticReason ?? "LOCAL_WAIT_INTERRUPTED" }),
|
|
101
174
|
...(failedAt === undefined ? {} : { failure_stage: failedAt }) };
|
|
102
175
|
},
|
|
@@ -124,18 +197,29 @@ export function createTelemetryInvocation(options) {
|
|
|
124
197
|
if (finished || !definition)
|
|
125
198
|
return [];
|
|
126
199
|
finished = true;
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
...(completion.
|
|
137
|
-
...(
|
|
138
|
-
|
|
200
|
+
const last = base();
|
|
201
|
+
if (completion.outcome === "success" && issued && last.command_kind === "technical") {
|
|
202
|
+
remember({ ...last, event_name: "command_step", step: "delivered", outcome: "success",
|
|
203
|
+
...(context.parameters ? { parameters: context.parameters } : {}) });
|
|
204
|
+
}
|
|
205
|
+
else if (completion.outcome !== "success" || !issued) {
|
|
206
|
+
const failedStep = last.command_kind === "technical" ? "delivered" : nextStep;
|
|
207
|
+
const stage = completion.outcome === "success" ? "process" : classify(completion.error).failureStage ?? failureStage(completion.error) ?? "command";
|
|
208
|
+
remember({ ...last, event_name: "stage_finished", stage, outcome: completion.outcome,
|
|
209
|
+
...(completion.outcome !== "success" && failedStep ? { failed_step: failedStep } : {}),
|
|
210
|
+
...(context.parameters && (!issued || last.command_kind === "technical") ? { parameters: context.parameters } : {}),
|
|
211
|
+
duration_ms: Math.max(0, options.now() - startedAt),
|
|
212
|
+
...(completion.outcome === "success" ? {} : {
|
|
213
|
+
failure_stage: classify(completion.error).failureStage ?? failureStage(completion.error) ?? "unknown"
|
|
214
|
+
}),
|
|
215
|
+
...(completion.outcome === "failure" ? errorFields(completion.error) : completion.outcome === "interrupted" && completion.error !== undefined ? errorEvidence(completion.error) : {}),
|
|
216
|
+
...(completion.outcome === "failure" ? {
|
|
217
|
+
error_code: completion.errorCode, error_message: completion.errorMessage,
|
|
218
|
+
...(completion.httpStatus === undefined ? {} : { http_status: completion.httpStatus }),
|
|
219
|
+
...(completion.remoteErrorCode === undefined ? {} : { remote_error_code: completion.remoteErrorCode }),
|
|
220
|
+
...(completion.remoteErrorBody === undefined ? {} : { remote_error_body: completion.remoteErrorBody })
|
|
221
|
+
} : {}) });
|
|
222
|
+
}
|
|
139
223
|
return events.filter(event => !published.has(event));
|
|
140
224
|
}
|
|
141
225
|
};
|
|
@@ -1,13 +1,43 @@
|
|
|
1
1
|
import { classifyTelemetryError, mapCliError } from "../cli/errors.js";
|
|
2
2
|
import { isInterruption } from "../platform/interruption.js";
|
|
3
3
|
import { randomBytes } from "node:crypto";
|
|
4
|
-
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
5
5
|
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
|
+
// The CLI module graph may not be loadable. Use packaged operation names only,
|
|
12
|
+
// so a user-supplied positional argument can never become an SLS operation name.
|
|
13
|
+
async function bootstrapDefinition(argv) {
|
|
14
|
+
const names = new Set(["agent.send", "tool.call", "editor.apply", "auth.login", "auth.logout", "org.switch", "credits", "update"]);
|
|
15
|
+
const contracts = new URL("../../../contracts/operations/", import.meta.url);
|
|
16
|
+
for (const name of await readdir(contracts).catch(() => []))
|
|
17
|
+
names.add(name);
|
|
18
|
+
const path = [];
|
|
19
|
+
let mode = "execute";
|
|
20
|
+
for (let i = 0; i < argv.length; i++) {
|
|
21
|
+
const token = argv[i];
|
|
22
|
+
if (token === "--")
|
|
23
|
+
break;
|
|
24
|
+
if (token === "--input" || token === "--locale") {
|
|
25
|
+
i++;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (token === "--help" || token === "-h")
|
|
29
|
+
mode = "help";
|
|
30
|
+
else if (token === "--version" || token === "-V")
|
|
31
|
+
mode = "version";
|
|
32
|
+
else if (token === "--schema" && mode === "execute")
|
|
33
|
+
mode = "schema";
|
|
34
|
+
else if (!token.startsWith("-") && !names.has(path.join(".")) && path.length < 3)
|
|
35
|
+
path.push(token);
|
|
36
|
+
}
|
|
37
|
+
const name = path.join(".");
|
|
38
|
+
const operation = mode === "version" ? "version" : names.has(name) ? name : !name && mode === "help" ? "help" : "bootstrap";
|
|
39
|
+
return { operation, mode: () => mode };
|
|
40
|
+
}
|
|
11
41
|
/** Independent fallback for entrypoints which cannot construct the full runtime. */
|
|
12
42
|
export async function reportProcessError(error, options) {
|
|
13
43
|
try {
|
|
@@ -34,7 +64,11 @@ export async function reportProcessError(error, options) {
|
|
|
34
64
|
traceIdFactory: () => options.traceId ?? randomBytes(16).toString("hex"), spanIdFactory: () => randomBytes(8).toString("hex"),
|
|
35
65
|
runtime: { os: process.platform, arch: process.arch, nodeMajor: Number(process.versions.node.split(".")[0]) },
|
|
36
66
|
classifyError: () => classification });
|
|
37
|
-
|
|
67
|
+
const definition = options.argv ? await bootstrapDefinition(options.argv) : { operation: options.operation };
|
|
68
|
+
telemetry.select(definition);
|
|
69
|
+
telemetry.annotate(hostTelemetryContext(process.env));
|
|
70
|
+
if ((options.processRole ?? "cli") === "cli")
|
|
71
|
+
await telemetry.issue(definition);
|
|
38
72
|
const events = telemetry.finish(mapped.kind === "interrupted" ? { outcome: "interrupted", error } : {
|
|
39
73
|
outcome: "failure", error, errorCode: mapped.failure.code, errorMessage: mapped.failure.message,
|
|
40
74
|
...(classification.httpStatus === undefined ? {} : { httpStatus: classification.httpStatus }),
|
|
@@ -42,7 +76,7 @@ export async function reportProcessError(error, options) {
|
|
|
42
76
|
...(classification.remoteErrorBody === undefined ? {} : { remoteErrorBody: classification.remoteErrorBody })
|
|
43
77
|
});
|
|
44
78
|
const sink = createSlsTelemetrySink({ fetch: globalThis.fetch, trackingUrl: options.trackingUrl ?? product.telemetryUrl,
|
|
45
|
-
directory: join(options.homeDirectory ?? homedir(), product.stateDirectory, "telemetry") });
|
|
79
|
+
directory: join(options.homeDirectory ?? homedir(), product.stateDirectory, "telemetry", "v6") });
|
|
46
80
|
// Automated process tests persist to their temporary home, without external traffic.
|
|
47
81
|
if (process.env.NODE_ENV === "test" || process.env.VITEST)
|
|
48
82
|
await sink.enqueue?.(events);
|