@insmind/cli 1.3.1 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/agent-worker.js +13 -1
- package/dist/bin/insmind-cli.js +7 -0
- package/dist/bin/postinstall.js +11 -2
- package/dist/src/bootstrap/create-cli.js +15 -7
- package/dist/src/bootstrap/create-runtime.js +73 -35
- package/dist/src/bootstrap/run-agent-worker.js +12 -1
- package/dist/src/cli/action-binding.js +1 -2
- package/dist/src/cli/errors.js +5 -3
- package/dist/src/cli/task-commands.js +3 -2
- package/dist/src/features/agent/creative-agent-adapter.js +1 -0
- package/dist/src/features/agent/creative-protocol.js +4 -2
- package/dist/src/features/auth/access-policy.js +8 -0
- package/dist/src/features/auth/sso-service.js +76 -26
- package/dist/src/features/auth/use-cases.js +1 -1
- package/dist/src/features/dam/file-downloader.js +6 -6
- package/dist/src/features/dam/object-storage.js +6 -4
- package/dist/src/features/editor/bridge-process.js +9 -3
- package/dist/src/features/editor/bridge-server.js +4 -2
- package/dist/src/features/org/use-cases.js +8 -3
- package/dist/src/features/task/store.js +34 -2
- package/dist/src/features/task/use-cases.js +71 -6
- package/dist/src/features/tool/tool-api-adapter.js +1 -0
- package/dist/src/features/update/update-notification.js +4 -2
- package/dist/src/platform/file-lock.js +68 -0
- package/dist/src/platform/redact.js +1 -1
- package/dist/src/platform/safe-upload-file.js +3 -3
- package/dist/src/platform/signed-http-transport.js +23 -9
- package/dist/src/telemetry/invocation.js +74 -122
- package/dist/src/telemetry/process-errors.js +43 -0
- package/dist/src/telemetry/sanitize.js +72 -0
- package/dist/src/telemetry/sls-sink.js +209 -22
- package/package.json +4 -4
- package/skills/insmind-cli/references/creation.md +12 -0
|
@@ -1,11 +1,16 @@
|
|
|
1
|
+
import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
1
2
|
import { normalizeScope } from "./state.js";
|
|
2
3
|
import { signBindOrganization } from "../../platform/signature.js";
|
|
3
4
|
export class SsoRequestError extends Error {
|
|
4
5
|
status;
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
remoteCode;
|
|
7
|
+
remoteBody;
|
|
8
|
+
constructor(status, evidence = {}, cause) {
|
|
9
|
+
super(status === undefined ? "无法连接稿定登录服务。" : `稿定登录服务请求失败(HTTP ${status})。`, { cause });
|
|
7
10
|
this.name = "SsoRequestError";
|
|
8
11
|
this.status = status;
|
|
12
|
+
this.remoteCode = evidence.remoteCode;
|
|
13
|
+
this.remoteBody = evidence.remoteBody;
|
|
9
14
|
}
|
|
10
15
|
}
|
|
11
16
|
export function classifyBindOutcome(input) {
|
|
@@ -24,22 +29,62 @@ export function createSsoService(options) {
|
|
|
24
29
|
const baseUrl = new URL(options.ssoApi);
|
|
25
30
|
if (!baseUrl.pathname.endsWith("/"))
|
|
26
31
|
baseUrl.pathname += "/";
|
|
32
|
+
const requests = new WeakMap();
|
|
33
|
+
async function responseError(response, networkError) {
|
|
34
|
+
let evidence = {};
|
|
35
|
+
if (!response.ok && !response.bodyUsed) {
|
|
36
|
+
try {
|
|
37
|
+
evidence = remoteErrorEvidence(await response.text());
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
networkError = error;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return new SsoRequestError(response.status, {
|
|
44
|
+
...(evidence.remoteCode === undefined ? {} : { remoteCode: evidence.remoteCode }),
|
|
45
|
+
...remoteErrorEvidence({ request: requests.get(response),
|
|
46
|
+
...(evidence.remoteBody === undefined ? {} : { response: evidence.remoteBody }),
|
|
47
|
+
...(networkError === undefined ? {} : { network: networkFailure(networkError) }) })
|
|
48
|
+
}, networkError);
|
|
49
|
+
}
|
|
50
|
+
async function responseRecord(response) {
|
|
51
|
+
if (!response.ok) {
|
|
52
|
+
// OAuth pending/slow_down are normal token polling responses.
|
|
53
|
+
const body = await response.clone().json().catch(() => undefined);
|
|
54
|
+
if (isRecord(body) && ["authorization_pending", "slow_down"].includes(String(body.error).toLowerCase()))
|
|
55
|
+
return body;
|
|
56
|
+
throw await responseError(response);
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const value = await response.json();
|
|
60
|
+
if (isRecord(value))
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
throw await responseError(response, error);
|
|
65
|
+
}
|
|
66
|
+
throw await responseError(response);
|
|
67
|
+
}
|
|
27
68
|
async function request(relativeUrl, signal, method = "POST") {
|
|
28
69
|
signal.throwIfAborted();
|
|
70
|
+
const url = new URL(relativeUrl, baseUrl);
|
|
71
|
+
const requestInfo = { method, path: url.pathname };
|
|
29
72
|
try {
|
|
30
|
-
|
|
73
|
+
const response = await options.fetch(url, {
|
|
31
74
|
method,
|
|
32
|
-
headers: { Accept: "application/json" },
|
|
75
|
+
headers: { Accept: "application/json", ...(options.traceparent ? { traceparent: options.traceparent() } : {}) },
|
|
33
76
|
signal: AbortSignal.any([
|
|
34
77
|
signal,
|
|
35
78
|
AbortSignal.timeout(options.timeoutMs ?? 30_000)
|
|
36
79
|
])
|
|
37
80
|
});
|
|
81
|
+
requests.set(response, requestInfo);
|
|
82
|
+
return response;
|
|
38
83
|
}
|
|
39
|
-
catch {
|
|
84
|
+
catch (error) {
|
|
40
85
|
if (signal.aborted)
|
|
41
86
|
throw signal.reason;
|
|
42
|
-
throw new SsoRequestError();
|
|
87
|
+
throw new SsoRequestError(undefined, remoteErrorEvidence({ request: requestInfo, network: networkFailure(error) }), error);
|
|
43
88
|
}
|
|
44
89
|
}
|
|
45
90
|
return {
|
|
@@ -48,14 +93,14 @@ export function createSsoService(options) {
|
|
|
48
93
|
clientId: options.clientId ?? "gdhub-cli"
|
|
49
94
|
})}`, signal);
|
|
50
95
|
if (!response.ok)
|
|
51
|
-
throw
|
|
96
|
+
throw await responseError(response);
|
|
52
97
|
const body = await responseRecord(response);
|
|
53
98
|
const authorizeCode = nonEmptyString(body.authorize_code);
|
|
54
99
|
const deviceCode = nonEmptyString(body.device_code);
|
|
55
100
|
const expiresInSeconds = positiveNumber(body.expires_in);
|
|
56
101
|
const intervalSeconds = positiveNumber(body.interval);
|
|
57
102
|
if (!authorizeCode || !deviceCode || !expiresInSeconds || !intervalSeconds) {
|
|
58
|
-
throw
|
|
103
|
+
throw await responseError(response);
|
|
59
104
|
}
|
|
60
105
|
return { authorizeCode, deviceCode, expiresInSeconds, intervalSeconds };
|
|
61
106
|
},
|
|
@@ -72,18 +117,18 @@ export function createSsoService(options) {
|
|
|
72
117
|
if (error === "slow_down")
|
|
73
118
|
return { status: "slow_down" };
|
|
74
119
|
if (!response.ok)
|
|
75
|
-
throw
|
|
120
|
+
throw await responseError(response);
|
|
76
121
|
const accessKey = nonEmptyString(body.ak);
|
|
77
122
|
const secretKey = nonEmptyString(body.sk);
|
|
78
123
|
const expiresAt = dateString(body.expires_at);
|
|
79
124
|
if (!accessKey || !secretKey || !expiresAt)
|
|
80
|
-
throw
|
|
125
|
+
throw await responseError(response);
|
|
81
126
|
let scope;
|
|
82
127
|
try {
|
|
83
128
|
scope = normalizeScope(body.scope);
|
|
84
129
|
}
|
|
85
130
|
catch {
|
|
86
|
-
throw
|
|
131
|
+
throw await responseError(response);
|
|
87
132
|
}
|
|
88
133
|
const result = {
|
|
89
134
|
status: "authorized",
|
|
@@ -104,7 +149,7 @@ export function createSsoService(options) {
|
|
|
104
149
|
const query = new URLSearchParams({ ak: accessKey });
|
|
105
150
|
const response = await request(`oauth/device/identity?${query}`, signal, "GET");
|
|
106
151
|
if (!response.ok)
|
|
107
|
-
throw
|
|
152
|
+
throw await responseError(response);
|
|
108
153
|
const body = await responseRecord(response);
|
|
109
154
|
const result = {};
|
|
110
155
|
const userId = identifier(body.userId);
|
|
@@ -130,8 +175,12 @@ export function createSsoService(options) {
|
|
|
130
175
|
});
|
|
131
176
|
const response = await request(`oauth/device/bind-org?${query}`, signal);
|
|
132
177
|
if (!response.ok)
|
|
133
|
-
throw
|
|
134
|
-
const text = await response.text()
|
|
178
|
+
throw await responseError(response);
|
|
179
|
+
const text = await response.text().catch(async (error) => {
|
|
180
|
+
if (signal.aborted)
|
|
181
|
+
throw signal.reason;
|
|
182
|
+
throw await responseError(response, error);
|
|
183
|
+
});
|
|
135
184
|
if (!text.trim())
|
|
136
185
|
return {};
|
|
137
186
|
let parsed;
|
|
@@ -142,7 +191,7 @@ export function createSsoService(options) {
|
|
|
142
191
|
return { message: text.trim() };
|
|
143
192
|
}
|
|
144
193
|
if (!isRecord(parsed))
|
|
145
|
-
throw
|
|
194
|
+
throw await responseError(response);
|
|
146
195
|
const result = {};
|
|
147
196
|
if (typeof parsed.code === "string" || typeof parsed.code === "number") {
|
|
148
197
|
result.code = parsed.code;
|
|
@@ -153,23 +202,24 @@ export function createSsoService(options) {
|
|
|
153
202
|
if (parsed.bind_expires_at !== undefined) {
|
|
154
203
|
const bindExpiresAt = dateString(parsed.bind_expires_at);
|
|
155
204
|
if (!bindExpiresAt)
|
|
156
|
-
throw
|
|
205
|
+
throw await responseError(response);
|
|
157
206
|
result.bindExpiresAt = bindExpiresAt;
|
|
158
207
|
}
|
|
159
208
|
return result;
|
|
160
209
|
}
|
|
161
210
|
};
|
|
162
211
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
}
|
|
172
|
-
|
|
212
|
+
// Preserve only bounded diagnostic identifiers, never arbitrary cause messages/URLs.
|
|
213
|
+
function networkFailure(error) {
|
|
214
|
+
const safe = (value) => typeof value === "string" && /^[A-Za-z0-9_]{1,80}$/u.test(value) ? value : undefined;
|
|
215
|
+
const one = (value) => {
|
|
216
|
+
const record = value !== null && typeof value === "object" ? value : {};
|
|
217
|
+
const name = safe(record.name);
|
|
218
|
+
const code = safe(record.code);
|
|
219
|
+
return { ...(name ? { name } : {}), ...(code ? { code } : {}) };
|
|
220
|
+
};
|
|
221
|
+
const cause = error !== null && typeof error === "object" && "cause" in error ? one(error.cause) : undefined;
|
|
222
|
+
return { ...one(error), ...(cause ? { cause } : {}) };
|
|
173
223
|
}
|
|
174
224
|
function positiveNumber(value) {
|
|
175
225
|
return typeof value === "number" && Number.isFinite(value) && value > 0
|
|
@@ -73,7 +73,7 @@ export function createAuthUseCases(dependencies) {
|
|
|
73
73
|
await input.interaction.showAuthorization(authorizationUrl);
|
|
74
74
|
if (!input.noBrowser) {
|
|
75
75
|
try {
|
|
76
|
-
await input.interaction.openBrowser(authorizationUrl);
|
|
76
|
+
await dependencies.telemetry.stage("browser", () => input.interaction.openBrowser(authorizationUrl));
|
|
77
77
|
}
|
|
78
78
|
catch {
|
|
79
79
|
input.interaction.warn(insmind
|
|
@@ -3,8 +3,8 @@ import { access, mkdir, open, rename, rm } from "node:fs/promises";
|
|
|
3
3
|
import { extname, resolve } from "node:path";
|
|
4
4
|
import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
|
|
5
5
|
export class DamDownloadError extends Error {
|
|
6
|
-
constructor() {
|
|
7
|
-
super("素材下载失败。");
|
|
6
|
+
constructor(cause) {
|
|
7
|
+
super("素材下载失败。", { cause });
|
|
8
8
|
this.name = "DamDownloadError";
|
|
9
9
|
}
|
|
10
10
|
}
|
|
@@ -42,8 +42,8 @@ function safeDownloadUrl(value) {
|
|
|
42
42
|
throw new Error("HTTPS required");
|
|
43
43
|
return url;
|
|
44
44
|
}
|
|
45
|
-
catch {
|
|
46
|
-
throw new DamDownloadError();
|
|
45
|
+
catch (cause) {
|
|
46
|
+
throw new DamDownloadError(cause);
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
function decodedFilename(value) {
|
|
@@ -98,10 +98,10 @@ async function fetchDownload(initial, fetch, signal) {
|
|
|
98
98
|
try {
|
|
99
99
|
response = await fetch(url, { method: "GET", redirect: "manual", signal });
|
|
100
100
|
}
|
|
101
|
-
catch {
|
|
101
|
+
catch (cause) {
|
|
102
102
|
if (signal.aborted)
|
|
103
103
|
throw signal.reason;
|
|
104
|
-
throw new DamDownloadError();
|
|
104
|
+
throw new DamDownloadError(cause);
|
|
105
105
|
}
|
|
106
106
|
signal.throwIfAborted();
|
|
107
107
|
if (!redirectStatuses.has(response.status)) {
|
|
@@ -3,8 +3,8 @@ import { createReadStream } from "node:fs";
|
|
|
3
3
|
import { stat } from "node:fs/promises";
|
|
4
4
|
import OSS from "ali-oss";
|
|
5
5
|
export class ObjectStorageUploadError extends Error {
|
|
6
|
-
constructor() {
|
|
7
|
-
super("素材上传失败。");
|
|
6
|
+
constructor(cause) {
|
|
7
|
+
super("素材上传失败。", { cause });
|
|
8
8
|
this.name = "ObjectStorageUploadError";
|
|
9
9
|
}
|
|
10
10
|
}
|
|
@@ -90,11 +90,12 @@ async function attemptOss(input, dependencies) {
|
|
|
90
90
|
catch (error) {
|
|
91
91
|
if (input.signal.aborted)
|
|
92
92
|
throw input.signal.reason;
|
|
93
|
+
await dependencies.reportError?.(error).catch(() => undefined);
|
|
93
94
|
if (!input.authorizationV4 && isUnsupportedAuthorization(error)) {
|
|
94
95
|
return "unsupported-authorization";
|
|
95
96
|
}
|
|
96
97
|
if (!isTransient(error))
|
|
97
|
-
throw new ObjectStorageUploadError();
|
|
98
|
+
throw new ObjectStorageUploadError(error);
|
|
98
99
|
if (attempt === 1)
|
|
99
100
|
return "transient-exhausted";
|
|
100
101
|
await dependencies.sleep(300, input.signal);
|
|
@@ -156,12 +157,13 @@ async function uploadObs(input, dependencies) {
|
|
|
156
157
|
throw input.signal.reason;
|
|
157
158
|
if (error instanceof ObjectStorageUploadError)
|
|
158
159
|
throw error;
|
|
159
|
-
throw new ObjectStorageUploadError();
|
|
160
|
+
throw new ObjectStorageUploadError(error);
|
|
160
161
|
}
|
|
161
162
|
}
|
|
162
163
|
export function createObjectStorageUploader(options = {}) {
|
|
163
164
|
const dependencies = {
|
|
164
165
|
putOss: options.putOss ?? defaultPutOss,
|
|
166
|
+
...(options.reportError ? { reportError: options.reportError } : {}),
|
|
165
167
|
fetch: options.fetch ?? globalThis.fetch,
|
|
166
168
|
sleep: options.sleep ?? sleepWithSignal,
|
|
167
169
|
now: options.now ?? (() => new Date())
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { reportProcessError } from "../../telemetry/process-errors.js";
|
|
1
2
|
import { spawn as nodeSpawn } from "node:child_process";
|
|
2
3
|
import { resolve } from "node:path";
|
|
3
4
|
import { fileURLToPath } from "node:url";
|
|
@@ -14,9 +15,9 @@ export async function runEditorBridgeProcess(targetOrigin, options = {}) {
|
|
|
14
15
|
? {}
|
|
15
16
|
: { stateDirectory: options.stateDirectory })
|
|
16
17
|
});
|
|
17
|
-
const bridge = await (options.startBridge ?? startEditorBridge)({ targetOrigin });
|
|
18
|
+
const bridge = await (options.startBridge ?? startEditorBridge)({ targetOrigin, ...(options.reportError ? { reportError: options.reportError } : {}) });
|
|
18
19
|
const shutdown = () => {
|
|
19
|
-
void bridge.close().catch(
|
|
20
|
+
void bridge.close().catch(error => options.reportError?.(error));
|
|
20
21
|
};
|
|
21
22
|
let signalListenersInstalled = false;
|
|
22
23
|
const removeSignalListeners = () => {
|
|
@@ -215,14 +216,19 @@ if (process.argv[1] && resolve(process.argv[1]) === resolve(ownPath)) {
|
|
|
215
216
|
const targetOrigin = process.argv[2];
|
|
216
217
|
const homeDirectory = process.argv[3] || undefined;
|
|
217
218
|
const stateDirectory = process.argv[4];
|
|
219
|
+
const reportError = (error) => reportProcessError(error, { operation: "editor.bridge", processRole: "editor_bridge",
|
|
220
|
+
...(stateDirectory ? { stateDirectory } : {}), ...(homeDirectory ? { homeDirectory } : {}) });
|
|
218
221
|
if (!targetOrigin) {
|
|
222
|
+
void reportError(new Error("Editor Bridge target missing."));
|
|
219
223
|
process.exitCode = 1;
|
|
220
224
|
}
|
|
221
225
|
else {
|
|
222
226
|
void runEditorBridgeProcess(targetOrigin, {
|
|
227
|
+
reportError,
|
|
223
228
|
...(homeDirectory === undefined ? {} : { homeDirectory }),
|
|
224
229
|
...(stateDirectory === undefined ? {} : { stateDirectory })
|
|
225
|
-
}).catch(() => {
|
|
230
|
+
}).catch(async (error) => {
|
|
231
|
+
await reportError(error);
|
|
226
232
|
process.exitCode = 1;
|
|
227
233
|
});
|
|
228
234
|
}
|
|
@@ -20,7 +20,8 @@ export async function startEditorBridge(options) {
|
|
|
20
20
|
resolveClosed = resolve;
|
|
21
21
|
});
|
|
22
22
|
const http = createServer((request, response) => {
|
|
23
|
-
void handleRequest(request, response).catch(
|
|
23
|
+
void handleRequest(request, response).catch(error => {
|
|
24
|
+
void options.reportError?.(error).catch(() => undefined);
|
|
24
25
|
sendError(response, 500, "SERVER_ERROR", "Editor Bridge request failed.");
|
|
25
26
|
});
|
|
26
27
|
});
|
|
@@ -175,7 +176,8 @@ export async function startEditorBridge(options) {
|
|
|
175
176
|
sendError(current.response, 503, "EDITOR_DISCONNECTED", "The Editor page disconnected.");
|
|
176
177
|
});
|
|
177
178
|
}
|
|
178
|
-
catch {
|
|
179
|
+
catch (error) {
|
|
180
|
+
void options.reportError?.(error).catch(() => undefined);
|
|
179
181
|
const current = takePending(requestId);
|
|
180
182
|
if (current) {
|
|
181
183
|
sendError(current.response, 503, "EDITOR_DISCONNECTED", "The Editor page disconnected.");
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
|
|
1
2
|
import { classifyBindOutcome, SsoRequestError } from "../auth/sso-service.js";
|
|
2
3
|
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
3
4
|
import { OrganizationResponseError } from "./org-service.js";
|
|
@@ -14,9 +15,13 @@ export class OrganizationInvalidError extends Error {
|
|
|
14
15
|
}
|
|
15
16
|
}
|
|
16
17
|
export class OrganizationBindFailedError extends Error {
|
|
17
|
-
|
|
18
|
+
remoteCode;
|
|
19
|
+
remoteBody;
|
|
20
|
+
constructor(evidence = {}) {
|
|
18
21
|
super("选择组织失败,请稍后重试。");
|
|
19
22
|
this.name = "OrganizationBindFailedError";
|
|
23
|
+
this.remoteCode = evidence.remoteCode;
|
|
24
|
+
this.remoteBody = evidence.remoteBody;
|
|
20
25
|
}
|
|
21
26
|
}
|
|
22
27
|
export function createOrgUseCases(dependencies) {
|
|
@@ -29,7 +34,7 @@ export function createOrgUseCases(dependencies) {
|
|
|
29
34
|
if (outcome.status === "invalid")
|
|
30
35
|
throw new OrganizationInvalidError();
|
|
31
36
|
if (outcome.status === "failed")
|
|
32
|
-
throw new OrganizationBindFailedError();
|
|
37
|
+
throw new OrganizationBindFailedError(remoteErrorEvidence(response));
|
|
33
38
|
return {
|
|
34
39
|
id: record.id,
|
|
35
40
|
name: record.publicName,
|
|
@@ -134,7 +139,7 @@ export function createOrgUseCases(dependencies) {
|
|
|
134
139
|
if (outcome.status === "invalid")
|
|
135
140
|
throw new OrganizationInvalidError();
|
|
136
141
|
if (outcome.status === "failed")
|
|
137
|
-
throw new OrganizationBindFailedError();
|
|
142
|
+
throw new OrganizationBindFailedError(remoteErrorEvidence(response));
|
|
138
143
|
return {
|
|
139
144
|
id: input.state.organization.id,
|
|
140
145
|
name: input.state.organization.name,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { withFileLock } from "../../platform/file-lock.js";
|
|
1
2
|
import { createHash } from "node:crypto";
|
|
2
3
|
import { readdir, lstat } from "node:fs/promises";
|
|
3
4
|
import { homedir } from "node:os";
|
|
@@ -56,8 +57,38 @@ export function createTaskStore(options) {
|
|
|
56
57
|
}
|
|
57
58
|
},
|
|
58
59
|
async write(scope, record) {
|
|
59
|
-
|
|
60
|
-
await
|
|
60
|
+
file(scope, record.task.taskId);
|
|
61
|
+
await withFileLock(join(root, scope, `${record.task.taskId}.lock`), async () => {
|
|
62
|
+
const previous = await store.read(scope, record.task.taskId);
|
|
63
|
+
if (previous) {
|
|
64
|
+
record.progress = { ...previous.progress, ...record.progress };
|
|
65
|
+
for (const key of ["accepted", "submissionStarted", "detached"]) {
|
|
66
|
+
if (previous.progress[key])
|
|
67
|
+
record.progress[key] = true;
|
|
68
|
+
}
|
|
69
|
+
if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed"))
|
|
70
|
+
record.task = previous.task;
|
|
71
|
+
if (previous.telemetry)
|
|
72
|
+
record.telemetry = {
|
|
73
|
+
...record.telemetry, ...previous.telemetry,
|
|
74
|
+
context: previous.telemetry.request_sent ? previous.telemetry.context : record.telemetry?.context ?? previous.telemetry.context
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
options.validate(record.task);
|
|
78
|
+
await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
|
|
79
|
+
});
|
|
80
|
+
},
|
|
81
|
+
async update(scope, id, change) {
|
|
82
|
+
file(scope, id);
|
|
83
|
+
return withFileLock(join(root, scope, `${id}.lock`), async () => {
|
|
84
|
+
const record = await store.read(scope, id);
|
|
85
|
+
if (!record)
|
|
86
|
+
throw new LocalFileError(undefined);
|
|
87
|
+
change(record);
|
|
88
|
+
options.validate(record.task);
|
|
89
|
+
await file(scope, id).writeTextAtomically(`${JSON.stringify(record)}\n`);
|
|
90
|
+
return record;
|
|
91
|
+
});
|
|
61
92
|
},
|
|
62
93
|
async list(scope) {
|
|
63
94
|
let names;
|
|
@@ -90,6 +121,7 @@ export function createTaskStore(options) {
|
|
|
90
121
|
}
|
|
91
122
|
}
|
|
92
123
|
return {
|
|
124
|
+
update: (scope, id, change) => access(() => store.update(scope, id, change)),
|
|
93
125
|
read: (scope, id) => access(() => store.read(scope, id)),
|
|
94
126
|
write: (scope, record) => access(() => store.write(scope, record)),
|
|
95
127
|
list: scope => access(() => store.list(scope))
|
|
@@ -35,6 +35,42 @@ const HEARTBEAT_MS = 5_000;
|
|
|
35
35
|
const LEASE_MS = 15_000;
|
|
36
36
|
export function createTaskUseCases(dependencies) {
|
|
37
37
|
const { text, commandName } = dependencies;
|
|
38
|
+
const telemetry = dependencies.telemetry;
|
|
39
|
+
async function fact(scope, record, name, at) {
|
|
40
|
+
if (!telemetry || !record.telemetry)
|
|
41
|
+
return;
|
|
42
|
+
let context = record.telemetry.context;
|
|
43
|
+
if (name === "request_sent") {
|
|
44
|
+
const current = telemetry.creationContext();
|
|
45
|
+
context = { ...context,
|
|
46
|
+
...(current.tool_name ? { tool_name: current.tool_name } : {}),
|
|
47
|
+
...(current.model_id ? { model_id: current.model_id } : {}) };
|
|
48
|
+
}
|
|
49
|
+
const candidate = { ...context, event_name: name, occurred_at_ms: at,
|
|
50
|
+
record_seq: name === "request_sent" ? 1 : 2 };
|
|
51
|
+
try {
|
|
52
|
+
const updated = await dependencies.store.update(scope, record.task.taskId, stored => {
|
|
53
|
+
if (stored.telemetry && !stored.telemetry[name]) {
|
|
54
|
+
stored.telemetry.context = context;
|
|
55
|
+
stored.telemetry[name] = candidate;
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
if (updated.telemetry)
|
|
59
|
+
record.telemetry = updated.telemetry;
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
// Business persistence has its own failure path. Keep the already known fact.
|
|
63
|
+
record.telemetry[name] ??= candidate;
|
|
64
|
+
await telemetry.stage("telemetry.task", () => { throw error; }).catch(() => undefined);
|
|
65
|
+
}
|
|
66
|
+
await telemetry.emit(record.telemetry[name] ?? candidate);
|
|
67
|
+
}
|
|
68
|
+
async function replay(record) {
|
|
69
|
+
for (const event of [record.telemetry?.request_sent, record.telemetry?.result_ready]) {
|
|
70
|
+
if (event)
|
|
71
|
+
await telemetry?.emit(event);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
38
74
|
function summary(record) {
|
|
39
75
|
const { result: _result, partialResult: _partial, ...task } = record.task;
|
|
40
76
|
if (!record.progress.detached && task.state === "running"
|
|
@@ -52,6 +88,13 @@ export function createTaskUseCases(dependencies) {
|
|
|
52
88
|
label: redactSensitiveText(input.label).slice(0, 200),
|
|
53
89
|
createdAt: timestamp, updatedAt: timestamp, state: "running" }
|
|
54
90
|
};
|
|
91
|
+
if (telemetry) {
|
|
92
|
+
telemetry.annotate({ cli_task_id: record.task.taskId, execution_mode: input.executionMode ?? "sync", result_state: "running" });
|
|
93
|
+
record.telemetry = { context: { ...telemetry.creationContext(), operation: input.operation,
|
|
94
|
+
cli_task_id: record.task.taskId, execution_mode: input.executionMode ?? "sync",
|
|
95
|
+
...(dependencies.creationVersion ? { cli_version: dependencies.creationVersion } : {}),
|
|
96
|
+
...(input.state.account ? { account_id: input.state.account.id } : {}), organization_id: input.state.organization.id } };
|
|
97
|
+
}
|
|
55
98
|
await dependencies.store.write(scope, record);
|
|
56
99
|
input.onUpdate?.(structuredClone(record.task), { ...record.progress });
|
|
57
100
|
dependencies.notice(text(`任务 ID: ${record.task.taskId};结果未收到时执行 ${commandName} task get ${record.task.taskId}`, `Task ID: ${record.task.taskId}; retrieve missing output with ${commandName} task get ${record.task.taskId}`));
|
|
@@ -62,10 +105,23 @@ export function createTaskUseCases(dependencies) {
|
|
|
62
105
|
writes = writes.catch(() => undefined).then(() => dependencies.store.write(scope, snapshot));
|
|
63
106
|
return writes;
|
|
64
107
|
};
|
|
65
|
-
|
|
108
|
+
let lastHeartbeatError = -Infinity;
|
|
109
|
+
const timer = setInterval(() => {
|
|
110
|
+
void save().catch(async (error) => {
|
|
111
|
+
const at = dependencies.now().getTime();
|
|
112
|
+
if (at - lastHeartbeatError < 60_000)
|
|
113
|
+
return;
|
|
114
|
+
lastHeartbeatError = at;
|
|
115
|
+
await telemetry?.stage("task.heartbeat", () => { throw error; }).catch(() => undefined);
|
|
116
|
+
});
|
|
117
|
+
}, HEARTBEAT_MS);
|
|
66
118
|
timer.unref();
|
|
67
119
|
try {
|
|
68
120
|
const result = await input.run(async (progress) => {
|
|
121
|
+
if (progress.dispatchedAt !== undefined) {
|
|
122
|
+
await fact(scope, record, "request_sent", progress.dispatchedAt);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
69
125
|
Object.assign(record.progress, progress);
|
|
70
126
|
if (progress.contextId)
|
|
71
127
|
record.task.contextId = progress.contextId;
|
|
@@ -74,6 +130,9 @@ export function createTaskUseCases(dependencies) {
|
|
|
74
130
|
});
|
|
75
131
|
clearInterval(timer);
|
|
76
132
|
finish(record, result);
|
|
133
|
+
telemetry?.annotate({ result_state: record.task.state });
|
|
134
|
+
if (record.task.state === "completed")
|
|
135
|
+
await fact(scope, record, "result_ready", dependencies.now().getTime());
|
|
77
136
|
await save();
|
|
78
137
|
return { task: record.task, result };
|
|
79
138
|
}
|
|
@@ -88,7 +147,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
88
147
|
const detail = dependencies.failureNote?.(error);
|
|
89
148
|
if (detail)
|
|
90
149
|
record.task.note = `${record.task.note} ${redactSensitiveText(detail)}`;
|
|
91
|
-
await save().catch(() => undefined);
|
|
150
|
+
await (telemetry ? telemetry.stage("task.persist", save) : save()).catch(() => undefined);
|
|
92
151
|
throw error;
|
|
93
152
|
}
|
|
94
153
|
}
|
|
@@ -102,7 +161,7 @@ export function createTaskUseCases(dependencies) {
|
|
|
102
161
|
})).result;
|
|
103
162
|
},
|
|
104
163
|
async submit(input) {
|
|
105
|
-
return (await execute(input, record => { record.progress.detached = true; })).task;
|
|
164
|
+
return (await execute({ ...input, executionMode: "async" }, record => { record.progress.detached = true; })).task;
|
|
106
165
|
},
|
|
107
166
|
async list({ state, limit, operation }) {
|
|
108
167
|
const records = await dependencies.store.list(taskScope(state));
|
|
@@ -114,6 +173,8 @@ export function createTaskUseCases(dependencies) {
|
|
|
114
173
|
const record = await dependencies.store.read(scope, id);
|
|
115
174
|
if (!record)
|
|
116
175
|
throw new TaskNotFoundError(text(`当前身份中没有该任务。请执行 ${commandName} task list 查找。`, `No task was found in the current identity context. Use ${commandName} task list to find it.`));
|
|
176
|
+
telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
|
|
177
|
+
await replay(record);
|
|
117
178
|
if (record.task.state === "completed" && record.task.result) {
|
|
118
179
|
return { ...record.task, result: await dependencies.recovery.authorize(record.task.result, state, signal) };
|
|
119
180
|
}
|
|
@@ -126,9 +187,13 @@ export function createTaskUseCases(dependencies) {
|
|
|
126
187
|
if (result.state === "unknown" && task.note) {
|
|
127
188
|
result.note = [task.note, recovered.note].filter(Boolean).join(" ");
|
|
128
189
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
190
|
+
telemetry?.annotate({ result_state: result.state });
|
|
191
|
+
if (result.state === "completed" && result.result) {
|
|
192
|
+
dependencies.validateResult?.(result.result);
|
|
193
|
+
await fact(scope, record, "result_ready", dependencies.now().getTime());
|
|
194
|
+
}
|
|
195
|
+
// Store merging protects terminal results and facts against stale heartbeats.
|
|
196
|
+
if (result.state === "completed" || result.state === "failed") {
|
|
132
197
|
result.updatedAt = dependencies.now().toISOString();
|
|
133
198
|
record.task = withoutResourceKeys(result);
|
|
134
199
|
await dependencies.store.write(scope, record);
|
|
@@ -304,6 +304,7 @@ export function createToolApiAdapter(dependencies) {
|
|
|
304
304
|
dependencies.telemetry.annotate({ content_id: managedContentId });
|
|
305
305
|
return submittedTask(await safePost(dependencies.transport, {
|
|
306
306
|
path: "/gdesign/tool/v1/dify/call_async",
|
|
307
|
+
...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
|
|
307
308
|
body: {
|
|
308
309
|
jsonrpc: "2.0",
|
|
309
310
|
id: 0,
|
|
@@ -56,7 +56,8 @@ export function createUpdateNotificationService(options) {
|
|
|
56
56
|
...(state.etag ? { etag: state.etag } : {})
|
|
57
57
|
});
|
|
58
58
|
}
|
|
59
|
-
catch {
|
|
59
|
+
catch (error) {
|
|
60
|
+
await options.reportError?.(error).catch(() => undefined);
|
|
60
61
|
if (signal.aborted)
|
|
61
62
|
return;
|
|
62
63
|
await writeState(stateFile, {
|
|
@@ -101,7 +102,8 @@ export function createUpdateNotificationService(options) {
|
|
|
101
102
|
if (shouldNotify)
|
|
102
103
|
notify(options, latest);
|
|
103
104
|
}
|
|
104
|
-
catch {
|
|
105
|
+
catch (error) {
|
|
106
|
+
await options.reportError?.(error).catch(() => undefined);
|
|
105
107
|
// Availability checks are best-effort and never change command behavior.
|
|
106
108
|
}
|
|
107
109
|
finally {
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, open, readFile, readdir, unlink, chmod } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
import { createLocalJsonFile } from "./local-json-file.js";
|
|
6
|
+
/** Local bakery lock: unique owner files avoid deleting a new owner's lock
|
|
7
|
+
* when several processes simultaneously recover a dead writer. */
|
|
8
|
+
export async function withFileLock(path, run) {
|
|
9
|
+
const directory = `${path}.d`;
|
|
10
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
11
|
+
await chmod(directory, 0o700);
|
|
12
|
+
const name = `${process.pid}-${randomUUID()}.json`;
|
|
13
|
+
const ownPath = join(directory, name);
|
|
14
|
+
const deadline = Date.now() + 2_000;
|
|
15
|
+
async function contenders() {
|
|
16
|
+
const found = [];
|
|
17
|
+
for (const entry of await readdir(directory)) {
|
|
18
|
+
const match = /^(\d+)-[a-f0-9-]{36}\.json$/u.exec(entry);
|
|
19
|
+
if (!match)
|
|
20
|
+
continue;
|
|
21
|
+
const pid = Number(match[1]);
|
|
22
|
+
try {
|
|
23
|
+
process.kill(pid, 0);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error instanceof Error && "code" in error && error.code === "ESRCH") {
|
|
27
|
+
await unlink(join(directory, entry)).catch(() => undefined);
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const text = await readFile(join(directory, entry), "utf8");
|
|
33
|
+
let ticket = null;
|
|
34
|
+
try {
|
|
35
|
+
const value = JSON.parse(text).ticket;
|
|
36
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value > 0)
|
|
37
|
+
ticket = value;
|
|
38
|
+
}
|
|
39
|
+
catch { /* The owner has opened its choosing file but not written it yet. */ }
|
|
40
|
+
found.push({ name: entry, ticket });
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return found;
|
|
48
|
+
}
|
|
49
|
+
const handle = await open(ownPath, "wx", 0o600);
|
|
50
|
+
try {
|
|
51
|
+
await handle.writeFile('{"ticket":null}');
|
|
52
|
+
const ticket = 1 + Math.max(0, ...(await contenders()).map(owner => owner.ticket ?? 0));
|
|
53
|
+
await createLocalJsonFile({ directory, filename: name }).writeTextAtomically(JSON.stringify({ ticket }));
|
|
54
|
+
for (;;) {
|
|
55
|
+
const waiting = (await contenders()).some(owner => owner.name !== name
|
|
56
|
+
&& (owner.ticket === null || owner.ticket < ticket || (owner.ticket === ticket && owner.name < name)));
|
|
57
|
+
if (!waiting)
|
|
58
|
+
return await run();
|
|
59
|
+
if (Date.now() >= deadline)
|
|
60
|
+
throw new Error("Local state lock timed out.");
|
|
61
|
+
await delay(10);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
finally {
|
|
65
|
+
await handle.close();
|
|
66
|
+
await unlink(ownPath).catch(() => undefined);
|
|
67
|
+
}
|
|
68
|
+
}
|