@tellagen/mcp-server 0.1.1 → 0.4.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 (82) hide show
  1. package/README.md +231 -12
  2. package/SKILL.md +407 -13
  3. package/contracts/runbooks/manifest.json +47 -0
  4. package/contracts/runbooks/v1/fixtures/global-runbook.json +7 -0
  5. package/contracts/runbooks/v1/runbook-definition.schema.json +25 -0
  6. package/contracts/runbooks/v2/compiled-plan.schema.json +40 -0
  7. package/contracts/runbooks/v2/fixtures/filesystem-pressure.json +181 -0
  8. package/contracts/runbooks/v2/fixtures/grafana-error-rate-plan.json +50 -0
  9. package/contracts/runbooks/v2/fixtures/grafana-error-rate.json +58 -0
  10. package/contracts/runbooks/v2/fixtures/timeline-event-blocks-rejected.json +90 -0
  11. package/contracts/runbooks/v2/fixtures/timeline-event-with-blocks.json +61 -0
  12. package/contracts/runbooks/v2/runbook-definition.schema.json +377 -0
  13. package/contracts/runbooks/v2/timeline-event-blocks.schema.json +480 -0
  14. package/contracts/tellagen-runbook-contracts.json +8 -0
  15. package/dist/auth.d.ts +2 -1
  16. package/dist/auth.js +2 -1
  17. package/dist/auth.js.map +1 -1
  18. package/dist/client.d.ts +20 -0
  19. package/dist/client.js +81 -12
  20. package/dist/client.js.map +1 -1
  21. package/dist/diagnosis-structure.d.ts +1416 -0
  22. package/dist/diagnosis-structure.js +656 -0
  23. package/dist/diagnosis-structure.js.map +1 -0
  24. package/dist/errors.d.ts +2 -1
  25. package/dist/errors.js +4 -1
  26. package/dist/errors.js.map +1 -1
  27. package/dist/figures.d.ts +2336 -0
  28. package/dist/figures.js +1288 -0
  29. package/dist/figures.js.map +1 -0
  30. package/dist/image-info.d.ts +14 -0
  31. package/dist/image-info.js +65 -0
  32. package/dist/image-info.js.map +1 -0
  33. package/dist/index.js +2 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/server.js +63 -6
  36. package/dist/server.js.map +1 -1
  37. package/dist/source-links.d.ts +101 -0
  38. package/dist/source-links.js +374 -0
  39. package/dist/source-links.js.map +1 -0
  40. package/dist/start.d.ts +11 -0
  41. package/dist/start.js +14 -0
  42. package/dist/start.js.map +1 -0
  43. package/dist/tools/attachments.d.ts +19 -0
  44. package/dist/tools/attachments.js +177 -0
  45. package/dist/tools/attachments.js.map +1 -0
  46. package/dist/tools/causes.d.ts +50 -0
  47. package/dist/tools/causes.js +97 -0
  48. package/dist/tools/causes.js.map +1 -0
  49. package/dist/tools/context.d.ts +3 -0
  50. package/dist/tools/context.js +146 -0
  51. package/dist/tools/context.js.map +1 -0
  52. package/dist/tools/datasources.d.ts +3 -0
  53. package/dist/tools/datasources.js +325 -0
  54. package/dist/tools/datasources.js.map +1 -0
  55. package/dist/tools/diagnostics.d.ts +3 -0
  56. package/dist/tools/diagnostics.js +113 -0
  57. package/dist/tools/diagnostics.js.map +1 -0
  58. package/dist/tools/figures.d.ts +8 -0
  59. package/dist/tools/figures.js +209 -0
  60. package/dist/tools/figures.js.map +1 -0
  61. package/dist/tools/findings.js +84 -6
  62. package/dist/tools/findings.js.map +1 -1
  63. package/dist/tools/incidents.js +112 -3
  64. package/dist/tools/incidents.js.map +1 -1
  65. package/dist/tools/index.js +18 -0
  66. package/dist/tools/index.js.map +1 -1
  67. package/dist/tools/investigations.js +834 -12
  68. package/dist/tools/investigations.js.map +1 -1
  69. package/dist/tools/postmortem-runbooks.d.ts +786 -0
  70. package/dist/tools/postmortem-runbooks.js +330 -0
  71. package/dist/tools/postmortem-runbooks.js.map +1 -0
  72. package/dist/tools/source-links.d.ts +47 -0
  73. package/dist/tools/source-links.js +302 -0
  74. package/dist/tools/source-links.js.map +1 -0
  75. package/dist/tools/timeline.d.ts +3 -0
  76. package/dist/tools/timeline.js +333 -0
  77. package/dist/tools/timeline.js.map +1 -0
  78. package/dist/version.d.ts +2 -0
  79. package/dist/version.js +12 -0
  80. package/dist/version.js.map +1 -0
  81. package/package.json +4 -3
  82. package/server.json +15 -1
