@insmind/cli 1.3.1 → 1.4.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 (33) hide show
  1. package/dist/bin/agent-worker.js +13 -1
  2. package/dist/bin/insmind-cli.js +7 -0
  3. package/dist/bin/postinstall.js +11 -2
  4. package/dist/src/bootstrap/create-cli.js +15 -7
  5. package/dist/src/bootstrap/create-runtime.js +73 -35
  6. package/dist/src/bootstrap/run-agent-worker.js +12 -1
  7. package/dist/src/cli/action-binding.js +1 -2
  8. package/dist/src/cli/errors.js +5 -3
  9. package/dist/src/cli/task-commands.js +3 -2
  10. package/dist/src/features/agent/creative-agent-adapter.js +1 -0
  11. package/dist/src/features/agent/creative-protocol.js +4 -2
  12. package/dist/src/features/auth/access-policy.js +8 -0
  13. package/dist/src/features/auth/sso-service.js +76 -26
  14. package/dist/src/features/auth/use-cases.js +1 -1
  15. package/dist/src/features/dam/file-downloader.js +6 -6
  16. package/dist/src/features/dam/object-storage.js +6 -4
  17. package/dist/src/features/editor/bridge-process.js +9 -3
  18. package/dist/src/features/editor/bridge-server.js +4 -2
  19. package/dist/src/features/org/use-cases.js +8 -3
  20. package/dist/src/features/task/store.js +34 -2
  21. package/dist/src/features/task/use-cases.js +71 -6
  22. package/dist/src/features/tool/tool-api-adapter.js +1 -0
  23. package/dist/src/features/update/update-notification.js +4 -2
  24. package/dist/src/platform/file-lock.js +68 -0
  25. package/dist/src/platform/redact.js +1 -1
  26. package/dist/src/platform/safe-upload-file.js +3 -3
  27. package/dist/src/platform/signed-http-transport.js +23 -9
  28. package/dist/src/telemetry/invocation.js +74 -122
  29. package/dist/src/telemetry/process-errors.js +43 -0
  30. package/dist/src/telemetry/sanitize.js +72 -0
  31. package/dist/src/telemetry/sls-sink.js +209 -22
  32. package/package.json +4 -4
  33. package/skills/insmind-cli/references/creation.md +12 -0
