@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.
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  ![Kairos SDK Demo](demo.gif)
10
10
 
11
- Kairos turns plain-English workflow descriptions into validated, deployable n8n workflow JSON. Use it as an **MCP server** (connect to Claude Code, Claude Desktop, or any MCP host — your LLM generates, Kairos validates and deploys, no Anthropic API key needed) or as a **TypeScript SDK** for programmatic control (calls Claude internally with a specialized prompt). Either way, workflows pass through a **23-rule structural validator** with automatic correction, and a local workflow library with **hybrid retrieval** (TF-IDF + node fingerprinting + outcome history + cluster reranking) injects past failure patterns into future generations. With a seeded template library, Kairos achieves **100% first-try structural validation pass rate** across 20 benchmark prompts (meaning the generated JSON is structurally valid on the first attempt — runtime behavior depends on your credentials and node configuration).
11
+ Kairos turns plain-English workflow descriptions into validated, deployable n8n workflow JSON. Use it as an **MCP server** (connect to Claude Code, Claude Desktop, or any MCP host — your LLM generates, Kairos validates and deploys, no Anthropic API key needed) or as a **TypeScript SDK** for programmatic control (calls Claude internally with a specialized prompt). Either way, workflows pass through a **34-rule structural validator** with automatic correction, and a local workflow library with **hybrid retrieval** (TF-IDF + node fingerprinting + outcome history + cluster reranking) injects past failure patterns into future generations. With a seeded template library, Kairos achieves **100% first-try structural validation pass rate** across 20 benchmark prompts (meaning the generated JSON is structurally valid on the first attempt — runtime behavior depends on your credentials and node configuration).
12
12
 
