@insmind/cli 1.5.1 → 1.5.3
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/contracts/operations/auth.status/output.schema.json +3 -4
- package/dist/bin/insmind-cli.js +12 -7
- package/dist/bin/postinstall.js +7 -5
- package/dist/bin/{agent-worker.js → task-worker.js} +5 -4
- package/dist/src/analytics/device.js +23 -0
- package/dist/src/analytics/wind.js +54 -0
- package/dist/src/bootstrap/create-cli.js +33 -19
- package/dist/src/bootstrap/create-runtime.js +45 -16
- package/dist/src/bootstrap/{run-agent-worker.js → run-task-worker.js} +20 -10
- package/dist/src/bootstrap/validators.js +10 -5
- package/dist/src/cli/action-binding.js +14 -0
- package/dist/src/cli/agent-commands.js +9 -4
- package/dist/src/cli/auth-commands.js +5 -3
- package/dist/src/cli/credits-command.js +2 -2
- package/dist/src/cli/dam-commands.js +51 -52
- package/dist/src/cli/editor-commands.js +13 -15
- package/dist/src/cli/errors.js +97 -44
- package/dist/src/cli/model-commands.js +6 -4
- package/dist/src/cli/presenter.js +13 -10
- package/dist/src/cli/task-commands.js +13 -5
- package/dist/src/cli/tool-commands.js +11 -5
- package/dist/src/features/agent/use-cases.js +11 -5
- package/dist/src/features/auth/access-policy.js +2 -0
- package/dist/src/features/auth/credential-store.js +2 -2
- package/dist/src/features/auth/sso-service.js +5 -4
- package/dist/src/features/auth/state.js +11 -1
- package/dist/src/features/auth/use-cases.js +43 -40
- package/dist/src/features/credits/use-cases.js +2 -0
- package/dist/src/features/dam/file-downloader.js +38 -16
- package/dist/src/features/dam/object-storage.js +23 -11
- package/dist/src/features/dam/operation-executor.js +46 -37
- package/dist/src/features/dam/registered-uploader.js +39 -29
- package/dist/src/features/dam/storage-upload.js +5 -4
- package/dist/src/features/dam/use-cases.js +81 -60
- package/dist/src/features/editor/bridge-client.js +6 -6
- package/dist/src/features/editor/bridge-process.js +2 -1
- package/dist/src/features/editor/session-state.js +6 -4
- package/dist/src/features/editor/session.js +26 -8
- package/dist/src/features/editor/use-cases.js +10 -3
- package/dist/src/features/org/use-cases.js +2 -1
- package/dist/src/features/task/store.js +4 -0
- package/dist/src/features/task/{agent-background.js → task-background.js} +5 -4
- package/dist/src/features/task/use-cases.js +123 -28
- package/dist/src/features/tool/catalog.js +11 -5
- package/dist/src/features/tool/dynamic-schema.js +9 -7
- package/dist/src/features/tool/mns-catalog-adapter.js +1 -0
- package/dist/src/features/tool/tool-api-adapter.js +8 -7
- package/dist/src/features/tool/use-cases.js +8 -4
- package/dist/src/features/update/update-notification.js +75 -70
- package/dist/src/features/update/update-service.js +24 -20
- package/dist/src/platform/file-lock.js +36 -9
- package/dist/src/platform/interruption.js +13 -0
- package/dist/src/platform/json-input.js +12 -9
- package/dist/src/platform/local-json-file.js +8 -4
- package/dist/src/platform/redact.js +7 -1
- package/dist/src/platform/remote-protocol.js +2 -2
- package/dist/src/platform/safe-upload-file.js +2 -1
- package/dist/src/platform/schema-issues.js +8 -0
- package/dist/src/platform/signed-http-transport.js +8 -7
- package/dist/src/platform/text-output.js +33 -0
- package/dist/src/telemetry/invocation.js +19 -4
- package/dist/src/telemetry/process-errors.js +14 -4
- package/dist/src/telemetry/sanitize.js +4 -2
- package/dist/src/telemetry/sls-sink.js +36 -20
- package/dist/vendor/README.md +10 -0
- package/dist/vendor/gd-tracker-node.mjs +1175 -0
- package/package.json +4 -4
package/dist/bin/insmind-cli.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { isInterruption } from "../src/platform/interruption.js";
|
|
2
4
|
import { insmindProduct } from "../src/product/config.js";
|
|
3
5
|
import { localeOption } from "../src/product/locale.js";
|
|
6
|
+
const startedAt = Date.now();
|
|
7
|
+
const bootstrapTraceId = randomBytes(16).toString("hex");
|
|
4
8
|
const controller = new AbortController();
|
|
5
9
|
const interrupt = () => controller.abort(new Error("SIGINT"));
|
|
6
10
|
process.once("SIGINT", interrupt);
|
|
@@ -35,28 +39,29 @@ try {
|
|
|
35
39
|
});
|
|
36
40
|
}
|
|
37
41
|
catch (error) {
|
|
42
|
+
const traceId = runtime?.telemetry.traceId ?? bootstrapTraceId;
|
|
38
43
|
try {
|
|
39
44
|
const { reportProcessError } = await import("../src/telemetry/process-errors.js");
|
|
40
|
-
await reportProcessError(error, { operation: "bootstrap", stateDirectory: ".insmind" });
|
|
45
|
+
await reportProcessError(error, { operation: "bootstrap", startedAt, traceId, signal: controller.signal, stateDirectory: ".insmind" });
|
|
41
46
|
}
|
|
42
47
|
catch { /* Retain startup error output even if diagnostic modules cannot load. */ }
|
|
43
48
|
if (mapCliError === undefined || redact === undefined) {
|
|
44
|
-
process.stderr.write(
|
|
49
|
+
process.stderr.write(`INTERNAL_ERROR: CLI failed to start. Diagnostic ID: ${traceId}\n`);
|
|
45
50
|
process.exitCode = 1;
|
|
46
51
|
}
|
|
47
52
|
else {
|
|
48
|
-
const outcome = redact(mapCliError(error, { aborted: controller.signal
|
|
53
|
+
const outcome = redact(mapCliError(error, { aborted: isInterruption(error, controller.signal), product: insmindProduct }));
|
|
49
54
|
if (runtime) {
|
|
50
|
-
runtime.presenter.error(outcome, { json: process.argv.includes("--json") });
|
|
55
|
+
runtime.presenter.error(outcome, { json: process.argv.includes("--json"), traceId });
|
|
51
56
|
}
|
|
52
57
|
else if (outcome.kind === "interrupted") {
|
|
53
|
-
process.stderr.write(
|
|
58
|
+
process.stderr.write(`Local waiting stopped; dispatched operations may still be active. Diagnostic ID: ${traceId}\n`);
|
|
54
59
|
}
|
|
55
60
|
else if (process.argv.includes("--json")) {
|
|
56
|
-
process.stderr.write(`${JSON.stringify({ error: outcome.failure })}\n`);
|
|
61
|
+
process.stderr.write(`${JSON.stringify({ error: { ...outcome.failure, trace_id: traceId } })}\n`);
|
|
57
62
|
}
|
|
58
63
|
else {
|
|
59
|
-
process.stderr.write(`${outcome.failure.code}: ${outcome.failure.message}\n`);
|
|
64
|
+
process.stderr.write(`${outcome.failure.code}: ${outcome.failure.message}\nDiagnostic ID: ${traceId}\n`);
|
|
60
65
|
}
|
|
61
66
|
process.exitCode = outcome.exitCode;
|
|
62
67
|
}
|
package/dist/bin/postinstall.js
CHANGED
|
@@ -18,11 +18,13 @@ export function isSupportedGlobalLifecycle(env) {
|
|
|
18
18
|
&& /\/v\d+\/[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16}$/u.test(initialDirectory);
|
|
19
19
|
}
|
|
20
20
|
export async function runPostinstall(options = {}) {
|
|
21
|
+
const startedAt = Date.now();
|
|
21
22
|
const env = options.env ?? process.env;
|
|
23
|
+
const english = env.npm_package_name === "@insmind/cli";
|
|
22
24
|
if (!isSupportedGlobalLifecycle(env))
|
|
23
25
|
return;
|
|
24
26
|
const reportError = options.reportError ?? (options.env ? async () => undefined : (error) => reportProcessError(error, {
|
|
25
|
-
operation: "postinstall", processRole: "postinstall", stateDirectory: env.npm_package_name === "@insmind/cli" ? ".insmind" : ".gd"
|
|
27
|
+
operation: "postinstall", startedAt, processRole: "postinstall", stateDirectory: env.npm_package_name === "@insmind/cli" ? ".insmind" : ".gd"
|
|
26
28
|
}));
|
|
27
29
|
const writeError = options.writeError ?? ((text) => process.stderr.write(text));
|
|
28
30
|
let skills;
|
|
@@ -32,9 +34,9 @@ export async function runPostinstall(options = {}) {
|
|
|
32
34
|
catch (error) {
|
|
33
35
|
await reportError(error);
|
|
34
36
|
if (env.GD_CLI_INSTALL_OWNER === "workbuddy") {
|
|
35
|
-
throw new Error("无法确认当前安装的 package。");
|
|
37
|
+
throw new Error(english ? "Cannot identify the installed package." : "无法确认当前安装的 package。", { cause: error });
|
|
36
38
|
}
|
|
37
|
-
writeError(
|
|
39
|
+
writeError(`${english ? "Warning: Agent Skill installation failed; inspect the target paths and permissions." : "警告: Agent Skill 安装失败,请检查目标路径和权限。"} ${oneLineMessage(error)}\n`);
|
|
38
40
|
return;
|
|
39
41
|
}
|
|
40
42
|
const [primarySkill] = skills;
|
|
@@ -49,7 +51,7 @@ export async function runPostinstall(options = {}) {
|
|
|
49
51
|
if (owner === "workbuddy")
|
|
50
52
|
return;
|
|
51
53
|
if (owner === "invalid")
|
|
52
|
-
throw new Error("无法确认当前安装的托管信息。");
|
|
54
|
+
throw new Error(english ? "Cannot identify the installation owner." : "无法确认当前安装的托管信息。");
|
|
53
55
|
try {
|
|
54
56
|
await (options.syncSkills ?? syncBundledSkills)(skills, {
|
|
55
57
|
env,
|
|
@@ -58,7 +60,7 @@ export async function runPostinstall(options = {}) {
|
|
|
58
60
|
}
|
|
59
61
|
catch (error) {
|
|
60
62
|
await reportError(error);
|
|
61
|
-
writeError(
|
|
63
|
+
writeError(`${english ? "Warning: Agent Skill installation failed; inspect the target paths and permissions." : "警告: Agent Skill 安装失败,请检查目标路径和权限。"} ${oneLineMessage(error)}\n`);
|
|
62
64
|
}
|
|
63
65
|
}
|
|
64
66
|
function oneLineMessage(error) {
|
|
@@ -4,11 +4,12 @@ import { once } from "node:events";
|
|
|
4
4
|
import { Readable } from "node:stream";
|
|
5
5
|
import { gaodingProduct, insmindProduct } from "../src/product/config.js";
|
|
6
6
|
import { createProductionRuntime } from "../src/bootstrap/create-runtime.js";
|
|
7
|
-
import {
|
|
7
|
+
import { runTaskWorker } from "../src/bootstrap/run-task-worker.js";
|
|
8
8
|
if (!process.send) {
|
|
9
9
|
process.exitCode = 2;
|
|
10
10
|
}
|
|
11
11
|
else {
|
|
12
|
+
const startedAt = Date.now();
|
|
12
13
|
const controller = new AbortController();
|
|
13
14
|
const interrupt = () => controller.abort(new Error("SIGINT"));
|
|
14
15
|
process.once("SIGINT", interrupt);
|
|
@@ -26,17 +27,17 @@ else {
|
|
|
26
27
|
for (const key of Object.keys(endpoints))
|
|
27
28
|
endpoints[key] = new URL(job.endpoints[key]);
|
|
28
29
|
const runtime = createProductionRuntime({
|
|
29
|
-
processRole: "agent_worker",
|
|
30
|
+
processRole: job.operation === "tool.call" ? "tool_worker" : "agent_worker",
|
|
30
31
|
...(job.telemetryVersion ? { telemetryVersion: job.telemetryVersion } : {}),
|
|
31
32
|
...(job.telemetryTrackingUrl ? { telemetryTrackingUrl: new URL(job.telemetryTrackingUrl) } : {}),
|
|
32
33
|
...(job.telemetryEnvironment ? { telemetryEnvironment: job.telemetryEnvironment } : {}),
|
|
33
34
|
product, endpoints, homeDirectory: job.homeDirectory, locale: job.locale,
|
|
34
35
|
io: { input: Readable.from([]), stdout: { write() { } }, stderr: { write() { } } }
|
|
35
36
|
});
|
|
36
|
-
await
|
|
37
|
+
await runTaskWorker({ runtime, job, signal: controller.signal, send });
|
|
37
38
|
}
|
|
38
39
|
catch (error) {
|
|
39
|
-
await reportProcessError(error, { operation: "bootstrap", processRole: "agent_worker",
|
|
40
|
+
await reportProcessError(error, { operation: "bootstrap", processRole: currentJob?.operation === "tool.call" ? "tool_worker" : "agent_worker", startedAt, signal: controller.signal,
|
|
40
41
|
stateDirectory: currentJob?.product === "insmind" ? ".insmind" : ".gd",
|
|
41
42
|
...(currentJob?.telemetryTrackingUrl ? { trackingUrl: new URL(currentJob.telemetryTrackingUrl) } : {}),
|
|
42
43
|
...(currentJob?.telemetryEnvironment ? { environment: currentJob.telemetryEnvironment } : {}),
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { withFileLock } from "../platform/file-lock.js";
|
|
4
|
+
import { createLocalJsonFile } from "../platform/local-json-file.js";
|
|
5
|
+
export async function loadAnalyticsDevice(directory, now) {
|
|
6
|
+
return withFileLock(join(directory, "analytics-device.lock"), async () => {
|
|
7
|
+
const file = createLocalJsonFile({ directory, filename: "analytics-device.json" });
|
|
8
|
+
const text = await file.readText();
|
|
9
|
+
if (text !== null) {
|
|
10
|
+
const device = JSON.parse(text);
|
|
11
|
+
if (!/^[A-Za-z0-9_-]{8,64}$/u.test(device.id) || !Number.isFinite(device.createdAt) || device.createdAt <= 0) {
|
|
12
|
+
throw new Error("Invalid analytics device state");
|
|
13
|
+
}
|
|
14
|
+
return device;
|
|
15
|
+
}
|
|
16
|
+
const device = { id: randomUUID(), createdAt: now() };
|
|
17
|
+
await file.writeTextAtomically(`${JSON.stringify(device)}\n`);
|
|
18
|
+
return device;
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
export function isFirstDay(createdAt, now) {
|
|
22
|
+
return new Date(createdAt).setHours(23, 59, 59, 999) >= now ? 1 : 0;
|
|
23
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { loadAnalyticsDevice, isFirstDay } from "./device.js";
|
|
2
|
+
/** One application adapter owns SDK identity and lifecycle. No SLS payloads enter Wind. */
|
|
3
|
+
export function createWindAnalytics(options) {
|
|
4
|
+
const trackers = new Set();
|
|
5
|
+
const insmind = options.product === "insmind";
|
|
6
|
+
const project = insmind ? "insmind_cli" : "gd_cli";
|
|
7
|
+
return {
|
|
8
|
+
async prepare(identity) {
|
|
9
|
+
try {
|
|
10
|
+
return await options.stage("wind.setup", async () => {
|
|
11
|
+
if (!identity.userId.trim() || !identity.organizationId.trim())
|
|
12
|
+
throw new Error("Missing analytics identity");
|
|
13
|
+
const device = await loadAnalyticsDevice(options.directory, options.now);
|
|
14
|
+
const { CliWindTracker, createNodeAdapters } = await import("../../vendor/gd-tracker-node.mjs");
|
|
15
|
+
const tracker = new CliWindTracker();
|
|
16
|
+
await tracker.setup({ mode: "cli", project, version: options.version, env: options.environment,
|
|
17
|
+
region: insmind ? "US" : "CHINA", deviceId: device.id,
|
|
18
|
+
userAgent: `${insmind ? "insmind-cli" : "gd-cli"}/${options.version}`,
|
|
19
|
+
adapters: createNodeAdapters({ fetch: options.fetch, deliveryBudgetMs: 1_500 }) });
|
|
20
|
+
tracker.set("common", { user_id: identity.userId, is_login: 1,
|
|
21
|
+
organization: { org_id: identity.organizationId },
|
|
22
|
+
channel_id: options.environment === "prod" ? (insmind ? "781" : "32") : (insmind ? "316" : "31") });
|
|
23
|
+
trackers.add(tracker);
|
|
24
|
+
return {
|
|
25
|
+
context: { ...identity, deviceId: device.id, version: options.version, project },
|
|
26
|
+
track(event, details) {
|
|
27
|
+
void options.stage("wind.send", async () => {
|
|
28
|
+
tracker.set("common", { is_first_day: isFirstDay(device.createdAt, options.now()) });
|
|
29
|
+
// Explicit whitelist: command parameters and diagnostics are never spread into details.
|
|
30
|
+
const payload = { event_id: event === "started" ? 37010 : 37011,
|
|
31
|
+
tool_type: details.tool_type, tool_name: details.tool_name,
|
|
32
|
+
...(details.model_name ? { model_name: details.model_name } : {}) };
|
|
33
|
+
const result = await tracker.trackEvent(event === "started" ? "tool_conflate_start" : "tool_conflate_completed", payload);
|
|
34
|
+
if (!result.accepted)
|
|
35
|
+
throw new Error(result.errorCode ?? "WIND_DELIVERY_FAILED");
|
|
36
|
+
}).catch(() => undefined);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
async shutdown() {
|
|
46
|
+
await Promise.all([...trackers].map(tracker => options.stage("wind.shutdown", async () => {
|
|
47
|
+
const summary = await tracker.shutdown({ timeoutMs: 500 });
|
|
48
|
+
if (!summary.flushed)
|
|
49
|
+
throw new Error(summary.errorCode ?? "WIND_FLUSH_TIMEOUT");
|
|
50
|
+
}).catch(() => undefined)));
|
|
51
|
+
trackers.clear();
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { isInterruption } from "../platform/interruption.js";
|
|
1
2
|
import { registerTaskCommands } from "../cli/task-commands.js";
|
|
2
3
|
import { Command, CommanderError } from "commander";
|
|
3
|
-
import { assertAllLeafCommandsBound, configureActionEnvironment } from "../cli/action-binding.js";
|
|
4
|
+
import { assertAllLeafCommandsBound, errorUsesJson, configureActionEnvironment } from "../cli/action-binding.js";
|
|
4
5
|
import { registerAgentCommands } from "../cli/agent-commands.js";
|
|
5
6
|
import { registerAuthCommands } from "../cli/auth-commands.js";
|
|
6
7
|
import { classifyTelemetryError, isHelpOutcome, mapCliError } from "../cli/errors.js";
|
|
@@ -13,6 +14,8 @@ import { registerUpdateCommand } from "../cli/update-command.js";
|
|
|
13
14
|
import { registerCreditsCommand } from "../cli/credits-command.js";
|
|
14
15
|
import { redact } from "../platform/redact.js";
|
|
15
16
|
export { assertAllLeafCommandsBound, bindAction } from "../cli/action-binding.js";
|
|
17
|
+
const outputs = new WeakMap();
|
|
18
|
+
const analyticsShutdown = new WeakMap();
|
|
16
19
|
export function createCli(runtime, options) {
|
|
17
20
|
runtime.telemetry.useSignal(options.signal);
|
|
18
21
|
const program = new Command()
|
|
@@ -28,6 +31,9 @@ export function createCli(runtime, options) {
|
|
|
28
31
|
writeOut: runtime.io.writeOut,
|
|
29
32
|
writeErr: () => undefined
|
|
30
33
|
});
|
|
34
|
+
program.addHelpText("after", runtime.product.id === "insmind"
|
|
35
|
+
? "\nstdout contains command results; stderr contains progress, warnings and errors. Fixed JSON commands and --json use {error:{code,message,details?,trace_id?}} for final errors. stderr may contain multiple messages.\nExit codes: 0 success, 1 execution failure, 2 invalid input, 130 local interruption; dispatched work may still be active.\n"
|
|
36
|
+
: "\nstdout 输出命令结果;stderr 输出进度、警告和错误。固定 JSON 命令和 --json 的最终错误使用 {error:{code,message,details?,trace_id?}},stderr 可能包含多条信息。\n退出码:0 成功,1 执行失败,2 输入无效,130 本地中断;已派发的工作可能仍在继续。\n");
|
|
31
37
|
if (runtime.product.id === "insmind") {
|
|
32
38
|
program.option("--locale <locale>", "locale for service-owned business descriptions");
|
|
33
39
|
}
|
|
@@ -50,26 +56,31 @@ export function createCli(runtime, options) {
|
|
|
50
56
|
registerUpdateCommand(program, runtime);
|
|
51
57
|
registerTaskCommands(program, runtime);
|
|
52
58
|
assertAllLeafCommandsBound(program);
|
|
59
|
+
outputs.set(program, runtime.io);
|
|
60
|
+
if (runtime.analytics)
|
|
61
|
+
analyticsShutdown.set(program, () => runtime.analytics.shutdown());
|
|
53
62
|
return program;
|
|
54
63
|
}
|
|
55
64
|
export async function executeCli(options) {
|
|
65
|
+
let helpOnly = false;
|
|
56
66
|
try {
|
|
57
|
-
|
|
58
|
-
|
|
67
|
+
try {
|
|
68
|
+
await options.program.parseAsync(options.argv, { from: "user" });
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
if (!isHelpOutcome(error))
|
|
72
|
+
throw error;
|
|
73
|
+
helpOnly = true;
|
|
74
|
+
if (options.argv[0] !== "update")
|
|
75
|
+
await checkUpdateNotification(options.updateNotification, options.signal);
|
|
76
|
+
options.signal.throwIfAborted();
|
|
77
|
+
}
|
|
78
|
+
await options.telemetry.stage("output", async () => { await outputs.get(options.program)?.flush?.(); });
|
|
79
|
+
if (!helpOnly)
|
|
80
|
+
await sendFinished(options, { outcome: "success" });
|
|
59
81
|
return 0;
|
|
60
82
|
}
|
|
61
83
|
catch (error) {
|
|
62
|
-
if (isHelpOutcome(error)) {
|
|
63
|
-
if (options.argv[0] !== "update") {
|
|
64
|
-
await checkUpdateNotification(options.updateNotification, options.signal);
|
|
65
|
-
}
|
|
66
|
-
if (options.signal.aborted) {
|
|
67
|
-
options.presenter.error({ kind: "interrupted", exitCode: 130 }, { json: options.argv.includes("--json") });
|
|
68
|
-
await sendFinished(options, { outcome: "interrupted" });
|
|
69
|
-
return 130;
|
|
70
|
-
}
|
|
71
|
-
return 0;
|
|
72
|
-
}
|
|
73
84
|
if (!options.telemetry.selected)
|
|
74
85
|
options.telemetry.select({ operation: "unknown" });
|
|
75
86
|
if (options.telemetry.selected && error instanceof CommanderError) {
|
|
@@ -81,22 +92,23 @@ export async function executeCli(options) {
|
|
|
81
92
|
}
|
|
82
93
|
}
|
|
83
94
|
const outcome = redact(mapCliError(error, {
|
|
84
|
-
aborted:
|
|
95
|
+
aborted: isInterruption(error, options.signal),
|
|
85
96
|
...(options.product ? { product: options.product } : {})
|
|
86
97
|
}));
|
|
87
|
-
const telemetryError = classifyTelemetryError(error, { aborted:
|
|
98
|
+
const telemetryError = classifyTelemetryError(error, { aborted: isInterruption(error, options.signal), ...(options.product ? { product: options.product } : {}) });
|
|
88
99
|
const traceId = options.telemetry.selected
|
|
89
100
|
? options.telemetry.traceId
|
|
90
101
|
: undefined;
|
|
91
102
|
try {
|
|
92
103
|
options.presenter.error(outcome, {
|
|
93
|
-
json: options.argv
|
|
104
|
+
json: errorUsesJson(options.program, options.argv),
|
|
94
105
|
...(traceId ? { traceId } : {})
|
|
95
106
|
});
|
|
96
107
|
}
|
|
97
108
|
catch (presenterError) {
|
|
98
109
|
await options.telemetry.stage("output", () => { throw presenterError; }).catch(() => undefined);
|
|
99
110
|
}
|
|
111
|
+
await options.telemetry.stage("output", async () => { await outputs.get(options.program)?.flush?.(); }).catch(() => undefined);
|
|
100
112
|
await sendFinished(options, outcome.kind === "interrupted"
|
|
101
113
|
? { outcome: "interrupted", error }
|
|
102
114
|
: {
|
|
@@ -127,6 +139,8 @@ async function checkUpdateNotification(updateNotification, signal) {
|
|
|
127
139
|
}
|
|
128
140
|
async function sendFinished(options, completion) {
|
|
129
141
|
const events = options.telemetry.finish(completion);
|
|
130
|
-
|
|
131
|
-
|
|
142
|
+
await Promise.all([
|
|
143
|
+
events.length > 0 ? options.telemetrySink.send(events).catch(() => undefined) : undefined,
|
|
144
|
+
analyticsShutdown.get(options.program)?.().catch(() => undefined)
|
|
145
|
+
]);
|
|
132
146
|
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import { createWindAnalytics } from "../analytics/wind.js";
|
|
1
2
|
import { taskScope } from "../features/task/store.js";
|
|
3
|
+
import { createTextOutput } from "../platform/text-output.js";
|
|
2
4
|
import { TaskNotFoundError } from "../features/task/use-cases.js";
|
|
3
5
|
import { homedir } from "node:os";
|
|
4
|
-
import {
|
|
6
|
+
import { createTaskBackgroundLauncher } from "../features/task/task-background.js";
|
|
5
7
|
import { createTaskStore } from "../features/task/store.js";
|
|
6
8
|
import { createTaskUseCases } from "../features/task/use-cases.js";
|
|
7
9
|
import { readAgentResult } from "../features/agent/result-reader.js";
|
|
@@ -98,6 +100,14 @@ export function createProductionRuntime(options = {}) {
|
|
|
98
100
|
classifyError: error => classifyTelemetryError(error, { product }),
|
|
99
101
|
onEvent: async (event) => { await telemetrySink.enqueue?.([event]); }
|
|
100
102
|
});
|
|
103
|
+
// Explicit test transport enables SDK tests; test-mode child processes never emit real analytics.
|
|
104
|
+
const analytics = options.analytics ?? (telemetryEnvironment === "production" || options.windFetch
|
|
105
|
+
? createWindAnalytics({ product: product.id, version: options.telemetryVersion ?? primarySkill.version,
|
|
106
|
+
directory: join(options.homeDirectory ?? homedir(), product.stateDirectory),
|
|
107
|
+
environment: telemetryEnvironment === "production" ? "prod" : "dev", fetch: options.windFetch ?? fetch,
|
|
108
|
+
now: () => now().getTime(),
|
|
109
|
+
stage: (name, run) => telemetry.stage(name, run)
|
|
110
|
+
}) : undefined);
|
|
101
111
|
const rawIo = options.io ?? {
|
|
102
112
|
input: process.stdin,
|
|
103
113
|
stdout: process.stdout,
|
|
@@ -105,9 +115,12 @@ export function createProductionRuntime(options = {}) {
|
|
|
105
115
|
inputTerminal: process.stdin.isTTY === true,
|
|
106
116
|
stderrTerminal: process.stderr.isTTY === true
|
|
107
117
|
};
|
|
118
|
+
const stdout = createTextOutput(rawIo.stdout);
|
|
119
|
+
const stderr = createTextOutput(rawIo.stderr);
|
|
108
120
|
const io = {
|
|
109
|
-
writeOut:
|
|
110
|
-
writeError:
|
|
121
|
+
writeOut: stdout.write,
|
|
122
|
+
writeError: stderr.write,
|
|
123
|
+
flush: async () => { await Promise.all([stdout.flush(), stderr.flush()]); },
|
|
111
124
|
inputTerminal: rawIo.inputTerminal ?? hasTerminal(rawIo.input),
|
|
112
125
|
stderrTerminal: rawIo.stderrTerminal ?? hasTerminal(rawIo.stderr)
|
|
113
126
|
};
|
|
@@ -188,7 +201,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
188
201
|
}
|
|
189
202
|
});
|
|
190
203
|
const storage = options.objectStorage ?? createObjectStorageUploader({ fetch, now,
|
|
191
|
-
|
|
204
|
+
telemetry
|
|
192
205
|
});
|
|
193
206
|
const credits = createCreditsUseCases({
|
|
194
207
|
transport: creditsTransport,
|
|
@@ -230,7 +243,8 @@ export function createProductionRuntime(options = {}) {
|
|
|
230
243
|
uploader: createDamRegisteredUploader({
|
|
231
244
|
api: damApi,
|
|
232
245
|
storage: storageUpload,
|
|
233
|
-
warn: (message) => { presenter.warning(message); },
|
|
246
|
+
warn: (message) => { telemetry.annotate({ warning_codes: ["ASSET_ANALYSIS_PENDING"] }); presenter.warning(message); },
|
|
247
|
+
...(product.id === "insmind" ? { analysisPendingMessage: "Asset analysis is still pending; the current registered asset is returned." } : {}),
|
|
234
248
|
now,
|
|
235
249
|
telemetry
|
|
236
250
|
}),
|
|
@@ -306,6 +320,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
306
320
|
};
|
|
307
321
|
const tasks = createTaskUseCases({
|
|
308
322
|
telemetry,
|
|
323
|
+
...(analytics ? { analytics } : {}),
|
|
309
324
|
...(options.telemetryVersion ? { creationVersion: options.telemetryVersion } : {}),
|
|
310
325
|
validateResult: result => {
|
|
311
326
|
if ("message" in result)
|
|
@@ -321,6 +336,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
321
336
|
idFactory: randomUUID,
|
|
322
337
|
now,
|
|
323
338
|
notice: message => presenter.notice(message),
|
|
339
|
+
warning: message => presenter.warning(message),
|
|
324
340
|
commandName: product.commandName,
|
|
325
341
|
text,
|
|
326
342
|
failureNote: error => {
|
|
@@ -351,16 +367,27 @@ export function createProductionRuntime(options = {}) {
|
|
|
351
367
|
state: "unknown", note: text("本地记录未取得可查询的 Tool 回执;不自动重新生成。", "No queryable Tool receipt was recorded; do not generate again.")
|
|
352
368
|
};
|
|
353
369
|
await authorizeTaskAccess(state, signal);
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
370
|
+
const taskId = progress.remoteTaskId;
|
|
371
|
+
let response;
|
|
372
|
+
try {
|
|
373
|
+
response = await telemetry.stage("task.query", async () => {
|
|
374
|
+
const result = await queryToolResult(toolTransport, {
|
|
375
|
+
taskId, credential: state.credential, organizationId: state.organization.id, signal
|
|
376
|
+
});
|
|
377
|
+
if (result.difyTaskId)
|
|
378
|
+
telemetry.annotate({ dify_task_id: result.difyTaskId });
|
|
379
|
+
if (result.state === "failed")
|
|
380
|
+
throw result.error;
|
|
381
|
+
return result;
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
if (!(error instanceof ToolTaskFailedError))
|
|
386
|
+
throw error;
|
|
387
|
+
return { state: "failed", note: text(error.message, "The Tool run failed.") };
|
|
388
|
+
}
|
|
358
389
|
if (response.state === "pending")
|
|
359
390
|
return { state: "running", note: text("原 Tool 查询尚未返回最终结果。", "The original Tool is still processing.") };
|
|
360
|
-
if (response.state === "failed") {
|
|
361
|
-
await telemetry.stage("task.recover", () => { throw response.error; }).catch(() => undefined);
|
|
362
|
-
return { state: "failed", note: text(response.error.message, response.error instanceof ToolTaskFailedError ? "The Tool run failed." : "The Tool service response is incompatible with this CLI.") };
|
|
363
|
-
}
|
|
364
391
|
return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
|
|
365
392
|
content: response.content, usage: progress.toolUsage
|
|
366
393
|
}, product.billingUnit), state, signal, true) };
|
|
@@ -382,6 +409,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
382
409
|
const tool = withToolBillingUnit(createToolUseCases({
|
|
383
410
|
catalog: modelCatalog,
|
|
384
411
|
tools: product.tools,
|
|
412
|
+
...(product.id === "insmind" ? { modelDescription: "Model machine identifier from model list." } : {}),
|
|
385
413
|
execution: createToolApiAdapter({ transport: toolTransport, telemetry }),
|
|
386
414
|
uploader: transientUploader,
|
|
387
415
|
warn: (message) => { presenter.warning(message); },
|
|
@@ -434,7 +462,7 @@ export function createProductionRuntime(options = {}) {
|
|
|
434
462
|
}
|
|
435
463
|
};
|
|
436
464
|
const updateNotification = createUpdateNotificationService({
|
|
437
|
-
|
|
465
|
+
telemetry,
|
|
438
466
|
currentVersion: primarySkill.version,
|
|
439
467
|
fetch,
|
|
440
468
|
now,
|
|
@@ -453,13 +481,14 @@ export function createProductionRuntime(options = {}) {
|
|
|
453
481
|
version: primarySkill.version,
|
|
454
482
|
telemetry,
|
|
455
483
|
telemetrySink,
|
|
484
|
+
...(analytics ? { analytics } : {}),
|
|
456
485
|
accessPolicies,
|
|
457
486
|
auth,
|
|
458
487
|
org,
|
|
459
488
|
agent,
|
|
460
489
|
tasks,
|
|
461
|
-
|
|
462
|
-
workerPath: join(packageRoot, "dist", "bin", "
|
|
490
|
+
startBackgroundTask: (input, signal) => (options.taskBackground ?? createTaskBackgroundLauncher({
|
|
491
|
+
workerPath: join(packageRoot, "dist", "bin", "task-worker.js"), env
|
|
463
492
|
})).submit({ ...input, product: product.id, homeDirectory: options.homeDirectory ?? homedir(),
|
|
464
493
|
telemetryEnvironment, telemetryVersion: primarySkill.version,
|
|
465
494
|
telemetryTrackingUrl: String(options.telemetryTrackingUrl ?? product.telemetryUrl),
|
|
@@ -1,20 +1,26 @@
|
|
|
1
|
+
import { requireUserIdentity } from "../features/auth/state.js";
|
|
2
|
+
import { isInterruption } from "../platform/interruption.js";
|
|
1
3
|
import { mapCliError } from "../cli/errors.js";
|
|
2
4
|
import { redact } from "../platform/redact.js";
|
|
3
|
-
export async function
|
|
5
|
+
export async function runTaskWorker(options) {
|
|
4
6
|
const runtime = options.runtime;
|
|
5
7
|
const { job, signal, send } = options;
|
|
6
8
|
runtime.telemetry.useSignal(signal);
|
|
7
|
-
runtime.telemetry.select({ operation:
|
|
9
|
+
runtime.telemetry.select({ operation: job.operation, mode: () => "execute" });
|
|
8
10
|
runtime.telemetry.annotate({ account_id: job.state.account?.id, organization_id: job.state.organization.id,
|
|
9
11
|
parameters: { ...job.input }, execution_mode: "async" });
|
|
10
12
|
let completion = { outcome: "success" };
|
|
11
13
|
let started = false;
|
|
12
14
|
let accepted = false;
|
|
13
15
|
try {
|
|
14
|
-
runtime.
|
|
16
|
+
await runtime.telemetry.stage("access", async () => { requireUserIdentity(job.state); });
|
|
17
|
+
if (job.operation === "agent.send")
|
|
18
|
+
runtime.validators.agentSendInput(job.input);
|
|
19
|
+
else
|
|
20
|
+
runtime.validators.toolCallInput(job.input);
|
|
15
21
|
await runtime.tasks.track({
|
|
16
22
|
state: job.state,
|
|
17
|
-
operation:
|
|
23
|
+
operation: job.operation,
|
|
18
24
|
label: job.label,
|
|
19
25
|
executionMode: "async",
|
|
20
26
|
onUpdate(task, progress) {
|
|
@@ -22,27 +28,31 @@ export async function runAgentWorker(options) {
|
|
|
22
28
|
started = true;
|
|
23
29
|
send({ type: "started", task });
|
|
24
30
|
}
|
|
25
|
-
if (progress.accepted && !accepted) {
|
|
31
|
+
if ((progress.accepted || progress.remoteTaskId) && !accepted) {
|
|
26
32
|
accepted = true;
|
|
27
33
|
send({ type: "accepted", task });
|
|
28
34
|
}
|
|
29
35
|
},
|
|
30
36
|
run: async (observe) => {
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
37
|
+
const access = { credential: job.state.credential, organizationId: job.state.organization.id };
|
|
38
|
+
const result = job.operation === "agent.send"
|
|
39
|
+
? await runtime.agent.send({ input: job.input, signal, observe, access })
|
|
40
|
+
: await runtime.tool.call({ input: job.input, signal, observe, access });
|
|
34
41
|
return result;
|
|
35
42
|
}
|
|
36
43
|
});
|
|
37
44
|
}
|
|
38
45
|
catch (error) {
|
|
39
|
-
const outcome = redact(mapCliError(error, { aborted:
|
|
46
|
+
const outcome = redact(mapCliError(error, { aborted: isInterruption(error, signal), product: runtime.product }));
|
|
40
47
|
completion = outcome.kind === "interrupted" ? { outcome: "interrupted", error }
|
|
41
48
|
: { outcome: "failure", error, errorCode: outcome.failure.code, errorMessage: outcome.failure.message };
|
|
42
49
|
if (outcome.kind === "failure")
|
|
43
50
|
send({ type: "error", failure: outcome.failure, exitCode: outcome.exitCode });
|
|
44
51
|
}
|
|
45
52
|
finally {
|
|
46
|
-
await
|
|
53
|
+
await Promise.all([
|
|
54
|
+
runtime.telemetrySink.send(runtime.telemetry.finish(completion)).catch(() => undefined),
|
|
55
|
+
runtime.analytics?.shutdown().catch(() => undefined)
|
|
56
|
+
]);
|
|
47
57
|
}
|
|
48
58
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { validationIssues } from "../platform/schema-issues.js";
|
|
1
2
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
2
3
|
import addFormatsImport, {} from "ajv-formats";
|
|
3
4
|
import { contractSchema } from "../contracts/schema.js";
|
|
@@ -43,14 +44,18 @@ const toolCallInputSchema = contractSchema("tool.call", "input");
|
|
|
43
44
|
const toolCallOutputSchema = contractSchema("tool.call", "output");
|
|
44
45
|
const toolListOutputSchema = contractSchema("tool.list", "output");
|
|
45
46
|
export class InputContractError extends Error {
|
|
46
|
-
|
|
47
|
-
|
|
47
|
+
issues;
|
|
48
|
+
constructor(issues = []) {
|
|
49
|
+
super(`输入不符合命令契约。${issues.length ? ` ${JSON.stringify(issues)}` : ""}`);
|
|
50
|
+
this.issues = issues;
|
|
48
51
|
this.name = "InputContractError";
|
|
49
52
|
}
|
|
50
53
|
}
|
|
51
54
|
export class OutputContractError extends Error {
|
|
52
|
-
|
|
53
|
-
|
|
55
|
+
issues;
|
|
56
|
+
constructor(issues = []) {
|
|
57
|
+
super(`命令结果不符合公开契约。${issues.length ? ` ${JSON.stringify(issues)}` : ""}`);
|
|
58
|
+
this.issues = issues;
|
|
54
59
|
this.name = "OutputContractError";
|
|
55
60
|
}
|
|
56
61
|
}
|
|
@@ -164,6 +169,6 @@ const unavailableValidator = Object.assign(() => false, { errors: null, schema:
|
|
|
164
169
|
function assertion(validate, ErrorType) {
|
|
165
170
|
return (value) => {
|
|
166
171
|
if (!validate(value))
|
|
167
|
-
throw new ErrorType();
|
|
172
|
+
throw new ErrorType(validationIssues(validate.errors));
|
|
168
173
|
};
|
|
169
174
|
}
|
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
const environments = new WeakMap();
|
|
2
2
|
const boundPolicies = new WeakMap();
|
|
3
|
+
const jsonCommands = new WeakSet();
|
|
4
|
+
const selectedCommands = new WeakMap();
|
|
5
|
+
/** Declare the existing fixed JSON contract alongside the command registration. */
|
|
6
|
+
export function jsonOutput(command) {
|
|
7
|
+
jsonCommands.add(command);
|
|
8
|
+
}
|
|
9
|
+
export function errorUsesJson(program, argv) {
|
|
10
|
+
const command = selectedCommands.get(program);
|
|
11
|
+
if (command)
|
|
12
|
+
return jsonCommands.has(command) || command.opts().json === true;
|
|
13
|
+
const end = argv.indexOf("--");
|
|
14
|
+
return (end < 0 ? argv : argv.slice(0, end)).includes("--json");
|
|
15
|
+
}
|
|
3
16
|
export function configureActionEnvironment(program, environment) {
|
|
4
17
|
environments.set(program, environment);
|
|
5
18
|
}
|
|
@@ -83,6 +96,7 @@ function bindTelemetrySelection(command, definition) {
|
|
|
83
96
|
command.parent.hook("preSubcommand", (parent, selected) => {
|
|
84
97
|
if (selected !== command)
|
|
85
98
|
return;
|
|
99
|
+
selectedCommands.set(rootCommand(parent), command);
|
|
86
100
|
const environment = environments.get(rootCommand(parent));
|
|
87
101
|
if (!environment)
|
|
88
102
|
throw new Error("CLI action environment is missing.");
|