@lightdash-tools/common 0.20.0 → 0.22.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.
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Secure-by-default flags for Lightdash AI agent create (MCP, CLI, agentops).
3
+ * More conservative than Lightdash UI defaults — elevation is explicit opt-in.
4
+ */
5
+
6
+ import { createHash } from 'node:crypto';
7
+
8
+ import type { CreateAiAgent } from '../types/v1/lightdash-api.js';
9
+
10
+ export const SECURE_AGENT_CREATE_DEFAULTS = {
11
+ enableDataAccess: false,
12
+ enableContentTools: false,
13
+ enableSqlMode: false,
14
+ enableUserContext: false,
15
+ adminOnly: true,
16
+ enableSelfImprovement: false,
17
+ } as const;
18
+
19
+ export type SecureAgentCreateFlags = {
20
+ enableDataAccess?: boolean;
21
+ enableContentTools?: boolean;
22
+ enableSqlMode?: boolean;
23
+ enableUserContext?: boolean;
24
+ adminOnly?: boolean;
25
+ enableSelfImprovement?: boolean;
26
+ };
27
+
28
+ export type ResolvedSecureAgentCreateFlags = {
29
+ enableDataAccess: boolean;
30
+ enableContentTools: boolean;
31
+ enableSqlMode: boolean;
32
+ enableUserContext: boolean;
33
+ adminOnly: boolean;
34
+ enableSelfImprovement: boolean;
35
+ };
36
+
37
+ export const AGENT_PERMISSION_UI_LABELS = {
38
+ enableDataAccess: 'Read rows behind chart',
39
+ enableContentTools: 'Create/edit content',
40
+ enableSqlMode: 'SQL mode',
41
+ enableUserContext: 'User context',
42
+ enableSelfImprovement: 'Self-improvement',
43
+ adminOnly: 'Admins & developers only',
44
+ } as const;
45
+
46
+ export type AgentCreatePayloadFields = SecureAgentCreateFlags & {
47
+ name: string;
48
+ description?: string | null;
49
+ instruction?: string | null;
50
+ tags?: string[] | null;
51
+ groupAccess?: string[];
52
+ userAccess?: string[];
53
+ spaceAccess?: string[];
54
+ mcpServerUuids?: string[];
55
+ };
56
+
57
+ export type BuildSecureCreateAiAgentInput = AgentCreatePayloadFields & {
58
+ projectUuid: string;
59
+ integrations?: CreateAiAgent['integrations'];
60
+ imageUrl?: CreateAiAgent['imageUrl'];
61
+ modelConfig?: CreateAiAgent['modelConfig'];
62
+ };
63
+
64
+ function sortedStrings(values: string[] | undefined): string[] {
65
+ return values === undefined ? [] : [...values].sort();
66
+ }
67
+
68
+ function canonicalTagsForDigest(tags: string[] | null | undefined): string[] | null {
69
+ const normalized = normalizeAgentTags(tags);
70
+ return normalized == null ? null : sortedStrings(normalized);
71
+ }
72
+
73
+ function canonicalCreateAgentPayload(payload: AgentCreatePayloadFields): Record<string, unknown> {
74
+ const flags = resolveSecureAgentCreateFlags(payload);
75
+ return {
76
+ adminOnly: flags.adminOnly,
77
+ description: payload.description ?? null,
78
+ enableContentTools: flags.enableContentTools,
79
+ enableDataAccess: flags.enableDataAccess,
80
+ enableSelfImprovement: flags.enableSelfImprovement,
81
+ enableSqlMode: flags.enableSqlMode,
82
+ enableUserContext: flags.enableUserContext,
83
+ groupAccess: sortedStrings(payload.groupAccess),
84
+ instruction: payload.instruction ?? null,
85
+ mcpServerUuids: sortedStrings(payload.mcpServerUuids),
86
+ name: payload.name,
87
+ spaceAccess: sortedStrings(payload.spaceAccess),
88
+ tags: canonicalTagsForDigest(payload.tags),
89
+ userAccess: sortedStrings(payload.userAccess),
90
+ };
91
+ }
92
+
93
+ /** Canonical digest of create fields (order-stable). Shared by elicitation and preview tokens. */
94
+ export function digestCreateAgentPayload(payload: AgentCreatePayloadFields): string {
95
+ return createHash('sha256')
96
+ .update(JSON.stringify(canonicalCreateAgentPayload(payload)))
97
+ .digest('hex');
98
+ }
99
+
100
+ /** Empty tag list means all explores — normalize to null for API/digest consistency. */
101
+ export function normalizeAgentTags(tags: string[] | null | undefined): string[] | null {
102
+ if (tags == null || tags.length === 0) {
103
+ return null;
104
+ }
105
+ return tags;
106
+ }
107
+
108
+ export type AgentElevationWarningCode =
109
+ | 'ELEVATED_CONTENT_TOOLS'
110
+ | 'ELEVATED_CONTENT_WITHOUT_DATA'
111
+ | 'ELEVATED_DATA_ACCESS'
112
+ | 'ELEVATED_PUBLIC_VISIBILITY'
113
+ | 'ELEVATED_SQL_MODE'
114
+ | 'ELEVATED_USER_CONTEXT';
115
+
116
+ export type AgentElevationWarning = {
117
+ code: AgentElevationWarningCode;
118
+ message: string;
119
+ };
120
+
121
+ export type AgentCreateVisibilityInput = SecureAgentCreateFlags & {
122
+ groupAccess?: string[];
123
+ userAccess?: string[];
124
+ };
125
+
126
+ /** Merge partial create args over secure defaults (explicit false/true honored). */
127
+ export function resolveSecureAgentCreateFlags(
128
+ partial: SecureAgentCreateFlags,
129
+ ): ResolvedSecureAgentCreateFlags {
130
+ return {
131
+ enableDataAccess: partial.enableDataAccess ?? SECURE_AGENT_CREATE_DEFAULTS.enableDataAccess,
132
+ enableContentTools:
133
+ partial.enableContentTools ?? SECURE_AGENT_CREATE_DEFAULTS.enableContentTools,
134
+ enableSqlMode: partial.enableSqlMode ?? SECURE_AGENT_CREATE_DEFAULTS.enableSqlMode,
135
+ enableUserContext: partial.enableUserContext ?? SECURE_AGENT_CREATE_DEFAULTS.enableUserContext,
136
+ adminOnly: partial.adminOnly ?? SECURE_AGENT_CREATE_DEFAULTS.adminOnly,
137
+ enableSelfImprovement:
138
+ partial.enableSelfImprovement ?? SECURE_AGENT_CREATE_DEFAULTS.enableSelfImprovement,
139
+ };
140
+ }
141
+
142
+ /** Build a create-agent API body with secure defaults applied (MCP, CLI, agentops). */
143
+ export function buildSecureCreateAiAgentBody(input: BuildSecureCreateAiAgentInput): CreateAiAgent {
144
+ const flags = resolveSecureAgentCreateFlags(input);
145
+ return {
146
+ name: input.name,
147
+ projectUuid: input.projectUuid,
148
+ description: input.description ?? null,
149
+ instruction: input.instruction ?? null,
150
+ tags: normalizeAgentTags(input.tags),
151
+ integrations: input.integrations ?? [],
152
+ imageUrl: input.imageUrl ?? null,
153
+ groupAccess: input.groupAccess ?? [],
154
+ userAccess: input.userAccess ?? [],
155
+ spaceAccess: input.spaceAccess ?? [],
156
+ enableDataAccess: flags.enableDataAccess,
157
+ enableContentTools: flags.enableContentTools,
158
+ enableSqlMode: flags.enableSqlMode,
159
+ enableUserContext: flags.enableUserContext,
160
+ adminOnly: flags.adminOnly,
161
+ enableSelfImprovement: flags.enableSelfImprovement,
162
+ version: 1,
163
+ ...(input.mcpServerUuids !== undefined ? { mcpServerUuids: input.mcpServerUuids } : {}),
164
+ ...(input.modelConfig !== undefined ? { modelConfig: input.modelConfig } : {}),
165
+ };
166
+ }
167
+
168
+ function onOff(value: boolean): string {
169
+ return value ? 'on' : 'off';
170
+ }
171
+
172
+ function formatVisibility(
173
+ resolved: ResolvedSecureAgentCreateFlags,
174
+ input: AgentCreateVisibilityInput,
175
+ ): string {
176
+ if (resolved.adminOnly) {
177
+ return 'Admins & developers only';
178
+ }
179
+ const groupCount = input.groupAccess?.length ?? 0;
180
+ const userCount = input.userAccess?.length ?? 0;
181
+ if (groupCount > 0 || userCount > 0) {
182
+ return `Specific users/groups (${userCount} user(s), ${groupCount} group(s))`;
183
+ }
184
+ return 'Everyone in the project';
185
+ }
186
+
187
+ /** Human-readable permission lines for create elicitation (UI-aligned labels). */
188
+ export function formatAgentPermissionSummary(
189
+ partial: SecureAgentCreateFlags,
190
+ visibilityInput: Pick<AgentCreateVisibilityInput, 'groupAccess' | 'userAccess'> = {},
191
+ ): string[] {
192
+ const resolved = resolveSecureAgentCreateFlags(partial);
193
+ return [
194
+ ` ${AGENT_PERMISSION_UI_LABELS.enableDataAccess}: ${onOff(resolved.enableDataAccess)}`,
195
+ ` ${AGENT_PERMISSION_UI_LABELS.enableContentTools}: ${onOff(resolved.enableContentTools)}`,
196
+ ` ${AGENT_PERMISSION_UI_LABELS.enableSqlMode}: ${onOff(resolved.enableSqlMode)}`,
197
+ ` ${AGENT_PERMISSION_UI_LABELS.enableUserContext}: ${onOff(resolved.enableUserContext)}`,
198
+ ` ${AGENT_PERMISSION_UI_LABELS.enableSelfImprovement}: ${onOff(resolved.enableSelfImprovement)}`,
199
+ ` Who can use: ${formatVisibility(resolved, { ...partial, ...visibilityInput })}`,
200
+ ];
201
+ }
202
+
203
+ const CONTENT_WITHOUT_DATA_WARNING: AgentElevationWarning = {
204
+ code: 'ELEVATED_CONTENT_WITHOUT_DATA',
205
+ message:
206
+ 'Content editing is enabled without data access. Lightdash locks content tools until data access is on.',
207
+ };
208
+
209
+ type CapabilityElevationCheck = {
210
+ code: AgentElevationWarningCode;
211
+ isActive: (resolved: ResolvedSecureAgentCreateFlags) => boolean;
212
+ isPatchActive: (patch: SecureAgentCreateFlags) => boolean;
213
+ createMessage: string;
214
+ updateMessage: string;
215
+ };
216
+
217
+ const CAPABILITY_ELEVATIONS: CapabilityElevationCheck[] = [
218
+ {
219
+ code: 'ELEVATED_DATA_ACCESS',
220
+ isActive: (resolved) => resolved.enableDataAccess,
221
+ isPatchActive: (patch) => patch.enableDataAccess === true,
222
+ createMessage:
223
+ 'Agent has data access enabled (Read rows behind chart). Warehouse row values may be sent to the LLM.',
224
+ updateMessage:
225
+ 'Update enables data access (Read rows behind chart). Warehouse row values may be sent to the LLM.',
226
+ },
227
+ {
228
+ code: 'ELEVATED_CONTENT_TOOLS',
229
+ isActive: (resolved) => resolved.enableContentTools,
230
+ isPatchActive: (patch) => patch.enableContentTools === true,
231
+ createMessage:
232
+ 'Agent has content editing enabled. It may create or mutate saved charts and dashboards.',
233
+ updateMessage:
234
+ 'Update enables content editing. The agent may create or mutate saved charts and dashboards.',
235
+ },
236
+ {
237
+ code: 'ELEVATED_SQL_MODE',
238
+ isActive: (resolved) => resolved.enableSqlMode,
239
+ isPatchActive: (patch) => patch.enableSqlMode === true,
240
+ createMessage:
241
+ 'Agent has SQL mode enabled. It may run raw SQL against the warehouse (subject to user approval per query).',
242
+ updateMessage:
243
+ 'Update enables SQL mode. The agent may run raw SQL against the warehouse (subject to user approval per query).',
244
+ },
245
+ {
246
+ code: 'ELEVATED_USER_CONTEXT',
247
+ isActive: (resolved) => resolved.enableUserContext,
248
+ isPatchActive: (patch) => patch.enableUserContext === true,
249
+ createMessage:
250
+ 'Agent has user context enabled. It receives the requesting user name, role, and group memberships.',
251
+ updateMessage:
252
+ 'Update enables user context. The agent receives the requesting user name, role, and group memberships.',
253
+ },
254
+ ];
255
+
256
+ function visibilityElevationMessage(
257
+ groupCount: number,
258
+ userCount: number,
259
+ prefix: string,
260
+ messages: { everyone: string; specific: string },
261
+ ): AgentElevationWarning {
262
+ return {
263
+ code: 'ELEVATED_PUBLIC_VISIBILITY',
264
+ message:
265
+ groupCount === 0 && userCount === 0
266
+ ? `${prefix} ${messages.everyone}`
267
+ : `${prefix} ${messages.specific}`,
268
+ };
269
+ }
270
+
271
+ /** Warn when resolved flags deviate from the secure baseline. */
272
+ export function collectElevationWarnings(
273
+ partial: AgentCreateVisibilityInput,
274
+ ): AgentElevationWarning[] {
275
+ const resolved = resolveSecureAgentCreateFlags(partial);
276
+ const warnings: AgentElevationWarning[] = [];
277
+
278
+ for (const check of CAPABILITY_ELEVATIONS) {
279
+ if (check.isActive(resolved)) {
280
+ warnings.push({ code: check.code, message: check.createMessage });
281
+ }
282
+ }
283
+
284
+ if (!resolved.adminOnly) {
285
+ warnings.push(
286
+ visibilityElevationMessage(
287
+ partial.groupAccess?.length ?? 0,
288
+ partial.userAccess?.length ?? 0,
289
+ 'Agent visibility is',
290
+ {
291
+ everyone:
292
+ 'Everyone in the project (adminOnly: false). All project members can use this agent.',
293
+ specific:
294
+ 'limited to specific users/groups (adminOnly: false). Verify access lists before release.',
295
+ },
296
+ ),
297
+ );
298
+ }
299
+ if (resolved.enableContentTools && !resolved.enableDataAccess) {
300
+ warnings.push(CONTENT_WITHOUT_DATA_WARNING);
301
+ }
302
+
303
+ return warnings;
304
+ }
305
+
306
+ function pushCapabilityElevation(
307
+ warnings: AgentElevationWarning[],
308
+ patch: Pick<AgentCreateVisibilityInput, 'groupAccess' | 'userAccess'> & SecureAgentCreateFlags,
309
+ ): void {
310
+ for (const check of CAPABILITY_ELEVATIONS) {
311
+ if (check.isPatchActive(patch)) {
312
+ warnings.push({ code: check.code, message: check.updateMessage });
313
+ }
314
+ }
315
+
316
+ if (patch.enableContentTools === true && patch.enableDataAccess === false) {
317
+ warnings.push({
318
+ ...CONTENT_WITHOUT_DATA_WARNING,
319
+ message:
320
+ 'Content editing enabled without data access in this patch. Lightdash locks content tools until data access is on.',
321
+ });
322
+ }
323
+ }
324
+
325
+ function pushVisibilityElevation(
326
+ warnings: AgentElevationWarning[],
327
+ patch: Pick<AgentCreateVisibilityInput, 'groupAccess' | 'userAccess'> & SecureAgentCreateFlags,
328
+ ): void {
329
+ if (patch.adminOnly === false) {
330
+ warnings.push(
331
+ visibilityElevationMessage(
332
+ patch.groupAccess?.length ?? 0,
333
+ patch.userAccess?.length ?? 0,
334
+ 'Update sets visibility to',
335
+ {
336
+ everyone: 'Everyone in the project (adminOnly: false).',
337
+ specific: `specific users/groups (adminOnly: false; ${patch.userAccess?.length ?? 0} user(s), ${patch.groupAccess?.length ?? 0} group(s)).`,
338
+ },
339
+ ),
340
+ );
341
+ }
342
+ }
343
+
344
+ /** Elevation warnings for update patches — only fields explicitly set in the patch. */
345
+ export function collectElevationWarningsFromPatch(
346
+ patch: Pick<AgentCreateVisibilityInput, 'groupAccess' | 'userAccess'> & SecureAgentCreateFlags,
347
+ ): AgentElevationWarning[] {
348
+ const warnings: AgentElevationWarning[] = [];
349
+ pushCapabilityElevation(warnings, patch);
350
+ pushVisibilityElevation(warnings, patch);
351
+ return warnings;
352
+ }
package/src/index.ts CHANGED
@@ -16,6 +16,12 @@ export * from './profile-ids';
16
16
  // Irrecoverable MCP tool denylist