13
13
  ```ts
14
14
  import { Kairos } from '@kairos-sdk/core'
@@ -32,7 +32,7 @@ console.log(result.credentialsNeeded) // what the user still needs to configure
32
32
  | Kairos does | Kairos does not guarantee (yet) |
33
33
  |---|---|
34
34
  | Generates valid n8n workflow JSON | Perfect business logic |
35
- | Validates structure before deploy (23 rules) | Correct credentials |
35
+ | Validates structure before deploy (34 rules) | Correct credentials |
36
36
  | Syncs node types from your live instance | Runtime success for every API |
37
37
  | Learns from prior successful builds | That every workflow matches intent perfectly |
38
38
  | Works through MCP, SDK, or CLI | Full replacement for human review |
@@ -95,7 +95,7 @@ The MCP server does **not** call an LLM internally. Instead, it gives your host
95
95
 
96
96
  1. **Host LLM calls `kairos_prompt`** — gets the n8n system prompt, node catalog, library matches, and failure patterns
97
97
  2. **Host LLM generates the workflow JSON** using that context (no separate API call)
98
- 3. **Host LLM calls `kairos_validate`** — checks the JSON against 23 structural rules
98
+ 3. **Host LLM calls `kairos_validate`** — checks the JSON against 34 structural rules
99
99
  4. If invalid, the host LLM fixes the issues and validates again
100
100
  5. **Host LLM calls `kairos_deploy`** — sends the validated workflow to n8n
101
101
 
@@ -108,7 +108,7 @@ This means Kairos works with **any LLM** — Claude, GPT, Gemini, Llama, or anyt
108
108
  | Tool | Description |
109
109
  |------|-------------|
110
110
  | `kairos_prompt` | Returns the specialized system prompt, node catalog, library matches, and failure patterns for a given description |
111
- | `kairos_validate` | Validates workflow JSON against 23 structural rules — returns errors and warnings |
111
+ | `kairos_validate` | Validates workflow JSON against 34 structural rules — returns errors and warnings |
112
112
  | `kairos_search` | Searches the local workflow library for similar past builds |
113
113
  | `kairos_sync` | Manually refresh the node catalog from your n8n instance (auto-runs on first `kairos_prompt` call) |
114
114
 
@@ -180,7 +180,7 @@ console.log(deployed.workflowId) // now live in n8n
180
180
 
181
181
  ## Benchmark Results
182
182
 
183
- Tested against 20 workflow prompts of varying complexity (simple triggers, multi-step conditional logic, AI agents with memory). Results measure **structural validation pass rate** — whether the generated workflow passes all 23 validator rules, not end-to-end execution correctness.
183
+ Tested against 20 workflow prompts of varying complexity (simple triggers, multi-step conditional logic, AI agents with memory). Results measure **structural validation pass rate** — whether the generated workflow passes all 34 validator rules, not end-to-end execution correctness.
184
184
 
185
185
  ### Before vs After: Template-Seeded Library
186
186
 
@@ -192,7 +192,7 @@ Tested against 20 workflow prompts of varying complexity (simple triggers, multi
192
192
  | Avg generation time | 30.6s | **20.7s** | -32% |
193
193
  | Failures | 0 | 0 | — |
194
194
 
195
- The baseline run used Claude with the 23-rule validator and correction loop but no library. The seeded run used the same validator plus a library of 105 workflows (16 organic + 89 ingested from the n8n community). The broader local development library now contains 286+ generated/ingested workflows. Template seeding eliminated the correction loop entirely and cut generation time by a third.
195
+ The baseline run used Claude with the 34-rule validator and correction loop but no library. The seeded run used the same validator plus a library of 105 workflows (16 organic + 89 ingested from the n8n community). The broader local development library now contains 286+ generated/ingested workflows. Template seeding eliminated the correction loop entirely and cut generation time by a third.
196
196
 
197
197
  > **Note:** These results confirm that generated workflows are structurally valid and deployable to n8n. They do not verify runtime execution correctness, credential configuration, or whether the workflow output matches user intent.
198
198
 
@@ -205,7 +205,7 @@ The baseline run used Claude with the 23-rule validator and correction loop but
205
205
  1. **Search** — Kairos searches its local workflow library for similar past builds. Matching workflows and their failure patterns are pulled into context.
206
206
  2. **Warn** — Known failure patterns (from library matches and global telemetry rates) are injected into the system prompt so Claude avoids repeating known mistakes.
207
207
  3. **Generate** — Your description is sent to Claude with a detailed system prompt, forcing a `generate_workflow` tool call that produces structured n8n workflow JSON.
208
- 4. **Validate** — The workflow is checked against **23 structural rules** covering node IDs, types, versions, names, positions, connections, forbidden fields, trigger presence, AI connection direction, cycle detection, webhook pairing, and required parameters.
208
+ 4. **Validate** — The workflow is checked against **34 structural rules** covering node IDs, types, versions, names, positions, connections, forbidden fields, trigger presence, AI connection direction, cycle detection, webhook pairing, required parameters, and content quality (placeholder URLs, empty code nodes, missing required fields for Slack/Gmail/IF/Set/Schedule/Webhook nodes).
209
209
  5. **Correct** — If validation fails, the specific rule violations are sent back to Claude for correction (up to 3 attempts, with tighter temperature on the final try).
210
210
  6. **Strip** — Forbidden server-assigned fields (`id`, `createdAt`, `updatedAt`, etc.) are stripped before deployment.
211
211
  7. **Deploy** — The validated workflow is posted to your n8n instance via REST API.
@@ -215,7 +215,7 @@ The baseline run used Claude with the 23-rule validator and correction loop but
215
215
 
216
216
  1. **Prompt** — Your LLM calls `kairos_prompt`, which searches the library and returns the specialized system prompt, node catalog, library matches, and failure patterns.
217
217
  2. **Generate** — Your LLM generates the workflow JSON itself using that context. No separate API call.
218
- 3. **Validate** — Your LLM calls `kairos_validate`, which checks the JSON against the same 23 structural rules.
218
+ 3. **Validate** — Your LLM calls `kairos_validate`, which checks the JSON against the same 34 structural rules.
219
219
  4. **Correct** — If validation fails, your LLM fixes the issues and calls `kairos_validate` again.
220
220
  5. **Deploy** — Your LLM calls `kairos_deploy`, which strips forbidden fields and posts the workflow to n8n.
221
221
  6. **Record** — The deployed workflow is saved to the local library for future retrieval.
@@ -224,7 +224,7 @@ The baseline run used Claude with the 23-rule validator and correction loop but
224
224
 
225
225
  ## Validator Rules
226
226
 
227
- The 23-rule validator is the core of what makes Kairos reliable. In baseline testing (no library), Claude needed the correction loop 45% of the time. Each rule targets a specific class of error:
227
+ The 34-rule validator is the core of what makes Kairos reliable. In baseline testing (no library), Claude needed the correction loop 45% of the time. Each rule targets a specific class of error:
228
228
 
229
229
  | Rule | Severity | What it checks |
230
230
  |------|----------|----------------|
@@ -251,6 +251,17 @@ The 23-rule validator is the core of what makes Kairos reliable. In baseline tes
251
251
  | 21 | warn | Webhook with responseMode="responseNode" has respondToWebhook |
252
252
  | 22 | warn | Required parameters present for known node types |
253
253
  | 23 | warn | Node type is recognized in the registry (unknown types may not exist in n8n) |
254
+ | 24 | warn | No deprecated `$node["..."]` accessor syntax in expressions |
255
+ | 25 | warn | No `$json.items[n]` array access (n8n flattens items automatically) |
256
+ | 26 | warn | Node references use `.first()` or `.all()` (bare `$('Node').json` throws at runtime) |
257
+ | 27 | warn | HTTP Request URLs are real endpoints (not `example.com` or `YOUR_URL` placeholders) |
258
+ | 28 | warn | Code nodes contain actual executable logic (not empty or comment-only) |
259
+ | 29 | warn | Slack message operations specify a channel (`channelId` with `__rl` object, or `channel`) |
260
+ | 30 | warn | Gmail send operations specify at least one recipient (`to` field non-empty) |
261
+ | 31 | warn | IF nodes have at least one condition in `conditions.conditions` |
262
+ | 32 | warn | Set nodes have at least one field assignment in `assignments.assignments` (typeVersion 3.x) |
263
+ | 33 | warn | Schedule triggers have at least one rule in `rule.interval` |
264
+ | 34 | warn | Webhook paths are relative — no spaces, no leading slash, no protocol prefix |
254
265
 
255
266
  Errors block deployment. Warnings are recorded and fed back into the prompt for future builds.
256
267
 
@@ -389,7 +400,7 @@ try {
389
400
  |---|---|
390
401
  | `GenerationError` | Anthropic API call failed |
391
402
  | `ResponseParseError` | Claude responded but produced no usable tool call |
392
- | `ValidationError` | Workflow failed 23-rule validation after max retries (carries `.attemptMetadata` and `.warnedRules`) |
403
+ | `ValidationError` | Workflow failed 34-rule validation after max retries (carries `.attemptMetadata` and `.warnedRules`) |
393
404
  | `ProviderError` | Network/auth failure talking to n8n |
394
405
  | `ApiError` | n8n returned a 4xx or 5xx (carries `.statusCode`) |
395
406
  | `GuardError` | Input validation failed (empty description) or `delete()` called without `{ confirm: true }` |
@@ -0,0 +1,411 @@
1
+ import {
2
+ GuardError,
3
+ KairosError,
4
+ N8nValidator,
5
+ ProviderError,
6
+ generateUUID
7
+ } from "./chunk-KIFT5LA7.js";
8
+
9
+ // src/library/null-library.ts
10
+ var NullLibrary = class {
11
+ async initialize() {
12
+ }
13
+ async search(_description, _options) {
14
+ return [];
15
+ }
16
+ async save(_workflow, _metadata) {
17
+ return generateUUID();
18
+ }
19
+ async recordDeployment(_id) {
20
+ }
21
+ async recordOutcome(_id, _outcome) {
22
+ }
23
+ async get(_id) {
24
+ return null;
25
+ }
26
+ async list(_filters) {
27
+ return [];
28
+ }
29
+ };
30
+
31
+ // src/providers/n8n/provider.ts
32
+ var SMOKE_TEST_TIMEOUT_MS = 3e4;
33
+ var SMOKE_TEST_POLL_INTERVAL_MS = 1e3;
34
+ var N8nProvider = class {
35
+ constructor(client, stripper) {
36
+ this.client = client;
37
+ this.stripper = stripper;
38
+ }
39
+ client;
40
+ stripper;
41
+ platform = "n8n";
42
+ async deploy(workflow) {
43
+ const stripped = this.stripper.stripForCreate(workflow);
44
+ const response = await this.client.createWorkflow(stripped);
45
+ return { workflowId: response.id, name: response.name };
46
+ }
47
+ async update(id, workflow) {
48
+ const stripped = this.stripper.stripForUpdate(workflow);
49
+ const response = await this.client.updateWorkflow(id, stripped);
50
+ return { workflowId: response.id, name: response.name };
51
+ }
52
+ async get(id) {
53
+ const response = await this.client.getWorkflow(id);
54
+ return {
55
+ name: response.name,
56
+ nodes: response.nodes,
57
+ connections: response.connections,
58
+ ...response.settings !== void 0 ? { settings: response.settings } : {},
59
+ ...response.tags !== void 0 ? { tags: response.tags } : {}
60
+ };
61
+ }
62
+ async list() {
63
+ return this.client.listWorkflows();
64
+ }
65
+ async activate(id) {
66
+ await this.client.activateWorkflow(id);
67
+ }
68
+ async deactivate(id) {
69
+ await this.client.deactivateWorkflow(id);
70
+ }
71
+ async delete(id, options) {
72
+ if (options.confirm !== true) {
73
+ throw new GuardError("delete() requires { confirm: true } to prevent accidental deletion");
74
+ }
75
+ await this.client.deleteWorkflow(id);
76
+ }
77
+ async executions(workflowId, filter) {
78
+ return this.client.getExecutions(workflowId, filter);
79
+ }
80
+ async execution(id) {
81
+ return this.client.getExecution(id);
82
+ }
83
+ async listTags() {
84
+ return this.client.listTags();
85
+ }
86
+ async createTag(name) {
87
+ return this.client.createTag(name);
88
+ }
89
+ async tag(workflowId, tagIds) {
90
+ await this.client.tagWorkflow(workflowId, tagIds);
91
+ }
92
+ async untag(workflowId, tagIds) {
93
+ await this.client.untagWorkflow(workflowId, tagIds);
94
+ }
95
+ async smokeTest(workflowId, workflow) {
96
+ const start = Date.now();
97
+ const trigger = this.detectTrigger(workflow);
98
+ if (trigger.type === "unsupported") {
99
+ return { status: "not-applicable", triggerType: "not-applicable" };
100
+ }
101
+ if (trigger.type === "manual") {
102
+ let executionId;
103
+ try {
104
+ executionId = await this.client.triggerManual(workflowId);
105
+ } catch (err) {
106
+ return { status: "error", triggerType: "manual", durationMs: Date.now() - start, error: String(err) };
107
+ }
108
+ try {
109
+ const execution = await this.pollExecution(executionId);
110
+ const durationMs = Date.now() - start;
111
+ if (execution.status === "success") {
112
+ return { status: "passed", triggerType: "manual", executionId, durationMs };
113
+ }
114
+ return {
115
+ status: "failed",
116
+ triggerType: "manual",
117
+ executionId,
118
+ durationMs,
119
+ error: `Execution ended with status: ${execution.status}`
120
+ };
121
+ } catch (err) {
122
+ return { status: "error", triggerType: "manual", executionId, durationMs: Date.now() - start, error: String(err) };
123
+ }
124
+ }
125
+ try {
126
+ const statusCode = await this.client.triggerWebhookTest(trigger.path);
127
+ const durationMs = Date.now() - start;
128
+ if (statusCode >= 200 && statusCode < 300) {
129
+ return { status: "passed", triggerType: "webhook", durationMs };
130
+ }
131
+ return { status: "failed", triggerType: "webhook", durationMs, error: `Webhook returned HTTP ${statusCode}` };
132
+ } catch (err) {
133
+ return { status: "error", triggerType: "webhook", durationMs: Date.now() - start, error: String(err) };
134
+ }
135
+ }
136
+ detectTrigger(workflow) {
137
+ for (const node of workflow.nodes) {
138
+ if (node.type === "n8n-nodes-base.manualTrigger") return { type: "manual" };
139
+ if (node.type === "n8n-nodes-base.webhook") {
140
+ const params = node.parameters;
141
+ const path = typeof params?.["path"] === "string" ? params["path"] : "webhook";
142
+ return { type: "webhook", path };
143
+ }
144
+ }
145
+ return { type: "unsupported" };
146
+ }
147
+ async pollExecution(executionId) {
148
+ const deadline = Date.now() + SMOKE_TEST_TIMEOUT_MS;
149
+ for (; ; ) {
150
+ const execution = await this.client.getExecution(executionId);
151
+ if (execution.status !== "running" && execution.status !== "waiting") {
152
+ return execution;
153
+ }
154
+ const remaining = deadline - Date.now();
155
+ if (remaining <= 0) break;
156
+ await new Promise((resolve) => setTimeout(resolve, Math.min(SMOKE_TEST_POLL_INTERVAL_MS, remaining)));
157
+ }
158
+ throw new ProviderError(`Smoke test: execution ${executionId} did not complete within ${SMOKE_TEST_TIMEOUT_MS}ms`);
159
+ }
160
+ };
161
+
162
+ // src/errors/generation-error.ts
163
+ var GenerationError = class extends KairosError {
164
+ constructor(message, cause) {
165
+ super(message, cause);
166
+ this.name = "GenerationError";
167
+ }
168
+ };
169
+
170
+ // src/errors/response-parse-error.ts
171
+ var ResponseParseError = class extends KairosError {
172
+ constructor(message, cause) {
173
+ super(message, cause);
174
+ this.name = "ResponseParseError";
175
+ }
176
+ };
177
+
178
+ // src/errors/validation-error.ts
179
+ var ValidationError = class extends KairosError {
180
+ constructor(message, issues, attemptMetadata, warnedRules) {
181
+ super(message);
182
+ this.issues = issues;
183
+ this.attemptMetadata = attemptMetadata;
184
+ this.warnedRules = warnedRules;
185
+ this.name = "ValidationError";
186
+ }
187
+ issues;
188
+ attemptMetadata;
189
+ warnedRules;
190
+ };
191
+
192
+ // src/templates/safety.ts
193
+ var BLOCKED_NODE_TYPES = /* @__PURE__ */ new Set([
194
+ "n8n-nodes-base.code",
195
+ "n8n-nodes-base.executeCommand",
196
+ "n8n-nodes-base.ssh"
197
+ ]);
198
+ var REVIEW_NODE_TYPES = /* @__PURE__ */ new Set([
199
+ "n8n-nodes-base.httpRequest"
200
+ ]);
201
+ var SECRET_PATTERNS = [
202
+ /sk-[a-zA-Z0-9]{20,}/,
203
+ /ghp_[a-zA-Z0-9]{36}/,
204
+ /xoxb-[0-9]+-[0-9]+-[a-zA-Z0-9]+/,
205
+ /AIza[a-zA-Z0-9_-]{35}/,
206
+ /AKIA[A-Z0-9]{16}/
207
+ ];
208
+ var SECRET_PREFIXES = ["sk-", "ghp_", "xoxb-", "AIza", "AKIA"];
209
+ function collectExpressionStrings(obj, out = []) {
210
+ if (typeof obj === "string") {
211
+ if (obj.includes("={{")) out.push(obj);
212
+ } else if (Array.isArray(obj)) {
213
+ for (const item of obj) collectExpressionStrings(item, out);
214
+ } else if (obj !== null && typeof obj === "object") {
215
+ for (const val of Object.values(obj)) {
216
+ collectExpressionStrings(val, out);
217
+ }
218
+ }
219
+ return out;
220
+ }
221
+ function assessTemplateSafety(workflow) {
222
+ const reasons = [];
223
+ let worst = "safe";
224
+ const escalate = (level, reason) => {
225
+ reasons.push(reason);
226
+ if (level === "blocked") worst = "blocked";
227
+ else if (level === "review" && worst === "safe") worst = "review";
228
+ };
229
+ for (const node of workflow.nodes) {
230
+ if (BLOCKED_NODE_TYPES.has(node.type)) {
231
+ escalate("blocked", `Contains ${node.type} node "${node.name}"`);
232
+ }
233
+ if (REVIEW_NODE_TYPES.has(node.type)) {
234
+ escalate("review", `Contains ${node.type} node "${node.name}"`);
235
+ }
236
+ const paramStr = JSON.stringify(node.parameters);
237
+ for (const pattern of SECRET_PATTERNS) {
238
+ if (pattern.test(paramStr)) {
239
+ escalate("blocked", `Node "${node.name}" parameters contain a hardcoded secret`);
240
+ break;
241
+ }
242
+ }
243
+ const expressions = collectExpressionStrings(node.parameters);
244
+ for (const expr of expressions) {
245
+ for (const prefix of SECRET_PREFIXES) {
246
+ if (expr.includes(prefix)) {
247
+ escalate("review", `Node "${node.name}" has an expression containing credential-like prefix "${prefix}"`);
248
+ break;
249
+ }
250
+ }
251
+ }
252
+ }
253
+ return { trustLevel: worst, reasons };
254
+ }
255
+
256
+ // src/templates/syncer.ts
257
+ var N8N_TEMPLATE_API = "https://api.n8n.io/api/templates";
258
+ var PAGE_SIZE = 50;
259
+ var DELAY_BETWEEN_FETCHES_MS = 200;
260
+ var DEFAULT_SETTINGS = {
261
+ executionOrder: "v1",
262
+ saveManualExecutions: true,
263
+ timezone: "UTC"
264
+ };
265
+ var TemplateSyncer = class {
266
+ constructor(library, logger) {
267
+ this.library = library;
268
+ this.validator = new N8nValidator();
269
+ this.logger = logger;
270
+ }
271
+ library;
272
+ validator;
273
+ logger;
274
+ async sync(options) {
275
+ const maxTemplates = options?.maxTemplates ?? 500;
276
+ await this.library.initialize();
277
+ const existing = await this.library.list();
278
+ const existingSourceIds = new Set(
279
+ existing.filter((w) => w.sourceKind === "n8n-template" && w.sourceId).map((w) => w.sourceId)
280
+ );
281
+ const progress = {
282
+ total: 0,
283
+ processed: 0,
284
+ saved: 0,
285
+ skippedPaid: 0,
286
+ skippedDuplicate: 0,
287
+ blocked: 0,
288
+ reviewed: 0
289
+ };
290
+ const templateIds = await this.fetchTemplateIds(maxTemplates, progress);
291
+ for (const id of templateIds) {
292
+ if (existingSourceIds.has(String(id))) {
293
+ progress.skippedDuplicate++;
294
+ progress.processed++;
295
+ options?.onProgress?.(progress);
296
+ continue;
297
+ }
298
+ try {
299
+ await this.processTemplate(id, progress);
300
+ } catch (err) {
301
+ this.logger.warn(`Failed to process template ${id}`, { err: String(err) });
302
+ }
303
+ progress.processed++;
304
+ options?.onProgress?.(progress);
305
+ await new Promise((resolve) => setTimeout(resolve, DELAY_BETWEEN_FETCHES_MS));
306
+ }
307
+ return progress;
308
+ }
309
+ async fetchWithBackoff(url, maxRetries = 3) {
310
+ let delayMs = DELAY_BETWEEN_FETCHES_MS;
311
+ let lastResponse;
312
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
313
+ lastResponse = await fetch(url);
314
+ if (lastResponse.status !== 429 && lastResponse.status !== 503) return lastResponse;
315
+ if (attempt === maxRetries) break;
316
+ const retryAfterHeader = lastResponse.headers.get("Retry-After");
317
+ const waitMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1e3 : delayMs * Math.pow(2, attempt);
318
+ this.logger.warn(`HTTP ${lastResponse.status} from template API, retrying in ${waitMs}ms`, { url, attempt });
319
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
320
+ }
321
+ return lastResponse;
322
+ }
323
+ async fetchTemplateIds(max, progress) {
324
+ const ids = [];
325
+ let page = 1;
326
+ while (ids.length < max) {
327
+ const url = `${N8N_TEMPLATE_API}/search?page=${page}&rows=${PAGE_SIZE}`;
328
+ const response = await this.fetchWithBackoff(url);
329
+ if (!response.ok) break;
330
+ const data = await response.json();
331
+ progress.total = Math.min(data.totalWorkflows, max);
332
+ for (const template of data.workflows) {
333
+ if (ids.length >= max) break;
334
+ if (template.price && template.price > 0) {
335
+ progress.skippedPaid++;
336
+ continue;
337
+ }
338
+ ids.push(template.id);
339
+ }
340
+ if (data.workflows.length < PAGE_SIZE) break;
341
+ page++;
342
+ await new Promise((resolve) => setTimeout(resolve, DELAY_BETWEEN_FETCHES_MS));
343
+ }
344
+ return ids;
345
+ }
346
+ async processTemplate(id, progress) {
347
+ const url = `${N8N_TEMPLATE_API}/workflows/${id}`;
348
+ const response = await this.fetchWithBackoff(url);
349
+ if (!response.ok) return;
350
+ const data = await response.json();
351
+ const templateMeta = data.workflow;
352
+ const rawWorkflow = templateMeta.workflow;
353
+ if (!rawWorkflow?.nodes?.length) return;
354
+ const workflow = {
355
+ name: templateMeta.name,
356
+ nodes: rawWorkflow.nodes.filter((n) => n.type && n.name),
357
+ connections: rawWorkflow.connections,
358
+ settings: rawWorkflow.settings ? { executionOrder: "v1", ...rawWorkflow.settings } : { ...DEFAULT_SETTINGS }
359
+ };
360
+ const validation = this.validator.validate(workflow);
361
+ const validationErrors = validation.issues.filter((i) => i.severity === "error");
362
+ if (validationErrors.length > 0) {
363
+ progress.blocked++;
364
+ this.logger.debug(`Template ${id} blocked: ${validationErrors.length} validation errors`);
365
+ return;
366
+ }
367
+ const safety = assessTemplateSafety(workflow);
368
+ if (safety.trustLevel === "blocked") {
369
+ progress.blocked++;
370
+ this.logger.debug(`Template ${id} blocked: ${safety.reasons.join(", ")}`);
371
+ return;
372
+ }
373
+ if (safety.trustLevel === "review") {
374
+ progress.reviewed++;
375
+ }
376
+ const description = this.cleanDescription(templateMeta.description);
377
+ const autoTags = Array.from(new Set(
378
+ workflow.nodes.flatMap((n) => {
379
+ const bare = n.type.split(".").pop() ?? "";
380
+ const tags = [bare];
381
+ if (n.type.includes("Trigger") || n.type.includes("trigger")) tags.push(`trigger:${bare}`);
382
+ if (n.type.includes("langchain")) tags.push("ai");
383
+ return tags;
384
+ })
385
+ ));
386
+ const metadata = {
387
+ description,
388
+ tags: autoTags,
389
+ sourceKind: "n8n-template",
390
+ sourceId: String(id),
391
+ sourceUrl: `https://n8n.io/workflows/${id}`,
392
+ trustLevel: safety.trustLevel
393
+ };
394
+ await this.library.save(workflow, metadata);
395
+ progress.saved++;
396
+ this.logger.debug(`Template ${id} saved: "${templateMeta.name}" (${safety.trustLevel})`);
397
+ }
398
+ cleanDescription(raw) {
399
+ return raw.replace(/#{1,6}\s*/g, "").replace(/\*{1,2}([^*]+)\*{1,2}/g, "$1").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/\n{3,}/g, "\n\n").trim().slice(0, 500);
400
+ }
401
+ };
402
+
403
+ export {
404
+ NullLibrary,
405
+ N8nProvider,
406
+ GenerationError,
407
+ ResponseParseError,
408
+ ValidationError,
409
+ TemplateSyncer
410
+ };
411
+ //# sourceMappingURL=chunk-5GAY7CSJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/library/null-library.ts","../src/providers/n8n/provider.ts","../src/errors/generation-error.ts","../src/errors/response-parse-error.ts","../src/errors/validation-error.ts","../src/templates/safety.ts","../src/templates/syncer.ts"],"sourcesContent":["import type { IWorkflowLibrary, WorkflowMatch, StoredWorkflow, WorkflowMetadataInput, LibraryFilters, SearchOptions, OutcomeData } from './types.js'\nimport type { N8nWorkflow } from '../types/workflow.js'\nimport { generateUUID } from '../utils/uuid.js'\n\nexport class NullLibrary implements IWorkflowLibrary {\n async initialize(): Promise<void> {}\n\n async search(_description: string, _options?: SearchOptions): Promise<WorkflowMatch[]> {\n return []\n }\n\n async save(_workflow: N8nWorkflow, _metadata: WorkflowMetadataInput): Promise<string> {\n return generateUUID()\n }\n\n async recordDeployment(_id: string): Promise<void> {}\n\n async recordOutcome(_id: string, _outcome: OutcomeData): Promise<void> {}\n\n async get(_id: string): Promise<StoredWorkflow | null> {\n return null\n }\n\n async list(_filters?: LibraryFilters): Promise<StoredWorkflow[]> {\n return []\n }\n}\n","import type { N8nWorkflow, Tag } from '../../types/workflow.js'\nimport type { DeployResult, WorkflowListItem, ExecutionSummary, ExecutionDetail, SmokeTestResult } from '../../types/result.js'\nimport type { DeleteOptions, ExecutionFilter } from '../../types/options.js'\nimport type { IProvider } from '../types.js'\nimport { GuardError } from '../../errors/guard-error.js'\nimport { ProviderError } from '../../errors/provider-error.js'\nimport { N8nApiClient } from './api-client.js'\nimport { N8nFieldStripper } from './stripper.js'\n\nconst SMOKE_TEST_TIMEOUT_MS = 30_000\nconst SMOKE_TEST_POLL_INTERVAL_MS = 1_000\n\ntype TriggerInfo =\n | { type: 'manual' }\n | { type: 'webhook'; path: string }\n | { type: 'unsupported' }\n\nexport class N8nProvider implements IProvider {\n readonly platform = 'n8n'\n\n constructor(\n private readonly client: N8nApiClient,\n private readonly stripper: N8nFieldStripper,\n ) {}\n\n async deploy(workflow: N8nWorkflow): Promise<DeployResult> {\n const stripped = this.stripper.stripForCreate(workflow)\n const response = await this.client.createWorkflow(stripped)\n return { workflowId: response.id, name: response.name }\n }\n\n async update(id: string, workflow: N8nWorkflow): Promise<DeployResult> {\n const stripped = this.stripper.stripForUpdate(workflow)\n const response = await this.client.updateWorkflow(id, stripped)\n return { workflowId: response.id, name: response.name }\n }\n\n async get(id: string): Promise<N8nWorkflow> {\n const response = await this.client.getWorkflow(id)\n return {\n name: response.name,\n nodes: response.nodes,\n connections: response.connections,\n ...(response.settings !== undefined ? { settings: response.settings } : {}),\n ...(response.tags !== undefined ? { tags: response.tags } : {}),\n }\n }\n\n async list(): Promise<WorkflowListItem[]> {\n return this.client.listWorkflows()\n }\n\n async activate(id: string): Promise<void> {\n await this.client.activateWorkflow(id)\n }\n\n async deactivate(id: string): Promise<void> {\n await this.client.deactivateWorkflow(id)\n }\n\n async delete(id: string, options: DeleteOptions): Promise<void> {\n if (options.confirm !== true) {\n throw new GuardError('delete() requires { confirm: true } to prevent accidental deletion')\n }\n await this.client.deleteWorkflow(id)\n }\n\n async executions(workflowId?: string, filter?: ExecutionFilter): Promise<ExecutionSummary[]> {\n return this.client.getExecutions(workflowId, filter)\n }\n\n async execution(id: string): Promise<ExecutionDetail> {\n return this.client.getExecution(id)\n }\n\n async listTags(): Promise<Tag[]> {\n return this.client.listTags()\n }\n\n async createTag(name: string): Promise<Tag> {\n return this.client.createTag(name)\n }\n\n async tag(workflowId: string, tagIds: string[]): Promise<void> {\n await this.client.tagWorkflow(workflowId, tagIds)\n }\n\n async untag(workflowId: string, tagIds: string[]): Promise<void> {\n await this.client.untagWorkflow(workflowId, tagIds)\n }\n\n async smokeTest(workflowId: string, workflow: N8nWorkflow): Promise<SmokeTestResult> {\n const start = Date.now()\n const trigger = this.detectTrigger(workflow)\n\n if (trigger.type === 'unsupported') {\n return { status: 'not-applicable', triggerType: 'not-applicable' }\n }\n\n if (trigger.type === 'manual') {\n let executionId: string\n try {\n executionId = await this.client.triggerManual(workflowId)\n } catch (err) {\n return { status: 'error', triggerType: 'manual', durationMs: Date.now() - start, error: String(err) }\n }\n try {\n const execution = await this.pollExecution(executionId)\n const durationMs = Date.now() - start\n if (execution.status === 'success') {\n return { status: 'passed', triggerType: 'manual', executionId, durationMs }\n }\n return {\n status: 'failed',\n triggerType: 'manual',\n executionId,\n durationMs,\n error: `Execution ended with status: ${execution.status}`,\n }\n } catch (err) {\n return { status: 'error', triggerType: 'manual', executionId, durationMs: Date.now() - start, error: String(err) }\n }\n }\n\n // webhook\n try {\n const statusCode = await this.client.triggerWebhookTest(trigger.path)\n const durationMs = Date.now() - start\n if (statusCode >= 200 && statusCode < 300) {\n return { status: 'passed', triggerType: 'webhook', durationMs }\n }\n return { status: 'failed', triggerType: 'webhook', durationMs, error: `Webhook returned HTTP ${statusCode}` }\n } catch (err) {\n return { status: 'error', triggerType: 'webhook', durationMs: Date.now() - start, error: String(err) }\n }\n }\n\n private detectTrigger(workflow: N8nWorkflow): TriggerInfo {\n for (const node of workflow.nodes) {\n if (node.type === 'n8n-nodes-base.manualTrigger') return { type: 'manual' }\n if (node.type === 'n8n-nodes-base.webhook') {\n const params = node.parameters as Record<string, unknown> | undefined\n const path = typeof params?.['path'] === 'string' ? params['path'] : 'webhook'\n return { type: 'webhook', path }\n }\n }\n return { type: 'unsupported' }\n }\n\n private async pollExecution(executionId: string): Promise<ExecutionDetail> {\n const deadline = Date.now() + SMOKE_TEST_TIMEOUT_MS\n for (;;) {\n const execution = await this.client.getExecution(executionId)\n if (execution.status !== 'running' && execution.status !== 'waiting') {\n return execution\n }\n const remaining = deadline - Date.now()\n if (remaining <= 0) break\n await new Promise<void>((resolve) => setTimeout(resolve, Math.min(SMOKE_TEST_POLL_INTERVAL_MS, remaining)))\n }\n throw new ProviderError(`Smoke test: execution ${executionId} did not complete within ${SMOKE_TEST_TIMEOUT_MS}ms`)\n }\n}\n","import { KairosError } from './base.js'\n\nexport class GenerationError extends KairosError {\n constructor(message: string, cause?: unknown) {\n super(message, cause)\n this.name = 'GenerationError'\n }\n}\n","import { KairosError } from './base.js'\n\nexport class ResponseParseError extends KairosError {\n constructor(message: string, cause?: unknown) {\n super(message, cause)\n this.name = 'ResponseParseError'\n }\n}\n","import { KairosError } from './base.js'\nimport type { ValidationIssue } from '../validation/types.js'\nimport type { AttemptMetadata } from '../telemetry/types.js'\n\nexport type { ValidationIssue }\n\nexport class ValidationError extends KairosError {\n constructor(\n message: string,\n public readonly issues: ValidationIssue[],\n public readonly attemptMetadata?: AttemptMetadata[],\n public readonly warnedRules?: number[],\n ) {\n super(message)\n this.name = 'ValidationError'\n }\n}\n","import type { TrustLevel } from '../library/types.js'\nimport type { N8nWorkflow } from '../types/workflow.js'\n\ninterface SafetyResult {\n trustLevel: TrustLevel\n reasons: string[]\n}\n\nconst BLOCKED_NODE_TYPES = new Set([\n 'n8n-nodes-base.code',\n 'n8n-nodes-base.executeCommand',\n 'n8n-nodes-base.ssh',\n])\n\nconst REVIEW_NODE_TYPES = new Set([\n 'n8n-nodes-base.httpRequest',\n])\n\nconst SECRET_PATTERNS = [\n /sk-[a-zA-Z0-9]{20,}/,\n /ghp_[a-zA-Z0-9]{36}/,\n /xoxb-[0-9]+-[0-9]+-[a-zA-Z0-9]+/,\n /AIza[a-zA-Z0-9_-]{35}/,\n /AKIA[A-Z0-9]{16}/,\n]\n\n// Looser prefixes for scanning inside expressions where the full token may be split\n// across string concatenation (e.g. \"ghp_\" + \"sometoken...\"). We flag any expression\n// containing one of these high-signal prefixes for human review.\nconst SECRET_PREFIXES = ['sk-', 'ghp_', 'xoxb-', 'AIza', 'AKIA']\n\nfunction collectExpressionStrings(obj: unknown, out: string[] = []): string[] {\n if (typeof obj === 'string') {\n if (obj.includes('={{')) out.push(obj)\n } else if (Array.isArray(obj)) {\n for (const item of obj) collectExpressionStrings(item, out)\n } else if (obj !== null && typeof obj === 'object') {\n for (const val of Object.values(obj as Record<string, unknown>)) {\n collectExpressionStrings(val, out)\n }\n }\n return out\n}\n\nexport function assessTemplateSafety(workflow: N8nWorkflow): SafetyResult {\n const reasons: string[] = []\n let worst: TrustLevel = 'safe'\n\n const escalate = (level: TrustLevel, reason: string) => {\n reasons.push(reason)\n if (level === 'blocked') worst = 'blocked'\n else if (level === 'review' && worst === 'safe') worst = 'review'\n }\n\n for (const node of workflow.nodes) {\n if (BLOCKED_NODE_TYPES.has(node.type)) {\n escalate('blocked', `Contains ${node.type} node \"${node.name}\"`)\n }\n\n if (REVIEW_NODE_TYPES.has(node.type)) {\n escalate('review', `Contains ${node.type} node \"${node.name}\"`)\n }\n\n // Scan serialized parameters for literal secrets\n const paramStr = JSON.stringify(node.parameters)\n for (const pattern of SECRET_PATTERNS) {\n if (pattern.test(paramStr)) {\n escalate('blocked', `Node \"${node.name}\" parameters contain a hardcoded secret`)\n break\n }\n }\n\n // Scan expression strings for split/concatenated secret prefixes\n // e.g. ={{ \"ghp_\" + variable }} won't match the full regex but the prefix is a red flag\n const expressions = collectExpressionStrings(node.parameters)\n for (const expr of expressions) {\n for (const prefix of SECRET_PREFIXES) {\n if (expr.includes(prefix)) {\n escalate('review', `Node \"${node.name}\" has an expression containing credential-like prefix \"${prefix}\"`)\n break\n }\n }\n }\n }\n\n return { trustLevel: worst, reasons }\n}\n","import type { IWorkflowLibrary, WorkflowMetadataInput } from '../library/types.js'\nimport type { N8nWorkflow, N8nNode } from '../types/workflow.js'\nimport type { ILogger } from '../utils/logger.js'\nimport type { TemplateSearchResponse, TemplateDetailResponse, SyncProgress } from './types.js'\nimport { N8nValidator } from '../validation/validator.js'\nimport { assessTemplateSafety } from './safety.js'\n\nconst N8N_TEMPLATE_API = 'https://api.n8n.io/api/templates'\nconst PAGE_SIZE = 50\nconst DELAY_BETWEEN_FETCHES_MS = 200\n\nconst DEFAULT_SETTINGS: N8nWorkflow['settings'] = {\n executionOrder: 'v1',\n saveManualExecutions: true,\n timezone: 'UTC',\n}\n\nexport interface SyncOptions {\n maxTemplates?: number\n onProgress?: (progress: SyncProgress) => void\n}\n\nexport class TemplateSyncer {\n private readonly validator: N8nValidator\n private readonly logger: ILogger\n\n constructor(\n private readonly library: IWorkflowLibrary,\n logger: ILogger,\n ) {\n this.validator = new N8nValidator()\n this.logger = logger\n }\n\n async sync(options?: SyncOptions): Promise<SyncProgress> {\n const maxTemplates = options?.maxTemplates ?? 500\n\n await this.library.initialize()\n\n const existing = await this.library.list()\n const existingSourceIds = new Set(\n existing\n .filter((w) => w.sourceKind === 'n8n-template' && w.sourceId)\n .map((w) => w.sourceId!),\n )\n\n const progress: SyncProgress = {\n total: 0,\n processed: 0,\n saved: 0,\n skippedPaid: 0,\n skippedDuplicate: 0,\n blocked: 0,\n reviewed: 0,\n }\n\n const templateIds = await this.fetchTemplateIds(maxTemplates, progress)\n\n for (const id of templateIds) {\n if (existingSourceIds.has(String(id))) {\n progress.skippedDuplicate++\n progress.processed++\n options?.onProgress?.(progress)\n continue\n }\n\n try {\n await this.processTemplate(id, progress)\n } catch (err) {\n this.logger.warn(`Failed to process template ${id}`, { err: String(err) })\n }\n\n progress.processed++\n options?.onProgress?.(progress)\n\n await new Promise((resolve) => setTimeout(resolve, DELAY_BETWEEN_FETCHES_MS))\n }\n\n return progress\n }\n\n private async fetchWithBackoff(url: string, maxRetries = 3): Promise<Response> {\n let delayMs = DELAY_BETWEEN_FETCHES_MS\n let lastResponse!: Response\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n lastResponse = await fetch(url)\n if (lastResponse.status !== 429 && lastResponse.status !== 503) return lastResponse\n if (attempt === maxRetries) break\n const retryAfterHeader = lastResponse.headers.get('Retry-After')\n const waitMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1000 : delayMs * Math.pow(2, attempt)\n this.logger.warn(`HTTP ${lastResponse.status} from template API, retrying in ${waitMs}ms`, { url, attempt })\n await new Promise((resolve) => setTimeout(resolve, waitMs))\n }\n return lastResponse\n }\n\n private async fetchTemplateIds(max: number, progress: SyncProgress): Promise<number[]> {\n const ids: number[] = []\n let page = 1\n\n while (ids.length < max) {\n const url = `${N8N_TEMPLATE_API}/search?page=${page}&rows=${PAGE_SIZE}`\n const response = await this.fetchWithBackoff(url)\n if (!response.ok) break\n\n const data = (await response.json()) as TemplateSearchResponse\n progress.total = Math.min(data.totalWorkflows, max)\n\n for (const template of data.workflows) {\n if (ids.length >= max) break\n if (template.price && template.price > 0) {\n progress.skippedPaid++\n continue\n }\n ids.push(template.id)\n }\n\n if (data.workflows.length < PAGE_SIZE) break\n page++\n\n await new Promise((resolve) => setTimeout(resolve, DELAY_BETWEEN_FETCHES_MS))\n }\n\n return ids\n }\n\n private async processTemplate(id: number, progress: SyncProgress): Promise<void> {\n const url = `${N8N_TEMPLATE_API}/workflows/${id}`\n const response = await this.fetchWithBackoff(url)\n if (!response.ok) return\n\n const data = (await response.json()) as TemplateDetailResponse\n const templateMeta = data.workflow\n const rawWorkflow = templateMeta.workflow\n\n if (!rawWorkflow?.nodes?.length) return\n\n const workflow: N8nWorkflow = {\n name: templateMeta.name,\n nodes: rawWorkflow.nodes.filter((n) => n.type && n.name) as N8nNode[],\n connections: rawWorkflow.connections as N8nWorkflow['connections'],\n settings: rawWorkflow.settings\n ? { executionOrder: 'v1' as const, ...rawWorkflow.settings }\n : { ...DEFAULT_SETTINGS },\n }\n\n const validation = this.validator.validate(workflow)\n const validationErrors = validation.issues.filter((i) => i.severity === 'error')\n\n if (validationErrors.length > 0) {\n progress.blocked++\n this.logger.debug(`Template ${id} blocked: ${validationErrors.length} validation errors`)\n return\n }\n\n const safety = assessTemplateSafety(workflow)\n\n if (safety.trustLevel === 'blocked') {\n progress.blocked++\n this.logger.debug(`Template ${id} blocked: ${safety.reasons.join(', ')}`)\n return\n }\n\n if (safety.trustLevel === 'review') {\n progress.reviewed++\n }\n\n const description = this.cleanDescription(templateMeta.description)\n\n const autoTags = Array.from(new Set(\n workflow.nodes.flatMap((n) => {\n const bare = n.type.split('.').pop() ?? ''\n const tags = [bare]\n if (n.type.includes('Trigger') || n.type.includes('trigger')) tags.push(`trigger:${bare}`)\n if (n.type.includes('langchain')) tags.push('ai')\n return tags\n }),\n ))\n\n const metadata: WorkflowMetadataInput = {\n description,\n tags: autoTags,\n sourceKind: 'n8n-template',\n sourceId: String(id),\n sourceUrl: `https://n8n.io/workflows/${id}`,\n trustLevel: safety.trustLevel,\n }\n\n await this.library.save(workflow, metadata)\n progress.saved++\n this.logger.debug(`Template ${id} saved: \"${templateMeta.name}\" (${safety.trustLevel})`)\n }\n\n private cleanDescription(raw: string): string {\n return raw\n .replace(/#{1,6}\\s*/g, '')\n .replace(/\\*{1,2}([^*]+)\\*{1,2}/g, '$1')\n .replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, '$1')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n .slice(0, 500)\n }\n}\n"],"mappings":";;;;;;;;;AAIO,IAAM,cAAN,MAA8C;AAAA,EACnD,MAAM,aAA4B;AAAA,EAAC;AAAA,EAEnC,MAAM,OAAO,cAAsB,UAAoD;AACrF,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAM,KAAK,WAAwB,WAAmD;AACpF,WAAO,aAAa;AAAA,EACtB;AAAA,EAEA,MAAM,iBAAiB,KAA4B;AAAA,EAAC;AAAA,EAEpD,MAAM,cAAc,KAAa,UAAsC;AAAA,EAAC;AAAA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