@jupiterone/jupiterone-mcp 2.1.1 → 2.3.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 (96) hide show
  1. package/README.md +18 -2
  2. package/dist/client/graphql/queries.d.ts +48 -1
  3. package/dist/client/graphql/queries.d.ts.map +1 -1
  4. package/dist/client/graphql/queries.js +329 -1
  5. package/dist/client/graphql/queries.js.map +1 -1
  6. package/dist/client/jupiterone-client.d.ts +8 -0
  7. package/dist/client/jupiterone-client.d.ts.map +1 -1
  8. package/dist/client/jupiterone-client.js +13 -0
  9. package/dist/client/jupiterone-client.js.map +1 -1
  10. package/dist/client/services/threat-service.d.ts +31 -0
  11. package/dist/client/services/threat-service.d.ts.map +1 -0
  12. package/dist/client/services/threat-service.js +72 -0
  13. package/dist/client/services/threat-service.js.map +1 -0
  14. package/dist/generated/description-map.d.ts.map +1 -1
  15. package/dist/generated/description-map.js +602 -14
  16. package/dist/generated/description-map.js.map +1 -1
  17. package/dist/server/mcp-server.d.ts.map +1 -1
  18. package/dist/server/mcp-server.js +51 -1
  19. package/dist/server/mcp-server.js.map +1 -1
  20. package/dist/server/tools/alerts.d.ts.map +1 -1
  21. package/dist/server/tools/alerts.js +2 -5
  22. package/dist/server/tools/alerts.js.map +1 -1
  23. package/dist/server/tools/dashboard-layout.d.ts +80 -3
  24. package/dist/server/tools/dashboard-layout.d.ts.map +1 -1
  25. package/dist/server/tools/dashboard-layout.js +220 -15
  26. package/dist/server/tools/dashboard-layout.js.map +1 -1
  27. package/dist/server/tools/dashboards.d.ts.map +1 -1
  28. package/dist/server/tools/dashboards.js +379 -10
  29. package/dist/server/tools/dashboards.js.map +1 -1
  30. package/dist/server/tools/errors.d.ts +61 -10
  31. package/dist/server/tools/errors.d.ts.map +1 -1
  32. package/dist/server/tools/errors.js +201 -10
  33. package/dist/server/tools/errors.js.map +1 -1
  34. package/dist/server/tools/index.d.ts.map +1 -1
  35. package/dist/server/tools/index.js +2 -0
  36. package/dist/server/tools/index.js.map +1 -1
  37. package/dist/server/tools/integrations.d.ts.map +1 -1
  38. package/dist/server/tools/integrations.js +15 -4
  39. package/dist/server/tools/integrations.js.map +1 -1
  40. package/dist/server/tools/j1ql.d.ts.map +1 -1
  41. package/dist/server/tools/j1ql.js +72 -4
  42. package/dist/server/tools/j1ql.js.map +1 -1
  43. package/dist/server/tools/rules.d.ts.map +1 -1
  44. package/dist/server/tools/rules.js +57 -6
  45. package/dist/server/tools/rules.js.map +1 -1
  46. package/dist/server/tools/telemetry.d.ts +7 -1
  47. package/dist/server/tools/telemetry.d.ts.map +1 -1
  48. package/dist/server/tools/telemetry.js.map +1 -1
  49. package/dist/server/tools/threat.d.ts +3 -0
  50. package/dist/server/tools/threat.d.ts.map +1 -0
  51. package/dist/server/tools/threat.js +284 -0
  52. package/dist/server/tools/threat.js.map +1 -0
  53. package/dist/server/tools/types.d.ts +5 -0
  54. package/dist/server/tools/types.d.ts.map +1 -1
  55. package/dist/server/tools/types.js +7 -1
  56. package/dist/server/tools/types.js.map +1 -1
  57. package/dist/server/tools/usage.d.ts +13 -3
  58. package/dist/server/tools/usage.d.ts.map +1 -1
  59. package/dist/server/tools/usage.js +186 -7
  60. package/dist/server/tools/usage.js.map +1 -1
  61. package/dist/server/tools/value-probe.d.ts +85 -0
  62. package/dist/server/tools/value-probe.d.ts.map +1 -0
  63. package/dist/server/tools/value-probe.js +473 -0
  64. package/dist/server/tools/value-probe.js.map +1 -0
  65. package/dist/server/tools/widget-config-lint.d.ts +39 -0
  66. package/dist/server/tools/widget-config-lint.d.ts.map +1 -0
  67. package/dist/server/tools/widget-config-lint.js +290 -0
  68. package/dist/server/tools/widget-config-lint.js.map +1 -0
  69. package/dist/server/tools/widget-preflight.d.ts +63 -0
  70. package/dist/server/tools/widget-preflight.d.ts.map +1 -0
  71. package/dist/server/tools/widget-preflight.js +238 -0
  72. package/dist/server/tools/widget-preflight.js.map +1 -0
  73. package/dist/server/tools/widget-render-contract.d.ts +134 -0
  74. package/dist/server/tools/widget-render-contract.d.ts.map +1 -0
  75. package/dist/server/tools/widget-render-contract.js +421 -0
  76. package/dist/server/tools/widget-render-contract.js.map +1 -0
  77. package/dist/server/tools/widget-settings-keys.d.ts +51 -0
  78. package/dist/server/tools/widget-settings-keys.d.ts.map +1 -0
  79. package/dist/server/tools/widget-settings-keys.js +152 -0
  80. package/dist/server/tools/widget-settings-keys.js.map +1 -0
  81. package/dist/types/jupiterone.d.ts +139 -0
  82. package/dist/types/jupiterone.d.ts.map +1 -1
  83. package/dist/utils/j1ql-filters.d.ts +48 -0
  84. package/dist/utils/j1ql-filters.d.ts.map +1 -0
  85. package/dist/utils/j1ql-filters.js +184 -0
  86. package/dist/utils/j1ql-filters.js.map +1 -0
  87. package/dist/utils/j1ql-validator.d.ts +0 -5
  88. package/dist/utils/j1ql-validator.d.ts.map +1 -1
  89. package/dist/utils/j1ql-validator.js +27 -6
  90. package/dist/utils/j1ql-validator.js.map +1 -1
  91. package/node_modules/dtrace-provider/build/Makefile +1 -1
  92. package/package.json +1 -1
  93. package/dist/utils/description-loader.d.ts +0 -2
  94. package/dist/utils/description-loader.d.ts.map +0 -1
  95. package/dist/utils/description-loader.js +0 -17
  96. package/dist/utils/description-loader.js.map +0 -1
