@insmind/cli 1.5.10 → 1.5.12
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 +1 -0
- 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/store.js +3 -1
- package/dist/src/features/task/task-background.js +5 -1
- package/dist/src/features/task/use-cases.js +67 -26
- package/dist/src/platform/file-lock.js +6 -5
- package/dist/src/telemetry/failure-summary.js +20 -0
- package/dist/src/telemetry/invocation.js +13 -1
- package/dist/src/telemetry/sls-sink.js +16 -5
- package/package.json +4 -4
|
@@ -139,6 +139,7 @@ async function checkUpdateNotification(updateNotification, signal) {
|
|
|
139
139
|
}
|
|
140
140
|
async function sendFinished(options, completion) {
|
|
141
141
|
await analyticsShutdown.get(options.program)?.().catch(() => undefined);
|
|
142
|
+
options.telemetry.annotate(options.telemetrySink.diagnostics?.() ?? {});
|
|
142
143
|
const events = options.telemetry.finish(completion);
|
|
143
144
|
if (events.length > 0)
|
|
144
145
|
await options.telemetrySink.send(events).catch(() => undefined);
|
|
@@ -384,7 +384,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
384
384
|
catch (error) {
|
|
385
385
|
if (!(error instanceof ToolTaskFailedError))
|
|
386
386
|
throw error;
|
|
387
|
-
return { state: "failed", note: text(error.message, "The Tool run failed.") };
|
|
387
|
+
return { state: "failed", note: text(error.message, "The Tool run failed."), failure: error };
|
|
388
388
|
}
|
|
389
389
|
if (response.state === "pending")
|
|
390
390
|
return { state: "running", note: text("原 Tool 查询尚未返回最终结果。", "The original Tool is still processing.") };
|
|
@@ -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
|
+
}
|
|
@@ -75,7 +75,9 @@ export function createTaskStore(options) {
|
|
|
75
75
|
if (previous.telemetry)
|
|
76
76
|
record.telemetry = {
|
|
77
77
|
...record.telemetry, ...previous.telemetry,
|
|
78
|
-
context: previous.telemetry.request_sent ? previous.telemetry.context : record.telemetry?.context ?? previous.telemetry.context
|
|
78
|
+
context: previous.telemetry.states?.length || previous.telemetry.request_sent ? previous.telemetry.context : record.telemetry?.context ?? previous.telemetry.context,
|
|
79
|
+
states: [...new Map([...(record.telemetry?.states ?? []), ...(previous.telemetry.states ?? [])]
|
|
80
|
+
.map(event => [event.task_revision, event])).values()].sort((a, b) => a.task_revision - b.task_revision)
|
|
79
81
|
};
|
|
80
82
|
}
|
|
81
83
|
options.validate(record.task);
|
|
@@ -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,9 @@ 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
|
+
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
7
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
6
8
|
export class TaskNotFoundError extends Error {
|
|
7
9
|
constructor(message) { super(message); this.name = "TaskNotFoundError"; }
|
|
8
10
|
}
|
|
@@ -34,6 +36,21 @@ export function withoutResourceKeys(value) {
|
|
|
34
36
|
}
|
|
35
37
|
return clean(value);
|
|
36
38
|
}
|
|
39
|
+
function resultTypes(result) {
|
|
40
|
+
const types = new Set();
|
|
41
|
+
const parts = "message" in result ? result.message.parts : result.content;
|
|
42
|
+
for (const part of parts) {
|
|
43
|
+
if ("text" in part)
|
|
44
|
+
types.add("text");
|
|
45
|
+
else if ("data" in part)
|
|
46
|
+
types.add("clarification");
|
|
47
|
+
else {
|
|
48
|
+
const mime = "mediaType" in part ? part.mediaType : "mimeType" in part ? part.mimeType : undefined;
|
|
49
|
+
types.add(mime?.startsWith("image/") ? "image" : mime?.startsWith("video/") ? "video" : "other");
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return [...types].sort();
|
|
53
|
+
}
|
|
37
54
|
const HEARTBEAT_MS = 5_000;
|
|
38
55
|
const LEASE_MS = 15_000;
|
|
39
56
|
export function createTaskUseCases(dependencies) {
|
|
@@ -48,42 +65,59 @@ export function createTaskUseCases(dependencies) {
|
|
|
48
65
|
telemetry?.annotate({ warning_codes: ["TASK_CACHE_UNAVAILABLE"] });
|
|
49
66
|
(dependencies.warning ?? dependencies.notice)(text(`任务 ${id} 的本地记录未能保存,task get 可能无法恢复。请保留本次输出,不要重新提交创作。`, `The local record for task ${id} could not be saved; task get may not recover it. Keep this output and do not submit the creation again.`));
|
|
50
67
|
}
|
|
51
|
-
async function fact(scope, record,
|
|
68
|
+
async function fact(scope, record, state, at, error) {
|
|
52
69
|
if (!telemetry || !record.telemetry)
|
|
53
70
|
return;
|
|
54
71
|
let context = record.telemetry.context;
|
|
55
|
-
if (
|
|
72
|
+
if (!record.telemetry.states?.length) {
|
|
56
73
|
const current = telemetry.creationContext();
|
|
57
|
-
context = { ...context,
|
|
74
|
+
context = { ...context, schema_version: "4",
|
|
58
75
|
...(current.tool_name ? { tool_name: current.tool_name } : {}),
|
|
59
76
|
...(current.model_id ? { model_id: current.model_id } : {}) };
|
|
60
|
-
// Fix the creation identity at dispatch even if the fact cannot be saved.
|
|
61
|
-
// Later completion and recovery must not use mutable command annotations.
|
|
62
77
|
record.telemetry.context = Object.freeze(context);
|
|
63
78
|
}
|
|
64
|
-
const
|
|
65
|
-
|
|
79
|
+
const make = (states) => {
|
|
80
|
+
const previous = states.at(-1);
|
|
81
|
+
if (previous?.result_state === state || previous?.result_state === "completed"
|
|
82
|
+
|| previous?.result_state === "failed" && state !== "completed")
|
|
83
|
+
return previous;
|
|
84
|
+
return { ...context, ...(error === undefined ? {} : telemetry.taskFailure(error)),
|
|
85
|
+
schema_version: "4", event_name: "task_state", result_state: state,
|
|
86
|
+
occurred_at_ms: at, started_at_ms: previous?.started_at_ms ?? record.telemetry?.request_sent?.occurred_at_ms ?? (state === "running" ? at : Date.parse(record.task.createdAt)),
|
|
87
|
+
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) } : {}) };
|
|
89
|
+
};
|
|
90
|
+
let event;
|
|
91
|
+
let writeConfirmed = false;
|
|
66
92
|
try {
|
|
67
93
|
const updated = await stage("telemetry.task", () => dependencies.store.update(scope, record.task.taskId, stored => {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
94
|
+
stored.telemetry ??= { context };
|
|
95
|
+
const states = stored.telemetry.states ??= [];
|
|
96
|
+
// A stale caller cannot overwrite the first immutable revision.
|
|
97
|
+
event = make(states);
|
|
98
|
+
if (event && !states.some(e => e.task_revision === event.task_revision))
|
|
99
|
+
states.push(event);
|
|
100
|
+
stored.telemetry.context = context;
|
|
72
101
|
}));
|
|
73
102
|
if (updated.telemetry)
|
|
74
103
|
record.telemetry = updated.telemetry;
|
|
104
|
+
writeConfirmed = true;
|
|
75
105
|
}
|
|
76
106
|
catch {
|
|
77
|
-
|
|
78
|
-
|
|
107
|
+
const states = record.telemetry.states ??= [];
|
|
108
|
+
event = make(states);
|
|
109
|
+
if (event && !states.some(e => e.task_revision === event.task_revision))
|
|
110
|
+
states.push(event);
|
|
111
|
+
}
|
|
112
|
+
if (event) {
|
|
113
|
+
telemetry.annotate({ task_state_revision: event.task_revision, task_state_write_confirmed: writeConfirmed });
|
|
114
|
+
await telemetry.emit(event);
|
|
79
115
|
}
|
|
80
|
-
await telemetry.emit(record.telemetry[name] ?? candidate);
|
|
81
116
|
}
|
|
82
117
|
async function replay(record) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
}
|
|
118
|
+
// Old request_sent/result_ready records are readable, but are never emitted by this binary.
|
|
119
|
+
for (const event of record.telemetry?.states ?? [])
|
|
120
|
+
await telemetry?.emit(event);
|
|
87
121
|
}
|
|
88
122
|
function summary(record) {
|
|
89
123
|
const { result: _result, partialResult: _partial, ...task } = record.task;
|
|
@@ -187,7 +221,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
187
221
|
const result = await input.run(async (progress) => {
|
|
188
222
|
if (progress.dispatchedAt !== undefined) {
|
|
189
223
|
dispatched = true;
|
|
190
|
-
await fact(scope, record, "
|
|
224
|
+
await fact(scope, record, "running", progress.dispatchedAt);
|
|
191
225
|
await analyticsFact("started");
|
|
192
226
|
return;
|
|
193
227
|
}
|
|
@@ -211,7 +245,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
211
245
|
await stage("task.validate", async () => { finish(record, result); });
|
|
212
246
|
telemetry?.annotate({ result_state: record.task.state });
|
|
213
247
|
if (record.task.state === "completed") {
|
|
214
|
-
await fact(scope, record, "
|
|
248
|
+
await fact(scope, record, "completed", dependencies.now().getTime());
|
|
215
249
|
await analyticsFact("completed");
|
|
216
250
|
}
|
|
217
251
|
try {
|
|
@@ -229,13 +263,15 @@ export function createTaskUseCases(dependencies) {
|
|
|
229
263
|
clearInterval(timer);
|
|
230
264
|
if (record.task.state !== "completed") {
|
|
231
265
|
const mayBeRunning = dispatched || record.progress.submissionStarted;
|
|
232
|
-
const auditRejected = error
|
|
233
|
-
const
|
|
266
|
+
const auditRejected = isContentReviewRejection(error);
|
|
267
|
+
const creditsRejected = (error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
|
|
268
|
+
&& error.remoteCode === "12020770";
|
|
269
|
+
const confirmedFailure = error instanceof ToolTaskFailedError || auditRejected || creditsRejected;
|
|
234
270
|
record.task.state = confirmedFailure || !mayBeRunning ? "failed" : "unknown";
|
|
235
271
|
record.task.note = auditRejected
|
|
236
272
|
? text("内容未通过审核,本次创作已拒绝;具体错误见原命令。", "Content review rejected this creation. See the original command for the error.")
|
|
237
273
|
: confirmedFailure
|
|
238
|
-
? text("
|
|
274
|
+
? text("服务已明确拒绝本次创作或返回任务失败;具体错误见原命令。", "The service explicitly rejected this creation or reported task failure. See the original command for the error.")
|
|
239
275
|
: mayBeRunning
|
|
240
276
|
? text("CLI 未取得完整回执或结果;远端可能仍在执行。查询原任务,不自动重新生成。", "The CLI did not receive a complete receipt or result; the service may still be running. Query this task instead of submitting again.")
|
|
241
277
|
: text("CLI 在提交创作前结束;具体错误见原命令。", "The CLI stopped before submitting the creation. See the original command for the error.");
|
|
@@ -244,6 +280,8 @@ export function createTaskUseCases(dependencies) {
|
|
|
244
280
|
if (detail)
|
|
245
281
|
record.task.note = [record.task.note, redactSensitiveText(detail)].filter(Boolean).join(" ");
|
|
246
282
|
telemetry?.annotate({ result_state: record.task.state });
|
|
283
|
+
if (dispatched)
|
|
284
|
+
await fact(scope, record, record.task.state, dependencies.now().getTime(), error);
|
|
247
285
|
await stage("task.persist", save).catch(() => undefined);
|
|
248
286
|
throw error;
|
|
249
287
|
}
|
|
@@ -280,7 +318,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
280
318
|
const task = summary(record);
|
|
281
319
|
if (task.state === "failed" || (task.state === "running" && !record.progress.detached))
|
|
282
320
|
return task;
|
|
283
|
-
const recovered = await stage("task.recover", () => dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal));
|
|
321
|
+
const { failure, ...recovered } = await stage("task.recover", () => dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal));
|
|
284
322
|
const { note: _note, ...metadata } = task;
|
|
285
323
|
const result = { ...metadata, ...recovered };
|
|
286
324
|
if (result.state === "unknown" && task.note) {
|
|
@@ -288,7 +326,10 @@ export function createTaskUseCases(dependencies) {
|
|
|
288
326
|
}
|
|
289
327
|
if (result.state === "completed" && result.result) {
|
|
290
328
|
await stage("task.validate", async () => { dependencies.validateResult?.(result.result); });
|
|
291
|
-
|
|
329
|
+
}
|
|
330
|
+
if (result.state === "completed" || result.state === "failed") {
|
|
331
|
+
record.task = withoutResourceKeys(result);
|
|
332
|
+
await fact(scope, record, result.state, dependencies.now().getTime(), failure);
|
|
292
333
|
}
|
|
293
334
|
telemetry?.annotate({ result_state: result.state });
|
|
294
335
|
// Store merging protects terminal results and facts against stale heartbeats.
|
|
@@ -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
|
+
}
|
|
@@ -38,6 +38,7 @@ export function createTelemetryInvocation(options) {
|
|
|
38
38
|
...(c.httpStatus === undefined ? {} : { http_status: c.httpStatus }),
|
|
39
39
|
...(c.remoteErrorCode === undefined ? {} : { remote_error_code: c.remoteErrorCode }),
|
|
40
40
|
...(c.remoteErrorBody === undefined ? {} : { remote_error_body: c.remoteErrorBody }),
|
|
41
|
+
...(c.diagnosticSummary === undefined ? {} : { diagnostic_summary: c.diagnosticSummary }),
|
|
41
42
|
...(c.diagnosticReason === undefined ? {} : { diagnostic_reason: c.diagnosticReason }) };
|
|
42
43
|
}
|
|
43
44
|
function failureStage(error) {
|
|
@@ -80,10 +81,21 @@ export function createTelemetryInvocation(options) {
|
|
|
80
81
|
}
|
|
81
82
|
},
|
|
82
83
|
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();
|
|
84
|
+
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
85
|
return cleanDiagnostic({ ...snapshot, mode: "execute" });
|
|
85
86
|
},
|
|
86
87
|
async emit(event) { await publish(remember(event)); },
|
|
88
|
+
taskFailure(error) {
|
|
89
|
+
const c = classify(error);
|
|
90
|
+
const failedAt = c.failureStage ?? failureStage(error);
|
|
91
|
+
return { error_type: c.errorType ?? (error instanceof Error ? error.name : typeof error),
|
|
92
|
+
...(c.errorCode === undefined ? {} : { error_code: c.errorCode }),
|
|
93
|
+
...(c.httpStatus === undefined ? {} : { http_status: c.httpStatus }),
|
|
94
|
+
...(c.remoteErrorCode === undefined ? {} : { remote_error_code: c.remoteErrorCode }),
|
|
95
|
+
...(c.diagnosticSummary === undefined ? {} : { diagnostic_summary: c.diagnosticSummary }),
|
|
96
|
+
...(c.diagnosticReason === undefined && c.outcome !== "interrupted" ? {} : { diagnostic_reason: c.diagnosticReason ?? "LOCAL_WAIT_INTERRUPTED" }),
|
|
97
|
+
...(failedAt === undefined ? {} : { failure_stage: failedAt }) };
|
|
98
|
+
},
|
|
87
99
|
async stage(name, run, details) {
|
|
88
100
|
const start = options.now();
|
|
89
101
|
const allowed = detailedStages[definition?.mode ? `${definition.operation}:${definition.mode()}` : definition?.operation ?? ""];
|
|
@@ -8,9 +8,11 @@ const TTL = 7 * 86_400_000;
|
|
|
8
8
|
const CAPACITY = 10 * 1024 * 1024;
|
|
9
9
|
const BUDGET = 2_000;
|
|
10
10
|
export function eventKey(event) {
|
|
11
|
-
const key = event.event_name === "
|
|
12
|
-
? [event.cli_name, event.env, event.cli_task_id, event.
|
|
13
|
-
:
|
|
11
|
+
const key = event.event_name === "task_state"
|
|
12
|
+
? [event.cli_name, event.env, event.cli_task_id, "task_state", Number(event.task_revision)]
|
|
13
|
+
: event.event_name === "request_sent" || event.event_name === "result_ready"
|
|
14
|
+
? [event.cli_name, event.env, event.cli_task_id, event.event_name]
|
|
15
|
+
: [event.cli_name, event.env, event.trace_id, event.process_role, Number(event.record_seq)];
|
|
14
16
|
return createHash("sha256").update(JSON.stringify(key)).digest("hex");
|
|
15
17
|
}
|
|
16
18
|
export function wireEvent(event) {
|
|
@@ -58,6 +60,8 @@ export function createSlsTelemetrySink(options) {
|
|
|
58
60
|
const now = options.now ?? Date.now;
|
|
59
61
|
const entries = new Map();
|
|
60
62
|
let writes = Promise.resolve();
|
|
63
|
+
let enqueueFailures = 0;
|
|
64
|
+
let lastEnqueueError;
|
|
61
65
|
const file = (id) => createLocalJsonFile({ directory: options.directory, filename: `${id}.json` });
|
|
62
66
|
let exitDeadline = Infinity;
|
|
63
67
|
const locked = (run, deadline) => options.directory
|
|
@@ -127,7 +131,7 @@ export function createSlsTelemetrySink(options) {
|
|
|
127
131
|
}
|
|
128
132
|
}
|
|
129
133
|
let size = [...entries.values()].reduce((sum, e) => sum + Buffer.byteLength(JSON.stringify(e)), 0);
|
|
130
|
-
const priority = (e) => e.event.event_name === "request_sent" || e.event.event_name === "result_ready" ? 2
|
|
134
|
+
const priority = (e) => e.event.event_name === "task_state" || e.event.event_name === "request_sent" || e.event.event_name === "result_ready" ? 2
|
|
131
135
|
: "outcome" in e.event && e.event.outcome !== "success" ? 1 : 0;
|
|
132
136
|
for (const [id, entry] of [...entries].sort((a, b) => priority(a[1]) - priority(b[1]) || a[1].queuedAt - b[1].queuedAt)) {
|
|
133
137
|
checkBudget(deadline);
|
|
@@ -152,7 +156,11 @@ export function createSlsTelemetrySink(options) {
|
|
|
152
156
|
await persist(id, { event: wireEvent(event), queuedAt: now(), nextAttempt: 0, attempts: 0 });
|
|
153
157
|
}
|
|
154
158
|
await trim(deadline);
|
|
155
|
-
}, deadline)).catch(
|
|
159
|
+
}, deadline)).catch(error => {
|
|
160
|
+
enqueueFailures++;
|
|
161
|
+
lastEnqueueError = error instanceof Error && error.message === "Local state lock timed out." ? "lock_timeout"
|
|
162
|
+
: error instanceof Error && error.message === "Telemetry delivery budget exhausted." ? "budget_exhausted" : "storage_error";
|
|
163
|
+
});
|
|
156
164
|
if (options.background && deadline === undefined)
|
|
157
165
|
void writes.then(() => { if (!sending)
|
|
158
166
|
void start(Math.min(Date.now() + BUDGET, exitDeadline)); });
|
|
@@ -221,6 +229,9 @@ export function createSlsTelemetrySink(options) {
|
|
|
221
229
|
return sending;
|
|
222
230
|
}
|
|
223
231
|
return { enqueue,
|
|
232
|
+
// This snapshot describes enqueue attempts before final flush, not SLS acceptance.
|
|
233
|
+
diagnostics: () => ({ sls_enqueue_failures: enqueueFailures,
|
|
234
|
+
...(lastEnqueueError ? { sls_last_enqueue_error: lastEnqueueError } : {}) }),
|
|
224
235
|
async send(events) {
|
|
225
236
|
const deadline = exitDeadline = Date.now() + BUDGET;
|
|
226
237
|
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.12",
|
|
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": "677a158421a331a863e725e8352b2fa65d6f50e8",
|
|
50
|
+
"pipelineId": "219692",
|
|
51
|
+
"pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/219692"
|
|
52
52
|
}
|
|
53
53
|
}
|