@@ -36,7 +36,7 @@ export function redactSensitiveText(value) {
36
36
  return value
37
37
  .replace(/(authorization\s*:\s*bearer\s+)[^\s,;]+/gi, `$1${REDACTED}`)
38
38
  .replace(/(cookie\s*:\s*)[^\r\n]+/gi, `$1${REDACTED}`)
39
- .replace(/\b(ak|sk|access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|auth[_-]?key|token|access[_-]?token|refresh[_-]?token|security[_-]?token|sts[_-]?token|signature|authorize[_-]?code|authorization[_-]?code|device[_-]?code|org[_-]?id|content[_-]?id|dify[_-]?task[_-]?id|task[_-]?id)\s*[:=]\s*[^\s,;}&]+/gi, `$1=${REDACTED}`);
39
+ .replace(/\b(ak|sk|access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|auth[_-]?key|token|access[_-]?token|refresh[_-]?token|security[_-]?token|sts[_-]?token|signature|authorize[_-]?code|authorization[_-]?code|device[_-]?code|org[_-]?id|content[_-]?id|dify[_-]?task[_-]?id|task[_-]?id)\s*[:=]\s*(?:\[REDACTED\]|[^\s,;}&"'\]]+)/gi, `$1=${REDACTED}`);
40
40
  }
41
41
  function redactValue(value, seen) {
42
42
  if (typeof value === "string")
@@ -2,8 +2,8 @@ import { open, realpath, stat } from "node:fs/promises";
2
2
  import { basename, extname, sep } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  export class LocalFileInputError extends Error {
5
- constructor() {
6
- super("本地文件不可用于上传。");
5
+ constructor(cause) {
6
+ super("本地文件不可用于上传。", { cause });
7
7
  this.name = "LocalFileInputError";
8
8
  }
9
9
  }
@@ -141,6 +141,6 @@ export async function inspectUploadFile(input) {
141
141
  throw input.signal.reason;
142
142
  if (error instanceof LocalFileInputError)
143
143
  throw error;
144
- throw new LocalFileInputError();
144
+ throw new LocalFileInputError(error);
145
145
  }
146
146
  }
@@ -6,8 +6,8 @@ export class RemoteRequestError extends Error {
6
6
  transient;
7
7
  remoteCode;
8
8
  remoteBody;
9
- constructor(status, transient = false, evidence = {}) {
10
- super(status === undefined ? "无法连接稿定服务。" : `稿定服务请求失败(HTTP ${status})。`);
9
+ constructor(status, transient = false, evidence = {}, cause) {
10
+ super(status === undefined ? "无法连接稿定服务。" : `稿定服务请求失败(HTTP ${status})。`, { cause });
11
11
  this.name = "RemoteRequestError";
12
12
  this.status = status;
13
13
  this.transient = transient;
@@ -77,18 +77,32 @@ export function createSignedHttpTransport(options) {
77
77
  AbortSignal.timeout(options.timeoutMs ?? 30_000)
78
78
  ])
79
79
  : request.signal;
80
+ signal.throwIfAborted();
81
+ let dispatched;
80
82
  try {
81
- return await options.fetch(url, {
82
- method,
83
- headers,
84
- ...(body === undefined ? {} : { body }),
85
- signal
86
- });
83
+ // Invoke fetch at this boundary; diagnostic persistence never gates dispatch.
84
+ let pending;
85
+ try {
86
+ pending = options.fetch(url, {
87
+ method,
88
+ headers,
89
+ ...(body === undefined ? {} : { body }),
90
+ signal
91
+ });
92
+ }
93
+ finally {
94
+ try {
95
+ dispatched = request.onDispatch?.(options.now().getTime()).catch(() => undefined);
96
+ }
97
+ catch { /* Diagnostic only. */ }
98
+ }
99
+ const [response] = await Promise.all([pending, dispatched]);
100
+ return response;
87
101
  }
88
102
  catch (error) {
89
103
  if (request.signal.aborted)
90
104
  throw request.signal.reason;
91
- throw new RemoteRequestError(undefined, isTransientNetworkFailure(error));
105
+ throw new RemoteRequestError(undefined, isTransientNetworkFailure(error), {}, error);
92
106
  }
93
107
  }
94
108
  async function json(response) {
@@ -1,3 +1,4 @@
1
+ import { cleanDiagnostic, errorEvidence } from "./sanitize.js";
1
2
  const detailedStages = {
2
3
  "auth.login": new Set(["authorize", "wait", "identity", "bind"]),
3
4
  "org.switch": new Set(["list", "bind"]),
@@ -10,147 +11,98 @@ export function createTelemetryInvocation(options) {
10
11
  const traceId = options.traceIdFactory();
11
12
  const startedAt = options.now();
12
13
  let definition;
14
+ let finished = false;
15
+ let signal;
16
+ let sequence = 0;
13
17
  const context = {};
14
- const stages = [];
18
+ const events = [];
19
+ const failures = [];
20
+ function base() {
21
+ const mode = definition?.mode?.();
22
+ return { ...context, schema_version: "3", cli_name: options.cliName ?? "gd-cli",
23
+ env: options.env ?? "production", process_role: options.processRole ?? "cli",
24
+ trace_id: traceId, record_seq: ++sequence, occurred_at_ms: options.now(),
25
+ operation: definition?.operation ?? "unknown", ...(mode ? { mode } : {}),
26
+ cli_version: options.cliVersion, os: options.runtime.os, arch: options.runtime.arch,
27
+ node_major: options.runtime.nodeMajor };
28
+ }
29
+ function classify(error) {
30
+ return signal?.aborted && error === signal.reason ? { outcome: "interrupted" } : options.classifyError(error);
31
+ }
32
+ function errorFields(error) {
33
+ const c = classify(error);
34
+ return { ...errorEvidence(error),
35
+ ...(c.errorCode === undefined ? {} : { error_code: c.errorCode }),
36
+ ...(c.httpStatus === undefined ? {} : { http_status: c.httpStatus }),
37
+ ...(c.remoteErrorCode === undefined ? {} : { remote_error_code: c.remoteErrorCode }),
38
+ ...(c.remoteErrorBody === undefined ? {} : { remote_error_body: c.remoteErrorBody }) };
39
+ }
40
+ function remember(event) {
41
+ const safe = cleanDiagnostic(event);
42
+ events.push(safe);
43
+ return safe;
44
+ }
45
+ async function publish(event) {
46
+ try {
47
+ await options.onEvent?.(event);
48
+ }
49
+ catch { /* Logging cannot fail the operation. */ }
50
+ }
15
51
  return {
16
52
  traceId,
17
- get selected() {
18
- return definition !== undefined;
19
- },
53
+ get selected() { return definition !== undefined; },
20
54
  traceparent() {
21
- return `00-${traceId}-${options.spanIdFactory()}-${traceFlags(definition)}`;
22
- },
23
- select(nextDefinition) {
24
- definition = nextDefinition;
55
+ const paid = (definition?.operation === "agent.send" || definition?.operation === "tool.call")
56
+ && definition.mode?.() === "execute";
57
+ return `00-${traceId}-${options.spanIdFactory()}-${paid ? "01" : "00"}`;
25
58
  },
59
+ select(next) { definition = next; },
60
+ useSignal(next) { signal = next; },
26
61
  annotate(annotation) {
27
- if (annotation.account_id !== undefined)
28
- context.account_id = annotation.account_id;
29
- if (annotation.organization_id !== undefined) {
30
- context.organization_id = annotation.organization_id;
31
- }
32
- if (annotation.tool_name !== undefined)
33
- context.tool_name = annotation.tool_name;
34
- if (annotation.model_id !== undefined)
35
- context.model_id = annotation.model_id;
36
- if (annotation.content_id !== undefined)
37
- context.content_id = annotation.content_id;
38
- if (annotation.task_id !== undefined)
39
- context.task_id = annotation.task_id;
40
- if (annotation.dify_task_id !== undefined) {
41
- context.dify_task_id = annotation.dify_task_id;
42
- }
43
- if (annotation.parameters !== undefined) {
44
- context.parameters = { ...annotation.parameters };
62
+ for (const [key, value] of Object.entries(annotation)) {
63
+ if (value !== undefined)
64
+ Object.assign(context, { [key]: key === "parameters" ? { ...value } : value });
45
65
  }
46
66
  },
67
+ creationContext() {
68
+ const { record_seq: _seq, occurred_at_ms: _time, parameters: _parameters, content_id: _content, task_id: _task, dify_task_id: _dify, result_state: _state, ...snapshot } = base();
69
+ return cleanDiagnostic({ ...snapshot, mode: "execute" });
70
+ },
71
+ async emit(event) { await publish(remember(event)); },
47
72
  async stage(name, run) {
48
- const stageStartedAt = options.now();
73
+ const start = options.now();
74
+ const allowed = detailedStages[definition?.mode ? `${definition.operation}:${definition.mode()}` : definition?.operation ?? ""];
49
75
  try {
50
76
  const result = await run();
51
- stages.push({
52
- name,
53
- durationMs: elapsed(options.now(), stageStartedAt),
54
- outcome: "success"
55
- });
77
+ if (definition && allowed?.has(name))
78
+ remember({ ...base(), event_name: "stage_finished",
79
+ stage: name, outcome: "success", duration_ms: Math.max(0, options.now() - start) });
56
80
  return result;
57
81
  }
58
82
  catch (error) {
59
- const classification = options.classifyError(error);
60
- stages.push({
61
- name,
62
- durationMs: elapsed(options.now(), stageStartedAt),
63
- outcome: classification.outcome,
64
- error,
65
- ...(classification.errorCode === undefined
66
- ? {}
67
- : { errorCode: classification.errorCode }),
68
- ...(classification.httpStatus === undefined
69
- ? {}
70
- : { httpStatus: classification.httpStatus })
71
- });
83
+ failures.push({ name, error });
84
+ const event = remember({ ...base(), event_name: "stage_finished", stage: name,
85
+ outcome: classify(error).outcome,
86
+ duration_ms: Math.max(0, options.now() - start), ...errorFields(error) });
87
+ await publish(event);
72
88
  throw error;
73
89
  }
74
90
  },
75
91
  finish(completion) {
76
- if (!definition)
92
+ if (finished || !definition)
77
93
  return [];
78
- const selectedDefinition = definition;
79
- const mode = selectedDefinition.mode?.();
80
- const allowedStages = detailedStages[stageKey(selectedDefinition.operation, mode)];
81
- const stageEvents = allowedStages
82
- ? stages
83
- .filter((stage) => allowedStages.has(stage.name))
84
- .map((stage) => ({
85
- schema_version: "2",
86
- event_name: "stage_finished",
87
- trace_id: traceId,
88
- operation: selectedDefinition.operation,
89
- stage: stage.name,
90
- outcome: stage.outcome,
91
- duration_ms: stage.durationMs,
92
- ...(stage.errorCode === undefined ? {} : { error_code: stage.errorCode }),
93
- ...(stage.httpStatus === undefined ? {} : { http_status: stage.httpStatus })
94
- }))
95
- : [];
96
- const command = {
97
- schema_version: "2",
98
- event_name: "command_finished",
99
- trace_id: traceId,
100
- operation: selectedDefinition.operation,
101
- ...(mode === undefined ? {} : { mode }),
102
- outcome: completion.outcome,
103
- duration_ms: elapsed(options.now(), startedAt),
104
- cli_version: options.cliVersion,
105
- os: options.runtime.os,
106
- arch: options.runtime.arch,
107
- node_major: options.runtime.nodeMajor,
108
- ...(context.account_id === undefined ? {} : { account_id: context.account_id }),
109
- ...(context.organization_id === undefined
110
- ? {}
111
- : { organization_id: context.organization_id }),
112
- ...(context.tool_name === undefined ? {} : { tool_name: context.tool_name }),
113
- ...(context.model_id === undefined ? {} : { model_id: context.model_id }),
114
- ...(context.content_id === undefined ? {} : { content_id: context.content_id }),
115
- ...(context.task_id === undefined ? {} : { task_id: context.task_id }),
116
- ...(context.dify_task_id === undefined
117
- ? {}
118
- : { dify_task_id: context.dify_task_id }),
119
- ...(context.parameters === undefined
120
- ? {}
121
- : { parameters: { ...context.parameters } }),
122
- ...(completion.outcome === "failure"
123
- ? {
124
- error_code: completion.errorCode,
125
- error_message: completion.errorMessage,
126
- failure_stage: stages.find((stage) => stage.error === completion.error)?.name
127
- ?? "unknown",
128
- ...(completion.httpStatus === undefined
129
- ? {}
130
- : { http_status: completion.httpStatus }),
131
- ...(completion.remoteErrorCode === undefined
132
- ? {}
133
- : { remote_error_code: completion.remoteErrorCode }),
134
- ...(completion.remoteErrorBody === undefined
135
- ? {}
136
- : { remote_error_body: completion.remoteErrorBody })
137
- }
138
- : {})
139
- };
140
- return [...stageEvents, command];
94
+ finished = true;
95
+ remember({ ...base(), event_name: "command_finished", outcome: completion.outcome,
96
+ duration_ms: Math.max(0, options.now() - startedAt),
97
+ ...(completion.outcome === "failure" ? errorFields(completion.error) : completion.outcome === "interrupted" && completion.error !== undefined ? errorEvidence(completion.error) : {}),
98
+ ...(completion.outcome === "failure" ? {
99
+ error_code: completion.errorCode, error_message: completion.errorMessage,
100
+ failure_stage: failures.find(f => f.error === completion.error)?.name ?? "unknown",
101
+ ...(completion.httpStatus === undefined ? {} : { http_status: completion.httpStatus }),
102
+ ...(completion.remoteErrorCode === undefined ? {} : { remote_error_code: completion.remoteErrorCode }),
103
+ ...(completion.remoteErrorBody === undefined ? {} : { remote_error_body: completion.remoteErrorBody })
104
+ } : {}) });
105
+ return events;
141
106
  }
142
107
  };
143
108
  }
144
- function traceFlags(definition) {
145
- if (definition === undefined)
146
- return "00";
147
- const paidExecution = (definition.operation === "agent.send"
148
- || definition.operation === "tool.call") && definition.mode?.() === "execute";
149
- return paidExecution ? "01" : "00";
150
- }
151
- function stageKey(operation, mode) {
152
- return mode === undefined ? operation : `${operation}:${mode}`;
153
- }
154
- function elapsed(now, startedAt) {
155
- return Math.max(0, now - startedAt);
156
- }
@@ -0,0 +1,43 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { homedir } from "node:os";
5
+ import { fileURLToPath } from "node:url";
6
+ import { gaodingProduct, insmindProduct } from "../product/config.js";
7
+ import { createTelemetryInvocation } from "./invocation.js";
8
+ import { createSlsTelemetrySink } from "./sls-sink.js";
9
+ /** Independent fallback for entrypoints which cannot construct the full runtime. */
10
+ export async function reportProcessError(error, options) {
11
+ try {
12
+ const product = options.stateDirectory === ".insmind" ? insmindProduct : gaodingProduct;
13
+ let directory = dirname(fileURLToPath(import.meta.url));
14
+ let version = "unknown";
15
+ for (let depth = 0; depth < 5; depth++, directory = dirname(directory)) {
16
+ try {
17
+ const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
18
+ if (pkg.name === "@gaoding/cli" || pkg.name === "@insmind/cli") {
19
+ version = pkg.version ?? "unknown";
20
+ break;
21
+ }
22
+ }
23
+ catch { /* The package file may be unavailable during startup failure. */ }
24
+ }
25
+ const telemetry = createTelemetryInvocation({ cliName: product.commandName, cliVersion: version,
26
+ env: options.environment ?? (process.env.CLI_TELEMETRY_ENV === "test" ? "test" : "production"),
27
+ processRole: options.processRole ?? "cli", now: Date.now,
28
+ traceIdFactory: () => randomBytes(16).toString("hex"), spanIdFactory: () => randomBytes(8).toString("hex"),
29
+ runtime: { os: process.platform, arch: process.arch, nodeMajor: Number(process.versions.node.split(".")[0]) },
30
+ classifyError: () => ({ outcome: "failure", errorCode: "INTERNAL_ERROR" }) });
31
+ telemetry.select({ operation: options.operation });
32
+ const events = telemetry.finish({ outcome: "failure", error, errorCode: "INTERNAL_ERROR",
33
+ errorMessage: error instanceof Error ? error.message : String(error) });
34
+ const sink = createSlsTelemetrySink({ fetch: globalThis.fetch, trackingUrl: options.trackingUrl ?? product.telemetryUrl,
35
+ directory: join(options.homeDirectory ?? homedir(), product.stateDirectory, "telemetry") });
36
+ // Automated process tests persist to their temporary home, without external traffic.
37
+ if (process.env.NODE_ENV === "test" || process.env.VITEST)
38
+ await sink.enqueue?.(events);
39
+ else
40
+ await sink.send(events);
41
+ }
42
+ catch { /* A broken installation or telemetry path must retain its original exit behavior. */ }
43
+ }
@@ -0,0 +1,72 @@
1
+ import { isSensitiveKey, redactSensitiveText } from "../platform/redact.js";
2
+ const ids = new Set(["account_id", "organization_id", "cli_task_id", "task_id", "dify_task_id", "content_id"]);
3
+ function sensitive(key) {
4
+ return isSensitiveKey(key) || /(?:token|secret)$/iu.test(key) || /^(?:x[-_]?)?(?:bridge[-_]?token|signature|access[-_]?key|cookie|authorization)$/iu.test(key);
5
+ }
6
+ export function cleanText(value) {
7
+ try {
8
+ const parsed = JSON.parse(value);
9
+ if (parsed !== null && typeof parsed === "object")
10
+ return JSON.stringify(cleanDiagnostic(parsed));
11
+ }
12
+ catch { /* Most messages are prose, not JSON. */ }
13
+ return redactSensitiveText(value.replace(/https?:\/\/[^\s<>"`\]\)]+/gu, raw => {
14
+ try {
15
+ const url = new URL(raw);
16
+ url.username = "";
17
+ url.password = "";
18
+ for (const key of [...url.searchParams.keys()])
19
+ if (sensitive(key))
20
+ url.searchParams.set(key, "[REDACTED]");
21
+ return url.href;
22
+ }
23
+ catch {
24
+ return raw;
25
+ }
26
+ })).replace(/\b(?:Bearer\s+)[^\s,;"']+/giu, "Bearer [REDACTED]")
27
+ .replace(/("(?:[^"\s]*token|[^"\s]*secret|(?:x[-_]?)?access[-_]?key(?:[-_]?id)?|authorization|cookie|signature|ak|sk)"\s*:\s*)"[^"\r\n]*"/giu, '$1"[REDACTED]"');
28
+ }
29
+ export function cleanDiagnostic(value) {
30
+ const seen = new WeakSet();
31
+ function clean(item, depth) {
32
+ if (typeof item === "string")
33
+ return /^data:[^,]*;base64,/iu.test(item) ? "[Binary omitted]" : cleanText(item);
34
+ if (typeof item === "bigint")
35
+ return String(item);
36
+ if (item === null || typeof item !== "object")
37
+ return item;
38
+ if (ArrayBuffer.isView(item) || item instanceof ArrayBuffer)
39
+ return "[Binary omitted]";
40
+ if (seen.has(item))
41
+ return "[Circular]";
42
+ if (depth > 20)
43
+ return "[Truncated]";
44
+ seen.add(item);
45
+ if (item instanceof Error)
46
+ return errorEvidence(item);
47
+ if (Array.isArray(item))
48
+ return item.map(v => clean(v, depth + 1));
49
+ return Object.fromEntries(Object.entries(item).map(([key, v]) => [key,
50
+ depth === 0 && ids.has(key) ? v : sensitive(key) ? "[REDACTED]" : clean(v, depth + 1)]));
51
+ }
52
+ return clean(value, 0);
53
+ }
54
+ export function errorEvidence(error) {
55
+ const seen = new WeakSet();
56
+ function describe(e, depth = 0) {
57
+ if (depth > 8)
58
+ return "[Truncated]";
59
+ if (!(e instanceof Error))
60
+ return cleanText(String(e));
61
+ if (seen.has(e))
62
+ return "[Circular]";
63
+ seen.add(e);
64
+ const code = "code" in e ? ` [${String(e.code)}]` : "";
65
+ return [e.stack ?? `${e.name}: ${e.message}`, code,
66
+ ...(e.cause === undefined ? [] : [`Caused by: ${describe(e.cause, depth + 1)}`]),
67
+ ...(e instanceof AggregateError ? e.errors.slice(0, 10).map(x => describe(x, depth + 1)) : [])].join("\n");
68
+ }
69
+ return { error_type: error instanceof Error ? error.name : typeof error,
70
+ error_message: cleanText(error instanceof Error ? error.message : String(error)).slice(0, 8192),
71
+ error_stack: cleanText(describe(error)).slice(0, 8192) };
72
+ }
@@ -1,30 +1,217 @@
1
- const TIMEOUT_MS = 2_000;
1
+ import { createHash } from "node:crypto";
2
+ import { readdir, readFile, unlink, mkdir, chmod } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { cleanDiagnostic } from "./sanitize.js";
5
+ import { createLocalJsonFile } from "../platform/local-json-file.js";
6
+ import { withFileLock } from "../platform/file-lock.js";
7
+ const TTL = 7 * 86_400_000;
8
+ const CAPACITY = 10 * 1024 * 1024;
9
+ const BUDGET = 2_000;
10
+ export function eventKey(event) {
11
+ const key = event.event_name === "request_sent" || event.event_name === "result_ready"
12
+ ? [event.cli_name, event.env, event.cli_task_id, event.event_name]
13
+ : [event.cli_name, event.env, event.trace_id, event.process_role, Number(event.record_seq)];
14
+ return createHash("sha256").update(JSON.stringify(key)).digest("hex");
15
+ }
16
+ export function wireEvent(event) {
17
+ const safe = cleanDiagnostic(event);
18
+ const wire = {};
19
+ for (const [key, value] of Object.entries(safe)) {
20
+ if (value !== undefined)
21
+ wire[key] = typeof value === "object" ? JSON.stringify(value) : String(value);
22
+ }
23
+ for (const key of ["error_stack", "remote_error_body", "error_message"]) {
24
+ if (wire[key] && wire[key].length > 8192) {
25
+ wire[key] = wire[key].slice(0, 8192);
26
+ wire.truncated = "true";
27
+ }
28
+ }
29
+ if (wire.parameters && Buffer.byteLength(wire.parameters) > 32 * 1024) {
30
+ wire.parameters = JSON.stringify({ truncated: true, preview: utf8Prefix(wire.parameters, 8 * 1024) });
31
+ wire.truncated = "true";
32
+ }
33
+ if (Buffer.byteLength(JSON.stringify(wire)) > 64 * 1024) {
34
+ wire.truncated = "true";
35
+ for (const key of ["parameters", "remote_error_body", "error_stack", "error_message"]) {
36
+ delete wire[key];
37
+ if (Buffer.byteLength(JSON.stringify(wire)) <= 64 * 1024)
38
+ break;
39
+ }
40
+ // Keep the envelope valid even for unexpectedly large identity or adapter fields.
41
+ for (const [key, value] of Object.entries(wire))
42
+ wire[key] = utf8Prefix(value, 1024);
43
+ }
44
+ return wire;
45
+ }
46
+ function utf8Prefix(value, bytes) {
47
+ let size = 0;
48
+ let result = "";
49
+ for (const char of value) {
50
+ size += Buffer.byteLength(char);
51
+ if (size > bytes)
52
+ break;
53
+ result += char;
54
+ }
55
+ return result;
56
+ }
2
57
  export function createSlsTelemetrySink(options) {
3
- return {
4
- async send(events) {
5
- if (events.length === 0)
6
- return;
58
+ const now = options.now ?? Date.now;
59
+ const entries = new Map();
60
+ let writes = Promise.resolve();
61
+ const file = (id) => createLocalJsonFile({ directory: options.directory, filename: `${id}.json` });
62
+ const locked = (run) => options.directory
63
+ ? withFileLock(join(options.directory, ".lock"), run) : run();
64
+ async function load() {
65
+ if (!options.directory)
66
+ return;
67
+ entries.clear();
68
+ await mkdir(options.directory, { recursive: true, mode: 0o700 });
69
+ await chmod(options.directory, 0o700);
70
+ for (const name of await readdir(options.directory)) {
71
+ // All writers hold the same lock, so remaining atomic-write temporaries are orphaned.
72
+ if (/^(?:[a-f0-9]{64}|delivery-status)\.json\.tmp-[a-f0-9-]+$/u.test(name)) {
73
+ await unlink(join(options.directory, name)).catch(() => undefined);
74
+ await dropped("interrupted_write", 1);
75
+ continue;
76
+ }
77
+ if (!/^[a-f0-9]{64}\.json$/u.test(name))
78
+ continue;
7
79
  try {
8
- await options.fetch(options.trackingUrl, {
9
- method: "POST",
10
- headers: { "Content-Type": "application/json" },
11
- body: JSON.stringify({ __logs__: events.map(wireEvent) }),
12
- redirect: "error",
13
- signal: AbortSignal.timeout(TIMEOUT_MS)
14
- });
80
+ const entry = JSON.parse(await readFile(join(options.directory, name), "utf8"));
81
+ if (!Number.isFinite(entry.queuedAt) || !entry.event || eventKey(entry.event) !== name.slice(0, -5))
82
+ throw new Error();
83
+ entries.set(name.slice(0, -5), entry);
15
84
  }
16
85
  catch {
17
- // Telemetry must never change command behavior.
86
+ await unlink(join(options.directory, name)).catch(() => undefined);
87
+ await dropped("corrupt", 1);
18
88
  }
19
89
  }
20
- };
21
- }
22
- function wireEvent(event) {
23
- const wire = {};
24
- for (const [key, value] of Object.entries(event)) {
25
- if (value === undefined)
26
- continue;
27
- wire[key] = key === "parameters" ? JSON.stringify(value) : String(value);
28
90
  }
29
- return wire;
91
+ async function dropped(reason, count) {
92
+ if (!options.directory)
93
+ return;
94
+ const status = createLocalJsonFile({ directory: options.directory, filename: "delivery-status.json" });
95
+ let prior = {};
96
+ try {
97
+ prior = JSON.parse(await status.readText() ?? "{}");
98
+ }
99
+ catch { /* Replace corrupt diagnostic status. */ }
100
+ await status.writeTextAtomically(JSON.stringify({ count: (prior.count ?? 0) + count,
101
+ first_at_ms: prior.first_at_ms ?? now(), last_at_ms: now(), reason }));
102
+ }
103
+ async function remove(id) {
104
+ entries.delete(id);
105
+ if (options.directory)
106
+ await file(id).remove();
107
+ }
108
+ async function persist(id, entry) {
109
+ entries.set(id, entry);
110
+ if (options.directory)
111
+ await file(id).writeTextAtomically(JSON.stringify(entry));
112
+ }
113
+ async function trim() {
114
+ for (const [id, entry] of entries) {
115
+ if (now() - entry.queuedAt > (options.retentionMs ?? TTL)) {
116
+ await remove(id);
117
+ await dropped("expired", 1);
118
+ }
119
+ }
120
+ let size = [...entries.values()].reduce((sum, e) => sum + Buffer.byteLength(JSON.stringify(e)), 0);
121
+ const priority = (e) => e.event.event_name === "request_sent" || e.event.event_name === "result_ready" ? 2
122
+ : "outcome" in e.event && e.event.outcome !== "success" ? 1 : 0;
123
+ for (const [id, entry] of [...entries].sort((a, b) => priority(a[1]) - priority(b[1]) || a[1].queuedAt - b[1].queuedAt)) {
124
+ if (size <= (options.maxBytes ?? CAPACITY))
125
+ break;
126
+ size -= Buffer.byteLength(JSON.stringify(entry));
127
+ await remove(id);
128
+ await dropped("capacity", 1);
129
+ }
130
+ }
131
+ function enqueue(events) {
132
+ writes = writes.catch(() => undefined).then(() => locked(async () => {
133
+ await load();
134
+ for (const event of events) {
135
+ const id = eventKey(event);
136
+ if (entries.has(id))
137
+ continue;
138
+ // Persist the sanitized, bounded wire payload and replay it unchanged.
139
+ await persist(id, { event: wireEvent(event), queuedAt: now(), nextAttempt: 0, attempts: 0 });
140
+ }
141
+ await trim();
142
+ })).catch(() => undefined);
143
+ if (options.background)
144
+ void writes.then(() => { if (!sending)
145
+ void start(Date.now() + BUDGET); });
146
+ return writes;
147
+ }
148
+ let sending;
149
+ async function flush(deadline) {
150
+ for (let attempt = 0; attempt < 2 && Date.now() < deadline; attempt++) {
151
+ let batch = [];
152
+ await locked(async () => {
153
+ await load();
154
+ await trim();
155
+ let bytes = 0;
156
+ batch = [...entries].filter(([, e]) => e.nextAttempt <= now()).filter(([, e]) => {
157
+ bytes += Buffer.byteLength(JSON.stringify(e.event));
158
+ return bytes <= 512 * 1024;
159
+ }).slice(0, 100);
160
+ });
161
+ if (!batch.length || Date.now() >= deadline)
162
+ return;
163
+ let response;
164
+ let retryAfter = 0;
165
+ try {
166
+ const timeout = Math.max(1, deadline - Date.now());
167
+ const signal = AbortSignal.timeout(timeout);
168
+ // Bound even a custom fetch that ignores AbortSignal.
169
+ response = await new Promise((resolve, reject) => {
170
+ const abort = () => reject(signal.reason);
171
+ signal.addEventListener("abort", abort, { once: true });
172
+ options.fetch(options.trackingUrl, { method: "POST", headers: { "Content-Type": "application/json" },
173
+ body: JSON.stringify({ __logs__: batch.map(([, e]) => e.event) }), redirect: "error", signal })
174
+ .then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
175
+ });
176
+ const header = response.headers.get("Retry-After");
177
+ if (header)
178
+ retryAfter = Math.max(0, /^\d+$/u.test(header) ? Number(header) * 1000 : Date.parse(header) - now()) || 0;
179
+ await response.body?.cancel().catch(() => undefined);
180
+ }
181
+ catch { /* Retain the original records for the next invocation. */ }
182
+ const accepted = response?.ok === true;
183
+ const rejected = response !== undefined && response.status >= 400 && response.status < 500 && response.status !== 429;
184
+ await locked(async () => {
185
+ await load();
186
+ for (const [id, original] of batch) {
187
+ const entry = entries.get(id);
188
+ if (!entry)
189
+ continue;
190
+ if (accepted || rejected)
191
+ await remove(id);
192
+ else
193
+ await persist(id, { ...entry, attempts: original.attempts + 1,
194
+ nextAttempt: now() + Math.max(retryAfter, attempt === 0 ? 0 : Math.min(60_000, 1000 * 2 ** Math.min(6, original.attempts))) });
195
+ }
196
+ if (rejected)
197
+ await dropped(`http_${response.status}`, batch.length);
198
+ });
199
+ if (!accepted && (retryAfter > 0 || rejected))
200
+ return;
201
+ }
202
+ }
203
+ function start(deadline) {
204
+ sending ??= flush(deadline).catch(() => undefined).finally(() => { sending = undefined; });
205
+ return sending;
206
+ }
207
+ return { enqueue,
208
+ async send(events) {
209
+ const deadline = Date.now() + BUDGET;
210
+ await enqueue(events);
211
+ if (sending)
212
+ await sending;
213
+ if (Date.now() < deadline)
214
+ await start(deadline);
215
+ }
216
+ };
30
217
  }