@kairos-sdk/core 0.4.0 → 0.4.5

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,566 @@
1
+ interface Tag {
2
+ id: string;
3
+ name: string;
4
+ }
5
+ interface N8nCredentialReference {
6
+ id: string;
7
+ name: string;
8
+ }
9
+ type ConnectionPort = {
10
+ node: string;
11
+ type: string;
12
+ index: number;
13
+ };
14
+ type ConnectionPortList = ConnectionPort[];
15
+ interface N8nConnections {
16
+ [nodeName: string]: {
17
+ main?: ConnectionPortList[];
18
+ ai_languageModel?: ConnectionPortList[];
19
+ ai_memory?: ConnectionPortList[];
20
+ ai_tool?: ConnectionPortList[];
21
+ ai_document?: ConnectionPortList[];
22
+ ai_embedding?: ConnectionPortList[];
23
+ ai_vectorStore?: ConnectionPortList[];
24
+ ai_retriever?: ConnectionPortList[];
25
+ ai_outputParser?: ConnectionPortList[];
26
+ ai_textSplitter?: ConnectionPortList[];
27
+ [key: string]: ConnectionPortList[] | undefined;
28
+ };
29
+ }
30
+ interface N8nNode {
31
+ id: string;
32
+ name: string;
33
+ type: string;
34
+ typeVersion: number;
35
+ position: [number, number];
36
+ parameters: Record<string, unknown>;
37
+ credentials?: Record<string, N8nCredentialReference>;
38
+ disabled?: boolean;
39
+ notes?: string;
40
+ notesInFlow?: boolean;
41
+ continueOnFail?: boolean;
42
+ retryOnFail?: boolean;
43
+ maxTries?: number;
44
+ waitBetweenTries?: number;
45
+ }
46
+ interface N8nSettings {
47
+ executionOrder?: 'v0' | 'v1';
48
+ saveManualExecutions?: boolean;
49
+ callerPolicy?: string;
50
+ errorWorkflow?: string;
51
+ timezone?: string;
52
+ [key: string]: unknown;
53
+ }
54
+ interface N8nWorkflow {
55
+ name: string;
56
+ nodes: N8nNode[];
57
+ connections: N8nConnections;
58
+ settings?: N8nSettings;
59
+ tags?: Tag[];
60
+ }
61
+
62
+ interface CredentialRequirement {
63
+ service: string;
64
+ credentialType: string;
65
+ description: string;
66
+ }
67
+ interface BuildResult {
68
+ workflowId: string | null;
69
+ name: string;
70
+ workflow: N8nWorkflow;
71
+ credentialsNeeded: CredentialRequirement[];
72
+ activationRequired: boolean;
73
+ generationAttempts: number;
74
+ dryRun: boolean;
75
+ }
76
+ interface DeployResult {
77
+ workflowId: string;
78
+ name: string;
79
+ }
80
+ interface WorkflowListItem {
81
+ id: string;
82
+ name: string;
83
+ active: boolean;
84
+ createdAt: string;
85
+ updatedAt: string;
86
+ tags?: Array<{
87
+ id: string;
88
+ name: string;
89
+ }>;
90
+ }
91
+ interface ExecutionSummary {
92
+ id: string;
93
+ workflowId: string;
94
+ status: 'success' | 'error' | 'waiting' | 'running' | 'canceled';
95
+ startedAt: string;
96
+ stoppedAt?: string;
97
+ mode: string;
98
+ }
99
+ interface ExecutionDetail extends ExecutionSummary {
100
+ data?: unknown;
101
+ workflowData?: unknown;
102
+ }
103
+
104
+ interface ILogger {
105
+ debug(msg: string, meta?: Record<string, unknown>): void;
106
+ info(msg: string, meta?: Record<string, unknown>): void;
107
+ warn(msg: string, meta?: Record<string, unknown>): void;
108
+ error(msg: string, meta?: Record<string, unknown>): void;
109
+ }
110
+ declare const nullLogger: ILogger;
111
+
112
+ interface FailurePattern {
113
+ rule: number;
114
+ message: string;
115
+ occurrences: number;
116
+ }
117
+ type SourceKind = 'organic' | 'n8n-template' | 'imported';
118
+ type TrustLevel = 'safe' | 'review' | 'blocked';
119
+ interface WorkflowMetadataInput {
120
+ description: string;
121
+ tags?: string[];
122
+ platform?: string;
123
+ failurePatterns?: Array<{
124
+ rule: number;
125
+ message: string;
126
+ }>;
127
+ sourceWorkflowIds?: string[];
128
+ generationMode?: 'direct' | 'reference' | 'scratch';
129
+ topMatchScore?: number;
130
+ generationAttempts?: number;
131
+ credentialsNeeded?: CredentialRequirement[];
132
+ sourceKind?: SourceKind;
133
+ sourceId?: string;
134
+ sourceUrl?: string;
135
+ trustLevel?: TrustLevel;
136
+ }
137
+ interface OutcomeData {
138
+ attempts: number;
139
+ firstTryPass: boolean;
140
+ failedRules: number[];
141
+ mode: 'direct' | 'reference';
142
+ }
143
+ interface OutcomeStats {
144
+ totalUses: number;
145
+ totalAttempts: number;
146
+ firstTryPasses: number;
147
+ failedRules: Record<string, number>;
148
+ }
149
+ interface StoredWorkflow {
150
+ id: string;
151
+ workflow: N8nWorkflow;
152
+ description: string;
153
+ tags: string[];
154
+ platform: string;
155
+ deployCount: number;
156
+ createdAt: string;
157
+ lastDeployedAt?: string;
158
+ failurePatterns?: FailurePattern[];
159
+ sourceWorkflowIds?: string[];
160
+ generationMode?: 'direct' | 'reference' | 'scratch';
161
+ topMatchScore?: number;
162
+ generationAttempts?: number;
163
+ credentialsNeeded?: CredentialRequirement[];
164
+ sourceKind?: SourceKind;
165
+ sourceId?: string;
166
+ sourceUrl?: string;
167
+ trustLevel?: TrustLevel;
168
+ timesRetrieved?: number;
169
+ timesUsedAsDirect?: number;
170
+ timesUsedAsReference?: number;
171
+ outcomeStats?: OutcomeStats;
172
+ }
173
+ interface WorkflowMatch {
174
+ workflow: StoredWorkflow;
175
+ score: number;
176
+ mode: 'direct' | 'reference' | 'scratch';
177
+ }
178
+ interface SearchOptions {
179
+ limit?: number;
180
+ platform?: string;
181
+ }
182
+ interface LibraryFilters {
183
+ platform?: string;
184
+ tags?: string[];
185
+ }
186
+ interface IWorkflowLibrary {
187
+ initialize(): Promise<void>;
188
+ search(description: string, options?: SearchOptions): Promise<WorkflowMatch[]>;
189
+ save(workflow: N8nWorkflow, metadata: WorkflowMetadataInput): Promise<string>;
190
+ recordDeployment(id: string): Promise<void>;
191
+ recordOutcome(id: string, outcome: OutcomeData): Promise<void>;
192
+ get(id: string): Promise<StoredWorkflow | null>;
193
+ list(filters?: LibraryFilters): Promise<StoredWorkflow[]>;
194
+ }
195
+
196
+ interface ClientOptions {
197
+ anthropicApiKey: string;
198
+ n8nBaseUrl?: string;
199
+ n8nApiKey?: string;
200
+ model?: string;
201
+ logger?: ILogger;
202
+ library?: IWorkflowLibrary;
203
+ telemetry?: boolean | string;
204
+ }
205
+ interface BuildOptions {
206
+ dryRun?: boolean;
207
+ activate?: boolean;
208
+ name?: string;
209
+ }
210
+ interface DeleteOptions {
211
+ confirm: true;
212
+ }
213
+ interface ExecutionFilter {
214
+ status?: 'success' | 'error' | 'waiting' | 'running';
215
+ limit?: number;
216
+ cursor?: string;
217
+ }
218
+
219
+ interface IProvider {
220
+ readonly platform: string;
221
+ deploy(workflow: N8nWorkflow): Promise<DeployResult>;
222
+ update(id: string, workflow: N8nWorkflow): Promise<DeployResult>;
223
+ get(id: string): Promise<N8nWorkflow>;
224
+ list(): Promise<WorkflowListItem[]>;
225
+ activate(id: string): Promise<void>;
226
+ deactivate(id: string): Promise<void>;
227
+ delete(id: string, options: DeleteOptions): Promise<void>;
228
+ executions(workflowId?: string, filter?: ExecutionFilter): Promise<ExecutionSummary[]>;
229
+ execution(id: string): Promise<ExecutionDetail>;
230
+ tag(workflowId: string, tagIds: string[]): Promise<void>;
231
+ untag(workflowId: string, tagIds: string[]): Promise<void>;
232
+ listTags(): Promise<Tag[]>;
233
+ createTag(name: string): Promise<Tag>;
234
+ }
235
+
236
+ interface N8nWorkflowResponse {
237
+ id: string;
238
+ name: string;
239
+ active: boolean;
240
+ nodes: N8nNode[];
241
+ connections: N8nConnections;
242
+ settings?: N8nSettings;
243
+ tags?: Tag[];
244
+ createdAt: string;
245
+ updatedAt: string;
246
+ versionId?: string;
247
+ meta?: Record<string, unknown>;
248
+ pinData?: Record<string, unknown>;
249
+ staticData?: unknown;
250
+ triggerCount?: number;
251
+ shared?: boolean;
252
+ isArchived?: boolean;
253
+ }
254
+ interface N8nNodeTypeInfo {
255
+ name: string;
256
+ displayName: string;
257
+ version: number | number[];
258
+ description?: string;
259
+ group?: string[];
260
+ credentials?: Array<{
261
+ name: string;
262
+ required?: boolean;
263
+ }>;
264
+ }
265
+
266
+ declare class N8nApiClient {
267
+ private readonly baseUrl;
268
+ private readonly apiKey;
269
+ private readonly logger;
270
+ constructor(baseUrl: string, apiKey: string, logger: ILogger);
271
+ private request;
272
+ private singleRequest;
273
+ createWorkflow(workflow: N8nWorkflow): Promise<N8nWorkflowResponse>;
274
+ updateWorkflow(id: string, workflow: N8nWorkflow): Promise<N8nWorkflowResponse>;
275
+ getWorkflow(id: string): Promise<N8nWorkflowResponse>;
276
+ listWorkflows(): Promise<WorkflowListItem[]>;
277
+ deleteWorkflow(id: string): Promise<void>;
278
+ activateWorkflow(id: string): Promise<void>;
279
+ deactivateWorkflow(id: string): Promise<void>;
280
+ getExecutions(workflowId?: string, filter?: ExecutionFilter): Promise<ExecutionSummary[]>;
281
+ getExecution(id: string): Promise<ExecutionDetail>;
282
+ listTags(): Promise<Tag[]>;
283
+ createTag(name: string): Promise<Tag>;
284
+ tagWorkflow(workflowId: string, tagIds: string[]): Promise<void>;
285
+ untagWorkflow(workflowId: string, tagIds: string[]): Promise<void>;
286
+ getNodeTypes(): Promise<N8nNodeTypeInfo[]>;
287
+ private mapExecution;
288
+ }
289
+
290
+ declare class N8nFieldStripper {
291
+ stripForCreate(workflow: N8nWorkflow): N8nWorkflow;
292
+ stripForUpdate(workflow: N8nWorkflow): N8nWorkflow;
293
+ private strip;
294
+ }
295
+
296
+ declare class N8nProvider implements IProvider {
297
+ private readonly client;
298
+ private readonly stripper;
299
+ readonly platform = "n8n";
300
+ constructor(client: N8nApiClient, stripper: N8nFieldStripper);
301
+ deploy(workflow: N8nWorkflow): Promise<DeployResult>;
302
+ update(id: string, workflow: N8nWorkflow): Promise<DeployResult>;
303
+ get(id: string): Promise<N8nWorkflow>;
304
+ list(): Promise<WorkflowListItem[]>;
305
+ activate(id: string): Promise<void>;
306
+ deactivate(id: string): Promise<void>;
307
+ delete(id: string, options: DeleteOptions): Promise<void>;
308
+ executions(workflowId?: string, filter?: ExecutionFilter): Promise<ExecutionSummary[]>;
309
+ execution(id: string): Promise<ExecutionDetail>;
310
+ listTags(): Promise<Tag[]>;
311
+ createTag(name: string): Promise<Tag>;
312
+ tag(workflowId: string, tagIds: string[]): Promise<void>;
313
+ untag(workflowId: string, tagIds: string[]): Promise<void>;
314
+ }
315
+
316
+ declare class NullLibrary implements IWorkflowLibrary {
317
+ initialize(): Promise<void>;
318
+ search(_description: string, _options?: SearchOptions): Promise<WorkflowMatch[]>;
319
+ save(_workflow: N8nWorkflow, _metadata: WorkflowMetadataInput): Promise<string>;
320
+ recordDeployment(_id: string): Promise<void>;
321
+ recordOutcome(_id: string, _outcome: OutcomeData): Promise<void>;
322
+ get(_id: string): Promise<StoredWorkflow | null>;
323
+ list(_filters?: LibraryFilters): Promise<StoredWorkflow[]>;
324
+ }
325
+
326
+ declare function tokenize(text: string): string[];
327
+ declare function buildSearchCorpus(w: StoredWorkflow): string;
328
+ declare class FileLibrary implements IWorkflowLibrary {
329
+ private readonly dir;
330
+ private meta;
331
+ private initPromise;
332
+ private writeQueue;
333
+ constructor(dir?: string);
334
+ private get workflowsDir();
335
+ private workflowFilePath;
336
+ initialize(): Promise<void>;
337
+ private doInitialize;
338
+ /**
339
+ * One-time transparent migration from v0.4.x monolithic index.json.
340
+ * Splits each stored workflow into a per-file workflow JSON and a lightweight
341
+ * meta entry. Rewrites index.json in the new format.
342
+ */
343
+ private migrateFromMonolithic;
344
+ private loadWorkflowFile;
345
+ private writeWorkflowFile;
346
+ /**
347
+ * Build a lightweight StoredWorkflow shell from a meta entry for use in
348
+ * scoring / clustering. Only node.type is populated in each node — no other
349
+ * node fields are used by hybridScore or clusterWorkflows.
350
+ */
351
+ private makeSearchShell;
352
+ search(description: string, options?: SearchOptions): Promise<WorkflowMatch[]>;
353
+ save(workflow: N8nWorkflow, metadata: WorkflowMetadataInput): Promise<string>;
354
+ recordDeployment(id: string): Promise<void>;
355
+ recordOutcome(id: string, outcome: OutcomeData): Promise<void>;
356
+ drain(): Promise<void>;
357
+ get(id: string): Promise<StoredWorkflow | null>;
358
+ list(filters?: LibraryFilters): Promise<StoredWorkflow[]>;
359
+ private deduplicateFailurePatterns;
360
+ /**
361
+ * Direct write used only during migration (before writeQueue is needed).
362
+ */
363
+ private persistNow;
364
+ private persist;
365
+ }
366
+
367
+ interface ScoredEntry {
368
+ workflow: StoredWorkflow;
369
+ score: number;
370
+ signals: {
371
+ tfidf: number;
372
+ nodeFingerprint: number;
373
+ outcome: number;
374
+ deploy: number;
375
+ };
376
+ }
377
+ declare function hybridScore(queryTokens: string[], queryDescription: string, workflows: StoredWorkflow[], docTokenArrays: string[][], idf: Map<string, number>): ScoredEntry[];
378
+
379
+ interface WorkflowCluster {
380
+ pattern: string;
381
+ fingerprint: string[];
382
+ members: StoredWorkflow[];
383
+ avgFirstTryPassRate: number;
384
+ avgAttempts: number;
385
+ commonFailedRules: Array<{
386
+ rule: number;
387
+ frequency: number;
388
+ }>;
389
+ }
390
+ declare function clusterWorkflows(workflows: StoredWorkflow[]): WorkflowCluster[];
391
+ declare function rerank(candidates: Array<{
392
+ workflow: StoredWorkflow;
393
+ score: number;
394
+ }>, clusters: WorkflowCluster[]): Array<{
395
+ workflow: StoredWorkflow;
396
+ score: number;
397
+ clusterPattern?: string;
398
+ }>;
399
+
400
+ interface ValidationIssue {
401
+ rule: number;
402
+ severity: 'error' | 'warn';
403
+ message: string;
404
+ nodeId?: string;
405
+ nodeType?: string;
406
+ }
407
+ interface ValidationResult {
408
+ valid: boolean;
409
+ issues: ValidationIssue[];
410
+ }
411
+
412
+ interface NodeDefinition {
413
+ type: string;
414
+ safeTypeVersions: number[];
415
+ requiredParams: string[];
416
+ credentialType?: string;
417
+ isTrigger?: boolean;
418
+ }
419
+ declare const DEFAULT_REGISTRY: NodeDefinition[];
420
+ declare class NodeRegistry {
421
+ private readonly byType;
422
+ constructor(definitions?: NodeDefinition[]);
423
+ get(type: string): NodeDefinition | undefined;
424
+ isTrigger(type: string): boolean;
425
+ isKnown(type: string): boolean;
426
+ isVersionSafe(type: string, version: number): boolean;
427
+ getRequiredParams(type: string): string[];
428
+ }
429
+
430
+ declare class N8nValidator {
431
+ private readonly registry;
432
+ constructor(registry?: NodeRegistry);
433
+ validate(workflow: N8nWorkflow): ValidationResult;
434
+ private err;
435
+ private warn;
436
+ private isTriggerNode;
437
+ private checkRule1;
438
+ private checkRule2;
439
+ private checkRule3;
440
+ private checkRule4;
441
+ private checkRule5;
442
+ private checkRule6;
443
+ private checkRule7;
444
+ private checkRule8;
445
+ private checkRule9;
446
+ private checkRule10;
447
+ private checkRule11;
448
+ private checkRule12;
449
+ private checkRule13;
450
+ private checkRule14;
451
+ private checkRule15;
452
+ private checkRule16;
453
+ private checkRule17;
454
+ private checkRule18;
455
+ private checkRule19;
456
+ private checkRule20;
457
+ private checkRule22;
458
+ private checkRule23;
459
+ private checkRule24;
460
+ private checkRule25;
461
+ private checkRule26;
462
+ private extractExpressions;
463
+ private checkRule21;
464
+ }
465
+
466
+ declare class KairosError extends Error {
467
+ readonly cause?: unknown | undefined;
468
+ constructor(message: string, cause?: unknown | undefined);
469
+ }
470
+
471
+ interface TelemetryEvent {
472
+ schemaVersion: number;
473
+ timestamp: string;
474
+ sessionId: string;
475
+ runId?: string;
476
+ eventType: 'build_start' | 'generation_attempt' | 'build_complete';
477
+ data: Record<string, unknown>;
478
+ }
479
+ interface AttemptMetadata {
480
+ attempt: number;
481
+ temperature: number;
482
+ durationMs: number;
483
+ tokensInput: number;
484
+ tokensOutput: number;
485
+ validationPassed: boolean;
486
+ issues: ValidationIssue[];
487
+ }
488
+
489
+ declare class ValidationError extends KairosError {
490
+ readonly issues: ValidationIssue[];
491
+ readonly attemptMetadata?: AttemptMetadata[] | undefined;
492
+ readonly warnedRules?: number[] | undefined;
493
+ constructor(message: string, issues: ValidationIssue[], attemptMetadata?: AttemptMetadata[] | undefined, warnedRules?: number[] | undefined);
494
+ }
495
+
496
+ declare class GenerationError extends KairosError {
497
+ constructor(message: string, cause?: unknown);
498
+ }
499
+
500
+ declare class ResponseParseError extends KairosError {
501
+ constructor(message: string, cause?: unknown);
502
+ }
503
+
504
+ declare class ProviderError extends KairosError {
505
+ constructor(message: string, cause?: unknown);
506
+ }
507
+
508
+ declare class ApiError extends KairosError {
509
+ readonly statusCode: number;
510
+ constructor(message: string, statusCode: number, cause?: unknown);
511
+ }
512
+
513
+ declare class GuardError extends KairosError {
514
+ constructor(message: string);
515
+ }
516
+
517
+ interface SyncProgress {
518
+ total: number;
519
+ processed: number;
520
+ saved: number;
521
+ skippedPaid: number;
522
+ skippedDuplicate: number;
523
+ blocked: number;
524
+ reviewed: number;
525
+ }
526
+
527
+ interface SyncOptions {
528
+ maxTemplates?: number;
529
+ onProgress?: (progress: SyncProgress) => void;
530
+ }
531
+ declare class TemplateSyncer {
532
+ private readonly library;
533
+ private readonly validator;
534
+ private readonly logger;
535
+ constructor(library: IWorkflowLibrary, logger: ILogger);
536
+ sync(options?: SyncOptions): Promise<SyncProgress>;
537
+ private fetchTemplateIds;
538
+ private processTemplate;
539
+ private cleanDescription;
540
+ }
541
+
542
+ declare class TelemetryCollector {
543
+ private readonly dir;
544
+ readonly sessionId: string;
545
+ private dirReady;
546
+ constructor(dir?: string);
547
+ emit(eventType: TelemetryEvent['eventType'], data: Record<string, unknown>, runId?: string): Promise<void>;
548
+ }
549
+
550
+ interface RuleFailureRate {
551
+ rule: number;
552
+ failureCount: number;
553
+ totalBuilds: number;
554
+ rate: number;
555
+ commonMessage: string;
556
+ }
557
+ declare class TelemetryReader {
558
+ private readonly dir;
559
+ private cache;
560
+ private cacheTime;
561
+ constructor(dir?: string);
562
+ getFailureRates(days?: number): Promise<RuleFailureRate[]>;
563
+ private readRecentEvents;
564
+ }
565
+
566
+ export { clusterWorkflows as $, ApiError as A, type BuildOptions as B, type ClientOptions as C, type DeleteOptions as D, type ExecutionFilter as E, type FailurePattern as F, GenerationError as G, type TelemetryEvent as H, type ILogger as I, TelemetryReader as J, KairosError as K, TemplateSyncer as L, type TrustLevel as M, type N8nWorkflow as N, type OutcomeData as O, ProviderError as P, type ValidationIssue as Q, ResponseParseError as R, type ScoredEntry as S, type Tag as T, type ValidationResult as U, ValidationError as V, type WorkflowListItem as W, type WorkflowCluster as X, type WorkflowMatch as Y, type WorkflowMetadataInput as Z, buildSearchCorpus as _, type BuildResult as a, hybridScore as a0, nullLogger as a1, rerank as a2, tokenize as a3, type ExecutionSummary as b, type ExecutionDetail as c, type AttemptMetadata as d, type CredentialRequirement as e, DEFAULT_REGISTRY as f, type DeployResult as g, FileLibrary as h, GuardError as i, type IProvider as j, type IWorkflowLibrary as k, N8nApiClient as l, type N8nConnections as m, N8nFieldStripper as n, type N8nNode as o, N8nProvider as p, type N8nSettings as q, N8nValidator as r, NodeRegistry as s, NullLibrary as t, type OutcomeStats as u, type RuleFailureRate as v, type SourceKind as w, type StoredWorkflow as x, type SyncProgress as y, TelemetryCollector as z };