@ycodium-ai/plugin-trace-diagnostics 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +39 -0
  2. package/dist/index.js +460 -0
  3. package/package.json +44 -0
package/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # @ycodium-ai/plugin-trace-diagnostics
2
+
3
+ Reads this machine's local trace files and aggregates span, failure, and log
4
+ summaries for Settings → Diagnostics.
5
+
6
+ ## What it does
7
+
8
+ The `summary` command scans the rotated trace files under the logs directory
9
+ the host injects at assembly (`logsDir`, `traceFilePath`, `maxFiles`). File
10
+ reads go through `ctx.fs` and are limited to that declared prefix.
11
+
12
+ Missing rotated files are skipped. A file that exists but cannot be read is
13
+ reported as a partial failure.
14
+
15
+ The diagnostics page in the Ycodium UI consumes this command. The old
16
+ `/x/trace-diagnostics` path redirects there.
17
+
18
+ ## Install
19
+
20
+ ```
21
+ ycodium plugin add @ycodium-ai/plugin-trace-diagnostics
22
+ ```
23
+
24
+ The plugin asks to read the logs directory (`config:logsDir`). The host
25
+ resolves that path from the server configuration before mount.
26
+
27
+ Ycodium ships it enabled as `core.trace-diagnostics`. Disabling it leaves the
28
+ diagnostics page without trace data. Uninstalling it writes a removal to the
29
+ home patch so a restart does not bring it back.
30
+
31
+ ## Developing
32
+
33
+ Built from the Ycodium repository. The Node entry is bundled, but
34
+ `@ycodium-ai/plugin-api` stays external and is provided by the Ycodium host at
35
+ load time.
36
+
37
+ ## License
38
+
39
+ UNLICENSED.
package/dist/index.js ADDED
@@ -0,0 +1,460 @@
1
+ // src/index.ts
2
+ import { definePlugin } from "@ycodium-ai/plugin-api";
3
+ var DEFAULT_MAX_FILES = 10;
4
+ var DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1e3;
5
+ var TOP_LIMIT = 10;
6
+ var RECENT_LIMIT = 20;
7
+ function isRecordObject(value) {
8
+ return typeof value === "object" && value !== null;
9
+ }
10
+ function toStringValue(value) {
11
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
12
+ }
13
+ function toNumberValue(value) {
14
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
15
+ }
16
+ function unixNanoToMillis(value) {
17
+ const text = toStringValue(value);
18
+ if (!text) return null;
19
+ try {
20
+ return Number(BigInt(text) / 1000000n);
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+ function readExitTag(exit) {
26
+ if (!isRecordObject(exit) || !("_tag" in exit)) return null;
27
+ return toStringValue(exit._tag);
28
+ }
29
+ function readExitCause(exit) {
30
+ if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
31
+ return toStringValue(exit.cause)?.trim() ?? "Failure";
32
+ }
33
+ function isTraceEvent(value) {
34
+ return typeof value === "object" && value !== null;
35
+ }
36
+ function readEventAttributes(event) {
37
+ return typeof event.attributes === "object" && event.attributes !== null ? event.attributes : {};
38
+ }
39
+ function toRotatedTracePaths(traceFilePath, maxFiles) {
40
+ const backupCount = Math.max(0, Math.floor(maxFiles));
41
+ const backups = Array.from(
42
+ { length: backupCount },
43
+ (_, index) => `${traceFilePath}.${backupCount - index}`
44
+ );
45
+ return [...backups, traceFilePath];
46
+ }
47
+ function insertBoundedSlowestSpan(slowestSpans, span) {
48
+ if (slowestSpans.length >= TOP_LIMIT && span.durationMs <= slowestSpans[slowestSpans.length - 1].durationMs) {
49
+ return;
50
+ }
51
+ slowestSpans.push(span);
52
+ slowestSpans.sort((left, right) => right.durationMs - left.durationMs);
53
+ if (slowestSpans.length > TOP_LIMIT) slowestSpans.length = TOP_LIMIT;
54
+ }
55
+ function makeEmptyDiagnostics(input) {
56
+ return {
57
+ traceFilePath: input.traceFilePath,
58
+ scannedFilePaths: input.scannedFilePaths,
59
+ readAt: input.readAt,
60
+ recordCount: 0,
61
+ parseErrorCount: 0,
62
+ firstSpanAt: null,
63
+ lastSpanAt: null,
64
+ failureCount: 0,
65
+ interruptionCount: 0,
66
+ slowSpanThresholdMs: DEFAULT_SLOW_SPAN_THRESHOLD_MS,
67
+ slowSpanCount: 0,
68
+ logLevelCounts: {},
69
+ topSpansByCount: [],
70
+ slowestSpans: [],
71
+ commonFailures: [],
72
+ latestFailures: [],
73
+ latestWarningAndErrorLogs: [],
74
+ partialFailure: input.partialFailure ?? false,
75
+ error: input.error ?? null
76
+ };
77
+ }
78
+ function aggregateTraceDiagnostics(input) {
79
+ const readAt = input.readAt;
80
+ const slowSpanThresholdMs = DEFAULT_SLOW_SPAN_THRESHOLD_MS;
81
+ if (input.files.length === 0) {
82
+ return makeEmptyDiagnostics({
83
+ ...input,
84
+ error: input.error ?? {
85
+ kind: "trace-file-not-found",
86
+ message: "No local trace files were found."
87
+ }
88
+ });
89
+ }
90
+ let parseErrorCount = 0;
91
+ let recordCount = 0;
92
+ let failureCount = 0;
93
+ let interruptionCount = 0;
94
+ let slowSpanCount = 0;
95
+ let firstSpanAtMs = null;
96
+ let lastSpanAtMs = null;
97
+ const spansByName = /* @__PURE__ */ new Map();
98
+ const failuresByKey = /* @__PURE__ */ new Map();
99
+ const latestFailures = [];
100
+ const slowestSpans = [];
101
+ const latestWarningAndErrorLogs = [];
102
+ const logLevelCounts = {};
103
+ for (const file of input.files) {
104
+ const lines = file.text.split(/\r?\n/);
105
+ for (const line of lines) {
106
+ if (line.trim().length === 0) continue;
107
+ let parsed;
108
+ try {
109
+ parsed = JSON.parse(line);
110
+ } catch {
111
+ parseErrorCount += 1;
112
+ continue;
113
+ }
114
+ if (!isRecordObject(parsed)) {
115
+ parseErrorCount += 1;
116
+ continue;
117
+ }
118
+ const name = toStringValue(parsed.name);
119
+ const traceId = toStringValue(parsed.traceId);
120
+ const spanId = toStringValue(parsed.spanId);
121
+ const durationMs = toNumberValue(parsed.durationMs);
122
+ const endedAtMs = unixNanoToMillis(parsed.endTimeUnixNano);
123
+ const startedAtMs = unixNanoToMillis(parsed.startTimeUnixNano);
124
+ if (!name || !traceId || !spanId || durationMs === null || endedAtMs === null) {
125
+ parseErrorCount += 1;
126
+ continue;
127
+ }
128
+ recordCount += 1;
129
+ firstSpanAtMs = startedAtMs !== null && (firstSpanAtMs === null || startedAtMs < firstSpanAtMs) ? startedAtMs : firstSpanAtMs;
130
+ lastSpanAtMs = lastSpanAtMs === null || endedAtMs > lastSpanAtMs ? endedAtMs : lastSpanAtMs;
131
+ const exitTag = readExitTag(parsed.exit);
132
+ const isFailure = exitTag === "Failure";
133
+ const isInterrupted = exitTag === "Interrupted";
134
+ if (isFailure) failureCount += 1;
135
+ if (isInterrupted) interruptionCount += 1;
136
+ const spanSummary = spansByName.get(name) ?? {
137
+ count: 0,
138
+ failureCount: 0,
139
+ totalDurationMs: 0,
140
+ maxDurationMs: 0
141
+ };
142
+ spanSummary.count += 1;
143
+ spanSummary.totalDurationMs += durationMs;
144
+ spanSummary.maxDurationMs = Math.max(spanSummary.maxDurationMs, durationMs);
145
+ if (isFailure) spanSummary.failureCount += 1;
146
+ spansByName.set(name, spanSummary);
147
+ if (durationMs >= slowSpanThresholdMs) slowSpanCount += 1;
148
+ insertBoundedSlowestSpan(slowestSpans, { name, durationMs, endedAtMs, traceId, spanId });
149
+ if (isFailure) {
150
+ const cause = readExitCause(parsed.exit);
151
+ latestFailures.push({
152
+ name,
153
+ cause,
154
+ durationMs,
155
+ endedAt: new Date(endedAtMs).toISOString(),
156
+ traceId,
157
+ spanId,
158
+ endedAtMs
159
+ });
160
+ const failureKey = `${name}\0${cause}`;
161
+ const existing = failuresByKey.get(failureKey);
162
+ const isLatest = existing === void 0 || endedAtMs > existing.lastSeenAtMs;
163
+ failuresByKey.set(failureKey, {
164
+ name,
165
+ cause,
166
+ count: (existing?.count ?? 0) + 1,
167
+ lastSeenAtMs: isLatest ? endedAtMs : existing.lastSeenAtMs,
168
+ lastSeenAt: new Date(isLatest ? endedAtMs : existing.lastSeenAtMs).toISOString(),
169
+ traceId: isLatest ? traceId : existing.traceId,
170
+ spanId: isLatest ? spanId : existing.spanId
171
+ });
172
+ }
173
+ if (Array.isArray(parsed.events)) {
174
+ for (const rawEvent of parsed.events) {
175
+ if (!isTraceEvent(rawEvent)) continue;
176
+ const attributes = readEventAttributes(rawEvent);
177
+ const level = toStringValue(attributes["effect.logLevel"]);
178
+ if (!level) continue;
179
+ logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
180
+ const normalizedLevel = level.toLowerCase();
181
+ if (normalizedLevel !== "warning" && normalizedLevel !== "warn" && normalizedLevel !== "error" && normalizedLevel !== "fatal") {
182
+ continue;
183
+ }
184
+ const seenAtMs = unixNanoToMillis(rawEvent.timeUnixNano) ?? endedAtMs;
185
+ const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
186
+ latestWarningAndErrorLogs.push({
187
+ spanName: name,
188
+ level,
189
+ message,
190
+ seenAt: new Date(seenAtMs).toISOString(),
191
+ traceId,
192
+ spanId,
193
+ seenAtMs
194
+ });
195
+ }
196
+ }
197
+ }
198
+ }
199
+ const topSpansByCount = [...spansByName.entries()].map(([name, span]) => ({
200
+ name,
201
+ count: span.count,
202
+ failureCount: span.failureCount,
203
+ totalDurationMs: span.totalDurationMs,
204
+ averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,
205
+ maxDurationMs: span.maxDurationMs
206
+ })).toSorted((left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs).slice(0, TOP_LIMIT);
207
+ return {
208
+ traceFilePath: input.traceFilePath,
209
+ scannedFilePaths: input.scannedFilePaths,
210
+ readAt,
211
+ recordCount,
212
+ parseErrorCount,
213
+ firstSpanAt: firstSpanAtMs === null ? null : new Date(firstSpanAtMs).toISOString(),
214
+ lastSpanAt: lastSpanAtMs === null ? null : new Date(lastSpanAtMs).toISOString(),
215
+ failureCount,
216
+ interruptionCount,
217
+ slowSpanThresholdMs,
218
+ slowSpanCount,
219
+ logLevelCounts,
220
+ topSpansByCount,
221
+ slowestSpans: slowestSpans.map(({ name, durationMs, endedAtMs, traceId, spanId }) => ({
222
+ name,
223
+ durationMs,
224
+ endedAt: new Date(endedAtMs).toISOString(),
225
+ traceId,
226
+ spanId
227
+ })),
228
+ commonFailures: [...failuresByKey.values()].toSorted((left, right) => right.count - left.count || right.lastSeenAtMs - left.lastSeenAtMs).slice(0, TOP_LIMIT).map(({ name, cause, count, lastSeenAt, traceId, spanId }) => ({
229
+ name,
230
+ cause,
231
+ count,
232
+ lastSeenAt,
233
+ traceId,
234
+ spanId
235
+ })),
236
+ latestFailures: latestFailures.toSorted((left, right) => right.endedAtMs - left.endedAtMs).slice(0, RECENT_LIMIT).map(({ name, cause, durationMs, endedAt, traceId, spanId }) => ({
237
+ name,
238
+ cause,
239
+ durationMs,
240
+ endedAt,
241
+ traceId,
242
+ spanId
243
+ })),
244
+ latestWarningAndErrorLogs: latestWarningAndErrorLogs.toSorted((left, right) => right.seenAtMs - left.seenAtMs).slice(0, RECENT_LIMIT).map(({ spanName, level, message, seenAt, traceId, spanId }) => ({
245
+ spanName,
246
+ level,
247
+ message,
248
+ seenAt,
249
+ traceId,
250
+ spanId
251
+ })),
252
+ partialFailure: input.partialFailure ?? false,
253
+ error: input.error ?? null
254
+ };
255
+ }
256
+ function describeError(error) {
257
+ return error instanceof Error ? error.message : String(error);
258
+ }
259
+ async function readCandidateFiles(fs, candidates) {
260
+ const files = [];
261
+ let readFailure = null;
262
+ for (const path of candidates) {
263
+ try {
264
+ await fs.stat(path);
265
+ } catch {
266
+ continue;
267
+ }
268
+ try {
269
+ const text = await fs.readFile(path);
270
+ files.push({ path, text });
271
+ } catch (error) {
272
+ readFailure ??= { path, message: describeError(error) };
273
+ }
274
+ }
275
+ return { files, readFailure };
276
+ }
277
+ var SUMMARY_PAYLOAD_SCHEMA = { type: "object", additionalProperties: false };
278
+ var SPAN_SUMMARY_SCHEMA = {
279
+ type: "object",
280
+ required: [
281
+ "name",
282
+ "count",
283
+ "failureCount",
284
+ "totalDurationMs",
285
+ "averageDurationMs",
286
+ "maxDurationMs"
287
+ ],
288
+ additionalProperties: false,
289
+ properties: {
290
+ name: { type: "string" },
291
+ count: { type: "integer" },
292
+ failureCount: { type: "integer" },
293
+ totalDurationMs: { type: "number" },
294
+ averageDurationMs: { type: "number" },
295
+ maxDurationMs: { type: "number" }
296
+ }
297
+ };
298
+ var SPAN_OCCURRENCE_SCHEMA = {
299
+ type: "object",
300
+ required: ["name", "durationMs", "endedAt", "traceId", "spanId"],
301
+ additionalProperties: false,
302
+ properties: {
303
+ name: { type: "string" },
304
+ durationMs: { type: "number" },
305
+ endedAt: { type: "string" },
306
+ traceId: { type: "string" },
307
+ spanId: { type: "string" }
308
+ }
309
+ };
310
+ var FAILURE_SUMMARY_SCHEMA = {
311
+ type: "object",
312
+ required: ["name", "cause", "count", "lastSeenAt", "traceId", "spanId"],
313
+ additionalProperties: false,
314
+ properties: {
315
+ name: { type: "string" },
316
+ cause: { type: "string" },
317
+ count: { type: "integer" },
318
+ lastSeenAt: { type: "string" },
319
+ traceId: { type: "string" },
320
+ spanId: { type: "string" }
321
+ }
322
+ };
323
+ var RECENT_FAILURE_SCHEMA = {
324
+ type: "object",
325
+ required: ["name", "cause", "durationMs", "endedAt", "traceId", "spanId"],
326
+ additionalProperties: false,
327
+ properties: {
328
+ name: { type: "string" },
329
+ cause: { type: "string" },
330
+ durationMs: { type: "number" },
331
+ endedAt: { type: "string" },
332
+ traceId: { type: "string" },
333
+ spanId: { type: "string" }
334
+ }
335
+ };
336
+ var LOG_EVENT_SCHEMA = {
337
+ type: "object",
338
+ required: ["spanName", "level", "message", "seenAt", "traceId", "spanId"],
339
+ additionalProperties: false,
340
+ properties: {
341
+ spanName: { type: "string" },
342
+ level: { type: "string" },
343
+ message: { type: "string" },
344
+ seenAt: { type: "string" },
345
+ traceId: { type: "string" },
346
+ spanId: { type: "string" }
347
+ }
348
+ };
349
+ var SUMMARY_RESULT_SCHEMA = {
350
+ type: "object",
351
+ required: [
352
+ "traceFilePath",
353
+ "scannedFilePaths",
354
+ "readAt",
355
+ "recordCount",
356
+ "parseErrorCount",
357
+ "firstSpanAt",
358
+ "lastSpanAt",
359
+ "failureCount",
360
+ "interruptionCount",
361
+ "slowSpanThresholdMs",
362
+ "slowSpanCount",
363
+ "logLevelCounts",
364
+ "topSpansByCount",
365
+ "slowestSpans",
366
+ "commonFailures",
367
+ "latestFailures",
368
+ "latestWarningAndErrorLogs",
369
+ "partialFailure",
370
+ "error"
371
+ ],
372
+ additionalProperties: false,
373
+ properties: {
374
+ traceFilePath: { type: "string" },
375
+ scannedFilePaths: { type: "array", items: { type: "string" } },
376
+ readAt: { type: "string" },
377
+ recordCount: { type: "integer" },
378
+ parseErrorCount: { type: "integer" },
379
+ firstSpanAt: { type: ["string", "null"] },
380
+ lastSpanAt: { type: ["string", "null"] },
381
+ failureCount: { type: "integer" },
382
+ interruptionCount: { type: "integer" },
383
+ slowSpanThresholdMs: { type: "number" },
384
+ slowSpanCount: { type: "integer" },
385
+ logLevelCounts: { type: "object", additionalProperties: { type: "integer" } },
386
+ topSpansByCount: { type: "array", items: SPAN_SUMMARY_SCHEMA },
387
+ slowestSpans: { type: "array", items: SPAN_OCCURRENCE_SCHEMA },
388
+ commonFailures: { type: "array", items: FAILURE_SUMMARY_SCHEMA },
389
+ latestFailures: { type: "array", items: RECENT_FAILURE_SCHEMA },
390
+ latestWarningAndErrorLogs: { type: "array", items: LOG_EVENT_SCHEMA },
391
+ partialFailure: { type: "boolean" },
392
+ // 读成功是 null,读失败是完整的 { kind, message }:两支写成 oneOf,
393
+ // 半个错误对象(只有 kind)到不了调用方。
394
+ error: {
395
+ oneOf: [
396
+ { type: "null" },
397
+ {
398
+ type: "object",
399
+ required: ["kind", "message"],
400
+ additionalProperties: false,
401
+ properties: {
402
+ kind: { enum: ["trace-file-not-found", "trace-file-read-failed"] },
403
+ message: { type: "string" }
404
+ }
405
+ }
406
+ ]
407
+ }
408
+ }
409
+ };
410
+ var traceDiagnosticsPlugin = definePlugin({
411
+ id: "trace-diagnostics",
412
+ apiVersion: 2,
413
+ activate: (ctx) => {
414
+ ctx.command({
415
+ name: "summary",
416
+ description: "Aggregate this environment's local trace files into span/failure summaries.",
417
+ scope: "read",
418
+ payloadSchema: SUMMARY_PAYLOAD_SCHEMA,
419
+ resultSchema: SUMMARY_RESULT_SCHEMA,
420
+ handle: async () => {
421
+ const config = ctx.config;
422
+ const traceFilePath = typeof config.traceFilePath === "string" && config.traceFilePath.length > 0 ? config.traceFilePath : null;
423
+ const readAt = (/* @__PURE__ */ new Date()).toISOString();
424
+ if (traceFilePath === null) {
425
+ return makeEmptyDiagnostics({
426
+ traceFilePath: "",
427
+ files: [],
428
+ scannedFilePaths: [],
429
+ readAt,
430
+ error: {
431
+ kind: "trace-file-not-found",
432
+ message: "This environment has not configured a trace file path for this plugin."
433
+ }
434
+ });
435
+ }
436
+ const maxFiles = typeof config.maxFiles === "number" && Number.isFinite(config.maxFiles) ? config.maxFiles : DEFAULT_MAX_FILES;
437
+ const candidates = toRotatedTracePaths(traceFilePath, maxFiles);
438
+ const { files, readFailure } = await readCandidateFiles(ctx.fs, candidates);
439
+ return aggregateTraceDiagnostics({
440
+ traceFilePath,
441
+ files,
442
+ scannedFilePaths: candidates,
443
+ readAt,
444
+ ...readFailure ? {
445
+ partialFailure: true,
446
+ error: {
447
+ kind: "trace-file-read-failed",
448
+ message: `Failed to read local trace file '${readFailure.path}': ${readFailure.message}`
449
+ }
450
+ } : {}
451
+ });
452
+ }
453
+ });
454
+ }
455
+ });
456
+ var index_default = traceDiagnosticsPlugin;
457
+ export {
458
+ aggregateTraceDiagnostics,
459
+ index_default as default
460
+ };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@ycodium-ai/plugin-trace-diagnostics",
3
+ "version": "0.2.0",
4
+ "description": "Reads this machine's trace files for the diagnostics page.",
5
+ "keywords": [
6
+ "diagnostics",
7
+ "trace",
8
+ "ycodium",
9
+ "ycodium-plugin"
10
+ ],
11
+ "license": "UNLICENSED",
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "type": "module",
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "devDependencies": {
20
+ "@effect/vitest": "4.0.0-beta.103",
21
+ "esbuild": "0.28.1",
22
+ "vite-plus": "0.2.2",
23
+ "@ycodium-ai/plugin-api": "0.1.1"
24
+ },
25
+ "ycodium": {
26
+ "plugin": "./dist/index.js",
27
+ "displayName": "Trace diagnostics",
28
+ "description": "Reads this machine's trace files for the diagnostics page.",
29
+ "icon": "activity",
30
+ "permissions": [
31
+ {
32
+ "kind": "fs.read",
33
+ "paths": [
34
+ "config:logsDir"
35
+ ]
36
+ }
37
+ ]
38
+ },
39
+ "scripts": {
40
+ "build": "node build.mjs",
41
+ "typecheck": "tsgo --noEmit",
42
+ "test": "vp test run --passWithNoTests"
43
+ }
44
+ }