@insmind/cli 1.3.0 → 1.4.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/agent-worker.js +13 -1
- package/dist/bin/insmind-cli.js +7 -0
- package/dist/bin/postinstall.js +13 -4
- package/dist/src/bootstrap/create-cli.js +15 -7
- package/dist/src/bootstrap/create-runtime.js +33 -14
- package/dist/src/bootstrap/run-agent-worker.js +12 -1
- package/dist/src/cli/action-binding.js +1 -2
- package/dist/src/cli/errors.js +3 -3
- package/dist/src/features/agent/creative-agent-adapter.js +1 -0
- package/dist/src/features/auth/sso-service.js +4 -4
- package/dist/src/features/auth/use-cases.js +1 -1
- package/dist/src/features/dam/file-downloader.js +6 -6
- package/dist/src/features/dam/object-storage.js +6 -4
- package/dist/src/features/editor/bridge-process.js +9 -3
- package/dist/src/features/editor/bridge-server.js +4 -2
- package/dist/src/features/task/store.js +34 -2
- package/dist/src/features/task/use-cases.js +71 -6
- package/dist/src/features/tool/tool-api-adapter.js +1 -0
- package/dist/src/features/update/update-notification.js +4 -2
- package/dist/src/platform/file-lock.js +68 -0
- package/dist/src/platform/redact.js +1 -1
- package/dist/src/platform/safe-upload-file.js +3 -3
- package/dist/src/platform/signed-http-transport.js +23 -9
- package/dist/src/telemetry/invocation.js +74 -122
- package/dist/src/telemetry/process-errors.js +43 -0
- package/dist/src/telemetry/sanitize.js +72 -0
- package/dist/src/telemetry/sls-sink.js +209 -22
- package/package.json +4 -4
|
@@ -35,6 +35,42 @@ const HEARTBEAT_MS = 5_000;
|
|
|
35
35
|
const LEASE_MS = 15_000;
|
|
36
36
|
export function createTaskUseCases(dependencies) {
|
|
37
37
|
const { text, commandName } = dependencies;
|
|
38
|
+
const telemetry = dependencies.telemetry;
|
|
39
|
+
async function fact(scope, record, name, at) {
|
|
40
|
+
if (!telemetry || !record.telemetry)
|
|
41
|
+
return;
|
|
42
|
+
let context = record.telemetry.context;
|
|
43
|
+
if (name === "request_sent") {
|
|
44
|
+
const current = telemetry.creationContext();
|
|
45
|
+
context = { ...context,
|
|
46
|
+
...(current.tool_name ? { tool_name: current.tool_name } : {}),
|
|
47
|
+
...(current.model_id ? { model_id: current.model_id } : {}) };
|
|
48
|
+
}
|
|
49
|
+
const candidate = { ...context, event_name: name, occurred_at_ms: at,
|
|
50
|
+
record_seq: name === "request_sent" ? 1 : 2 };
|
|
51
|
+
try {
|
|
52
|
+
const updated = await dependencies.store.update(scope, record.task.taskId, stored => {
|
|
53
|
+
if (stored.telemetry && !stored.telemetry[name]) {
|
|
54
|
+
stored.telemetry.context = context;
|
|
55
|
+
stored.telemetry[name] = candidate;
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
if (updated.telemetry)
|
|
59
|
+
record.telemetry = updated.telemetry;
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
// Business persistence has its own failure path. Keep the already known fact.
|
|
63
|
+
record.telemetry[name] ??= candidate;
|
|
64
|
+
await telemetry.stage("telemetry.task", () => { throw error; }).catch(() => undefined);
|
|
65
|
+
}
|
|
66
|
+
await telemetry.emit(record.telemetry[name] ?? candidate);
|
|
67
|
+
}
|
|
68
|
+
async function replay(record) {
|
|
69
|
+
for (const event of [record.telemetry?.request_sent, record.telemetry?.result_ready]) {
|
|
70
|
+
if (event)
|
|
71
|
+
await telemetry?.emit(event);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
38
74
|
function summary(record) {
|
|
39
75
|
const { result: _result, partialResult: _partial, ...task } = record.task;
|
|
40
76
|
if (!record.progress.detached && task.state === "running"
|
|
@@ -52,6 +88,13 @@ export function createTaskUseCases(dependencies) {
|
|
|
52
88
|
label: redactSensitiveText(input.label).slice(0, 200),
|
|
53
89
|
createdAt: timestamp, updatedAt: timestamp, state: "running" }
|
|
54
90
|
};
|
|
91
|
+
if (telemetry) {
|
|
92
|
+
telemetry.annotate({ cli_task_id: record.task.taskId, execution_mode: input.executionMode ?? "sync", result_state: "running" });
|
|
93
|
+
record.telemetry = { context: { ...telemetry.creationContext(), operation: input.operation,
|
|
94
|
+
cli_task_id: record.task.taskId, execution_mode: input.executionMode ?? "sync",
|
|
95
|
+
...(dependencies.creationVersion ? { cli_version: dependencies.creationVersion } : {}),
|
|
96
|
+
...(input.state.account ? { account_id: input.state.account.id } : {}), organization_id: input.state.organization.id } };
|
|
97
|
+
}
|
|
55
98
|
await dependencies.store.write(scope, record);
|
|
56
99
|
input.onUpdate?.(structuredClone(record.task), { ...record.progress });
|
|
57
100
|
dependencies.notice(text(`任务 ID: ${record.task.taskId};结果未收到时执行 ${commandName} task get ${record.task.taskId}`, `Task ID: ${record.task.taskId}; retrieve missing output with ${commandName} task get ${record.task.taskId}`));
|
|
@@ -62,10 +105,23 @@ export function createTaskUseCases(dependencies) {
|
|
|
62
105
|
writes = writes.catch(() => undefined).then(() => dependencies.store.write(scope, snapshot));
|
|
63
106
|
return writes;
|
|
64
107
|
};
|
|
65
|
-
|
|
108
|
+
let lastHeartbeatError = -Infinity;
|
|
109
|
+
const timer = setInterval(() => {
|
|
110
|
+
void save().catch(async (error) => {
|
|
111
|
+
const at = dependencies.now().getTime();
|
|
112
|
+
if (at - lastHeartbeatError < 60_000)
|
|
113
|
+
return;
|
|
114
|
+
lastHeartbeatError = at;
|
|
115
|
+
await telemetry?.stage("task.heartbeat", () => { throw error; }).catch(() => undefined);
|
|
116
|
+
});
|
|
117
|
+
}, HEARTBEAT_MS);
|
|
66
118
|
timer.unref();
|
|
67
119
|
try {
|
|
68
120
|
const result = await input.run(async (progress) => {
|
|
121
|
+
if (progress.dispatchedAt !== undefined) {
|
|
122
|
+
await fact(scope, record, "request_sent", progress.dispatchedAt);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
69
125
|
Object.assign(record.progress, progress);
|
|
70
126
|
if (progress.contextId)
|
|
71
127
|
record.task.contextId = progress.contextId;
|
|
@@ -74,6 +130,9 @@ export function createTaskUseCases(dependencies) {
|
|
|
74
130
|
});
|
|
75
131
|
clearInterval(timer);
|
|
76
132
|
finish(record, result);
|
|
133
|
+
telemetry?.annotate({ result_state: record.task.state });
|
|
134
|
+
if (record.task.state === "completed")
|
|
135
|
+
await fact(scope, record, "result_ready", dependencies.now().getTime());
|
|
77
136
|
await save();
|
|
78
137
|
return { task: record.task, result };
|
|
79
138
|
}
|
|
@@ -88,7 +147,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
88
147
|
const detail = dependencies.failureNote?.(error);
|
|
89
148
|
if (detail)
|
|
90
149
|
record.task.note = `${record.task.note} ${redactSensitiveText(detail)}`;
|
|
91
|
-
await save().catch(() => undefined);
|
|
150
|
+
await (telemetry ? telemetry.stage("task.persist", save) : save()).catch(() => undefined);
|
|
92
151
|
throw error;
|
|
93
152
|
}
|
|
94
153
|
}
|
|
@@ -102,7 +161,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
102
161
|
})).result;
|
|
103
162
|
},
|
|
104
163
|
async submit(input) {
|
|
105
|
-
return (await execute(input, record => { record.progress.detached = true; })).task;
|
|
164
|
+
return (await execute({ ...input, executionMode: "async" }, record => { record.progress.detached = true; })).task;
|
|
106
165
|
},
|
|
107
166
|
async list({ state, limit, operation }) {
|
|
108
167
|
const records = await dependencies.store.list(taskScope(state));
|
|
@@ -114,6 +173,8 @@ export function createTaskUseCases(dependencies) {
|
|
|
114
173
|
const record = await dependencies.store.read(scope, id);
|
|
115
174
|
if (!record)
|
|
116
175
|
throw new TaskNotFoundError(text(`当前身份中没有该任务。请执行 ${commandName} task list 查找。`, `No task was found in the current identity context. Use ${commandName} task list to find it.`));
|
|
176
|
+
telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
|
|
177
|
+
await replay(record);
|
|
117
178
|
if (record.task.state === "completed" && record.task.result) {
|
|
118
179
|
return { ...record.task, result: await dependencies.recovery.authorize(record.task.result, state, signal) };
|
|
119
180
|
}
|
|
@@ -126,9 +187,13 @@ export function createTaskUseCases(dependencies) {
|
|
|
126
187
|
if (result.state === "unknown" && task.note) {
|
|
127
188
|
result.note = [task.note, recovered.note].filter(Boolean).join(" ");
|
|
128
189
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
190
|
+
telemetry?.annotate({ result_state: result.state });
|
|
191
|
+
if (result.state === "completed" && result.result) {
|
|
192
|
+
dependencies.validateResult?.(result.result);
|
|
193
|
+
await fact(scope, record, "result_ready", dependencies.now().getTime());
|
|
194
|
+
}
|
|
195
|
+
// Store merging protects terminal results and facts against stale heartbeats.
|
|
196
|
+
if (result.state === "completed" || result.state === "failed") {
|
|
132
197
|
result.updatedAt = dependencies.now().toISOString();
|
|
133
198
|
record.task = withoutResourceKeys(result);
|
|
134
199
|
await dependencies.store.write(scope, record);
|
|
@@ -304,6 +304,7 @@ export function createToolApiAdapter(dependencies) {
|
|
|
304
304
|
dependencies.telemetry.annotate({ content_id: managedContentId });
|
|
305
305
|
return submittedTask(await safePost(dependencies.transport, {
|
|
306
306
|
path: "/gdesign/tool/v1/dify/call_async",
|
|
307
|
+
...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
|
|
307
308
|
body: {
|
|
308
309
|
jsonrpc: "2.0",
|
|
309
310
|
id: 0,
|
|
@@ -56,7 +56,8 @@ export function createUpdateNotificationService(options) {
|
|
|
56
56
|
...(state.etag ? { etag: state.etag } : {})
|
|
57
57
|
});
|
|
58
58
|
}
|
|
59
|
-
catch {
|
|
59
|
+
catch (error) {
|
|
60
|
+
await options.reportError?.(error).catch(() => undefined);
|
|
60
61
|
if (signal.aborted)
|
|
61
62
|
return;
|
|
62
63
|
await writeState(stateFile, {
|
|
@@ -101,7 +102,8 @@ export function createUpdateNotificationService(options) {
|
|
|
101
102
|
if (shouldNotify)
|
|
102
103
|
notify(options, latest);
|
|
103
104
|
}
|
|
104
|
-
catch {
|
|
105
|
+
catch (error) {
|
|
106
|
+
await options.reportError?.(error).catch(() => undefined);
|
|
105
107
|
// Availability checks are best-effort and never change command behavior.
|
|
106
108
|
}
|
|
107
109
|
finally {
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, open, readFile, readdir, unlink, chmod } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
import { createLocalJsonFile } from "./local-json-file.js";
|
|
6
|
+
/** Local bakery lock: unique owner files avoid deleting a new owner's lock
|
|
7
|
+
* when several processes simultaneously recover a dead writer. */
|
|
8
|
+
export async function withFileLock(path, run) {
|
|
9
|
+
const directory = `${path}.d`;
|
|
10
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
11
|
+
await chmod(directory, 0o700);
|
|
12
|
+
const name = `${process.pid}-${randomUUID()}.json`;
|
|
13
|
+
const ownPath = join(directory, name);
|
|
14
|
+
const deadline = Date.now() + 2_000;
|
|
15
|
+
async function contenders() {
|
|
16
|
+
const found = [];
|
|
17
|
+
for (const entry of await readdir(directory)) {
|
|
18
|
+
const match = /^(\d+)-[a-f0-9-]{36}\.json$/u.exec(entry);
|
|
19
|
+
if (!match)
|
|
20
|
+
continue;
|
|
21
|
+
const pid = Number(match[1]);
|
|
22
|
+
try {
|
|
23
|
+
process.kill(pid, 0);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error instanceof Error && "code" in error && error.code === "ESRCH") {
|
|
27
|
+
await unlink(join(directory, entry)).catch(() => undefined);
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const text = await readFile(join(directory, entry), "utf8");
|
|
33
|
+
let ticket = null;
|
|
34
|
+
try {
|
|
35
|
+
const value = JSON.parse(text).ticket;
|
|
36
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value > 0)
|
|
37
|
+
ticket = value;
|
|
38
|
+
}
|
|
39
|
+
catch { /* The owner has opened its choosing file but not written it yet. */ }
|
|
40
|
+
found.push({ name: entry, ticket });
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return found;
|
|
48
|
+
}
|
|
49
|
+
const handle = await open(ownPath, "wx", 0o600);
|
|
50
|
+
try {
|
|
51
|
+
await handle.writeFile('{"ticket":null}');
|
|
52
|
+
const ticket = 1 + Math.max(0, ...(await contenders()).map(owner => owner.ticket ?? 0));
|
|
53
|
+
await createLocalJsonFile({ directory, filename: name }).writeTextAtomically(JSON.stringify({ ticket }));
|
|
54
|
+
for (;;) {
|
|
55
|
+
const waiting = (await contenders()).some(owner => owner.name !== name
|
|
56
|
+
&& (owner.ticket === null || owner.ticket < ticket || (owner.ticket === ticket && owner.name < name)));
|
|
57
|
+
if (!waiting)
|
|
58
|
+
return await run();
|
|
59
|
+
if (Date.now() >= deadline)
|
|
60
|
+
throw new Error("Local state lock timed out.");
|
|
61
|
+
await delay(10);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
finally {
|
|
65
|
+
await handle.close();
|
|
66
|
+
await unlink(ownPath).catch(() => undefined);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -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,;}&]
|
|
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
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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
|
|
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
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
|
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
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
?
|
|
83
|
-
.
|
|
84
|
-
.
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
+
}
|