@@ -0,0 +1,39 @@
1
+ import type { JupiterOneClient } from '../../client/jupiterone-client.js';
2
+ import type { Query } from '../../types/jupiterone.js';
3
+ import type { ToolResult } from './types.js';
4
+ /**
5
+ * Static checks against documented product behaviour, run before a widget is written.
6
+ *
7
+ * A different certainty class from the value diagnosis: these are facts about what JupiterOne
8
+ * Insights supports, stable on product-release timescales, not point-in-time facts about an
9
+ * account's data. That is why one of them blocks and the others inform.
10
+ */
11
+ export interface WidgetConfigFinding {
12
+ code: 'managed-board' | 'markdown-without-text' | 'percentage-line-without-x' | 'percentage-numerator-unmatched' | 'percentage-total-empty' | 'percentage-without-total' | 'trend-with-parameters' | 'trend-has-no-history' | 'unsupported-chart-type';
13
+ blocking: boolean;
14
+ message: string;
15
+ }
16
+ /**
17
+ * Check a widget's configuration against documented product behaviour.
18
+ *
19
+ * Returns findings in severity order — every blocking finding precedes the advisory ones, so the
20
+ * rejection's `lintCode` names the first real reason. A finding blocks only where the widget is
21
+ * verified to draw nothing (`managed-board`, `markdown-without-text`, `unsupported-chart-type`) or
22
+ * to draw a number that is provably not the one asked for (`percentage-numerator-unmatched`).
23
+ */
24
+ export declare function lintWidgetConfig(client: JupiterOneClient, dashboardId: string, input: {
25
+ type?: string;
26
+ config?: {
27
+ queries?: Query[];
28
+ settings?: unknown;
29
+ };
30
+ } | undefined, operation: 'create' | 'update'): Promise<WidgetConfigFinding[]>;
31
+ /**
32
+ * The rejection an agent receives for a blocking configuration finding.
33
+ *
34
+ * Carries `lintCode` so the telemetry chokepoint can count blocks by cause rather than
35
+ * string-matching the message, the same way the render-contract gate carries `contractOk`. Error
36
+ * results are exempt from output-schema validation, so it never reaches a client validator.
37
+ */
38
+ export declare function widgetConfigErrorResponse(operation: 'create' | 'update', findings: WidgetConfigFinding[]): ToolResult;
39
+ //# sourceMappingURL=widget-config-lint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"widget-config-lint.d.ts","sourceRoot":"","sources":["../../../src/server/tools/widget-config-lint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAG7C;;;;;;GAMG;AACH,MAAM,WAAW,mBAAmB;IAClC,IAAI,EACA,eAAe,GACf,uBAAuB,GACvB,2BAA2B,GAC3B,gCAAgC,GAChC,wBAAwB,GACxB,0BAA0B,GAC1B,uBAAuB,GACvB,sBAAsB,GACtB,wBAAwB,CAAC;IAC7B,QAAQ,EAAE,OAAO,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;CACjB;AA8PD;;;;;;;GAOG;AACH,wBAAsB,gBAAgB,CACpC,MAAM,EAAE,gBAAgB,EACxB,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE,CAAA;CAAE,GAAG,SAAS,EACxF,SAAS,EAAE,QAAQ,GAAG,QAAQ,GAC7B,OAAO,CAAC,mBAAmB,EAAE,CAAC,CAmDhC;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,SAAS,EAAE,QAAQ,GAAG,QAAQ,EAC9B,QAAQ,EAAE,mBAAmB,EAAE,GAC9B,UAAU,CAQZ"}
@@ -0,0 +1,290 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lintWidgetConfig = lintWidgetConfig;
4
+ exports.widgetConfigErrorResponse = widgetConfigErrorResponse;
5
+ const widget_render_contract_js_1 = require("./widget-render-contract.js");
6
+ /** Dashboards the agent creates get a UUID; JupiterOne's managed boards carry slug ids. */
7
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
+ function trendEnabled(settings) {
9
+ if (!settings || typeof settings !== 'object')
10
+ return false;
11
+ return Object.values(settings).some((perChart) => perChart?.trendDataIsEnabled === true);
12
+ }
13
+ /** Chart types whose settings carry the percentage-calculation keys. */
14
+ const PERCENTAGE_CHART_TYPES = ['number', 'line'];
15
+ /**
16
+ * The percentage block this widget's renderer will actually read, when percentage mode is on.
17
+ *
18
+ * Keyed on the widget's own chart type, not scanned across all of them: the renderer reads
19
+ * `settings[type]`, so `settings.number.showAsPercentage` on a `bar` widget is dead configuration
20
+ * and blocking a legitimate bar chart over it would be a lint causing the failure it exists to stop.
21
+ */
22
+ function percentageSettings(chartType, settings) {
23
+ if (!chartType || !PERCENTAGE_CHART_TYPES.includes(chartType))
24
+ return null;
25
+ if (!settings || typeof settings !== 'object')
26
+ return null;
27
+ const perChart = settings[chartType];
28
+ if (!perChart || typeof perChart !== 'object')
29
+ return null;
30
+ const percentage = perChart;
31
+ return percentage.showAsPercentage === true ? percentage : null;
32
+ }
33
+ /** SEVERAL numerator queries are comma-joined into the single `numeratorQueryName` string. */
34
+ function numeratorNames(value) {
35
+ if (typeof value !== 'string')
36
+ return [];
37
+ return value
38
+ .split(',')
39
+ .map((name) => name.trim())
40
+ .filter((name) => name !== '');
41
+ }
42
+ /**
43
+ * Every query on the widget is a numerator, so there is nothing left to divide by.
44
+ *
45
+ * Advisory, not blocking: what the renderer does with a zero denominator was never measured, and
46
+ * the two neighbouring cases behave differently enough (a missing numerator draws a flat 0%) that
47
+ * guessing this one would be asserting a measurement nobody took.
48
+ */
49
+ function totalEmptyFinding(numerators) {
50
+ return {
51
+ code: 'percentage-total-empty',
52
+ blocking: false,
53
+ message: 'This widget shows a percentage and `numeratorQueryName` names every query on it ' +
54
+ `(${numerators.map((name) => `\`${name}\``).join(', ')}), so the total it divides by is ` +
55
+ 'empty. The figure is the sum of the named queries divided by the sum of the ones it does ' +
56
+ 'not name. Either leave the query that counts the population out of `numeratorQueryName`, ' +
57
+ 'or set `includeNumeratorInTotal: true` to divide by all of them together.',
58
+ };
59
+ }
60
+ /**
61
+ * Percentage mode on a LINE chart correlates its queries positionally.
62
+ *
63
+ * The renderer buckets rows by the `x` column and plots only the positions present in EVERY query,
64
+ * so a query with no `x` has no position to contribute and drops out of the ratio silently. `x` is
65
+ * merely recommended for a plain line chart, which is why this is a percentage-mode finding rather
66
+ * than a contract requirement — and advisory, because the shape still renders, just not over the
67
+ * whole series. Fails open on a query the reader cannot judge.
68
+ */
69
+ function linePercentageFindings(queries) {
70
+ const missing = queries.filter((queryObj) => {
71
+ if (!queryObj?.query)
72
+ return false;
73
+ const check = (0, widget_render_contract_js_1.checkWidgetContract)('line', queryObj.query);
74
+ if (check.skipped)
75
+ return false;
76
+ return !check.aliases.some((alias) => alias?.toLowerCase() === 'x');
77
+ });
78
+ if (missing.length === 0)
79
+ return [];
80
+ return [
81
+ {
82
+ code: 'percentage-line-without-x',
83
+ blocking: false,
84
+ message: 'This line chart shows a percentage, and ' +
85
+ `${missing.map((queryObj) => `\`${queryObj.name || 'unnamed'}\``).join(', ')} ` +
86
+ `${missing.length > 1 ? 'return' : 'returns'} no \`x\` column. A percentage line chart ` +
87
+ 'buckets its rows by `x` and plots only the positions present in every query, so a query ' +
88
+ 'without one contributes nothing to the ratio at any point on the line. Alias the shared ' +
89
+ 'axis value — the date or the category both queries share — as `x` in every query.',
90
+ },
91
+ ];
92
+ }
93
+ /**
94
+ * What percentage mode needs that this widget does not have.
95
+ *
96
+ * A percentage widget is a ratio between its queries: the numerator is the SUM of the queries named
97
+ * in `numeratorQueryName`, the total is the sum of the others — or of all of them under
98
+ * `includeNumeratorInTotal`. Every failure below produces a number that renders, which is why they
99
+ * are worth a finding at all: a numerator summing nothing draws a flat 0%, and every row count and
100
+ * every column check calls that widget healthy.
101
+ *
102
+ * A name matching no query BLOCKS: the ratio is provably wrong and the fix is a spelling. An empty
103
+ * `numeratorQueryName`, too few queries to divide, an empty total, and a percentage line chart
104
+ * missing its shared axis are advisory — nothing is *named* wrong, and a caller mid-build may know
105
+ * something this does not.
106
+ */
107
+ function percentageFindings(input) {
108
+ const percentage = percentageSettings(input?.type, input?.config?.settings);
109
+ if (!percentage)
110
+ return [];
111
+ const queries = input?.config?.queries ?? [];
112
+ const queryNames = queries
113
+ .map((queryObj) => queryObj?.name)
114
+ .filter((name) => typeof name === 'string' && name !== '');
115
+ const numerators = numeratorNames(percentage.numeratorQueryName);
116
+ const unmatched = numerators.filter((name) => !queryNames.includes(name));
117
+ if (unmatched.length > 0) {
118
+ return [
119
+ {
120
+ code: 'percentage-numerator-unmatched',
121
+ blocking: true,
122
+ message: `This widget shows a percentage and \`numeratorQueryName\` names ` +
123
+ `${unmatched.map((name) => `\`${name}\``).join(', ')}, which no query on it is called. ` +
124
+ `Its queries are named ${queryNames.map((name) => `\`${name}\``).join(', ') || '(none)'}. ` +
125
+ 'The numerator is the sum of the queries it names, so an unmatched name sums to nothing ' +
126
+ 'and the widget renders a flat 0% that every row count reports as healthy. Match the ' +
127
+ 'name exactly — several numerator queries are comma-joined into that one string.',
128
+ },
129
+ ];
130
+ }
131
+ if (numerators.length === 0 || queries.length < 2) {
132
+ const shortfall = numerators.length === 0
133
+ ? 'names no numerator query'
134
+ : `carries ${queries.length === 1 ? 'only one query' : 'no queries'}`;
135
+ return [
136
+ {
137
+ code: 'percentage-without-total',
138
+ blocking: false,
139
+ message: `This widget shows a percentage but ${shortfall}. The figure is the sum of the queries ` +
140
+ 'named in `numeratorQueryName` divided by the sum of the others — or by all of them, ' +
141
+ 'with `includeNumeratorInTotal` — so it needs a named numerator and something to divide ' +
142
+ 'by. As configured the ratio is the query against itself, or against nothing. Add the ' +
143
+ 'query that counts the population, or drop `showAsPercentage` and show the count.',
144
+ },
145
+ ];
146
+ }
147
+ const findings = [];
148
+ const everyQueryNamed = queries.every((queryObj) => typeof queryObj?.name === 'string' && numerators.includes(queryObj.name));
149
+ if (everyQueryNamed && percentage.includeNumeratorInTotal !== true) {
150
+ findings.push(totalEmptyFinding(numerators));
151
+ }
152
+ if (input?.type === 'line')
153
+ findings.push(...linePercentageFindings(queries));
154
+ return findings;
155
+ }
156
+ /**
157
+ * `area` is not a supported Insights widget type, on either operation.
158
+ *
159
+ * JupiterOne's documentation lists Number, Pie, Line, Bar, Matrix, Table, Graph and Status and says
160
+ * "Area Chart is coming soon" (Questions only); no rendering `area` widget exists anywhere in
161
+ * j1dev. The API accepts one and it draws nothing — the same verified-product-behaviour class as
162
+ * the managed-board block, so it blocks the same way.
163
+ *
164
+ * This is the counterpart to the render contract's deliberately empty `area` row: no column
165
+ * arrangement makes an area widget draw, so the gate must not reject it for a missing column, which
166
+ * would name a reason that is not the real one. This finding names the real one.
167
+ */
168
+ function unsupportedChartTypeFinding() {
169
+ return {
170
+ code: 'unsupported-chart-type',
171
+ blocking: true,
172
+ message: "`area` is not a supported Insights widget type. JupiterOne's documentation lists Number, " +
173
+ 'Pie, Line, Bar, Matrix, Table, Graph and Status, and says "Area Chart is coming soon" — an ' +
174
+ 'area trend comes from a Question today. The API accepts the write and the widget renders ' +
175
+ 'nothing, so no query or column arrangement will fix it: use `bar` or `line` instead.',
176
+ };
177
+ }
178
+ /**
179
+ * Whether the target is a JupiterOne-managed board, which silently discards added widgets.
180
+ *
181
+ * Verified on j1dev 2026-08-19: adding a widget to `aws-s3-security` returned a success envelope
182
+ * with a widget id, and the widget was absent from the board immediately afterwards. The docs say
183
+ * managed dashboards do not support additional widgets; the API does not enforce it, so an agent
184
+ * gets "created" back and reports a dashboard that does not exist.
185
+ *
186
+ * The lookup is skipped entirely for UUID ids, which is every board the agent just created — so the
187
+ * common path costs nothing and only the rarer "add to an existing named board" pays a round-trip.
188
+ */
189
+ async function isManagedBoard(client, dashboardId) {
190
+ if (UUID.test(dashboardId))
191
+ return false;
192
+ try {
193
+ const dashboards = await client.getDashboards();
194
+ return dashboards.some((dashboard) => dashboard.id === dashboardId && dashboard.isJ1ManagedBoard === true);
195
+ }
196
+ catch {
197
+ // A lint must never be the reason a legitimate write fails.
198
+ return false;
199
+ }
200
+ }
201
+ /**
202
+ * What a managed board means for the write being attempted.
203
+ *
204
+ * The measurement is of an add: it succeeded and the widget was gone. Whether replacing a widget
205
+ * already on such a board persists was never tested, so the update wording rests on who owns the
206
+ * board rather than claiming a second measurement.
207
+ */
208
+ function managedBoardFinding(dashboardId, operation) {
209
+ const board = `\`${dashboardId}\` is a JupiterOne-managed dashboard`;
210
+ return {
211
+ code: 'managed-board',
212
+ blocking: true,
213
+ message: operation === 'update'
214
+ ? `${board}. Adding a widget to one returns success and the widget is then silently ` +
215
+ 'discarded, and JupiterOne owns what these boards show, so an edit to a widget already ' +
216
+ 'on it cannot be relied on to last either. Duplicate the board and edit your copy.'
217
+ : `${board}, which does not accept added widgets. The API returns success and the widget ` +
218
+ 'is silently discarded, so nothing would appear on the board. Create your own dashboard ' +
219
+ 'with `create-dashboard` and add widgets there, or duplicate the managed board first.',
220
+ };
221
+ }
222
+ /**
223
+ * Check a widget's configuration against documented product behaviour.
224
+ *
225
+ * Returns findings in severity order — every blocking finding precedes the advisory ones, so the
226
+ * rejection's `lintCode` names the first real reason. A finding blocks only where the widget is
227
+ * verified to draw nothing (`managed-board`, `markdown-without-text`, `unsupported-chart-type`) or
228
+ * to draw a number that is provably not the one asked for (`percentage-numerator-unmatched`).
229
+ */
230
+ async function lintWidgetConfig(client, dashboardId, input, operation) {
231
+ const findings = [];
232
+ if (input?.type === 'area')
233
+ findings.push(unsupportedChartTypeFinding());
234
+ // A markdown widget draws exactly one thing: its text. Without it there is nothing to render and
235
+ // no query to blame, so it is a blank tile that every other check passes over — the widget has no
236
+ // query, so the preflight skips it, and no columns, so the contract does not apply.
237
+ if (input?.type === 'markdown') {
238
+ const settings = input.config?.settings;
239
+ const text = settings?.markdown?.text;
240
+ if (typeof text !== 'string' || text.trim() === '') {
241
+ findings.push({
242
+ code: 'markdown-without-text',
243
+ blocking: true,
244
+ message: 'A markdown widget renders its text and nothing else, so this one would be a blank ' +
245
+ 'tile. Put the body in `config.settings.markdown.text` — note it is nested under the ' +
246
+ 'chart type, like every other widget setting.',
247
+ });
248
+ }
249
+ }
250
+ if (await isManagedBoard(client, dashboardId)) {
251
+ findings.push(managedBoardFinding(dashboardId, operation));
252
+ }
253
+ findings.push(...percentageFindings(input));
254
+ if (trendEnabled(input?.config?.settings)) {
255
+ const queries = input?.config?.queries ?? [];
256
+ if (queries.some((queryObj) => queryObj?.query?.includes('{{'))) {
257
+ findings.push({
258
+ code: 'trend-with-parameters',
259
+ blocking: false,
260
+ message: 'This widget enables trend collection and its query uses a `{{parameter}}`. Query ' +
261
+ 'variables are not supported in trend widgets, so the trend will not collect. Either ' +
262
+ 'drop `trendDataIsEnabled` or replace the parameter with a literal.',
263
+ });
264
+ }
265
+ findings.push({
266
+ code: 'trend-has-no-history',
267
+ blocking: false,
268
+ message: 'Trend widgets collect once a day, so this one renders little or nothing until it has ' +
269
+ 'accumulated points. That is expected, not a fault — say so rather than rebuilding it.',
270
+ });
271
+ }
272
+ return findings;
273
+ }
274
+ /**
275
+ * The rejection an agent receives for a blocking configuration finding.
276
+ *
277
+ * Carries `lintCode` so the telemetry chokepoint can count blocks by cause rather than
278
+ * string-matching the message, the same way the render-contract gate carries `contractOk`. Error
279
+ * results are exempt from output-schema validation, so it never reaches a client validator.
280
+ */
281
+ function widgetConfigErrorResponse(operation, findings) {
282
+ const outcome = operation === 'update' ? 'Widget not updated' : 'Widget not created';
283
+ const text = `${outcome} — ${findings.map((finding) => finding.message).join('\n\n')}`;
284
+ return {
285
+ content: [{ type: 'text', text }],
286
+ isError: true,
287
+ structuredContent: { lintCode: findings[0].code },
288
+ };
289
+ }
290
+ //# sourceMappingURL=widget-config-lint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"widget-config-lint.js","sourceRoot":"","sources":["../../../src/server/tools/widget-config-lint.ts"],"names":[],"mappings":";;AA+RA,4CAwDC;AASD,8DAWC;AAxWD,2EAAkE;AAwBlE,2FAA2F;AAC3F,MAAM,IAAI,GAAG,iEAAiE,CAAC;AAM/E,SAAS,YAAY,CAAC,QAAiB;IACrC,IAAI,CAAC,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,QAA0B,CAAC,CAAC,IAAI,CACnD,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,EAAE,kBAAkB,KAAK,IAAI,CACpD,CAAC;AACJ,CAAC;AAED,wEAAwE;AACxE,MAAM,sBAAsB,GAAsB,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAQrE;;;;;;GAMG;AACH,SAAS,kBAAk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AE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QACjC,OAAO,EAAE,IAAI;QACb,iBAAiB,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE;KAClD,CAAC;AACJ,CAAC"}
@@ -0,0 +1,63 @@
1
+ import type { JupiterOneClient } from '../../client/jupiterone-client.js';
2
+ import type { Query } from '../../types/jupiterone.js';
3
+ import { type LiteralDiagnosis } from './value-probe.js';
4
+ /**
5
+ * What a widget will actually draw, reported alongside the created widget.
6
+ *
7
+ * A widget whose query returns no rows is created successfully and renders blank, with no error
8
+ * anywhere in the flow (TD-9016). The column contract is checked before creation and blocks; row
9
+ * emptiness cannot block, because an empty widget is often the right answer — "critical findings:
10
+ * 0" is good news. So the server reports the fact and the agent judges the intent.
11
+ */
12
+ export interface WidgetRenderPreflight {
13
+ /**
14
+ * `probed` means the queries were run and what follows is measured. It is NOT a certificate that
15
+ * the widget is correct — nothing here inspects the renderer, and the data can change under a
16
+ * correct widget. `skipped` means no query ran, and `reason` says why.
17
+ */
18
+ status: 'probed' | 'skipped';
19
+ /** Why no query was run, when `status` is `skipped`. */
20
+ reason?: string;
21
+ /** Rows returned across the widget's queries. Null when skipped. */
22
+ rowsReturned: number | null;
23
+ /**
24
+ * Wall-clock time this preflight took, including the value diagnosis.
25
+ *
26
+ * The telemetry event's `durationMs` covers the whole tool call, so since the preflight landed it
27
+ * silently includes up to PREFLIGHT_WITH_DIAGNOSIS_BUDGET_MS of advisory work — the write path
28
+ * looks slower with no way to say how much of that is the write. Reported on skipped outcomes
29
+ * too: a skip is not free, and one that took ten seconds before giving up is worth seeing.
30
+ */
31
+ preflightMs: number;
32
+ /** True when the widget will draw nothing as configured. */
33
+ willRenderEmpty: boolean;
34
+ /**
35
+ * Required columns that are absent or null in every row returned.
36
+ *
37
+ * A query can return rows and still draw nothing: `RETURN avg(e.nonexistent) AS value` yields one
38
+ * row with no keys at all, so a row count alone reports the widget as fine. This is the column
39
+ * the chart actually reads coming back empty.
40
+ */
41
+ emptyColumns?: string[];
42
+ /** Columns the chart type uses when present — absent here, so the chart renders degraded. */
43
+ missingRecommended?: string[];
44
+ /**
45
+ * What the query's string literals turned out to mean against this account's data.
46
+ *
47
+ * Row counts alone cannot tell a correct widget from a confidently wrong one: a filter on one
48
+ * casing of a value that is stored in three returns a plausible number and silently omits the
49
+ * rest. Present only when a literal has something to say.
50
+ */
51
+ diagnosis?: LiteralDiagnosis[];
52
+ /** One sentence for the caller to act on or relay. */
53
+ note?: string;
54
+ }
55
+ /**
56
+ * Run a widget's queries and report what it will draw.
57
+ *
58
+ * Fails open on every error, including a timeout: this runs after the widget has already been
59
+ * created, so advisory work must never turn a successful create into a failure. A skipped preflight
60
+ * says so rather than claiming the widget is fine.
61
+ */
62
+ export declare function runRenderPreflight(client: JupiterOneClient, chartType: string | undefined, queries: Query[] | undefined, noResultMessage: string | undefined): Promise<WidgetRenderPreflight>;
63
+ //# sourceMappingURL=widget-preflight.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"widget-preflight.d.ts","sourceRoot":"","sources":["../../../src/server/tools/widget-preflight.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAC;AAOvD,OAAO,EAIL,KAAK,gBAAgB,EACtB,MAAM,kBAAkB,CAAC;AAwB1B;;;;;;;GAOG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC7B,wDAAwD;IACxD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oEAAoE;IACpE,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B;;;;;;;OAOG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB,4DAA4D;IAC5D,eAAe,EAAE,OAAO,CAAC;IACzB;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,6FAA6F;IAC7F,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9B;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,gBAAgB,EAAE,CAAC;IAC/B,sDAAsD;IACtD,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAuID;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,gBAAgB,EACxB,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,OAAO,EAAE,KAAK,EAAE,GAAG,SAAS,EAC5B,eAAe,EAAE,MAAM,GAAG,SAAS,GAClC,OAAO,CAAC,qBAAqB,CAAC,CA6GhC"}
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runRenderPreflight = runRenderPreflight;
4
+ const widget_render_contract_js_1 = require("./widget-render-contract.js");
5
+ const value_probe_js_1 = require("./value-probe.js");
6
+ /**
7
+ * Poll budget for a preflight query, in attempts × 1s. Deliberately far below the executor's
8
+ * `DEFAULT_MAX_POLL_ATTEMPTS` (45, sized against the remote's 55s request deadline): this is
9
+ * advisory work running after the widget already exists, so it gets a small slice and gives up.
10
+ */
11
+ const PREFLIGHT_POLL_ATTEMPTS = 8;
12
+ /**
13
+ * Wall-clock ceiling for the whole preflight, across every query on the widget.
14
+ *
15
+ * The per-query poll budget alone is not a bound: a `status` widget legitimately carries six
16
+ * queries, and running them sequentially at 8s each would spend ~48s of advisory work AFTER the
17
+ * widget already exists — past the remote's ~55s request deadline. The widget survives that, but
18
+ * the HTTP response does not, so the agent sees a failure for a successful create and retries,
19
+ * producing a duplicate. Advisory work must never be able to manufacture the rework this feature
20
+ * exists to reduce.
21
+ */
22
+ const PREFLIGHT_TOTAL_BUDGET_MS = 15_000;
23
+ /** Ceiling for the whole preflight including the value diagnosis, inside the remote's ~55s deadline. */
24
+ const PREFLIGHT_WITH_DIAGNOSIS_BUDGET_MS = 25_000;
25
+ /**
26
+ * Rows in a completed J1QL envelope, or null when the envelope carries no `data` at all.
27
+ *
28
+ * `RETURN TREE` yields an object rather than an array, and its emptiness is countable: a tree
29
+ * envelope holding no vertices is a graph widget that draws nothing, which counting the envelope
30
+ * itself as one row reported as healthy — the graph is usually the widget on screen when someone is
31
+ * being shown the product. Any other non-array payload is still one row: it is a shape this has not
32
+ * seen, and calling it empty would assert something the preflight never observed. A missing payload
33
+ * is unknown, not zero, for the same reason.
34
+ */
35
+ function rowCount(result) {
36
+ const envelope = result;
37
+ if (!envelope || !('data' in envelope) || envelope.data === null || envelope.data === undefined) {
38
+ return null;
39
+ }
40
+ if (Array.isArray(envelope.data))
41
+ return envelope.data.length;
42
+ const vertices = envelope.data.vertices;
43
+ return Array.isArray(vertices) ? vertices.length : 1;
44
+ }
45
+ /**
46
+ * Required columns the chart reads that are absent or null in every row.
47
+ *
48
+ * Checked against the rows already in hand, so it costs nothing. A query can return rows and still
49
+ * draw nothing: `RETURN avg(e.nonexistent) AS value` yields one row with no keys at all, so a row
50
+ * count alone reports the widget as fine. Only meaningful where a contract exists — an exempt chart
51
+ * type renders whatever it is given.
52
+ */
53
+ function emptyRequiredColumns(chartType, rows) {
54
+ const required = widget_render_contract_js_1.WIDGET_COLUMN_CONTRACT[chartType]?.required ?? [];
55
+ if (required.length === 0 || rows.length === 0)
56
+ return [];
57
+ return required.filter((column) => rows.every((row) => {
58
+ const value = row?.[column];
59
+ return value === undefined || value === null;
60
+ }));
61
+ }
62
+ /**
63
+ * Whether the widget draws a zero rather than nothing.
64
+ *
65
+ * `count(e)` over an empty set returns one row holding `0`, so the widget is not blank — it shows a
66
+ * confident, permanent zero, which every row count reports as healthy. That is the shape worth
67
+ * explaining, so it triggers the same diagnosis an empty result does.
68
+ */
69
+ function rendersOnlyZero(chartType, rows) {
70
+ const required = widget_render_contract_js_1.WIDGET_COLUMN_CONTRACT[chartType]?.required ?? [];
71
+ const measures = required.filter((column) => column === 'value' || column === 'y');
72
+ if (measures.length === 0 || rows.length === 0)
73
+ return false;
74
+ return rows.every((row) => measures.every((column) => row?.[column] === 0));
75
+ }
76
+ /** The result rows, when the envelope carries an array of them. */
77
+ function resultRows(result) {
78
+ const data = result?.data;
79
+ return Array.isArray(data) ? data : [];
80
+ }
81
+ function buildNote(rowsReturned, noResultMessage, missingRecommended, diagnosis, emptyColumns) {
82
+ const notes = [];
83
+ // Lead with the diagnosis: a widget that renders a wrong number needs saying before anything else.
84
+ const partial = diagnosis.find((entry) => entry.verdict === 'partial-case-match');
85
+ if (partial) {
86
+ notes.push(`This widget renders a PARTIAL count — ${partial.field} is stored in more than one casing, ` +
87
+ `and the filter matches only one of them. See diagnosis[0]`);
88
+ }
89
+ if (rowsReturned === 0) {
90
+ // Deliberately does NOT tell the caller to change anything. "No critical findings" and "no
91
+ // public buckets" are the answers a security dashboard exists to give, and a widget that reads
92
+ // zero because the estate is clean is working. Only the caller knows which this is.
93
+ notes.push('This widget will draw nothing right now — its query returned no rows. That may be exactly ' +
94
+ 'right: an empty result is a real answer on a posture or compliance board. Keep it if zero ' +
95
+ 'is what you mean to show; change the query only if you expected data');
96
+ }
97
+ else if (emptyColumns.length > 0) {
98
+ notes.push(`This widget will render empty despite returning ${rowsReturned} row(s): the column(s) it ` +
99
+ `reads (${emptyColumns.map((column) => `\`${column}\``).join(', ')}) are absent or null ` +
100
+ 'in every row — usually a property name that does not exist on this entity type');
101
+ }
102
+ // Not conditional on the row count: data that exists today can empty out next month, and the
103
+ // widget is blank either way. The nudge is cheap and the omission is invisible until it matters.
104
+ if (!noResultMessage) {
105
+ notes.push('set `noResultMessage` so this widget explains itself instead of showing blank when its ' +
106
+ 'query returns nothing — that is what makes a legitimately-empty widget readable');
107
+ }
108
+ const split = diagnosis.find((entry) => entry.verdict === 'split-categories');
109
+ if (split) {
110
+ notes.push(`This chart will render more categories than exist — ${split.note}`);
111
+ }
112
+ const missingTarget = diagnosis.find((entry) => entry.verdict === 'target-empty');
113
+ if (missingTarget) {
114
+ notes.push(`this widget shows a zero that cannot change — ${missingTarget.note}`);
115
+ }
116
+ const dead = diagnosis.find((entry) => entry.verdict === 'case-mismatch' || entry.verdict === 'type-mismatch');
117
+ if (dead) {
118
+ notes.push(`the filter itself is the reason — ${dead.note}`);
119
+ }
120
+ const exonerated = diagnosis.find((entry) => entry.verdict === 'value-not-found');
121
+ if (exonerated) {
122
+ notes.push('the filter was verified correct, so this is a true zero rather than a mistake');
123
+ }
124
+ if (missingRecommended.length > 0) {
125
+ notes.push(`the chart also reads ${missingRecommended
126
+ .map((column) => `\`${column}\``)
127
+ .join(', ')}, which this query does not return`);
128
+ }
129
+ // Clauses are joined into one sentence, so any that already ends in a full stop would double it.
130
+ const joined = notes.map((note) => note.replace(/\.$/, '')).join('; ');
131
+ return joined.length > 0 ? `${joined}.` : undefined;
132
+ }
133
+ /**
134
+ * Run a widget's queries and report what it will draw.
135
+ *
136
+ * Fails open on every error, including a timeout: this runs after the widget has already been
137
+ * created, so advisory work must never turn a successful create into a failure. A skipped preflight
138
+ * says so rather than claiming the widget is fine.
139
+ */
140
+ async function runRenderPreflight(client, chartType, queries, noResultMessage) {
141
+ const startedAt = Date.now();
142
+ const skip = (reason) => ({
143
+ status: 'skipped',
144
+ reason,
145
+ rowsReturned: null,
146
+ willRenderEmpty: false,
147
+ preflightMs: Date.now() - startedAt,
148
+ });
149
+ const runnable = (queries ?? []).filter((queryObj) => queryObj?.query);
150
+ if (runnable.length === 0)
151
+ return skip('no-queries');
152
+ // Substituted at render time from the dashboard's parameters, so the stored form proves nothing.
153
+ if (runnable.some((queryObj) => queryObj.query.includes('{{')))
154
+ return skip('parameterized');
155
+ // Rows are SUMMED, not minimised. A multi-query widget draws one series per query, so it renders
156
+ // as long as any query returns something — several live j1dev boards pair a populated series with
157
+ // an empty one deliberately. Taking the minimum called those widgets blank.
158
+ let rowsReturned = 0;
159
+ const allRows = [];
160
+ try {
161
+ for (const [index, queryObj] of runnable.entries()) {
162
+ const elapsed = Date.now() - startedAt;
163
+ if (elapsed >= PREFLIGHT_TOTAL_BUDGET_MS)
164
+ return skip('budget-exhausted');
165
+ // Give the remaining budget to this query rather than a fresh full allowance each time.
166
+ const remainingAttempts = Math.max(1, Math.min(PREFLIGHT_POLL_ATTEMPTS, Math.ceil((PREFLIGHT_TOTAL_BUDGET_MS - elapsed) / 1000 / (runnable.length - index))));
167
+ const result = await client.executeJ1qlQuery({
168
+ query: queryObj.query,
169
+ maxPollAttempts: remainingAttempts,
170
+ });
171
+ const rows = rowCount(result);
172
+ if (rows === null)
173
+ return skip('no-result-payload');
174
+ allRows.push(...resultRows(result));
175
+ rowsReturned += rows;
176
+ }
177
+ }
178
+ catch (error) {
179
+ return skip(error instanceof Error ? error.constructor.name : 'unknown-error');
180
+ }
181
+ // Only advise on a single-query widget. Multi-query charts label their series by query name
182
+ // (`mapColorsByQuery`), so a missing `name`/`label` column is correct there, and saying otherwise
183
+ // is a false advisory against widgets that render.
184
+ const missingRecommended = chartType && runnable.length === 1
185
+ ? (0, widget_render_contract_js_1.checkWidgetContract)(chartType, runnable[0].query).missingRecommended
186
+ : [];
187
+ // Diagnose the literals regardless of the row count: the failure this catches is a widget that
188
+ // renders a confident, wrong number, which no row count can distinguish from a correct one.
189
+ const diagnosisDeadline = startedAt + PREFLIGHT_WITH_DIAGNOSIS_BUDGET_MS;
190
+ const diagnosis = [];
191
+ const drawsZero = rendersOnlyZero(chartType, allRows);
192
+ for (const queryObj of runnable) {
193
+ if (Date.now() > diagnosisDeadline)
194
+ break;
195
+ diagnosis.push(...(await (0, value_probe_js_1.diagnoseQueryLiterals)(client, queryObj.query, {
196
+ queryName: queryObj.name,
197
+ deadlineAt: diagnosisDeadline,
198
+ })));
199
+ // A zero measure and no literal to blame means the target itself may hold nothing.
200
+ if ((rowsReturned === 0 || drawsZero) && diagnosis.length === 0) {
201
+ diagnosis.push(...(await (0, value_probe_js_1.diagnoseEmptyTargets)(client, queryObj.query, { deadlineAt: diagnosisDeadline })));
202
+ }
203
+ }
204
+ // Single-query widgets only, the same guard the column advisory above uses: a multi-query chart
205
+ // labels its series by query name (`mapColorsByQuery`) and the renderer reads no category column
206
+ // at all, so a `name`-aliased column on a multi-query pie is not a split — diagnosing one there
207
+ // reports a category division the chart never draws.
208
+ //
209
+ // Judged on the rows this widget actually returned, so a query whose filters happen to select a
210
+ // consistently-stored subset is never accused of a split it does not have. Costs no extra probe.
211
+ // The category column is whatever the query aliased it, not what the chart type recommends: the
212
+ // live pie that split into eighteen casing slices aliased it `severity`, and grouping the rows on
213
+ // `name` found nothing to judge.
214
+ const source = chartType && runnable.length === 1
215
+ ? (0, widget_render_contract_js_1.categorySource)(chartType, runnable[0].query, { queryCount: 1 })
216
+ : null;
217
+ if (source) {
218
+ const split = (0, value_probe_js_1.detectCategorySplit)(source.target, source.field, source.column, allRows, {
219
+ queryName: runnable[0].name,
220
+ measure: source.measure,
221
+ });
222
+ if (split)
223
+ diagnosis.push(split);
224
+ }
225
+ const emptyColumns = emptyRequiredColumns(chartType, allRows);
226
+ return {
227
+ status: 'probed',
228
+ rowsReturned,
229
+ preflightMs: Date.now() - startedAt,
230
+ // Rows alone do not mean the widget draws: the column it reads can come back null in all of them.
231
+ willRenderEmpty: rowsReturned === 0 || emptyColumns.length > 0,
232
+ ...(emptyColumns.length > 0 ? { emptyColumns } : {}),
233
+ ...(missingRecommended.length > 0 ? { missingRecommended } : {}),
234
+ ...(diagnosis.length > 0 ? { diagnosis } : {}),
235
+ note: buildNote(rowsReturned, noResultMessage, missingRecommended, diagnosis, emptyColumns),
236
+ };
237
+ }
238
+ //# sourceMappingURL=widget-preflight.js.map