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