@insmind/cli 1.5.11 → 1.5.13
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/src/bootstrap/create-cli.js +5 -3
- package/dist/src/bootstrap/create-runtime.js +1 -1
- package/dist/src/bootstrap/run-task-worker.js +1 -0
- package/dist/src/cli/errors.js +23 -6
- package/dist/src/features/agent/creative-protocol.js +2 -2
- package/dist/src/features/agent/creative-stream.js +9 -1
- package/dist/src/features/agent/filems-resource-auth-key-provider.js +10 -1
- package/dist/src/features/task/creation-refusal.js +15 -0
- package/dist/src/features/task/task-background.js +5 -1
- package/dist/src/features/task/use-cases.js +42 -28
- package/dist/src/platform/file-lock.js +6 -5
- package/dist/src/telemetry/failure-summary.js +20 -0
- package/dist/src/telemetry/invocation.js +9 -3
- package/dist/src/telemetry/sls-sink.js +14 -3
- package/package.json +4 -4
|
@@ -56,7 +56,7 @@ export function createCli(runtime, options) {
|
|
|
56
56
|
registerUpdateCommand(program, runtime);
|
|
57
57
|
registerTaskCommands(program, runtime);
|
|
58
58
|
assertAllLeafCommandsBound(program);
|
|
59
|
-
outputs.set(program, runtime
|
|
59
|
+
outputs.set(program, runtime);
|
|
60
60
|
if (runtime.analytics)
|
|
61
61
|
analyticsShutdown.set(program, () => runtime.analytics.shutdown());
|
|
62
62
|
return program;
|
|
@@ -75,7 +75,8 @@ export async function executeCli(options) {
|
|
|
75
75
|
await checkUpdateNotification(options.updateNotification, options.signal);
|
|
76
76
|
options.signal.throwIfAborted();
|
|
77
77
|
}
|
|
78
|
-
await options.telemetry.stage("output", async () => { await outputs.get(options.program)?.flush?.(); });
|
|
78
|
+
await options.telemetry.stage("output", async () => { await outputs.get(options.program)?.io.flush?.(); });
|
|
79
|
+
await outputs.get(options.program)?.tasks.outputCompleted();
|
|
79
80
|
if (!helpOnly)
|
|
80
81
|
await sendFinished(options, { outcome: "success" });
|
|
81
82
|
return 0;
|
|
@@ -108,7 +109,7 @@ export async function executeCli(options) {
|
|
|
108
109
|
catch (presenterError) {
|
|
109
110
|
await options.telemetry.stage("output", () => { throw presenterError; }).catch(() => undefined);
|
|
110
111
|
}
|
|
111
|
-
await options.telemetry.stage("output", async () => { await outputs.get(options.program)?.flush?.(); }).catch(() => undefined);
|
|
112
|
+
await options.telemetry.stage("output", async () => { await outputs.get(options.program)?.io.flush?.(); }).catch(() => undefined);
|
|
112
113
|
await sendFinished(options, outcome.kind === "interrupted"
|
|
113
114
|
? { outcome: "interrupted", error }
|
|
114
115
|
: {
|
|
@@ -139,6 +140,7 @@ async function checkUpdateNotification(updateNotification, signal) {
|
|
|
139
140
|
}
|
|
140
141
|
async function sendFinished(options, completion) {
|
|
141
142
|
await analyticsShutdown.get(options.program)?.().catch(() => undefined);
|
|
143
|
+
options.telemetry.annotate(options.telemetrySink.diagnostics?.() ?? {});
|
|
142
144
|
const events = options.telemetry.finish(completion);
|
|
143
145
|
if (events.length > 0)
|
|
144
146
|
await options.telemetrySink.send(events).catch(() => undefined);
|
|
@@ -98,7 +98,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
98
98
|
spanIdFactory: () => randomBytes(8).toString("hex"),
|
|
99
99
|
runtime: { os: process.platform, arch: process.arch, nodeMajor: Number.parseInt(process.versions.node, 10) },
|
|
100
100
|
classifyError: error => classifyTelemetryError(error, { product }),
|
|
101
|
-
onEvent:
|
|
101
|
+
...(telemetrySink.enqueue ? { onEvent: (event) => telemetrySink.enqueue([event]) } : {})
|
|
102
102
|
});
|
|
103
103
|
// Explicit test transport enables SDK tests; test-mode child processes never emit real analytics.
|
|
104
104
|
const analytics = options.analytics ?? (telemetryEnvironment === "production" || options.windFetch
|
|
@@ -53,6 +53,7 @@ export async function runTaskWorker(options) {
|
|
|
53
53
|
}
|
|
54
54
|
finally {
|
|
55
55
|
await runtime.analytics?.shutdown().catch(() => undefined);
|
|
56
|
+
runtime.telemetry.annotate(runtime.telemetrySink.diagnostics?.() ?? {});
|
|
56
57
|
await runtime.telemetrySink.send(runtime.telemetry.finish(completion)).catch(() => undefined);
|
|
57
58
|
}
|
|
58
59
|
}
|
package/dist/src/cli/errors.js
CHANGED
|
@@ -10,6 +10,7 @@ import { AgentInputError } from "../features/agent/use-cases.js";
|
|
|
10
10
|
import { ToolInputError } from "../features/tool/catalog.js";
|
|
11
11
|
import { ToolTaskFailedError } from "../features/tool/tool-api-adapter.js";
|
|
12
12
|
import { AgentAuditRejectedError } from "../features/agent/creative-protocol.js";
|
|
13
|
+
import { isContentReviewRejection } from "../features/task/creation-refusal.js";
|
|
13
14
|
import { ObjectStorageUploadError } from "../features/dam/object-storage.js";
|
|
14
15
|
import { DamAssetNotDownloadableError, DamAssetNotFoundError, DamFolderNotFoundError } from "../features/dam/dam-api-adapter.js";
|
|
15
16
|
import { DamDownloadError, DamDownloadDestinationExistsError } from "../features/dam/file-downloader.js";
|
|
@@ -28,6 +29,7 @@ import { redactSensitiveText } from "../platform/redact.js";
|
|
|
28
29
|
import { EditorNotReadyError, EditorSessionNotFoundError, EditorTargetError } from "../features/editor/session.js";
|
|
29
30
|
import { UpdateError } from "../features/update/update-service.js";
|
|
30
31
|
import { WindAnalyticsError } from "../analytics/wind.js";
|
|
32
|
+
import { safeFailureSummary } from "../telemetry/failure-summary.js";
|
|
31
33
|
export class CliUsageError extends Error {
|
|
32
34
|
constructor() {
|
|
33
35
|
super("命令或参数无效。");
|
|
@@ -133,14 +135,15 @@ export function mapCliError(error, options) {
|
|
|
133
135
|
return failure("INSUFFICIENT_CREDITS", "There are not enough insMind credits to complete this creation.", 1, [`Buy credits at ${options.product.pricingUrl.href}`, "Retry after adding credits."]);
|
|
134
136
|
return failure("INSUFFICIENT_CREDITS", "当前组织稿豆不足,无法完成本次创作。", 1, INSUFFICIENT_CREDITS_NEXT_STEPS);
|
|
135
137
|
}
|
|
136
|
-
if (error
|
|
137
|
-
const
|
|
138
|
-
const
|
|
138
|
+
if (isContentReviewRejection(error)) {
|
|
139
|
+
const phase = error instanceof AgentAuditRejectedError ? error.phase : undefined;
|
|
140
|
+
const reason = phase === undefined ? "audit_rejected" : `${phase}_audit_rejected`;
|
|
141
|
+
const message = phase === "input"
|
|
139
142
|
? text("输入内容未通过审核,本次创作已拒绝。", "The input did not pass content review. This creation was rejected.")
|
|
140
|
-
:
|
|
143
|
+
: phase === "output"
|
|
141
144
|
? text("生成内容未通过审核,无法交付本次结果。", "The generated content did not pass review. This result cannot be delivered.")
|
|
142
145
|
: text("本次创作被内容审核拒绝。", "This creation was rejected by content review.");
|
|
143
|
-
return failure("REMOTE_REQUEST_FAILED", message, 1, [text("请检查并调整创作内容;不要重复提交相同请求。", "Review and adjust the creation content; do not resubmit the same request.")], { reason });
|
|
146
|
+
return failure(error instanceof ToolTaskFailedError ? "TOOL_TASK_FAILED" : "REMOTE_REQUEST_FAILED", message, 1, [text("请检查并调整创作内容;不要重复提交相同请求。", "Review and adjust the creation content; do not resubmit the same request.")], { reason });
|
|
144
147
|
}
|
|
145
148
|
if (error instanceof RemoteProtocolError) {
|
|
146
149
|
return failure("REMOTE_PROTOCOL_INCOMPATIBLE", text("稿定服务返回了当前 CLI 无法安全处理的结果;为避免重复创作,已停止处理。", "The insMind service returned a result this CLI cannot safely process; processing stopped to avoid duplicate creation."), 1, [text(`保留诊断 ID。若已有任务 ID,用 ${command} task get <id> 查询原任务;查询异常不能证明生成失败,不要重新提交。`, `Keep the diagnostic ID. If a Task ID is available, use ${command} task get <id>. A query error does not prove generation failed; do not resubmit.`)]);
|
|
@@ -243,6 +246,7 @@ export function classifyTelemetryError(error, options = {}) {
|
|
|
243
246
|
...(diagnostics?.failure_stage ? { failureStage: diagnostics.failure_stage } : {}),
|
|
244
247
|
...(diagnostics?.http_status === undefined ? {} : { httpStatus: diagnostics.http_status }),
|
|
245
248
|
...(diagnostics?.remote_error_code ? { remoteErrorCode: diagnostics.remote_error_code } : {}),
|
|
249
|
+
...(diagnostics?.diagnostic_summary ? { diagnosticSummary: diagnostics.diagnostic_summary } : {}),
|
|
246
250
|
...(diagnostics?.diagnostic_reason ? { diagnosticReason: diagnostics.diagnostic_reason } : {}) };
|
|
247
251
|
}
|
|
248
252
|
let remoteError;
|
|
@@ -253,8 +257,21 @@ export function classifyTelemetryError(error, options = {}) {
|
|
|
253
257
|
break;
|
|
254
258
|
}
|
|
255
259
|
}
|
|
260
|
+
let summary;
|
|
261
|
+
if ((remoteError instanceof RemoteRequestError || remoteError instanceof RemoteProtocolError)
|
|
262
|
+
&& /^(?:RESPONSE_|AGENT_)/u.test(remoteError.diagnosticReason ?? "")) {
|
|
263
|
+
try {
|
|
264
|
+
summary = JSON.parse(remoteError.remoteBody ?? "null");
|
|
265
|
+
}
|
|
266
|
+
catch { /* No safe summary available. */ }
|
|
267
|
+
}
|
|
268
|
+
const diagnosticSummary = safeFailureSummary({
|
|
269
|
+
...(summary && typeof summary === "object" && !Array.isArray(summary) ? summary : {}),
|
|
270
|
+
systemCode: systemErrorCode(error)
|
|
271
|
+
});
|
|
256
272
|
return {
|
|
257
273
|
outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
|
|
274
|
+
...(diagnosticSummary ? { diagnosticSummary } : {}),
|
|
258
275
|
...(outcome.kind === "failure" ? { errorCode: outcome.failure.code } : {}),
|
|
259
276
|
...((remoteError instanceof RemoteRequestError || remoteError instanceof SsoRequestError) && remoteError.status !== undefined
|
|
260
277
|
? { httpStatus: remoteError.status }
|
|
@@ -282,7 +299,7 @@ function failure(code, message, exitCode, nextSteps, details) {
|
|
|
282
299
|
}
|
|
283
300
|
function systemErrorCode(error) {
|
|
284
301
|
for (let depth = 0; error instanceof Error && depth < 10; depth++, error = error.cause) {
|
|
285
|
-
if ("code" in error && typeof error.code === "string" && /^E[A-Z0-9_]{1,40}$/u.test(error.code))
|
|
302
|
+
if ("code" in error && typeof error.code === "string" && /^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,40}|LOCAL_LOCK_TIMEOUT)$/u.test(error.code))
|
|
286
303
|
return error.code;
|
|
287
304
|
}
|
|
288
305
|
return undefined;
|
|
@@ -421,7 +421,7 @@ export function normalizeCreativeMessages(messages) {
|
|
|
421
421
|
}
|
|
422
422
|
const publicParts = dedupeParts(parts);
|
|
423
423
|
if (publicParts.length === 0)
|
|
424
|
-
return fail();
|
|
424
|
+
return fail("AGENT_RESULT_EMPTY", { messageCount: normalized.length, publicPartCount: 0 });
|
|
425
425
|
const usageItems = [];
|
|
426
426
|
for (const message of normalized) {
|
|
427
427
|
if (contentOf(message)?.type !== "function_response")
|
|
@@ -436,7 +436,7 @@ export function normalizeCreativeMessages(messages) {
|
|
|
436
436
|
continue;
|
|
437
437
|
const model = nonEmptyString(extra?.scene_code);
|
|
438
438
|
if (model === undefined)
|
|
439
|
-
return fail();
|
|
439
|
+
return fail("AGENT_USAGE_MODEL_MISSING", { messageCount: normalized.length, publicPartCount: publicParts.length });
|
|
440
440
|
usageItems.push({ model, cost: { unit: "gaodou", amount } });
|
|
441
441
|
}
|
|
442
442
|
return {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
1
2
|
function isMessage(value) {
|
|
2
3
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3
4
|
}
|
|
@@ -118,7 +119,14 @@ export async function parseCreativeStream(stream, signal, onContextId) {
|
|
|
118
119
|
signal.removeEventListener("abort", onAbort);
|
|
119
120
|
reader.releaseLock();
|
|
120
121
|
}
|
|
121
|
-
|
|
122
|
+
const messages = messagesFrom(raw);
|
|
123
|
+
if (messages.length === 0) {
|
|
124
|
+
const payloads = extractPayloads(raw);
|
|
125
|
+
throw new RemoteProtocolError({ remoteBody: JSON.stringify({ messageCount: 0, contextIdPresent: false, systemErrorCount: 0,
|
|
126
|
+
streamHadBytes: raw.length > 0, streamPayloadCount: Math.min(payloads.length, 100_000),
|
|
127
|
+
streamJsonValueCount: Math.min(payloads.reduce((count, payload) => count + parseSequence(payload).length, 0), 100_000) }) }, undefined, "AGENT_CONTEXT_ID_MISSING");
|
|
128
|
+
}
|
|
129
|
+
return messages;
|
|
122
130
|
}
|
|
123
131
|
function messagesFrom(raw) {
|
|
124
132
|
const messages = [];
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
|
+
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
2
3
|
function isRecord(value) {
|
|
3
4
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4
5
|
}
|
|
@@ -11,11 +12,19 @@ export function createFilemsResourceAuthKeyProvider(dependencies) {
|
|
|
11
12
|
credential: access.credential,
|
|
12
13
|
organizationId: access.organizationId,
|
|
13
14
|
signal
|
|
15
|
+
}).catch(error => {
|
|
16
|
+
if (error instanceof RemoteRequestError) {
|
|
17
|
+
throw new RemoteRequestError(error.status, error.transient, {
|
|
18
|
+
...(error.remoteCode === undefined ? {} : { remoteCode: error.remoteCode }),
|
|
19
|
+
...(error.remoteBody === undefined ? {} : { remoteBody: error.remoteBody })
|
|
20
|
+
}, error, "RESOURCE_AUTH_REQUEST_FAILED");
|
|
21
|
+
}
|
|
22
|
+
throw error;
|
|
14
23
|
});
|
|
15
24
|
signal.throwIfAborted();
|
|
16
25
|
if (!isRecord(response) || typeof response.auth_key !== "string"
|
|
17
26
|
|| ["", "null", "undefined"].includes(response.auth_key.trim())) {
|
|
18
|
-
throw new RemoteProtocolError();
|
|
27
|
+
throw new RemoteProtocolError({}, undefined, "RESOURCE_AUTH_INVALID_RESPONSE");
|
|
19
28
|
}
|
|
20
29
|
return response.auth_key;
|
|
21
30
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { AgentAuditRejectedError } from "../agent/creative-protocol.js";
|
|
2
|
+
import { ToolTaskFailedError } from "../tool/tool-api-adapter.js";
|
|
3
|
+
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
4
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
5
|
+
// Explicit CRC_SPAM refusals. Review timeouts and unknown request errors do not
|
|
6
|
+
// prove that a dispatched creation stopped, even when they use HTTP 400.
|
|
7
|
+
const CONTENT_REVIEW_CODES = new Set([
|
|
8
|
+
"12020751", "12020752", "12020753", "12020754", "12020755", "12020756",
|
|
9
|
+
"12020757", "12020758", "12020759", "12020760", "12020761"
|
|
10
|
+
]);
|
|
11
|
+
export function isContentReviewRejection(error) {
|
|
12
|
+
return error instanceof AgentAuditRejectedError
|
|
13
|
+
|| ((error instanceof RemoteRequestError || error instanceof RemoteProtocolError || error instanceof ToolTaskFailedError)
|
|
14
|
+
&& error.remoteCode !== undefined && CONTENT_REVIEW_CODES.has(error.remoteCode));
|
|
15
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { fork } from "node:child_process";
|
|
2
|
+
import { safeFailureSummary } from "../../telemetry/failure-summary.js";
|
|
2
3
|
function diagnosticToken(value, pattern) {
|
|
3
4
|
return typeof value === "string" && pattern.test(value) ? value : undefined;
|
|
4
5
|
}
|
|
@@ -10,6 +11,7 @@ function safeDiagnostics(value) {
|
|
|
10
11
|
const remote_error_code = diagnosticToken(record.remote_error_code, /^(?:-?\d{1,16}|[A-Z][A-Z0-9_.:-]{0,79})$/u);
|
|
11
12
|
const diagnostic_reason = diagnosticToken(record.diagnostic_reason, /^[A-Z][A-Z0-9_]{0,79}$/u);
|
|
12
13
|
const failure_stage = diagnosticToken(record.failure_stage, /^[a-z][a-z0-9_.-]{0,79}$/u);
|
|
14
|
+
const diagnostic_summary = safeFailureSummary(record.diagnostic_summary);
|
|
13
15
|
const http_status = typeof record.http_status === "number" && Number.isInteger(record.http_status)
|
|
14
16
|
&& record.http_status >= 100 && record.http_status <= 599 ? record.http_status : undefined;
|
|
15
17
|
const causes = Array.isArray(record.causes) ? record.causes.slice(0, 10).flatMap(cause => {
|
|
@@ -23,6 +25,7 @@ function safeDiagnostics(value) {
|
|
|
23
25
|
return {
|
|
24
26
|
...(error_type ? { error_type } : {}), ...(http_status === undefined ? {} : { http_status }),
|
|
25
27
|
...(remote_error_code ? { remote_error_code } : {}), ...(diagnostic_reason ? { diagnostic_reason } : {}),
|
|
28
|
+
...(diagnostic_summary ? { diagnostic_summary } : {}),
|
|
26
29
|
...(failure_stage ? { failure_stage } : {}), ...(causes?.length ? { causes } : {})
|
|
27
30
|
};
|
|
28
31
|
}
|
|
@@ -35,7 +38,8 @@ export function taskWorkerDiagnostics(error, classification, failureStage) {
|
|
|
35
38
|
}
|
|
36
39
|
return safeDiagnostics({ error_type: error instanceof Error ? error.name : typeof error,
|
|
37
40
|
http_status: classification.httpStatus, remote_error_code: classification.remoteErrorCode,
|
|
38
|
-
diagnostic_reason: classification.diagnosticReason,
|
|
41
|
+
diagnostic_reason: classification.diagnosticReason, diagnostic_summary: classification.diagnosticSummary,
|
|
42
|
+
failure_stage: failureStage, causes }) ?? {};
|
|
39
43
|
}
|
|
40
44
|
function diagnosticCause(diagnostics) {
|
|
41
45
|
let cause;
|
|
@@ -2,7 +2,7 @@ import { redactSensitiveText } from "../../platform/redact.js";
|
|
|
2
2
|
import { TaskStoreError, taskScope } from "./store.js";
|
|
3
3
|
import { LocalFileError } from "../../platform/local-json-file.js";
|
|
4
4
|
import { ToolTaskFailedError } from "../tool/tool-api-adapter.js";
|
|
5
|
-
import {
|
|
5
|
+
import { isContentReviewRejection } from "./creation-refusal.js";
|
|
6
6
|
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
7
7
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
8
8
|
export class TaskNotFoundError extends Error {
|
|
@@ -56,6 +56,7 @@ const LEASE_MS = 15_000;
|
|
|
56
56
|
export function createTaskUseCases(dependencies) {
|
|
57
57
|
const { text, commandName } = dependencies;
|
|
58
58
|
const telemetry = dependencies.telemetry;
|
|
59
|
+
let pendingOutput;
|
|
59
60
|
const warnedTasks = new Set();
|
|
60
61
|
const stage = (name, run) => telemetry ? telemetry.stage(name, run) : run();
|
|
61
62
|
function cacheWarning(id) {
|
|
@@ -71,23 +72,25 @@ export function createTaskUseCases(dependencies) {
|
|
|
71
72
|
let context = record.telemetry.context;
|
|
72
73
|
if (!record.telemetry.states?.length) {
|
|
73
74
|
const current = telemetry.creationContext();
|
|
74
|
-
context = { ...context, schema_version: "
|
|
75
|
+
context = { ...context, schema_version: "5",
|
|
75
76
|
...(current.tool_name ? { tool_name: current.tool_name } : {}),
|
|
76
77
|
...(current.model_id ? { model_id: current.model_id } : {}) };
|
|
77
78
|
record.telemetry.context = Object.freeze(context);
|
|
78
79
|
}
|
|
79
|
-
const
|
|
80
|
+
const failure = error === undefined ? {} : telemetry.taskFailure(error);
|
|
81
|
+
const make = (states = []) => {
|
|
80
82
|
const previous = states.at(-1);
|
|
81
|
-
if (
|
|
82
|
-
||
|
|
83
|
-
return
|
|
84
|
-
return { ...context, ...
|
|
85
|
-
schema_version: "
|
|
86
|
-
occurred_at_ms: at, started_at_ms: previous?.started_at_ms ?? record.telemetry?.request_sent?.occurred_at_ms ?? (state === "
|
|
83
|
+
if (states.some(event => event.schema_version === "5" && (event.result_state === "completed" || event.result_state === "success" && state === "failed"
|
|
84
|
+
|| event.result_state === state && (state !== "failed" || Object.entries(failure).every(([key, value]) => JSON.stringify(event[key]) === JSON.stringify(value))))))
|
|
85
|
+
return;
|
|
86
|
+
return { ...context, ...failure,
|
|
87
|
+
schema_version: "5", event_name: "task_state", result_state: state,
|
|
88
|
+
occurred_at_ms: at, started_at_ms: previous?.started_at_ms ?? record.telemetry?.request_sent?.occurred_at_ms ?? (state === "start" ? at : Date.parse(record.task.createdAt)),
|
|
87
89
|
task_revision: (previous?.task_revision ?? 0) + 1, record_seq: (previous?.task_revision ?? 0) + 1,
|
|
88
|
-
...(state === "completed" && record.task.result ? { result_types: resultTypes(record.task.result) } : {}) };
|
|
90
|
+
...((state === "success" || state === "completed") && record.task.result ? { result_types: resultTypes(record.task.result) } : {}) };
|
|
89
91
|
};
|
|
90
92
|
let event;
|
|
93
|
+
let writeConfirmed = false;
|
|
91
94
|
try {
|
|
92
95
|
const updated = await stage("telemetry.task", () => dependencies.store.update(scope, record.task.taskId, stored => {
|
|
93
96
|
stored.telemetry ??= { context };
|
|
@@ -100,6 +103,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
100
103
|
}));
|
|
101
104
|
if (updated.telemetry)
|
|
102
105
|
record.telemetry = updated.telemetry;
|
|
106
|
+
writeConfirmed = true;
|
|
103
107
|
}
|
|
104
108
|
catch {
|
|
105
109
|
const states = record.telemetry.states ??= [];
|
|
@@ -107,13 +111,10 @@ export function createTaskUseCases(dependencies) {
|
|
|
107
111
|
if (event && !states.some(e => e.task_revision === event.task_revision))
|
|
108
112
|
states.push(event);
|
|
109
113
|
}
|
|
110
|
-
if (event)
|
|
114
|
+
if (event) {
|
|
115
|
+
telemetry.annotate({ task_state_revision: event.task_revision, task_state_write_confirmed: writeConfirmed });
|
|
111
116
|
await telemetry.emit(event);
|
|
112
|
-
|
|
113
|
-
async function replay(record) {
|
|
114
|
-
// Old request_sent/result_ready records are readable, but are never emitted by this binary.
|
|
115
|
-
for (const event of record.telemetry?.states ?? [])
|
|
116
|
-
await telemetry?.emit(event);
|
|
117
|
+
}
|
|
117
118
|
}
|
|
118
119
|
function summary(record) {
|
|
119
120
|
const { result: _result, partialResult: _partial, ...task } = record.task;
|
|
@@ -139,7 +140,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
139
140
|
...(dependencies.creationVersion ? { cli_version: dependencies.creationVersion } : {}),
|
|
140
141
|
...(input.state.account ? { account_id: input.state.account.id } : {}), organization_id: input.state.organization.id } };
|
|
141
142
|
}
|
|
142
|
-
//
|
|
143
|
+
// Wind belongs to execution; result queries never call it.
|
|
143
144
|
const analytics = input.state.account ? await dependencies.analytics?.prepare({
|
|
144
145
|
userId: input.state.account.id, organizationId: input.state.organization.id
|
|
145
146
|
}).catch(() => undefined) : undefined;
|
|
@@ -217,7 +218,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
217
218
|
const result = await input.run(async (progress) => {
|
|
218
219
|
if (progress.dispatchedAt !== undefined) {
|
|
219
220
|
dispatched = true;
|
|
220
|
-
await fact(scope, record, "
|
|
221
|
+
await fact(scope, record, "start", progress.dispatchedAt);
|
|
221
222
|
await analyticsFact("started");
|
|
222
223
|
return;
|
|
223
224
|
}
|
|
@@ -241,7 +242,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
241
242
|
await stage("task.validate", async () => { finish(record, result); });
|
|
242
243
|
telemetry?.annotate({ result_state: record.task.state });
|
|
243
244
|
if (record.task.state === "completed") {
|
|
244
|
-
await fact(scope, record, "
|
|
245
|
+
await fact(scope, record, "success", dependencies.now().getTime());
|
|
245
246
|
await analyticsFact("completed");
|
|
246
247
|
}
|
|
247
248
|
try {
|
|
@@ -253,13 +254,13 @@ export function createTaskUseCases(dependencies) {
|
|
|
253
254
|
}
|
|
254
255
|
cacheWarning(record.task.taskId);
|
|
255
256
|
}
|
|
256
|
-
return { task: record.task, result };
|
|
257
|
+
return { task: record.task, result, record };
|
|
257
258
|
}
|
|
258
259
|
catch (error) {
|
|
259
260
|
clearInterval(timer);
|
|
260
261
|
if (record.task.state !== "completed") {
|
|
261
262
|
const mayBeRunning = dispatched || record.progress.submissionStarted;
|
|
262
|
-
const auditRejected = error
|
|
263
|
+
const auditRejected = isContentReviewRejection(error);
|
|
263
264
|
const creditsRejected = (error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
|
|
264
265
|
&& error.remoteCode === "12020770";
|
|
265
266
|
const confirmedFailure = error instanceof ToolTaskFailedError || auditRejected || creditsRejected;
|
|
@@ -276,21 +277,25 @@ export function createTaskUseCases(dependencies) {
|
|
|
276
277
|
if (detail)
|
|
277
278
|
record.task.note = [record.task.note, redactSensitiveText(detail)].filter(Boolean).join(" ");
|
|
278
279
|
telemetry?.annotate({ result_state: record.task.state });
|
|
279
|
-
if (dispatched)
|
|
280
|
-
await fact(scope, record,
|
|
280
|
+
if (dispatched && record.task.state !== "completed")
|
|
281
|
+
await fact(scope, record, "failed", dependencies.now().getTime(), error);
|
|
281
282
|
await stage("task.persist", save).catch(() => undefined);
|
|
282
283
|
throw error;
|
|
283
284
|
}
|
|
284
285
|
}
|
|
285
286
|
return {
|
|
286
287
|
async track(input) {
|
|
287
|
-
|
|
288
|
+
const execution = await execute(input, (record, result) => {
|
|
288
289
|
dependencies.validateResult?.(result);
|
|
289
290
|
record.task.state = "completed";
|
|
290
291
|
record.task.result = withoutResourceKeys(result);
|
|
291
292
|
if ("message" in result)
|
|
292
293
|
record.task.contextId = result.message.contextId;
|
|
293
|
-
})
|
|
294
|
+
});
|
|
295
|
+
if (input.executionMode !== "async") {
|
|
296
|
+
pendingOutput = { scope: taskScope(input.state), record: execution.record };
|
|
297
|
+
}
|
|
298
|
+
return execution.result;
|
|
294
299
|
},
|
|
295
300
|
async submit(input) {
|
|
296
301
|
return (await execute({ ...input, executionMode: "async" }, record => { record.progress.detached = true; })).task;
|
|
@@ -307,9 +312,10 @@ export function createTaskUseCases(dependencies) {
|
|
|
307
312
|
if (!record)
|
|
308
313
|
throw new TaskNotFoundError(text(`当前身份中没有该任务。请执行 ${commandName} task list 查找。`, `No task was found in the current identity context. Use ${commandName} task list to find it.`));
|
|
309
314
|
telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
|
|
310
|
-
await replay(record);
|
|
311
315
|
if (record.task.state === "completed" && record.task.result) {
|
|
312
|
-
|
|
316
|
+
const result = { ...record.task, result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal)) };
|
|
317
|
+
pendingOutput = { scope, record };
|
|
318
|
+
return result;
|
|
313
319
|
}
|
|
314
320
|
const task = summary(record);
|
|
315
321
|
if (task.state === "failed" || (task.state === "running" && !record.progress.detached))
|
|
@@ -325,7 +331,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
325
331
|
}
|
|
326
332
|
if (result.state === "completed" || result.state === "failed") {
|
|
327
333
|
record.task = withoutResourceKeys(result);
|
|
328
|
-
await fact(scope, record, result.state, dependencies.now().getTime(), failure);
|
|
334
|
+
await fact(scope, record, result.state === "completed" ? "success" : "failed", dependencies.now().getTime(), failure);
|
|
329
335
|
}
|
|
330
336
|
telemetry?.annotate({ result_state: result.state });
|
|
331
337
|
// Store merging protects terminal results and facts against stale heartbeats.
|
|
@@ -341,7 +347,15 @@ export function createTaskUseCases(dependencies) {
|
|
|
341
347
|
cacheWarning(id);
|
|
342
348
|
}
|
|
343
349
|
}
|
|
350
|
+
if (result.state === "completed" && result.result)
|
|
351
|
+
pendingOutput = { scope, record };
|
|
344
352
|
return result;
|
|
353
|
+
},
|
|
354
|
+
async outputCompleted() {
|
|
355
|
+
const output = pendingOutput;
|
|
356
|
+
pendingOutput = undefined;
|
|
357
|
+
if (output)
|
|
358
|
+
await fact(output.scope, output.record, "completed", dependencies.now().getTime());
|
|
345
359
|
}
|
|
346
360
|
};
|
|
347
361
|
}
|
|
@@ -3,12 +3,13 @@ import * as nodeFileSystem from "node:fs/promises";
|
|
|
3
3
|
import { join, resolve } from "node:path";
|
|
4
4
|
import { setTimeout as delay } from "node:timers/promises";
|
|
5
5
|
const localTurns = new Map();
|
|
6
|
+
const lockTimeout = () => Object.assign(new Error("Local state lock timed out."), { code: "LOCAL_LOCK_TIMEOUT" });
|
|
6
7
|
/** Same-process waiters queue before creating bakery owners. Separate processes
|
|
7
8
|
* still coordinate through unique owner files and retain the two-second budget. */
|
|
8
9
|
export async function withFileLock(path, run, options = {}) {
|
|
9
10
|
const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
|
|
10
11
|
if (Date.now() >= deadline)
|
|
11
|
-
throw
|
|
12
|
+
throw lockTimeout();
|
|
12
13
|
const key = resolve(path);
|
|
13
14
|
const previous = localTurns.get(key) ?? Promise.resolve();
|
|
14
15
|
let release;
|
|
@@ -18,7 +19,7 @@ export async function withFileLock(path, run, options = {}) {
|
|
|
18
19
|
let timer;
|
|
19
20
|
try {
|
|
20
21
|
await new Promise((ready, reject) => {
|
|
21
|
-
timer = setTimeout(() => reject(
|
|
22
|
+
timer = setTimeout(() => reject(lockTimeout()), Math.max(0, deadline - Date.now()));
|
|
22
23
|
void previous.then(ready);
|
|
23
24
|
});
|
|
24
25
|
clearTimeout(timer);
|
|
@@ -38,7 +39,7 @@ async function acquireFileLock(path, run, options) {
|
|
|
38
39
|
const { mkdir, open, readFile, readdir, unlink, chmod, rename } = fileSystem;
|
|
39
40
|
const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
|
|
40
41
|
if (Date.now() >= deadline)
|
|
41
|
-
throw
|
|
42
|
+
throw lockTimeout();
|
|
42
43
|
const directory = `${path}.d`;
|
|
43
44
|
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
44
45
|
await chmod(directory, 0o700);
|
|
@@ -91,12 +92,12 @@ async function acquireFileLock(path, run, options) {
|
|
|
91
92
|
await handle.close();
|
|
92
93
|
for (;;) {
|
|
93
94
|
if (Date.now() >= deadline)
|
|
94
|
-
throw
|
|
95
|
+
throw lockTimeout();
|
|
95
96
|
const waiting = (await contenders()).some(owner => owner.name !== name
|
|
96
97
|
&& (owner.ticket === null || owner.ticket < ticket || (owner.ticket === ticket && owner.name < name)));
|
|
97
98
|
if (!waiting) {
|
|
98
99
|
if (Date.now() >= deadline)
|
|
99
|
-
throw
|
|
100
|
+
throw lockTimeout();
|
|
100
101
|
return await run();
|
|
101
102
|
}
|
|
102
103
|
await delay(10);
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const flags = new Set(["bodyUsedAtReceipt", "bodyLockedAtReceipt", "bodyUsedBeforeRead",
|
|
2
|
+
"bodyLockedBeforeRead", "reusedResponse", "contextIdPresent", "streamHadBytes"]);
|
|
3
|
+
const counts = new Set(["messageCount", "invalidMessageCount", "systemErrorCount", "publicPartCount",
|
|
4
|
+
"streamPayloadCount", "streamJsonValueCount"]);
|
|
5
|
+
/** Fixed diagnostic facts, never arbitrary response fields or error messages. */
|
|
6
|
+
export function safeFailureSummary(value) {
|
|
7
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
8
|
+
return undefined;
|
|
9
|
+
const result = {};
|
|
10
|
+
for (const [key, field] of Object.entries(value)) {
|
|
11
|
+
if (flags.has(key) && typeof field === "boolean")
|
|
12
|
+
result[key] = field;
|
|
13
|
+
if (counts.has(key) && typeof field === "number" && Number.isSafeInteger(field) && field >= 0 && field <= 100_000)
|
|
14
|
+
result[key] = field;
|
|
15
|
+
if (key === "systemCode" && typeof field === "string"
|
|
16
|
+
&& /^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,40}|LOCAL_LOCK_TIMEOUT)$/u.test(field))
|
|
17
|
+
result[key] = field;
|
|
18
|
+
}
|
|
19
|
+
return Object.keys(result).length ? result : undefined;
|
|
20
|
+
}
|
|
@@ -17,6 +17,7 @@ export function createTelemetryInvocation(options) {
|
|
|
17
17
|
let sequence = 0;
|
|
18
18
|
const context = {};
|
|
19
19
|
const events = [];
|
|
20
|
+
const published = new Set();
|
|
20
21
|
const failures = [];
|
|
21
22
|
function base() {
|
|
22
23
|
const mode = definition?.mode?.();
|
|
@@ -38,6 +39,7 @@ export function createTelemetryInvocation(options) {
|
|
|
38
39
|
...(c.httpStatus === undefined ? {} : { http_status: c.httpStatus }),
|
|
39
40
|
...(c.remoteErrorCode === undefined ? {} : { remote_error_code: c.remoteErrorCode }),
|
|
40
41
|
...(c.remoteErrorBody === undefined ? {} : { remote_error_body: c.remoteErrorBody }),
|
|
42
|
+
...(c.diagnosticSummary === undefined ? {} : { diagnostic_summary: c.diagnosticSummary }),
|
|
41
43
|
...(c.diagnosticReason === undefined ? {} : { diagnostic_reason: c.diagnosticReason }) };
|
|
42
44
|
}
|
|
43
45
|
function failureStage(error) {
|
|
@@ -54,8 +56,11 @@ export function createTelemetryInvocation(options) {
|
|
|
54
56
|
return safe;
|
|
55
57
|
}
|
|
56
58
|
async function publish(event) {
|
|
59
|
+
if (!options.onEvent)
|
|
60
|
+
return;
|
|
57
61
|
try {
|
|
58
|
-
await options.onEvent
|
|
62
|
+
if (await options.onEvent(event) !== false)
|
|
63
|
+
published.add(event);
|
|
59
64
|
}
|
|
60
65
|
catch { /* Logging cannot fail the operation. */ }
|
|
61
66
|
}
|
|
@@ -80,7 +85,7 @@ export function createTelemetryInvocation(options) {
|
|
|
80
85
|
}
|
|
81
86
|
},
|
|
82
87
|
creationContext() {
|
|
83
|
-
const { record_seq: _seq, occurred_at_ms: _time, parameters: _parameters, warning_codes: _warnings, invalid_model_count: _invalidModels, content_id: _content, task_id: _task, dify_task_id: _dify, result_state: _state, ...snapshot } = base();
|
|
88
|
+
const { record_seq: _seq, occurred_at_ms: _time, parameters: _parameters, warning_codes: _warnings, invalid_model_count: _invalidModels, task_state_revision: _revision, task_state_write_confirmed: _written, sls_enqueue_failures: _queueFailures, sls_last_enqueue_error: _queueError, content_id: _content, task_id: _task, dify_task_id: _dify, result_state: _state, ...snapshot } = base();
|
|
84
89
|
return cleanDiagnostic({ ...snapshot, mode: "execute" });
|
|
85
90
|
},
|
|
86
91
|
async emit(event) { await publish(remember(event)); },
|
|
@@ -91,6 +96,7 @@ export function createTelemetryInvocation(options) {
|
|
|
91
96
|
...(c.errorCode === undefined ? {} : { error_code: c.errorCode }),
|
|
92
97
|
...(c.httpStatus === undefined ? {} : { http_status: c.httpStatus }),
|
|
93
98
|
...(c.remoteErrorCode === undefined ? {} : { remote_error_code: c.remoteErrorCode }),
|
|
99
|
+
...(c.diagnosticSummary === undefined ? {} : { diagnostic_summary: c.diagnosticSummary }),
|
|
94
100
|
...(c.diagnosticReason === undefined && c.outcome !== "interrupted" ? {} : { diagnostic_reason: c.diagnosticReason ?? "LOCAL_WAIT_INTERRUPTED" }),
|
|
95
101
|
...(failedAt === undefined ? {} : { failure_stage: failedAt }) };
|
|
96
102
|
},
|
|
@@ -130,7 +136,7 @@ export function createTelemetryInvocation(options) {
|
|
|
130
136
|
...(completion.remoteErrorCode === undefined ? {} : { remote_error_code: completion.remoteErrorCode }),
|
|
131
137
|
...(completion.remoteErrorBody === undefined ? {} : { remote_error_body: completion.remoteErrorBody })
|
|
132
138
|
} : {}) });
|
|
133
|
-
return events;
|
|
139
|
+
return events.filter(event => !published.has(event));
|
|
134
140
|
}
|
|
135
141
|
};
|
|
136
142
|
}
|
|
@@ -60,6 +60,8 @@ export function createSlsTelemetrySink(options) {
|
|
|
60
60
|
const now = options.now ?? Date.now;
|
|
61
61
|
const entries = new Map();
|
|
62
62
|
let writes = Promise.resolve();
|
|
63
|
+
let enqueueFailures = 0;
|
|
64
|
+
let lastEnqueueError;
|
|
63
65
|
const file = (id) => createLocalJsonFile({ directory: options.directory, filename: `${id}.json` });
|
|
64
66
|
let exitDeadline = Infinity;
|
|
65
67
|
const locked = (run, deadline) => options.directory
|
|
@@ -142,7 +144,8 @@ export function createSlsTelemetrySink(options) {
|
|
|
142
144
|
}
|
|
143
145
|
function enqueue(events, deadline) {
|
|
144
146
|
if (events.length === 0)
|
|
145
|
-
return writes;
|
|
147
|
+
return writes.then(() => true);
|
|
148
|
+
let accepted = true;
|
|
146
149
|
writes = writes.catch(() => undefined).then(() => locked(async () => {
|
|
147
150
|
await load(deadline);
|
|
148
151
|
for (const event of events) {
|
|
@@ -154,11 +157,16 @@ export function createSlsTelemetrySink(options) {
|
|
|
154
157
|
await persist(id, { event: wireEvent(event), queuedAt: now(), nextAttempt: 0, attempts: 0 });
|
|
155
158
|
}
|
|
156
159
|
await trim(deadline);
|
|
157
|
-
}, deadline)).catch(
|
|
160
|
+
}, deadline)).catch(error => {
|
|
161
|
+
accepted = false;
|
|
162
|
+
enqueueFailures++;
|
|
163
|
+
lastEnqueueError = error instanceof Error && error.message === "Local state lock timed out." ? "lock_timeout"
|
|
164
|
+
: error instanceof Error && error.message === "Telemetry delivery budget exhausted." ? "budget_exhausted" : "storage_error";
|
|
165
|
+
});
|
|
158
166
|
if (options.background && deadline === undefined)
|
|
159
167
|
void writes.then(() => { if (!sending)
|
|
160
168
|
void start(Math.min(Date.now() + BUDGET, exitDeadline)); });
|
|
161
|
-
return writes;
|
|
169
|
+
return writes.then(() => accepted);
|
|
162
170
|
}
|
|
163
171
|
let sending;
|
|
164
172
|
async function flush(deadline) {
|
|
@@ -223,6 +231,9 @@ export function createSlsTelemetrySink(options) {
|
|
|
223
231
|
return sending;
|
|
224
232
|
}
|
|
225
233
|
return { enqueue,
|
|
234
|
+
// This snapshot describes enqueue attempts before final flush, not SLS acceptance.
|
|
235
|
+
diagnostics: () => ({ sls_enqueue_failures: enqueueFailures,
|
|
236
|
+
...(lastEnqueueError ? { sls_last_enqueue_error: lastEnqueueError } : {}) }),
|
|
226
237
|
async send(events) {
|
|
227
238
|
const deadline = exitDeadline = Date.now() + BUDGET;
|
|
228
239
|
await enqueue(events, deadline);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@insmind/cli",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.13",
|
|
4
4
|
"description": "insMind command-line interface for agents and people.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"@gaoding/cli": "workspace:*"
|
|
47
47
|
},
|
|
48
48
|
"gaodingRelease": {
|
|
49
|
-
"sourceCommit": "
|
|
50
|
-
"pipelineId": "
|
|
51
|
-
"pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/
|
|
49
|
+
"sourceCommit": "3cfa7151f00ae7207dbb5d7148adaeb5b6c3a413",
|
|
50
|
+
"pipelineId": "221754",
|
|
51
|
+
"pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/221754"
|
|
52
52
|
}
|
|
53
53
|
}
|