@@ -0,0 +1,1288 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Figures are the typed widgets Tellagen draws in the Diagnosis tab, on the
4
+ * timeline and in the postmortem. The agent sends data and Tellagen draws it.
5
+ *
6
+ * The limits below mirror the Tellagen API contract
7
+ * (contracts/runbooks/v2/timeline-event-blocks.schema.json) and the API's own
8
+ * figure validation, which stay the source of truth. A figure over a limit is
9
+ * rejected with the field named. Nothing is trimmed, because a silently
10
+ * shortened label or a dropped row would misstate the evidence.
11
+ */
12
+ /**
13
+ * Types a causal step may carry as its `figure`. table and changes are
14
+ * timeline blocks only.
15
+ */
16
+ export const STEP_FIGURE_TYPES = [
17
+ "stats",
18
+ "compare",
19
+ "trend",
20
+ "checks",
21
+ "range_overlap",
22
+ "histogram",
23
+ "run_history",
24
+ "diff",
25
+ ];
26
+ /** Types the API accepts in a timeline event's `blocks`. */
27
+ export const TIMELINE_BLOCK_TYPES = [
28
+ "stats",
29
+ "compare",
30
+ "trend",
31
+ "table",
32
+ "checks",
33
+ "changes",
34
+ "range_overlap",
35
+ "histogram",
36
+ "run_history",
37
+ "diff",
38
+ ];
39
+ /** The most JSON one step figure may take, as the backend measures it. */
40
+ export const MAX_STEP_FIGURE_BYTES = 16 * 1024;
41
+ const MAX_ABS = 1_000_000_000_000;
42
+ const MAX_TREND_POINTS = 500;
43
+ const number = z.number().finite().min(-MAX_ABS).max(MAX_ABS);
44
+ const positive = z.number().finite().gt(0).max(MAX_ABS);
45
+ const text = (min, max) => z.string().min(min).max(max);
46
+ const thresholdSchema = z
47
+ .object({
48
+ value: number.describe("Where the line is drawn, in the figure's unit"),
49
+ label: z.string().max(80).optional().describe("Name of the line, for example SLO 500 ms"),
50
+ })
51
+ .strict();
52
+ const statsBase = z
53
+ .object({
54
+ type: z.literal("stats"),
55
+ items: z
56
+ .array(z
57
+ .object({
58
+ label: text(1, 48),
59
+ value: text(1, 32).describe("The value as measured, with no unit inside a number you also chart"),
60
+ caption: z.string().max(64).optional().describe("What the value is measured on"),
61
+ tone: z
62
+ .enum(["good", "warn", "bad", "neutral"])
63
+ .optional()
64
+ .describe("A meaning: good healthy or recovered, warn needs attention, bad failing. Never emphasis."),
65
+ })
66
+ .strict())
67
+ .min(1)
68
+ .max(4)
69
+ .describe("One to four numbers a responder scans for"),
70
+ })
71
+ .strict();
72
+ const compareBase = z
73
+ .object({
74
+ type: z.literal("compare"),
75
+ title: z.string().max(80).optional(),
76
+ metric: z.string().max(32).optional().describe("What is measured, for example p95 latency"),
77
+ unit: z.string().max(12).optional().describe("The unit once for every row, for example ms"),
78
+ better: z.enum(["lower", "higher"]).optional().describe("Which direction is an improvement"),
79
+ delta: z.enum(["rel", "abs"]).optional().describe("Show the change as a percentage or an absolute amount"),
80
+ max: positive.optional().describe("Top of the axis. Leave out to let Tellagen choose."),
81
+ threshold: thresholdSchema.optional().describe("An SLO or alert line"),
82
+ rows: z
83
+ .array(z
84
+ .object({
85
+ label: text(1, 80).describe("One host, route, query or job"),
86
+ mono: z.boolean().optional().describe("Draw the label in a monospace face"),
87
+ before: number,
88
+ after: number,
89
+ details: z
90
+ .array(z
91
+ .object({ label: text(1, 32), before: text(1, 32), after: text(1, 32) })
92
+ .strict())
93
+ .max(3)
94
+ .optional(),
95
+ })
96
+ .strict())
97
+ .min(1)
98
+ .max(8)
99
+ .describe("One row per host, route, query or job, biggest movers first"),
100
+ })
101
+ .strict();
102
+ const trendSourceSchema = z
103
+ .object({
104
+ kind: z.string().max(80).optional().describe("promql, logql, sql, trace_metrics"),
105
+ datasource: z.string().max(80).optional(),
106
+ query: z.string().max(2000).optional().describe("The query that produced the series"),
107
+ from: z.string().max(80).optional(),
108
+ to: z.string().max(80).optional(),
109
+ step: z.string().max(80).optional(),
110
+ artifact_id: z.string().max(80).optional(),
111
+ })
112
+ .strict();
113
+ const trendBase = z
114
+ .object({
115
+ type: z.literal("trend"),
116
+ title: z.string().max(80).optional(),
117
+ unit: z.string().max(12).optional(),
118
+ series: z.array(number).min(2).max(MAX_TREND_POINTS),
119
+ start: z.string().datetime().optional().describe("Time of the first value. Send with step_seconds."),
120
+ step_seconds: z.number().int().min(1).max(86400).optional().describe("Seconds between values. Send with start."),
121
+ max: positive.optional(),
122
+ threshold: thresholdSchema.optional(),
123
+ marks: z
124
+ .array(z.object({ i: z.number().int().min(0).describe("An index into series"), label: text(1, 48) }).strict())
125
+ .max(3)
126
+ .optional()
127
+ .describe("At most three events that explain the shape"),
128
+ source: trendSourceSchema.optional().describe("Provenance only. The values stay in series."),
129
+ })
130
+ .strict();
131
+ const tableBase = z
132
+ .object({
133
+ type: z.literal("table"),
134
+ title: z.string().max(80).optional(),
135
+ columns: z.array(z.object({ label: text(1, 80) }).strict()).min(1).max(6),
136
+ rows: z
137
+ .array(z.object({ cells: z.array(z.string().max(64)) }).strict())
138
+ .min(1)
139
+ .max(12),
140
+ })
141
+ .strict();
142
+ const checksBase = z
143
+ .object({
144
+ type: z.literal("checks"),
145
+ title: z.string().max(80).optional(),
146
+ items: z
147
+ .array(z
148
+ .object({
149
+ label: text(1, 80),
150
+ state: z.enum(["pass", "fail", "pending", "skipped"]),
151
+ detail: z.string().max(160).optional(),
152
+ })
153
+ .strict())
154
+ .min(1)
155
+ .max(12),
156
+ })
157
+ .strict();
158
+ const changesBase = z
159
+ .object({
160
+ type: z.literal("changes"),
161
+ title: z.string().max(80).optional(),
162
+ rows: z
163
+ .array(z
164
+ .object({
165
+ label: text(1, 80),
166
+ from: z.string().max(80).optional(),
167
+ to: z.string().max(80).optional(),
168
+ note: z.string().max(160).optional(),
169
+ })
170
+ .strict())
171
+ .min(1)
172
+ .max(8),
173
+ })
174
+ .strict();
175
+ /*
176
+ * The four figure types range_overlap, histogram, run_history and diff.
177
+ * Lengths count Unicode characters after trimming, as the API counts them,
178
+ * and text is one line without control characters.
179
+ */
180
+ /** Control characters, line and paragraph separators and bidirectional controls. */
181
+ const BLOCK_UNSAFE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]/;
182
+ /** The same for a line of code, which may also hold tabs. */
183
+ const CODE_UNSAFE = /[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]/;
184
+ const charCount = (value) => [...value].length;
185
+ /** One line of at most max characters after trimming; required needs a non-space character. */
186
+ function blockText(max, required = false) {
187
+ return z.string().superRefine((value, ctx) => {
188
+ const trimmed = value.trim();
189
+ if (trimmed === "") {
190
+ if (required)
191
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "is required" });
192
+ return;
193
+ }
194
+ if (BLOCK_UNSAFE.test(trimmed)) {
195
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "must be one line without control characters" });
196
+ return;
197
+ }
198
+ const n = charCount(trimmed);
199
+ if (n > max)
200
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `at most ${max} characters (got ${n})` });
201
+ });
202
+ }
203
+ /** A line of code: kept as sent (indentation too), may be empty, tabs allowed. */
204
+ function codeLine(max) {
205
+ return z.string().superRefine((value, ctx) => {
206
+ if (CODE_UNSAFE.test(value)) {
207
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "must not contain control characters other than tabs" });
208
+ return;
209
+ }
210
+ const n = charCount(value);
211
+ if (n > max)
212
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `at most ${max} characters (got ${n})` });
213
+ });
214
+ }
215
+ const rfc3339 = z
216
+ .string()
217
+ .datetime({ offset: true })
218
+ .describe("RFC 3339 time, for example 2026-08-12T09:00:00Z");
219
+ const REPO_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
220
+ const repoField = blockText(80)
221
+ .refine((value) => value.trim() === "" || REPO_PATTERN.test(value.trim()), {
222
+ message: "must look like owner/name (letters, digits, dots, underscores and dashes)",
223
+ })
224
+ .describe("GitHub repository as owner/name, so each run or commit links to its page");
225
+ const httpsLink = blockText(500).refine((value) => {
226
+ const t = value.trim();
227
+ return t === "" || (t.startsWith("https://") && t.length > "https://".length && !/\s/.test(t));
228
+ }, { message: "must be an https:// link without spaces" });
229
+ const wholeCount = z.number().int().min(0).max(1_000_000);
230
+ export const RUN_RESULTS = ["success", "failure", "cancelled", "pending"];
231
+ export const RUN_MARK_CHANGES = ["regression", "fix", "change"];
232
+ const rangeOverlapBase = z
233
+ .object({
234
+ type: z.literal("range_overlap"),
235
+ title: blockText(80).optional(),
236
+ unit: blockText(12).optional().describe("The one unit every row is in, for example px or MB"),
237
+ min: number.optional().describe("Start of the whole range drawn in the overview. Send with max."),
238
+ max: number.optional().describe("End of the whole range drawn in the overview. Send with min."),
239
+ rows: z
240
+ .array(z
241
+ .object({
242
+ label: blockText(80, true),
243
+ from: number,
244
+ to: number.describe("Not below from"),
245
+ })
246
+ .strict())
247
+ .min(2)
248
+ .max(4)
249
+ .describe("Two to four ranges. Tellagen computes where they overlap; never send the overlap."),
250
+ window: z
251
+ .tuple([number, number])
252
+ .optional()
253
+ .describe("[from, to] to choose the zoom yourself. Leave out to zoom to the overlap."),
254
+ })
255
+ .strict();
256
+ const histogramBase = z
257
+ .object({
258
+ type: z.literal("histogram"),
259
+ title: blockText(80).optional(),
260
+ unit: blockText(12).optional(),
261
+ edges: z
262
+ .array(number)
263
+ .min(3)
264
+ .max(61)
265
+ .describe("Bucket edges, 3 to 61, none negative, each greater than the one before: 2 to 60 buckets"),
266
+ before: z.array(number).max(60).describe("One count per bucket before the change"),
267
+ after: z.array(number).max(60).describe("One count per bucket after the change"),
268
+ threshold: thresholdSchema.optional().describe("The SLO line. Tellagen computes the share over it."),
269
+ source: trendSourceSchema.optional().describe("Provenance only. The counts stay in before and after."),
270
+ })
271
+ .strict();
272
+ const runRef = blockText(80, true);
273
+ const runSchema = z
274
+ .object({
275
+ ref: runRef.describe("The run number or id, unique in the block. Marks and the span name runs by ref."),
276
+ result: z.enum(RUN_RESULTS),
277
+ sha: blockText(64).optional(),
278
+ at: rfc3339.optional(),
279
+ trigger: blockText(32).optional().describe("What started the run, for example push or schedule"),
280
+ job: blockText(80).optional().describe("The job that failed"),
281
+ url: httpsLink.optional(),
282
+ })
283
+ .strict();
284
+ const runMarkSchema = z
285
+ .object({
286
+ between: z
287
+ .tuple([runRef, runRef])
288
+ .describe("Refs of two neighbouring runs, the second right after the first"),
289
+ change_ref: z.enum(RUN_MARK_CHANGES).describe("regression for the change that broke it, fix for the one that fixed it"),
290
+ sha: blockText(64).optional(),
291
+ at: rfc3339.optional(),
292
+ title: blockText(80).optional(),
293
+ })
294
+ .strict();
295
+ const runSpanSchema = z
296
+ .object({
297
+ from: runRef,
298
+ to: runRef.describe("Not a run before from"),
299
+ label: blockText(48, true).describe("For example E2E Tests failed"),
300
+ })
301
+ .strict();
302
+ const runHistoryBase = z
303
+ .object({
304
+ type: z.literal("run_history"),
305
+ title: blockText(80).optional(),
306
+ repo: repoField.optional(),
307
+ branch: blockText(80).optional(),
308
+ runs: z.array(runSchema).min(2).max(30).describe("2 to 30 runs, oldest first"),
309
+ marks: z.array(runMarkSchema).max(4).optional().describe("At most four changes between neighbouring runs"),
310
+ span: runSpanSchema.optional().describe("A stretch of runs bracketed under the strip"),
311
+ })
312
+ .strict();
313
+ const diffLineSchema = z
314
+ .object({
315
+ op: z.enum(["+", "-"]),
316
+ text: codeLine(160).describe("The line as it is in the change, indentation kept, up to 160 characters"),
317
+ })
318
+ .strict();
319
+ const diffBase = z
320
+ .object({
321
+ type: z.literal("diff"),
322
+ title: blockText(80).optional(),
323
+ path: blockText(200, true).describe("The file the lines are from"),
324
+ repo: repoField.optional(),
325
+ ref: blockText(64, true).describe("The commit sha or ref"),
326
+ at: rfc3339.optional(),
327
+ additions: wholeCount.describe("Added lines in the whole change, from the commit or pull request"),
328
+ deletions: wholeCount.describe("Removed lines in the whole change, from the commit or pull request"),
329
+ hunks: z
330
+ .array(z.array(diffLineSchema).min(1))
331
+ .min(1)
332
+ .max(6)
333
+ .describe("1 to 6 hunks of + and - lines, at most 12 lines in all. Do not send the whole diff."),
334
+ })
335
+ .strict();
336
+ /** Exported for the step figure schema of tellagen_complete_investigation. */
337
+ export const checksBlockSchema = checksBase;
338
+ export const rangeOverlapBlockSchema = rangeOverlapBase;
339
+ export const histogramBlockSchema = histogramBase;
340
+ export const runHistoryBlockSchema = runHistoryBase;
341
+ export const diffBlockSchema = diffBase;
342
+ const formatEdge = (n) => String(n);
343
+ /**
344
+ * The rules of range_overlap, histogram, run_history and diff that span
345
+ * fields, with the messages the API uses. The block has passed its schema.
346
+ */
347
+ export function figureRuleIssues(block) {
348
+ const issues = [];
349
+ const add = (path, message) => issues.push({ path, message });
350
+ if (block.type === "range_overlap") {
351
+ const b = block;
352
+ let bounded = false;
353
+ if (b.min !== undefined && b.max === undefined)
354
+ add(["max"], "is required when min is set");
355
+ else if (b.max !== undefined && b.min === undefined)
356
+ add(["min"], "is required when max is set");
357
+ else if (b.min !== undefined && b.max !== undefined) {
358
+ if (b.min >= b.max)
359
+ add(["max"], "must be greater than min");
360
+ else
361
+ bounded = true;
362
+ }
363
+ for (const [i, row] of b.rows.entries()) {
364
+ if (row.from > row.to)
365
+ add(["rows", i, "to"], "must not be below from");
366
+ if (bounded) {
367
+ const within = `must be within min and max (${formatEdge(b.min)} to ${formatEdge(b.max)})`;
368
+ if (row.from < b.min || row.from > b.max)
369
+ add(["rows", i, "from"], within);
370
+ if (row.to < b.min || row.to > b.max)
371
+ add(["rows", i, "to"], within);
372
+ }
373
+ }
374
+ if (b.window && b.window[0] >= b.window[1])
375
+ add(["window"], "must have from below to");
376
+ }
377
+ if (block.type === "histogram") {
378
+ const b = block;
379
+ for (const [i, edge] of b.edges.entries()) {
380
+ if (edge < 0)
381
+ add(["edges", i], "must not be negative");
382
+ else if (i > 0 && edge <= b.edges[i - 1])
383
+ add(["edges", i], "must be greater than the edge before it");
384
+ }
385
+ const buckets = b.edges.length - 1;
386
+ for (const key of ["before", "after"]) {
387
+ const counts = b[key];
388
+ if (counts.length !== buckets) {
389
+ add([key], `needs exactly ${buckets} counts (got ${counts.length})`);
390
+ continue;
391
+ }
392
+ let valid = true;
393
+ for (const [i, count] of counts.entries()) {
394
+ if (count < 0) {
395
+ add([key, i], "must not be negative");
396
+ valid = false;
397
+ }
398
+ }
399
+ if (valid && counts.reduce((sum, c) => sum + c, 0) <= 0)
400
+ add([key], "must add up to more than 0");
401
+ }
402
+ }
403
+ if (block.type === "run_history") {
404
+ const b = block;
405
+ const index = new Map();
406
+ for (const [i, run] of b.runs.entries()) {
407
+ const ref = run.ref.trim();
408
+ if (index.has(ref))
409
+ add(["runs", i, "ref"], "is already used by another run of this block");
410
+ else
411
+ index.set(ref, i);
412
+ }
413
+ for (const [k, mark] of (b.marks ?? []).entries()) {
414
+ const at = mark.between.map((ref) => index.get(ref.trim()));
415
+ mark.between.forEach((ref, j) => {
416
+ if (at[j] === undefined)
417
+ add(["marks", k, "between", j], "is not the ref of a run of this block");
418
+ });
419
+ if (at[0] !== undefined && at[1] !== undefined && at[1] !== at[0] + 1) {
420
+ add(["marks", k, "between"], "must name two neighbouring runs, the second right after the first");
421
+ }
422
+ }
423
+ if (b.span) {
424
+ const from = index.get(b.span.from.trim());
425
+ const to = index.get(b.span.to.trim());
426
+ if (from === undefined)
427
+ add(["span", "from"], "is not the ref of a run of this block");
428
+ if (to === undefined)
429
+ add(["span", "to"], "is not the ref of a run of this block");
430
+ if (from !== undefined && to !== undefined && from > to)
431
+ add(["span", "to"], "must not be a run before from");
432
+ }
433
+ }
434
+ if (block.type === "diff") {
435
+ const b = block;
436
+ const lines = b.hunks.reduce((sum, hunk) => sum + hunk.length, 0);
437
+ if (lines > 12)
438
+ add(["hunks"], `at most 12 lines in all (got ${lines})`);
439
+ }
440
+ return issues;
441
+ }
442
+ /** Where a block sits on a timeline event. Not together. */
443
+ const placementFields = {
444
+ slot: z.literal("summary").optional().describe("Draw the block above the note. Not together with anchor."),
445
+ anchor: z.string().max(80).optional().describe("The exact heading text in the note the block sits under. Not together with slot."),
446
+ postmortem: z.boolean().optional().describe("false keeps the block out of the postmortem. Leave out otherwise."),
447
+ };
448
+ /**
449
+ * One block as the timeline tools accept it. Cross-field rules (a trend's
450
+ * start and step_seconds travel together, a table row has one cell per
451
+ * column) are checked by validateBlock and by the API.
452
+ */
453
+ export const timelineBlockSchema = z.discriminatedUnion("type", [
454
+ statsBase.extend(placementFields),
455
+ compareBase.extend(placementFields),
456
+ trendBase.extend(placementFields),
457
+ tableBase.extend(placementFields),
458
+ checksBase.extend(placementFields),
459
+ changesBase.extend(placementFields),
460
+ rangeOverlapBase.extend(placementFields),
461
+ histogramBase.extend(placementFields),
462
+ runHistoryBase.extend(placementFields),
463
+ diffBase.extend(placementFields),
464
+ ]);
465
+ /**
466
+ * The light check the timeline tools apply to `blocks`. The full schema above
467
+ * would add about 8 KB to each tool listing, and the API validates every block
468
+ * itself (400 invalid_block names the field), so the tools only check that the
469
+ * type is one the API accepts. tellagen_build_figure does the full check.
470
+ */
471
+ export const timelineBlockRefSchema = z.object({ type: z.enum(TIMELINE_BLOCK_TYPES) }).passthrough();
472
+ /** A trend with the extra inputs the builder understands. */
473
+ const trendInput = z
474
+ .object({
475
+ type: z.literal("trend"),
476
+ title: z.string().max(80).optional(),
477
+ unit: z.string().max(12).optional(),
478
+ series: z
479
+ .array(number)
480
+ .min(2)
481
+ .max(MAX_TREND_POINTS)
482
+ .optional()
483
+ .describe("Values already on an even grid. Send with start and step_seconds. Or send points instead."),
484
+ start: z.string().datetime().optional(),
485
+ step_seconds: z.number().int().min(1).max(86400).optional(),
486
+ points: z
487
+ .array(z
488
+ .object({
489
+ t: z
490
+ .union([z.string(), z.number()])
491
+ .describe("ISO 8601 time, or Unix time in seconds or milliseconds"),
492
+ v: z
493
+ .union([z.number(), z.string()])
494
+ .nullable()
495
+ .describe("The value. A numeric string such as a Prometheus value is accepted; null, NaN and gaps are skipped."),
496
+ })
497
+ .strict())
498
+ .min(2)
499
+ .max(5000)
500
+ .optional()
501
+ .describe("Raw samples from a range query. Tellagen puts them on an even grid of at most max_points."),
502
+ events: z
503
+ .array(z.object({ at: z.union([z.string(), z.number()]), label: text(1, 48) }).strict())
504
+ .max(10)
505
+ .optional()
506
+ .describe("Events by time, such as a deploy or a rollback. Converted to marks. At most three may fall inside the range."),
507
+ marks: trendBase.shape.marks.describe("Marks by index into series, when you already know the indexes. Use events with points."),
508
+ max_points: z.number().int().min(2).max(MAX_TREND_POINTS).optional().describe("Most points to keep. Default 240."),
509
+ reduce: z
510
+ .enum(["mean", "max", "min", "last"])
511
+ .optional()
512
+ .describe("How samples that share a step combine. Default mean. Use max for error rate or latency spikes so the peak survives."),
513
+ precision: z.number().int().min(1).max(12).optional().describe("Significant digits to keep. Default 4."),
514
+ max: positive.optional(),
515
+ threshold: thresholdSchema.optional(),
516
+ source: trendSourceSchema.optional(),
517
+ })
518
+ .strict();
519
+ const tableInput = z
520
+ .object({
521
+ type: z.literal("table"),
522
+ title: z.string().max(80).optional(),
523
+ columns: z.array(z.object({ label: text(1, 80) }).strict()).min(1).max(6),
524
+ rows: z
525
+ .array(z.object({ cells: z.array(z.union([z.string(), z.number()])) }).strict())
526
+ .min(1)
527
+ .max(12),
528
+ })
529
+ .strict();
530
+ /** A number as a tool returns it: a JSON number or a numeric string. */
531
+ const measured = z.union([z.number(), z.string()]);
532
+ /** A histogram, either as the contract has it or as cumulative le buckets. */
533
+ const histogramInput = z
534
+ .object({
535
+ type: z.literal("histogram"),
536
+ title: blockText(80).optional(),
537
+ unit: blockText(12).optional(),
538
+ edges: histogramBase.shape.edges.optional().describe("Bucket edges. Send with before and after. Or send buckets instead."),
539
+ before: histogramBase.shape.before.optional(),
540
+ after: histogramBase.shape.after.optional(),
541
+ buckets: z
542
+ .array(z
543
+ .object({
544
+ le: measured.describe('The upper bound, as the le label of a Prometheus bucket: a number, or "+Inf" for the last one'),
545
+ before: measured.describe("Cumulative count of the before window at this le (observations <= le)"),
546
+ after: measured.describe("Cumulative count of the after window at this le"),
547
+ })
548
+ .strict())
549
+ .min(2)
550
+ .max(61)
551
+ .optional()
552
+ .describe("Cumulative bucket counts of two equal windows, one entry per le, as sum by (le) (increase(..._bucket[window])) returns them. Tellagen turns them into edges and one count per bucket."),
553
+ lower_edge: z
554
+ .number()
555
+ .finite()
556
+ .min(0)
557
+ .max(MAX_ABS)
558
+ .optional()
559
+ .describe("With buckets: where the first bucket starts. Default 0."),
560
+ overflow: z
561
+ .enum(["reject", "drop"])
562
+ .optional()
563
+ .describe('With buckets: what to do with observations above the last finite le (the +Inf bucket). A histogram has no open bucket. Default reject; drop leaves them out and says so in notes.'),
564
+ threshold: thresholdSchema.optional(),
565
+ source: trendSourceSchema.optional(),
566
+ })
567
+ .strict();
568
+ /** Change roles of change_refs, mapped to the three marks a run history draws. */
569
+ const ROLE_TO_MARK = {
570
+ regression: "regression",
571
+ fix: "fix",
572
+ change: "change",
573
+ regression_source: "regression",
574
+ first_bad: "regression",
575
+ rollback: "change",
576
+ last_good: "change",
577
+ verified_by: "change",
578
+ context: "change",
579
+ };
580
+ const runMarkInput = z
581
+ .object({
582
+ between: runMarkSchema.shape.between.optional(),
583
+ sha: blockText(64)
584
+ .optional()
585
+ .describe("The commit of the change. Without between, the mark goes before the first run built from this sha."),
586
+ change_ref: z
587
+ .enum(Object.keys(ROLE_TO_MARK))
588
+ .describe("regression, fix or change. A change_refs role is accepted too: regression_source and first_bad become regression, fix stays fix, any other role becomes change."),
589
+ at: rfc3339.optional(),
590
+ title: blockText(80).optional(),
591
+ })
592
+ .strict();
593
+ /** One workflow run as the GitHub Actions REST API or gh run list --json returns it. */
594
+ const githubRunInput = z
595
+ .object({
596
+ id: z.union([z.number(), z.string()]).optional(),
597
+ databaseId: z.union([z.number(), z.string()]).optional(),
598
+ run_number: z.number().int().optional(),
599
+ number: z.number().int().optional(),
600
+ head_sha: z.string().optional(),
601
+ headSha: z.string().optional(),
602
+ conclusion: z.string().nullable().optional(),
603
+ status: z.string().nullable().optional(),
604
+ run_started_at: z.string().optional(),
605
+ startedAt: z.string().optional(),
606
+ created_at: z.string().optional(),
607
+ createdAt: z.string().optional(),
608
+ event: z.string().optional(),
609
+ html_url: z.string().optional(),
610
+ url: z.string().optional(),
611
+ job: z.string().optional().describe("The failing job, from the run's jobs list. GitHub's run list does not carry it."),
612
+ })
613
+ .passthrough();
614
+ const runHistoryInput = z
615
+ .object({
616
+ type: z.literal("run_history"),
617
+ title: blockText(80).optional(),
618
+ repo: repoField.optional(),
619
+ branch: blockText(80).optional(),
620
+ runs: runHistoryBase.shape.runs.optional().describe("2 to 30 runs, oldest first. Or send github_runs instead."),
621
+ github_runs: z
622
+ .array(githubRunInput)
623
+ .min(2)
624
+ .max(30)
625
+ .optional()
626
+ .describe("Workflow runs exactly as the GitHub Actions list returns them (REST or gh run list --json). Tellagen maps each to a run and puts them oldest first."),
627
+ marks: z.array(runMarkInput).max(4).optional(),
628
+ span: runSpanSchema.optional(),
629
+ })
630
+ .strict();
631
+ const diffInput = z
632
+ .object({
633
+ type: z.literal("diff"),
634
+ title: blockText(80).optional(),
635
+ path: diffBase.shape.path,
636
+ repo: repoField.optional(),
637
+ ref: diffBase.shape.ref,
638
+ at: rfc3339.optional(),
639
+ additions: diffBase.shape.additions,
640
+ deletions: diffBase.shape.deletions,
641
+ hunks: diffBase.shape.hunks.optional().describe("1 to 6 hunks, at most 12 lines in all. Or send patch instead."),
642
+ patch: z
643
+ .string()
644
+ .max(200_000)
645
+ .optional()
646
+ .describe("A unified diff, as the patch of a GitHub commit or pull request file. Tellagen keeps its + and - lines; it must have at most 12."),
647
+ })
648
+ .strict();
649
+ /** What tellagen_build_figure accepts. */
650
+ export const figureInputSchema = z.discriminatedUnion("type", [
651
+ statsBase,
652
+ compareBase,
653
+ trendInput,
654
+ tableInput,
655
+ checksBase,
656
+ changesBase,
657
+ rangeOverlapBase,
658
+ histogramInput,
659
+ runHistoryInput,
660
+ diffInput,
661
+ ]);
662
+ /** The four figure types whose fields the tool listing leaves to the guide. */
663
+ export const GUIDE_ONLY_FIGURE_TYPES = ["range_overlap", "histogram", "run_history", "diff"];
664
+ /**
665
+ * The figure as tellagen_build_figure lists it. The six original types carry
666
+ * their full schema; the four newer ones only their type, so the listing stays
667
+ * small (their fields are in the figure guide). buildFigure checks every type
668
+ * in full with figureInputSchema and names each bad field.
669
+ */
670
+ export const figureToolInputSchema = z.discriminatedUnion("type", [
671
+ statsBase,
672
+ compareBase,
673
+ trendInput,
674
+ tableInput,
675
+ checksBase,
676
+ changesBase,
677
+ z
678
+ .object({ type: z.enum(GUIDE_ONLY_FIGURE_TYPES) })
679
+ .passthrough()
680
+ .describe("range_overlap, histogram, run_history or diff, with the fields in resource://tellagen/figure-guide. Checked in full when the tool runs."),
681
+ ]);
682
+ const issuesOf = (error) => error.issues.map((issue) => {
683
+ const path = issue.path.join(".");
684
+ return path ? `${path}: ${issue.message}` : issue.message;
685
+ });
686
+ /**
687
+ * Checks one block against the contract, including the rules that span
688
+ * fields. Returns the problems, empty when the block is valid.
689
+ */
690
+ export function validateBlock(block) {
691
+ const parsed = timelineBlockSchema.safeParse(block);
692
+ if (!parsed.success)
693
+ return issuesOf(parsed.error);
694
+ const b = parsed.data;
695
+ const issues = [];
696
+ if (b.slot && b.anchor)
697
+ issues.push("slot: send slot or anchor, not both");
698
+ if (b.type === "trend") {
699
+ if ((b.start === undefined) !== (b.step_seconds === undefined)) {
700
+ issues.push("start: send start and step_seconds together, or neither");
701
+ }
702
+ for (const [k, m] of (b.marks ?? []).entries()) {
703
+ if (m.i >= b.series.length) {
704
+ issues.push(`marks.${k}.i: ${m.i} is past the end of series, which has ${b.series.length} values`);
705
+ }
706
+ }
707
+ }
708
+ if (b.type === "table") {
709
+ for (const [k, row] of b.rows.entries()) {
710
+ if (row.cells.length !== b.columns.length) {
711
+ issues.push(`rows.${k}.cells: ${row.cells.length} cells for ${b.columns.length} columns, one cell per column`);
712
+ }
713
+ }
714
+ }
715
+ if (b.type === "changes") {
716
+ for (const [k, row] of b.rows.entries()) {
717
+ if (row.from === undefined && row.to === undefined) {
718
+ issues.push(`rows.${k}: send from, to, or both`);
719
+ }
720
+ }
721
+ }
722
+ for (const issue of figureRuleIssues(b)) {
723
+ issues.push(`${issue.path.join(".")}: ${issue.message}`);
724
+ }
725
+ return issues;
726
+ }
727
+ const toSeconds = (t) => {
728
+ if (typeof t === "number") {
729
+ if (!Number.isFinite(t))
730
+ return null;
731
+ return t >= 1e11 ? t / 1000 : t;
732
+ }
733
+ const trimmed = t.trim();
734
+ if (/^\d+(\.\d+)?$/.test(trimmed))
735
+ return toSeconds(Number(trimmed));
736
+ const ms = Date.parse(trimmed);
737
+ return Number.isNaN(ms) ? null : ms / 1000;
738
+ };
739
+ const toValue = (v) => {
740
+ if (v === null)
741
+ return null;
742
+ const n = typeof v === "number" ? v : Number(v);
743
+ return Number.isFinite(n) ? n : null;
744
+ };
745
+ const roundSig = (v, digits) => Number(v.toPrecision(digits));
746
+ const median = (xs) => {
747
+ const sorted = [...xs].sort((a, b) => a - b);
748
+ const mid = Math.floor(sorted.length / 2);
749
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
750
+ };
751
+ function buildTrend(input) {
752
+ const notes = [];
753
+ const digits = input.precision ?? 4;
754
+ const { points, events, series, start, step_seconds, marks, max_points, reduce, precision, ...rest } = input;
755
+ void precision;
756
+ void max_points;
757
+ void reduce;
758
+ if (points && series) {
759
+ return { issues: ["points: send points or series, not both"] };
760
+ }
761
+ if (!points && !series) {
762
+ return { issues: ["points: send points (raw samples with times) or series (values on an even grid)"] };
763
+ }
764
+ if (series) {
765
+ if (events && events.length > 0) {
766
+ return { issues: ["events: events need points to place them in time. With series, send marks by index."] };
767
+ }
768
+ const block = {
769
+ ...rest,
770
+ series: series.map((v) => roundSig(v, digits)),
771
+ ...(start !== undefined ? { start } : {}),
772
+ ...(step_seconds !== undefined ? { step_seconds } : {}),
773
+ ...(marks ? { marks } : {}),
774
+ };
775
+ return { block, notes };
776
+ }
777
+ // Raw samples: sort, drop what has no usable time or value, then put them on an even grid.
778
+ const raw = points
779
+ .map((p) => ({ t: toSeconds(p.t), v: toValue(p.v) }))
780
+ .filter((p) => p.t !== null && p.v !== null)
781
+ .sort((a, b) => a.t - b.t);
782
+ const dropped = points.length - raw.length;
783
+ if (dropped > 0)
784
+ notes.push(`${dropped} sample${dropped === 1 ? "" : "s"} had no usable time or value and were skipped.`);
785
+ if (raw.length < 2)
786
+ return { issues: ["points: at least two samples with a time and a value are needed"] };
787
+ const t0 = Math.floor(raw[0].t);
788
+ const span = raw[raw.length - 1].t - t0;
789
+ if (span <= 0)
790
+ return { issues: ["points: the samples all share one time"] };
791
+ const limit = Math.min(MAX_TREND_POINTS, max_points ?? 240);
792
+ const spacing = Math.max(1, Math.round(median(raw.slice(1).map((p, i) => p.t - raw[i].t).filter((d) => d > 0))));
793
+ let step = step_seconds ?? spacing;
794
+ step = Math.max(step, Math.ceil(span / (limit - 1)));
795
+ if (step > 86400) {
796
+ return { issues: [`points: the range is too long for ${limit} points at one day or less per step. Send a shorter range.`] };
797
+ }
798
+ const count = Math.floor(span / step) + 1;
799
+ const buckets = Array.from({ length: count }, () => []);
800
+ for (const p of raw) {
801
+ const index = Math.min(count - 1, Math.max(0, Math.round((p.t - t0) / step)));
802
+ buckets[index].push(p.v);
803
+ }
804
+ const combine = reduce ?? "mean";
805
+ const values = buckets.map((b) => {
806
+ if (b.length === 0)
807
+ return null;
808
+ if (combine === "max")
809
+ return Math.max(...b);
810
+ if (combine === "min")
811
+ return Math.min(...b);
812
+ if (combine === "last")
813
+ return b[b.length - 1];
814
+ return b.reduce((a, c) => a + c, 0) / b.length;
815
+ });
816
+ // Fill empty steps with a straight line between the neighbours that exist.
817
+ let filled = 0;
818
+ let previous = -1;
819
+ for (let i = 0; i < values.length; i += 1) {
820
+ if (values[i] === null)
821
+ continue;
822
+ if (previous >= 0 && i - previous > 1) {
823
+ const a = values[previous];
824
+ const b = values[i];
825
+ for (let k = previous + 1; k < i; k += 1) {
826
+ values[k] = a + ((b - a) * (k - previous)) / (i - previous);
827
+ filled += 1;
828
+ }
829
+ }
830
+ previous = i;
831
+ }
832
+ if (filled > 0) {
833
+ notes.push(`${filled} empty step${filled === 1 ? "" : "s"} were filled with a straight line between neighbours. Say so in the step if it matters.`);
834
+ if (filled / count > 0.2)
835
+ notes.push("More than a fifth of the steps were filled. Check the query range and step before you rely on this chart.");
836
+ }
837
+ const out = values.map((v) => roundSig(v, digits));
838
+ if (raw.length !== out.length) {
839
+ notes.push(`${raw.length} samples became ${out.length} points at ${step} s, combined with ${combine}.`);
840
+ }
841
+ let outMarks = marks;
842
+ if (events && events.length > 0) {
843
+ if (marks && marks.length > 0)
844
+ return { issues: ["marks: send events or marks, not both"] };
845
+ const placed = [];
846
+ for (const e of events) {
847
+ const at = toSeconds(e.at);
848
+ const i = at === null ? -1 : Math.round((at - t0) / step);
849
+ if (i < 0 || i >= out.length) {
850
+ notes.push(`The event "${e.label}" falls outside the range and was left out.`);
851
+ continue;
852
+ }
853
+ placed.push({ i, label: e.label });
854
+ }
855
+ if (placed.length > 3) {
856
+ return { issues: [`events: ${placed.length} events fall inside the range, and a trend carries at most three marks. Keep the ones that explain the shape.`] };
857
+ }
858
+ outMarks = placed.sort((a, b) => a.i - b.i);
859
+ }
860
+ const block = {
861
+ ...rest,
862
+ series: out,
863
+ start: new Date(t0 * 1000).toISOString().replace(/\.\d{3}Z$/, "Z"),
864
+ step_seconds: step,
865
+ ...(outMarks && outMarks.length > 0 ? { marks: outMarks } : {}),
866
+ };
867
+ return { block, notes };
868
+ }
869
+ const toMeasured = (v) => {
870
+ const n = typeof v === "number" ? v : Number(v.trim());
871
+ return typeof v === "string" && v.trim() === "" ? null : Number.isFinite(n) ? n : null;
872
+ };
873
+ const toBound = (le) => {
874
+ if (typeof le === "string" && /^\+?inf$/i.test(le.trim()))
875
+ return Number.POSITIVE_INFINITY;
876
+ if (le === Number.POSITIVE_INFINITY)
877
+ return le;
878
+ return toMeasured(le);
879
+ };
880
+ /**
881
+ * A histogram from cumulative le buckets: the edges are the lower edge and the
882
+ * finite bounds, and the count of a bucket is the cumulative count at its
883
+ * bound less the one below it. Observations above the last finite bound have
884
+ * no bucket to go in; they are rejected unless overflow is drop.
885
+ */
886
+ function buildHistogram(input) {
887
+ const { buckets, lower_edge, overflow, edges, before, after, ...rest } = input;
888
+ if (buckets && (edges || before || after)) {
889
+ return { issues: ["buckets: send buckets, or edges with before and after, not both"] };
890
+ }
891
+ if (!buckets) {
892
+ if (!edges || !before || !after) {
893
+ return { issues: ["edges: send edges with before and after (one count per bucket), or send buckets (cumulative counts per le)"] };
894
+ }
895
+ return { block: { ...rest, edges, before, after }, notes: [] };
896
+ }
897
+ const notes = [];
898
+ const parsed = [];
899
+ const issues = [];
900
+ for (const [i, bucket] of buckets.entries()) {
901
+ const le = toBound(bucket.le);
902
+ const b = toMeasured(bucket.before);
903
+ const a = toMeasured(bucket.after);
904
+ if (le === null)
905
+ issues.push(`buckets.${i}.le: must be a number or +Inf`);
906
+ if (b === null)
907
+ issues.push(`buckets.${i}.before: must be a number`);
908
+ if (a === null)
909
+ issues.push(`buckets.${i}.after: must be a number`);
910
+ if (le !== null && b !== null && a !== null)
911
+ parsed.push({ le, before: b, after: a, at: i });
912
+ }
913
+ if (issues.length > 0)
914
+ return { issues };
915
+ parsed.sort((x, y) => x.le - y.le);
916
+ for (let i = 1; i < parsed.length; i += 1) {
917
+ if (parsed[i].le === parsed[i - 1].le)
918
+ return { issues: [`buckets.${parsed[i].at}.le: ${parsed[i].le} is sent twice`] };
919
+ }
920
+ const finite = parsed.filter((p) => Number.isFinite(p.le));
921
+ const open = parsed.find((p) => !Number.isFinite(p.le));
922
+ if (finite.length < 2)
923
+ return { issues: ["buckets: at least two buckets with a finite le are needed"] };
924
+ if (finite.length > 60)
925
+ return { issues: [`buckets: ${finite.length} finite buckets; a histogram has at most 60. Query a coarser set of buckets.`] };
926
+ const lower = lower_edge ?? 0;
927
+ if (lower >= finite[0].le) {
928
+ return { issues: [`lower_edge: ${lower} must be below the first le (${finite[0].le})`] };
929
+ }
930
+ if (lower_edge === undefined)
931
+ notes.push(`The first bucket starts at 0 (lower_edge) and ends at ${finite[0].le}.`);
932
+ const counts = { before: [], after: [] };
933
+ for (const key of ["before", "after"]) {
934
+ const top = Math.max(1, ...parsed.map((p) => Math.abs(p[key])));
935
+ const noise = top * 1e-9;
936
+ let previous = 0;
937
+ for (const p of finite) {
938
+ let count = p[key] - previous;
939
+ if (count < 0) {
940
+ if (-count > noise) {
941
+ return { issues: [`buckets.${p.at}.${key}: cumulative counts must not go down as le grows (${p[key]} after ${previous})`] };
942
+ }
943
+ count = 0;
944
+ }
945
+ counts[key].push(Number(count.toPrecision(12)));
946
+ previous = p[key];
947
+ }
948
+ if (open) {
949
+ const above = open[key] - previous;
950
+ if (above > noise) {
951
+ if (overflow !== "drop") {
952
+ return {
953
+ issues: [
954
+ `buckets: ${Number(above.toPrecision(12))} ${key} observations are above the last finite le (${finite[finite.length - 1].le}), in the +Inf bucket. A histogram has no open bucket: query a higher bucket, or set overflow to drop to leave them out and say so in the step.`,
955
+ ],
956
+ };
957
+ }
958
+ notes.push(`${Number(above.toPrecision(12))} ${key} observations above ${finite[finite.length - 1].le} (the +Inf bucket) were left out. Say so in the step.`);
959
+ }
960
+ else if (above < -noise) {
961
+ return { issues: [`buckets.${open.at}.${key}: the +Inf count is below the count at the last finite le`] };
962
+ }
963
+ }
964
+ }
965
+ const block = {
966
+ ...rest,
967
+ edges: [lower, ...finite.map((p) => p.le)],
968
+ before: counts.before,
969
+ after: counts.after,
970
+ };
971
+ notes.push(`${buckets.length} cumulative buckets became ${finite.length} bucket counts per window.`);
972
+ return { block, notes };
973
+ }
974
+ const GITHUB_RESULTS = {
975
+ success: "success",
976
+ failure: "failure",
977
+ timed_out: "failure",
978
+ startup_failure: "failure",
979
+ cancelled: "cancelled",
980
+ };
981
+ const GITHUB_UNFINISHED = new Set(["queued", "in_progress", "waiting", "requested", "pending"]);
982
+ const webUrl = (value) => {
983
+ if (!value)
984
+ return undefined;
985
+ try {
986
+ const url = new URL(value);
987
+ return url.protocol === "https:" && !url.hostname.startsWith("api.") ? value : undefined;
988
+ }
989
+ catch {
990
+ return undefined;
991
+ }
992
+ };
993
+ function runFromGithub(run, i) {
994
+ const number = run.run_number ?? run.number;
995
+ const id = run.id ?? run.databaseId;
996
+ const ref = number !== undefined ? `#${number}` : id !== undefined ? String(id) : "";
997
+ if (!ref)
998
+ return { issue: `github_runs.${i}: needs run_number or id` };
999
+ const conclusion = (run.conclusion ?? "").trim().toLowerCase();
1000
+ const status = (run.status ?? "").trim().toLowerCase();
1001
+ let result;
1002
+ let mapped;
1003
+ if (conclusion === "") {
1004
+ if (status === "" || GITHUB_UNFINISHED.has(status))
1005
+ result = "pending";
1006
+ }
1007
+ else {
1008
+ result = GITHUB_RESULTS[conclusion];
1009
+ if (result && conclusion !== result)
1010
+ mapped = `${ref} ${conclusion} is drawn as ${result}`;
1011
+ }
1012
+ if (!result) {
1013
+ const what = conclusion || status;
1014
+ return { issue: `github_runs.${i}.conclusion: "${what}" has no run_history result (success, failure, cancelled, pending). Leave the run out, or send runs yourself.` };
1015
+ }
1016
+ const out = { ref, result };
1017
+ const sha = run.head_sha ?? run.headSha;
1018
+ if (sha)
1019
+ out.sha = sha;
1020
+ const at = run.run_started_at ?? run.startedAt ?? run.created_at ?? run.createdAt;
1021
+ if (at)
1022
+ out.at = at;
1023
+ if (run.event)
1024
+ out.trigger = run.event;
1025
+ if (run.job)
1026
+ out.job = run.job;
1027
+ const url = webUrl(run.html_url) ?? webUrl(run.url);
1028
+ if (url)
1029
+ out.url = url;
1030
+ return { run: out, mapped };
1031
+ }
1032
+ /** A run history, from runs or from the GitHub Actions run list; marks may be placed by sha. */
1033
+ function buildRunHistory(input) {
1034
+ const { github_runs, runs, marks, ...rest } = input;
1035
+ if (github_runs && runs)
1036
+ return { issues: ["runs: send runs or github_runs, not both"] };
1037
+ if (!github_runs && !runs)
1038
+ return { issues: ["runs: send runs (oldest first) or github_runs (as GitHub lists them)"] };
1039
+ const notes = [];
1040
+ let list;
1041
+ if (github_runs) {
1042
+ const issues = [];
1043
+ const mapped = [];
1044
+ list = [];
1045
+ for (const [i, run] of github_runs.entries()) {
1046
+ const out = runFromGithub(run, i);
1047
+ if (out.issue)
1048
+ issues.push(out.issue);
1049
+ if (out.mapped)
1050
+ mapped.push(out.mapped);
1051
+ if (out.run)
1052
+ list.push(out.run);
1053
+ }
1054
+ if (issues.length > 0)
1055
+ return { issues };
1056
+ if (mapped.length > 0)
1057
+ notes.push(`${mapped.join("; ")}.`);
1058
+ if (list.every((run) => typeof run.at === "string" && Number.isFinite(Date.parse(run.at)))) {
1059
+ const sorted = [...list].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
1060
+ if (sorted.some((run, i) => run !== list[i]))
1061
+ notes.push("The runs were put oldest first by their start time.");
1062
+ list = sorted;
1063
+ }
1064
+ else {
1065
+ notes.push("Some runs have no start time, so they are kept in the order sent. Runs must be oldest first.");
1066
+ }
1067
+ }
1068
+ else {
1069
+ list = runs.map((run) => ({ ...run }));
1070
+ }
1071
+ const outMarks = [];
1072
+ for (const [k, mark] of (marks ?? []).entries()) {
1073
+ const change = ROLE_TO_MARK[mark.change_ref];
1074
+ if (change !== mark.change_ref)
1075
+ notes.push(`marks.${k}: change_ref ${mark.change_ref} is drawn as ${change}.`);
1076
+ let between = mark.between;
1077
+ if (!between) {
1078
+ const sha = mark.sha?.trim().toLowerCase();
1079
+ if (!sha)
1080
+ return { issues: [`marks.${k}: send between (two neighbouring run refs) or the sha of the change`] };
1081
+ const first = list.findIndex((run) => {
1082
+ const runSha = typeof run.sha === "string" ? run.sha.trim().toLowerCase() : "";
1083
+ return runSha !== "" && (runSha.startsWith(sha) || sha.startsWith(runSha));
1084
+ });
1085
+ if (first <= 0) {
1086
+ return {
1087
+ issues: [
1088
+ first === 0
1089
+ ? `marks.${k}.sha: the first run is already built from ${mark.sha}, so there is no run before it. Send between, or add the run before it.`
1090
+ : `marks.${k}.sha: no run is built from ${mark.sha}. Send between with the two runs the change falls between.`,
1091
+ ],
1092
+ };
1093
+ }
1094
+ between = [String(list[first - 1].ref), String(list[first].ref)];
1095
+ }
1096
+ const out = { between, change_ref: change };
1097
+ if (mark.sha)
1098
+ out.sha = mark.sha;
1099
+ if (mark.at)
1100
+ out.at = mark.at;
1101
+ if (mark.title)
1102
+ out.title = mark.title;
1103
+ outMarks.push(out);
1104
+ }
1105
+ const block = { ...rest, runs: list };
1106
+ if (outMarks.length > 0)
1107
+ block.marks = outMarks;
1108
+ return { block, notes };
1109
+ }
1110
+ /** The + and - lines of a unified diff, one hunk per @@ header. */
1111
+ function buildDiff(input) {
1112
+ const { patch, hunks, ...rest } = input;
1113
+ if (patch !== undefined && hunks)
1114
+ return { issues: ["patch: send patch or hunks, not both"] };
1115
+ if (patch === undefined) {
1116
+ if (!hunks)
1117
+ return { issues: ["hunks: send hunks (at most 12 + and - lines) or patch (a unified diff)"] };
1118
+ return { block: { ...rest, hunks }, notes: [] };
1119
+ }
1120
+ const lines = patch.split(/\r?\n/);
1121
+ if (lines.filter((line) => line.startsWith("diff --git ")).length > 1) {
1122
+ return { issues: [`patch: holds more than one file. Send the patch of ${input.path} only.`] };
1123
+ }
1124
+ const parsed = [];
1125
+ let current = null;
1126
+ for (const line of lines) {
1127
+ if (line.startsWith("@@")) {
1128
+ current = [];
1129
+ parsed.push(current);
1130
+ continue;
1131
+ }
1132
+ // File headers come before the first hunk; "" is not a line.
1133
+ if (current === null || line.startsWith("\\"))
1134
+ continue;
1135
+ if (line.startsWith("+") || line.startsWith("-"))
1136
+ current.push({ op: line[0], text: line.slice(1) });
1137
+ }
1138
+ const kept = parsed.filter((hunk) => hunk.length > 0);
1139
+ const changed = kept.reduce((sum, hunk) => sum + hunk.length, 0);
1140
+ if (parsed.length === 0)
1141
+ return { issues: ["patch: no hunk found. Send the patch as GitHub gives it, from the first @@ line."] };
1142
+ if (changed === 0)
1143
+ return { issues: ["patch: no added or removed line"] };
1144
+ if (changed > 12 || kept.length > 6) {
1145
+ return {
1146
+ issues: [
1147
+ `patch: ${changed} changed lines in ${kept.length} hunks. A diff shows at most 12 lines in at most 6 hunks: send hunks with the lines that show the change, copied as they are.`,
1148
+ ],
1149
+ };
1150
+ }
1151
+ const notes = parsed.length !== kept.length ? [`${parsed.length - kept.length} hunks with no + or - line were left out.`] : [];
1152
+ return { block: { ...rest, hunks: kept }, notes };
1153
+ }
1154
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1155
+ const describe = (block) => {
1156
+ switch (block.type) {
1157
+ case "trend": {
1158
+ const series = block.series;
1159
+ const marks = block.marks?.length ?? 0;
1160
+ return `trend of ${series.length} points${block.step_seconds ? ` at ${block.step_seconds} s` : ""} with ${marks} mark${marks === 1 ? "" : "s"}`;
1161
+ }
1162
+ case "compare":
1163
+ return `compare with ${block.rows.length} row${block.rows.length === 1 ? "" : "s"}`;
1164
+ case "stats":
1165
+ return `stats with ${block.items.length} number${block.items.length === 1 ? "" : "s"}`;
1166
+ case "table":
1167
+ return `table of ${block.rows.length} rows by ${block.columns.length} columns`;
1168
+ case "checks":
1169
+ return `checks with ${block.items.length} items`;
1170
+ case "range_overlap": {
1171
+ // For the agent only: Tellagen computes and draws the overlap itself.
1172
+ const rows = block.rows;
1173
+ const from = Math.max(...rows.map((r) => r.from));
1174
+ const to = Math.min(...rows.map((r) => r.to));
1175
+ const unit = typeof block.unit === "string" ? ` ${block.unit}` : "";
1176
+ return `range_overlap of ${rows.length} rows; ${from <= to ? `they overlap from ${from} to ${to}${unit}` : "they do not all overlap"}`;
1177
+ }
1178
+ case "histogram": {
1179
+ const total = (key) => Number(block[key].reduce((a, c) => a + c, 0).toPrecision(12));
1180
+ return `histogram of ${block.edges.length - 1} buckets, ${total("before")} observations before and ${total("after")} after`;
1181
+ }
1182
+ case "run_history": {
1183
+ const runs = block.runs;
1184
+ const count = (result) => runs.filter((r) => r.result === result).length;
1185
+ const marks = block.marks?.length ?? 0;
1186
+ return `run_history of ${runs.length} runs (${count("success")} passed, ${count("failure")} failed, ${count("cancelled")} cancelled, ${count("pending")} pending) with ${plural(marks, "mark")}`;
1187
+ }
1188
+ case "diff": {
1189
+ const lines = block.hunks.reduce((a, h) => a + h.length, 0);
1190
+ return `diff of ${block.path} at ${block.ref}: +${block.additions} -${block.deletions} in the whole change, ${plural(lines, "line")} shown`;
1191
+ }
1192
+ default:
1193
+ return `changes with ${block.rows.length} rows`;
1194
+ }
1195
+ };
1196
+ /**
1197
+ * Turns the numbers an agent already read from a tool result into a figure
1198
+ * Tellagen accepts. It reshapes and checks. It has no data source of its own
1199
+ * and never makes up a value.
1200
+ */
1201
+ export function buildFigure(input) {
1202
+ const parsed = figureInputSchema.safeParse(input.figure);
1203
+ if (!parsed.success)
1204
+ return { ok: false, issues: issuesOf(parsed.error) };
1205
+ const figure = parsed.data;
1206
+ if (input.placement === "step_figure") {
1207
+ if (!STEP_FIGURE_TYPES.includes(figure.type)) {
1208
+ return {
1209
+ ok: false,
1210
+ issues: [`type: a step figure is ${STEP_FIGURE_TYPES.join(", ")}. A ${figure.type} block is a timeline block, so use placement "timeline_block" or pick one of those.`],
1211
+ };
1212
+ }
1213
+ if (input.slot || input.anchor || input.postmortem !== undefined) {
1214
+ return { ok: false, issues: ["slot: slot, anchor and postmortem place a block on a timeline event. A step figure has no placement."] };
1215
+ }
1216
+ }
1217
+ const notes = [];
1218
+ let block;
1219
+ const take = (built) => {
1220
+ if ("issues" in built)
1221
+ return { ok: false, issues: built.issues };
1222
+ block = built.block;
1223
+ notes.push(...built.notes);
1224
+ return null;
1225
+ };
1226
+ if (figure.type === "trend") {
1227
+ const failed = take(buildTrend(figure));
1228
+ if (failed)
1229
+ return failed;
1230
+ }
1231
+ else if (figure.type === "histogram") {
1232
+ const failed = take(buildHistogram(figure));
1233
+ if (failed)
1234
+ return failed;
1235
+ }
1236
+ else if (figure.type === "run_history") {
1237
+ const failed = take(buildRunHistory(figure));
1238
+ if (failed)
1239
+ return failed;
1240
+ }
1241
+ else if (figure.type === "diff") {
1242
+ const failed = take(buildDiff(figure));
1243
+ if (failed)
1244
+ return failed;
1245
+ }
1246
+ else if (figure.type === "table") {
1247
+ block = {
1248
+ ...figure,
1249
+ rows: figure.rows.map((r) => ({ cells: r.cells.map((c) => (typeof c === "number" ? String(c) : c)) })),
1250
+ };
1251
+ }
1252
+ else {
1253
+ block = { ...figure };
1254
+ }
1255
+ block = Object.fromEntries(Object.entries(block).filter(([, v]) => v !== undefined));
1256
+ if (input.placement === "timeline_block") {
1257
+ if (input.slot)
1258
+ block.slot = input.slot;
1259
+ if (input.anchor)
1260
+ block.anchor = input.anchor;
1261
+ if (input.postmortem !== undefined)
1262
+ block.postmortem = input.postmortem;
1263
+ }
1264
+ const issues = validateBlock(block);
1265
+ if (issues.length > 0)
1266
+ return { ok: false, issues };
1267
+ if (input.placement === "step_figure") {
1268
+ const bytes = new TextEncoder().encode(JSON.stringify(block)).length;
1269
+ if (bytes > MAX_STEP_FIGURE_BYTES) {
1270
+ return {
1271
+ ok: false,
1272
+ issues: [`figure: ${bytes} bytes; a step figure holds at most ${MAX_STEP_FIGURE_BYTES}. Send fewer points, runs or rows, or put it on a timeline event.`],
1273
+ };
1274
+ }
1275
+ }
1276
+ return {
1277
+ ok: true,
1278
+ type: String(block.type),
1279
+ placement: input.placement,
1280
+ block,
1281
+ summary: describe(block),
1282
+ notes,
1283
+ use: input.placement === "step_figure"
1284
+ ? "Put this object in result_summary.causal_paths[].steps[].figure. One figure per step. It needs the diagnosis structure the pickup advertises as diagnosis_structure_v1. A Tellagen older than these figure types drops a checks, range_overlap, histogram, run_history or diff figure and says so in the completion warnings (figure_invalid)."
1285
+ : "Put this object in the blocks array of tellagen_post_timeline_event or tellagen_update_timeline_event. An update replaces the whole array, so send every block you want to keep.",
1286
+ };
1287
+ }
1288
+ //# sourceMappingURL=figures.js.map