17
17
  export * from './agent-safe';
18
18
 
19
+ // Secure AI agent create defaults (MCP, CLI, agentops)
20
+ export * from './ai-agents/secure-create-defaults';
21
+
22
+ // AI agent knowledge document limits
23
+ export * from './ai-agents/document-limits';
24
+
19
25
  // Export AgentOps bundle and gate types
20
26
  export * from './agentops/types';
21
27
  export * from './agentops/snapshots';
@@ -114,6 +114,12 @@ export type {
114
114
  AgentSuggestions,
115
115
  GenerateThreadTitleResult,
116
116
  CloneThreadBody,
117
+ AiAgentDocument,
118
+ AiAgentDocumentSummary,
119
+ AiAgentDocumentContent,
120
+ CreateAgentDocumentBody,
121
+ UpdateAgentDocumentContentBody,
122
+ UpdateAgentDocumentSettingsBody,
117
123
  AiAgentVerifiedArtifact,
118
124
  AiAgentVerifiedArtifactsListResult,
119
125
  ListVerifiedArtifactsParams,
@@ -168,6 +168,22 @@ export namespace AiAgents {
168
168
  createdFrom?: 'evals' | 'web_app';
169
169
  }
170
170
 
171
+ // ─── Knowledge documents ─────────────────────────────────────────────────────
172
+
173
+ /** Full knowledge document (POST create response). */
174
+ export type AiAgentDocument = components['schemas']['AiAgentDocument'];
175
+ /** Document summary in list responses (no full content). */
176
+ export type AiAgentDocumentSummary = components['schemas']['AiAgentDocumentSummary'];
177
+ /** Document content payload (GET …/content). */
178
+ export type AiAgentDocumentContent = components['schemas']['AiAgentDocumentContent'];
179
+ /** Request body for POST …/documents. */
180
+ export type CreateAgentDocumentBody = components['schemas']['ApiCreateAgentDocument'];
181
+ /** Request body for PATCH …/documents/{uuid}/content. */
182
+ export type UpdateAgentDocumentContentBody =
183
+ components['schemas']['ApiUpdateAgentDocumentContent'];
184
+ /** Request body for PATCH …/documents/{uuid} settings. */
185
+ export type UpdateAgentDocumentSettingsBody = components['schemas']['ApiUpdateAgentDocument'];
186
+
171
187
  // ─── Artifacts ─────────────────────────────────────────────────────────────────
172
188
 
173
189
  /** Verified artifact summary (GET …/verified-artifacts). */
@@ -143,6 +143,13 @@ export namespace V1 {
143
143
  // Threads: title & clone
144
144
  export type GenerateThreadTitleResult = A.GenerateThreadTitleResult;
145
145
  export type CloneThreadBody = A.CloneThreadBody;
146
+ // Knowledge documents
147
+ export type AiAgentDocument = A.AiAgentDocument;
148
+ export type AiAgentDocumentSummary = A.AiAgentDocumentSummary;
149
+ export type AiAgentDocumentContent = A.AiAgentDocumentContent;
150
+ export type CreateAgentDocumentBody = A.CreateAgentDocumentBody;
151
+ export type UpdateAgentDocumentContentBody = A.UpdateAgentDocumentContentBody;
152
+ export type UpdateAgentDocumentSettingsBody = A.UpdateAgentDocumentSettingsBody;
146
153
  // Artifacts
147
154
  export type AiAgentVerifiedArtifact = A.AiAgentVerifiedArtifact;
148
155
  export type AiAgentVerifiedArtifactsListResult = A.AiAgentVerifiedArtifactsListResult;
@@ -248,6 +248,13 @@ export namespace LightdashApi {
248
248
  // Threads: title & clone
249
249
  export type GenerateThreadTitleResult = AiAgentsTypes.GenerateThreadTitleResult;
250
250
  export type CloneThreadBody = AiAgentsTypes.CloneThreadBody;
251
+ // Knowledge documents
252
+ export type AiAgentDocument = AiAgentsTypes.AiAgentDocument;
253
+ export type AiAgentDocumentSummary = AiAgentsTypes.AiAgentDocumentSummary;
254
+ export type AiAgentDocumentContent = AiAgentsTypes.AiAgentDocumentContent;
255
+ export type CreateAgentDocumentBody = AiAgentsTypes.CreateAgentDocumentBody;
256
+ export type UpdateAgentDocumentContentBody = AiAgentsTypes.UpdateAgentDocumentContentBody;
257
+ export type UpdateAgentDocumentSettingsBody = AiAgentsTypes.UpdateAgentDocumentSettingsBody;
251
258
  // Artifacts
252
259
  export type AiAgentVerifiedArtifact = AiAgentsTypes.AiAgentVerifiedArtifact;
253
260
  export type AiAgentVerifiedArtifactsListResult =
@@ -421,6 +428,13 @@ export type AgentSuggestions = AiAgents.AgentSuggestions;
421
428
  // AI agents (flat exports) — threads: title & clone
422
429
  export type GenerateThreadTitleResult = AiAgents.GenerateThreadTitleResult;
423
430
  export type CloneThreadBody = AiAgents.CloneThreadBody;
431
+ // AI agents (flat exports) — knowledge documents
432
+ export type AiAgentDocument = AiAgents.AiAgentDocument;
433
+ export type AiAgentDocumentSummary = AiAgents.AiAgentDocumentSummary;
434
+ export type AiAgentDocumentContent = AiAgents.AiAgentDocumentContent;
435
+ export type CreateAgentDocumentBody = AiAgents.CreateAgentDocumentBody;
436
+ export type UpdateAgentDocumentContentBody = AiAgents.UpdateAgentDocumentContentBody;
437
+ export type UpdateAgentDocumentSettingsBody = AiAgents.UpdateAgentDocumentSettingsBody;
424
438
  // AI agents (flat exports) — artifacts
425
439
  export type AiAgentVerifiedArtifact = AiAgents.AiAgentVerifiedArtifact;
426
440
  export type AiAgentVerifiedArtifactsListResult = AiAgents.AiAgentVerifiedArtifactsListResult;