forked from KunAgent/Kun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkflow-runtime.ts
More file actions
2330 lines (2233 loc) · 94.1 KB
/
Copy pathworkflow-runtime.ts
File metadata and controls
2330 lines (2233 loc) · 94.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { spawn } from 'node:child_process'
import { randomBytes, randomUUID } from 'node:crypto'
import { existsSync } from 'node:fs'
import { mkdir, writeFile } from 'node:fs/promises'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
import { isAbsolute, join, resolve } from 'node:path'
import { URL } from 'node:url'
import { compileFunction, runInNewContext } from 'node:vm'
import type {
AppSettingsV1,
WorkflowCodeCheckResult,
WorkflowCodeLanguage,
WorkflowConditionConfigV1,
WorkflowCustomModuleV1,
WorkflowConnectionV1,
WorkflowEnvVarV1,
WorkflowHttpRequestConfigV1,
WorkflowInputFieldV1,
WorkflowApprovalDecision,
WorkflowNodeRunResultV1,
WorkflowNodeTestResult,
WorkflowPendingApprovalV1,
WorkflowNodeRunStatus,
WorkflowNodeV1,
WorkflowRunResult,
WorkflowRunStatus,
WorkflowRunV1,
WorkflowRuntimeStatus,
WorkflowScheduleV1,
WorkflowV1
} from '../shared/app-settings'
import { resolveKunImageGenerationSettings } from '../shared/app-settings'
import { MAX_WORKFLOW_RUNS } from '../shared/app-settings-workflow'
import {
SCHEDULER_INTERVAL_MS,
hasEnabledScheduledTask,
parseJsonObject,
readRequestBody,
resolveScheduleModelConfig,
runPromptViaRuntime,
sleep,
summarizeTaskResult,
writeJson,
type ScheduleRuntimeDeps
} from './schedule-runtime-helpers'
import { resolveCodexOAuthApiKey } from './codex-auth'
const MAX_NODE_EXECUTIONS = 200
const MAX_RUN_DURATION_MS = 30 * 60_000
/** Sentinel branch that matches no output handle (e.g. switch with no rule + no fallback). */
const NO_BRANCH = '__none__'
const AI_NODE_RESPONSE_TIMEOUT_MS = 30 * 60_000
const HTTP_MAX_RESPONSE_BYTES = 5_000_000
const LIVE_STATUS_LINGER_MS = 8_000
type WorkflowPayload = { json: unknown; text: string }
type ScheduleTriggerNode = Extract<WorkflowNodeV1, { type: 'schedule-trigger' }>
type NodeOutcome = {
payload: WorkflowPayload
message: string
/** For condition nodes: which outgoing handle to follow ('true' | 'false'). */
branch?: string
/** For ai-agent nodes: the Kun thread created. */
threadId?: string
}
// ---------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------
function isScheduleTrigger(node: WorkflowNodeV1): node is ScheduleTriggerNode {
return node.type === 'schedule-trigger'
}
function activeScheduleTriggers(workflow: WorkflowV1): ScheduleTriggerNode[] {
return workflow.nodes
.filter(isScheduleTrigger)
.filter((node) => !node.disabled && node.config.schedule.kind !== 'manual')
}
export function workflowHasScheduleTrigger(workflow: WorkflowV1): boolean {
return activeScheduleTriggers(workflow).length > 0
}
export function hasEnabledScheduledWorkflow(settings: AppSettingsV1): boolean {
return settings.workflow.workflows.some((workflow) => workflow.enabled && workflowHasScheduleTrigger(workflow))
}
/** Minimal, dependency-free 5-field cron field parser ("* , - /"). */
function parseCronField(field: string, min: number, max: number): Set<number> | null {
const out = new Set<number>()
for (const part of field.split(',')) {
const match = part.trim().match(/^(\*|\d+)(?:-(\d+))?(?:\/(\d+))?$/)
if (!match) return null
const star = match[1] === '*'
const lo = star ? min : Number(match[1])
const hi = star ? max : match[2] !== undefined ? Number(match[2]) : match[3] !== undefined ? max : lo
const step = match[3] !== undefined ? Number(match[3]) : 1
if (!Number.isFinite(lo) || !Number.isFinite(hi) || step < 1) return null
for (let value = lo; value <= hi; value += step) {
if (value >= min && value <= max) out.add(value)
}
}
return out.size ? out : null
}
/** Next fire time at or after `from` for a standard "min hour dom month dow" cron, in local time. */
export function cronNextRun(expr: string, from: Date): Date | null {
const parts = expr.trim().split(/\s+/)
if (parts.length !== 5) return null
const minutes = parseCronField(parts[0], 0, 59)
const hours = parseCronField(parts[1], 0, 23)
const doms = parseCronField(parts[2], 1, 31)
const months = parseCronField(parts[3], 1, 12)
const dowsRaw = parseCronField(parts[4], 0, 7)
if (!minutes || !hours || !doms || !months || !dowsRaw) return null
const dows = new Set([...dowsRaw].map((day) => (day === 7 ? 0 : day)))
const domRestricted = parts[2].trim() !== '*'
const dowRestricted = parts[4].trim() !== '*'
const cursor = new Date(from.getTime())
cursor.setSeconds(0, 0)
cursor.setMinutes(cursor.getMinutes() + 1)
const limit = 366 * 24 * 60
for (let i = 0; i < limit; i += 1) {
if (months.has(cursor.getMonth() + 1)) {
const dom = cursor.getDate()
const dow = cursor.getDay()
// Standard cron: when both DOM and DOW are restricted, match either.
const dayOk =
domRestricted && dowRestricted
? doms.has(dom) || dows.has(dow)
: (domRestricted ? doms.has(dom) : true) && (dowRestricted ? dows.has(dow) : true)
if (dayOk && hours.has(cursor.getHours()) && minutes.has(cursor.getMinutes())) {
return new Date(cursor.getTime())
}
}
cursor.setMinutes(cursor.getMinutes() + 1)
}
return null
}
function nextRunFromSchedule(schedule: WorkflowScheduleV1, from: Date): string {
switch (schedule.kind) {
case 'manual':
return ''
case 'at':
return schedule.atTime.trim()
case 'interval':
return new Date(from.getTime() + schedule.everyMinutes * 60_000).toISOString()
case 'cron': {
const next = schedule.cron.trim() ? cronNextRun(schedule.cron, from) : null
return next ? next.toISOString() : ''
}
case 'daily':
default: {
const [hourRaw, minuteRaw] = schedule.timeOfDay.split(':')
const hour = Number(hourRaw)
const minute = Number(minuteRaw)
const next = new Date(from)
next.setSeconds(0, 0)
next.setHours(Number.isFinite(hour) ? hour : 9, Number.isFinite(minute) ? minute : 0, 0, 0)
if (next.getTime() <= from.getTime()) next.setDate(next.getDate() + 1)
return next.toISOString()
}
}
}
export function computeWorkflowNextRunAt(workflow: WorkflowV1, from: Date): string {
if (!workflow.enabled) return ''
const candidates = activeScheduleTriggers(workflow)
.map((node) => nextRunFromSchedule(node.config.schedule, from).trim())
.filter((value) => value && Number.isFinite(Date.parse(value)))
.sort()
return candidates[0] ?? ''
}
function buildAdjacency(connections: WorkflowConnectionV1[]): Map<string, WorkflowConnectionV1[]> {
const map = new Map<string, WorkflowConnectionV1[]>()
for (const edge of connections) {
const list = map.get(edge.source) ?? []
list.push(edge)
map.set(edge.source, list)
}
return map
}
function safeJson(value: unknown): string {
if (value === undefined || value === null) return ''
try {
return JSON.stringify(value)
} catch {
return ''
}
}
function readPath(payload: WorkflowPayload, path: string): unknown {
const trimmed = path.trim()
if (!trimmed || trimmed === 'text') return payload.text
if (trimmed === 'json') return payload.json
const segments = trimmed.replace(/^json\.?/, '').split('.').filter(Boolean)
let cursor: unknown = payload.json
for (const segment of segments) {
if (cursor && typeof cursor === 'object' && segment in (cursor as Record<string, unknown>)) {
cursor = (cursor as Record<string, unknown>)[segment]
} else {
return undefined
}
}
return cursor
}
/** Drill into a value by a dot-path (e.g. "user.name"); empty path returns the value itself. */
function getByPath(value: unknown, path: string): unknown {
const trimmed = path.trim()
if (!trimmed) return value
const segments = trimmed.replace(/^json\.?/, '').split('.').filter(Boolean)
let cursor: unknown = value
for (const segment of segments) {
if (cursor && typeof cursor === 'object' && segment in (cursor as Record<string, unknown>)) {
cursor = (cursor as Record<string, unknown>)[segment]
} else {
return undefined
}
}
return cursor
}
function stringifyValue(value: unknown): string {
if (value === undefined || value === null) return ''
return typeof value === 'string' ? value : safeJson(value)
}
/** Cross-node / variable scope available to {{ }} expressions during a run. */
export type InterpScope = {
/** This node's resolved typed inputs, exposed as {{$input.key}}. */
input?: Record<string, unknown>
/** nodeId -> that node's output payload (only completed, reachable nodes). */
nodes?: Record<string, WorkflowPayload>
/** workflow env vars, exposed as {{$env.key}}. */
env?: Record<string, unknown>
/** run-scoped vars (set-fields scope=run), exposed as {{$run.key}}. */
run?: Record<string, unknown>
/** current loop frame, exposed as {{$loop.index}} / {{$loop.item}} / {{$loop.total}}. */
loop?: { index: number; item: unknown; total: number }
}
function resolveExpr(payload: WorkflowPayload, expr: string, scope?: InterpScope): unknown {
const t = expr.trim()
if (t.startsWith('$nodes.')) {
const rest = t.slice('$nodes.'.length)
const dot = rest.indexOf('.')
const nodeId = dot === -1 ? rest : rest.slice(0, dot)
const sub = dot === -1 ? '' : rest.slice(dot + 1)
const np = scope?.nodes?.[nodeId]
if (!np) return undefined
if (!sub || sub === 'json') return np.json
if (sub === 'text') return np.text
return getByPath(np.json, sub.replace(/^json\.?/, ''))
}
if (t.startsWith('$input.')) {
const rest = t.slice('$input.'.length)
const dot = rest.indexOf('.')
const key = dot === -1 ? rest : rest.slice(0, dot)
const sub = dot === -1 ? '' : rest.slice(dot + 1)
const base = scope?.input?.[key]
return sub ? getByPath(base, sub) : base
}
if (t.startsWith('$env.')) return scope?.env?.[t.slice('$env.'.length)]
if (t.startsWith('$run.')) {
const rest = t.slice('$run.'.length)
const dot = rest.indexOf('.')
const key = dot === -1 ? rest : rest.slice(0, dot)
const sub = dot === -1 ? '' : rest.slice(dot + 1)
const base = scope?.run?.[key]
return sub ? getByPath(base, sub) : base
}
if (t === '$loop.index') return scope?.loop?.index
if (t === '$loop.total') return scope?.loop?.total
if (t === '$loop.item' || t.startsWith('$loop.item.')) {
const item = scope?.loop?.item
const sub = t === '$loop.item' ? '' : t.slice('$loop.item.'.length)
return sub ? getByPath(item, sub) : item
}
return readPath(payload, t)
}
function interpolate(template: string, payload: WorkflowPayload, scope?: InterpScope): string {
return template.replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_, expr: string) => stringifyValue(resolveExpr(payload, expr, scope)))
}
/** Whether a template references at least one {{ }} expression. */
function hasInterpolation(template: string): boolean {
return /\{\{\s*[^}]+?\s*\}\}/.test(template)
}
/** A trimmed string, treating empty JSON literals ({} / [] / null) as "no content". */
function meaningfulText(value: string): string {
const trimmed = value.trim()
return trimmed === '{}' || trimmed === '[]' || trimmed === 'null' ? '' : trimmed
}
/**
* The upstream input rendered as plain text, for AI prompts that don't explicitly
* template it. A node's declared typed inputs ($input) win; otherwise the upstream
* payload's text, then a primitive json value. Empty/empty-object payloads → ''.
*/
function buildUpstreamContext(payload: WorkflowPayload, inputs?: Record<string, unknown>): string {
if (inputs && Object.keys(inputs).length > 0) {
return Object.entries(inputs)
.map(([key, value]) => `${key}: ${stringifyValue(value)}`)
.join('\n')
.trim()
}
const text = meaningfulText(payload.text ?? '')
if (text) return text
const json = payload.json
if (json !== null && json !== undefined && typeof json !== 'object') return stringifyValue(json)
return ''
}
/**
* Assemble an AI node's prompt. The configured prompt is interpolated as usual;
* when it has no {{ }} reference, the upstream input is appended so an AI node
* that doesn't explicitly template its input still receives it.
*/
function buildAiPrompt(template: string, payload: WorkflowPayload, scope: InterpScope): string {
const rendered = interpolate(template, payload, scope)
if (hasInterpolation(template)) return rendered
const context = buildUpstreamContext(payload, scope.input)
if (!context) return rendered
const base = rendered.trim()
return base ? `${base}\n\n${context}` : context
}
function evaluateCondition(
config: WorkflowConditionConfigV1,
payload: WorkflowPayload,
scope?: InterpScope
): boolean {
const leftRaw = config.leftExpr.trim() ? resolveExpr(payload, config.leftExpr, scope) : payload.text
const left = stringifyValue(leftRaw)
const right = config.rightValue
const l = config.caseSensitive ? left : left.toLowerCase()
const r = config.caseSensitive ? right : right.toLowerCase()
switch (config.operator) {
case 'contains':
return l.includes(r)
case 'notContains':
return !l.includes(r)
case 'equals':
return l === r
case 'notEquals':
return l !== r
case 'startsWith':
return l.startsWith(r)
case 'endsWith':
return l.endsWith(r)
case 'isEmpty':
return left.trim() === ''
case 'isNotEmpty':
return left.trim() !== ''
case 'gt':
return Number(left) > Number(right)
case 'gte':
return Number(left) >= Number(right)
case 'lt':
return Number(left) < Number(right)
case 'lte':
return Number(left) <= Number(right)
default:
return false
}
}
async function readBodyCapped(response: Response, limit: number): Promise<string> {
const body = response.body
if (!body) return response.text()
const reader = body.getReader()
const chunks: Buffer[] = []
let size = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
if (value) {
size += value.length
if (size > limit) {
await reader.cancel()
throw new Error('Response body exceeds the 5MB limit.')
}
chunks.push(Buffer.from(value))
}
}
return Buffer.concat(chunks).toString('utf8')
}
async function runHttpNode(
config: WorkflowHttpRequestConfigV1,
payload: WorkflowPayload,
scope?: InterpScope
): Promise<NodeOutcome> {
const url = interpolate(config.url, payload, scope).trim()
let parsed: URL
try {
parsed = new URL(url)
} catch {
throw new Error(`Invalid URL: ${url || '(empty)'}`)
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
throw new Error('Only http(s) URLs are allowed.')
}
const headers: Record<string, string> = {}
for (const header of config.headers) {
const key = header.key.trim()
if (key) headers[key] = interpolate(header.value, payload, scope)
}
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), config.timeoutMs)
try {
const init: RequestInit = { method: config.method, headers, signal: controller.signal }
if (config.method !== 'GET' && config.method !== 'DELETE' && config.body.trim()) {
init.body = interpolate(config.body, payload, scope)
}
const response = await fetch(url, init)
const raw = await readBodyCapped(response, HTTP_MAX_RESPONSE_BYTES)
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${raw.slice(0, 500)}`)
}
let json: unknown = { status: response.status, body: raw }
if (config.parseJson) {
try {
json = JSON.parse(raw)
} catch {
json = { status: response.status, body: raw }
}
}
return { payload: { json, text: raw }, message: `${response.status} ${response.statusText}`.trim() }
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
throw new Error(`Request timed out after ${config.timeoutMs}ms.`)
}
throw error
} finally {
clearTimeout(timer)
}
}
const CODE_TIMEOUT_MS = 2_000
/** python/bash scripts may do real work (network, files), so they get longer than the JS sandbox. */
const COMMAND_TIMEOUT_MS = 30_000
const PYTHON_BIN = process.env.WORKFLOW_PYTHON_BIN?.trim() || 'python3'
const MAX_SUBWORKFLOW_DEPTH = 5
function resolveBashBin(): string {
const configured = process.env.WORKFLOW_BASH_BIN?.trim()
if (configured) return configured
if (process.platform !== 'win32') return 'bash'
const candidates = [
join(process.env.PROGRAMFILES || 'C:\\Program Files', 'Git', 'bin', 'bash.exe'),
join(process.env.PROGRAMFILES || 'C:\\Program Files', 'Git', 'usr', 'bin', 'bash.exe'),
join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'Git', 'bin', 'bash.exe')
]
if (process.env.LOCALAPPDATA) {
candidates.push(join(process.env.LOCALAPPDATA, 'Programs', 'Git', 'bin', 'bash.exe'))
}
return candidates.find((candidate) => existsSync(candidate)) ?? 'bash'
}
const BASH_BIN = resolveBashBin()
function runCodeNode(
code: string,
payload: WorkflowPayload,
fields: Record<string, unknown> = {}
): NodeOutcome {
const sandbox: Record<string, unknown> = {
$json: payload.json,
$text: payload.text,
$fields: fields,
__result: undefined
}
try {
runInNewContext(`__result = (function(){\n${code}\n})()`, sandbox, {
timeout: CODE_TIMEOUT_MS,
displayErrors: true
})
} catch (error) {
throw new Error(`Code error: ${error instanceof Error ? error.message : String(error)}`)
}
const out = sandbox.__result
if (out === undefined || out === null) return { payload: { json: {}, text: '' }, message: 'ok' }
if (typeof out === 'string') return { payload: { json: { value: out }, text: out }, message: 'ok' }
const json = typeof out === 'object' ? out : { value: out }
return { payload: { json, text: safeJson(json) }, message: 'ok' }
}
/**
* Run a python or bash script in a child process. The script reads its input on
* stdin as JSON ({ json, text }) and via the $WORKFLOW_JSON / $WORKFLOW_TEXT env
* vars; whatever it writes to stdout becomes the node output (parsed as JSON when
* the whole stdout is a JSON object/array, otherwise passed through as text).
*/
function runCommandNode(
language: 'python' | 'bash',
code: string,
payload: WorkflowPayload,
fields: Record<string, unknown> = {}
): Promise<NodeOutcome> {
const bin = language === 'python' ? PYTHON_BIN : BASH_BIN
return new Promise((resolve, reject) => {
const child = spawn(bin, ['-c', code], {
env: {
...process.env,
WORKFLOW_TEXT: payload.text ?? '',
WORKFLOW_JSON: safeJson(payload.json),
WORKFLOW_FIELDS: safeJson(fields)
}
})
let stdout = ''
let stderr = ''
let settled = false
const finish = (run: () => void): void => {
if (settled) return
settled = true
clearTimeout(timer)
run()
}
const timer = setTimeout(() => {
child.kill('SIGKILL')
finish(() => reject(new Error(`${language} script timed out after ${COMMAND_TIMEOUT_MS}ms`)))
}, COMMAND_TIMEOUT_MS)
child.stdout.on('data', (chunk) => {
stdout += String(chunk)
})
child.stderr.on('data', (chunk) => {
stderr += String(chunk)
})
child.on('error', (error) => {
const reason =
(error as NodeJS.ErrnoException).code === 'ENOENT'
? `${bin} was not found on this machine`
: error.message
finish(() => reject(new Error(`${language} error: ${reason}`)))
})
child.on('close', (exitCode) => {
finish(() => {
if (exitCode !== 0) {
reject(new Error(`${language} exited with code ${exitCode}: ${(stderr || stdout).trim().slice(0, 500)}`))
return
}
const out = stdout.trim()
let parsed: unknown
try {
parsed = out ? JSON.parse(out) : undefined
} catch {
parsed = undefined
}
if (parsed !== null && typeof parsed === 'object') {
resolve({ payload: { json: parsed, text: out }, message: 'ok' })
} else {
resolve({ payload: { json: out ? { text: out } : {}, text: out }, message: 'ok' })
}
})
})
// Scripts that never read stdin trigger EPIPE on write — ignore it.
child.stdin.on('error', () => {})
child.stdin.write(JSON.stringify({ json: payload.json, text: payload.text }))
child.stdin.end()
})
}
/**
* Resolve the image-generation config for a generate-image node. When the node
* picks its own provider/model we patch them into the runtime image config and
* reuse the shared resolver, so a node-selected provider goes through the exact
* same provider→image-capability resolution as the global Settings path. Empty
* fields fall back to whatever is configured in Settings.
*/
function resolveWorkflowImageGen(
settings: AppSettingsV1,
nodeProviderId: string,
nodeModel: string
): ReturnType<typeof resolveKunImageGenerationSettings> {
const providerId = nodeProviderId.trim()
const model = nodeModel.trim()
if (!providerId && !model) return resolveKunImageGenerationSettings(settings)
const kun = settings.agents.kun
const patched: AppSettingsV1 = {
...settings,
agents: {
...settings.agents,
kun: {
...kun,
imageGeneration: {
...kun.imageGeneration,
...(providerId ? { providerId } : {}),
...(model ? { model } : {})
}
}
}
}
return resolveKunImageGenerationSettings(patched)
}
/** Coerce a custom node's stored string values into typed $fields for its module. */
function coerceModuleFields(
module: WorkflowCustomModuleV1,
values: Record<string, string>
): Record<string, unknown> {
const out: Record<string, unknown> = {}
for (const field of module.fields) {
const raw = values[field.key] ?? field.defaultValue ?? ''
if (field.type === 'number') out[field.key] = raw === '' ? 0 : Number(raw) || 0
else if (field.type === 'boolean') out[field.key] = raw === 'true' || raw === '1'
else out[field.key] = raw
}
return out
}
/**
* Editor-time syntax check for a Code node. JavaScript compiles in-process
* (never executed); python/bash are parse-checked with the local interpreter
* (`ast.parse` / `bash -n`). A missing interpreter returns `unavailable` rather
* than a hard error so the editor can show a soft note.
*/
export function checkWorkflowCode(language: WorkflowCodeLanguage, code: string): Promise<WorkflowCodeCheckResult> {
if (!code.trim()) return Promise.resolve({ status: 'ok' })
if (language === 'javascript') {
try {
// Compiles the function body without running it — surfaces SyntaxError only.
compileFunction(code, ['$json', '$text'])
return Promise.resolve({ status: 'ok' })
} catch (error) {
return Promise.resolve({ status: 'error', message: error instanceof Error ? error.message : String(error) })
}
}
const bin = language === 'python' ? PYTHON_BIN : BASH_BIN
const args = language === 'python' ? ['-c', 'import ast, sys; ast.parse(sys.stdin.read())'] : ['-n']
return new Promise((resolveResult) => {
let settled = false
const done = (result: WorkflowCodeCheckResult): void => {
if (settled) return
settled = true
clearTimeout(timer)
resolveResult(result)
}
let child: ReturnType<typeof spawn>
try {
child = spawn(bin, args)
} catch {
done({ status: 'unavailable', message: `${bin} is not available — cannot check ${language} syntax.` })
return
}
const timer = setTimeout(() => {
try {
child.kill('SIGKILL')
} catch {
/* already exited */
}
done({ status: 'error', message: 'Syntax check timed out.' })
}, 8_000)
let stderr = ''
child.stderr?.on('data', (chunk) => {
stderr += String(chunk)
})
child.on('error', (error) => {
done(
(error as NodeJS.ErrnoException).code === 'ENOENT'
? { status: 'unavailable', message: `${bin} was not found — cannot check ${language} syntax.` }
: { status: 'error', message: error.message }
)
})
child.on('close', (exitCode) => {
done(
exitCode === 0
? { status: 'ok' }
: { status: 'error', message: stderr.trim().slice(0, 800) || `Exited with code ${exitCode}.` }
)
})
child.stdin?.on('error', () => {})
child.stdin?.write(code)
child.stdin?.end()
})
}
/**
* The run's working directory: the firing trigger's workspaceRoot, else the
* workflow-settings default, else the app workspace. Used as the default cwd
* for AI / image / code nodes that don't set their own.
*/
function coerceInputFieldValue(field: WorkflowInputFieldV1, raw: unknown): unknown {
const asString = typeof raw === 'string' ? raw : raw === undefined || raw === null ? '' : String(raw)
switch (field.type) {
case 'number':
return typeof raw === 'number' ? raw : asString.trim() === '' ? 0 : Number(asString) || 0
case 'boolean':
return typeof raw === 'boolean' ? raw : asString === 'true' || asString === '1'
case 'json':
if (raw && typeof raw === 'object') return raw
try {
return JSON.parse(asString)
} catch {
return asString
}
default:
return raw && typeof raw === 'object' ? raw : asString
}
}
/** Build the run's initial payload from the manual trigger's input schema (or pass input through verbatim). */
function coerceInputToPayload(schema: WorkflowInputFieldV1[] | undefined, input: unknown): WorkflowPayload {
if (!schema || schema.length === 0) {
if (input === undefined || input === null) return { json: {}, text: '' }
if (typeof input === 'string') return { json: { text: input }, text: input }
return { json: input, text: safeJson(input) }
}
let src: Record<string, unknown> = {}
if (input && typeof input === 'object' && !Array.isArray(input)) {
src = input as Record<string, unknown>
} else if (typeof input === 'string' && input.trim()) {
try {
const parsed = JSON.parse(input)
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) src = parsed as Record<string, unknown>
} catch {
/* not a JSON object — fields fall back to defaults */
}
}
const json: Record<string, unknown> = {}
for (const field of schema) {
json[field.key] = coerceInputFieldValue(field, field.key in src ? src[field.key] : field.defaultValue)
}
return { json, text: safeJson(json) }
}
/** Returns the first required input key missing from `input`, or null if all present. */
function missingRequiredInput(schema: WorkflowInputFieldV1[] | undefined, input: unknown): string | null {
if (!schema) return null
const src = input && typeof input === 'object' && !Array.isArray(input) ? (input as Record<string, unknown>) : {}
for (const field of schema) {
if (field.required && !(field.key in src) && !field.defaultValue.trim()) return field.label || field.key
}
return null
}
/** Parse a JSON object out of an LLM reply, tolerating ```json fences and surrounding prose. */
function extractJsonObject(raw: string): Record<string, unknown> | null {
const text = raw
.trim()
.replace(/^```(?:json)?\s*/i, '')
.replace(/```\s*$/i, '')
.trim()
const tryParse = (candidate: string): Record<string, unknown> | null => {
try {
const parsed = JSON.parse(candidate)
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null
} catch {
return null
}
}
const direct = tryParse(text)
if (direct) return direct
const match = text.match(/\{[\s\S]*\}/)
return match ? tryParse(match[0]) : null
}
/** Run `fn` over items with at most `limit` in flight, preserving result order. */
async function mapWithConcurrency<T, R>(
items: T[],
limit: number,
fn: (item: T, index: number) => Promise<R>
): Promise<R[]> {
const results = new Array<R>(items.length)
let cursor = 0
const workerCount = Math.max(1, Math.min(limit, items.length))
const workers = Array.from({ length: workerCount }, async () => {
for (;;) {
const index = cursor
cursor += 1
if (index >= items.length) break
results[index] = await fn(items[index], index)
}
})
await Promise.all(workers)
return results
}
/** Replace every secret value with *** in a string. */
function redactSecrets(secretValues: string[], text: string): string {
return secretValues.reduce((acc, secret) => acc.split(secret).join('***'), text)
}
/**
* All secret-typed env values across every workflow. Used so a parent run redacts
* secrets that belong to a sub-workflow / loop body it invoked, not just its own.
*/
function collectSecretValues(settings: AppSettingsV1): string[] {
const values: string[] = []
for (const workflow of settings.workflow.workflows) {
for (const entry of workflow.env) {
if (entry.type === 'secret' && entry.value.trim()) values.push(entry.value)
}
}
return values
}
/** Coerce a resolved node-input value to its declared type. */
function coerceNodeInputValue(type: 'text' | 'number' | 'boolean' | 'json', raw: unknown): unknown {
switch (type) {
case 'number': {
const n = typeof raw === 'number' ? raw : Number(String(raw ?? '').trim())
return Number.isFinite(n) ? n : 0
}
case 'boolean':
return raw === true || raw === 'true' || raw === 1 || raw === '1'
case 'json': {
if (raw && typeof raw === 'object') return raw
try {
return JSON.parse(String(raw ?? ''))
} catch {
return raw ?? null
}
}
default:
return typeof raw === 'string' ? raw : raw == null ? '' : safeJson(raw)
}
}
/**
* Resolve a node's typed inputs (bound to upstream output) into a {{$input.key}}
* lookup. A single `{{ expr }}` source yields the raw value (object/number/…);
* anything else is interpolated as a string. Returns undefined when no inputs.
*/
function resolveNodeInputs(
node: WorkflowNodeV1,
payload: WorkflowPayload,
scope: InterpScope
): Record<string, unknown> | undefined {
const bindings = node.inputs
if (!bindings || bindings.length === 0) return undefined
const out: Record<string, unknown> = {}
for (const binding of bindings) {
const key = binding.key.trim()
if (!key) continue
const single = binding.source.trim().match(/^\{\{([^}]+)\}\}$/)
const raw = single ? resolveExpr(payload, single[1], scope) : interpolate(binding.source, payload, scope)
out[key] = coerceNodeInputValue(binding.type, raw)
}
return out
}
/** Coerce a workflow's env vars into a {{$env.key}} lookup (secrets are plain values here). */
function resolveEnv(env: WorkflowEnvVarV1[]): Record<string, unknown> {
const out: Record<string, unknown> = {}
for (const entry of env) {
if (!entry.key) continue
out[entry.key] =
entry.type === 'number'
? Number(entry.value) || 0
: entry.type === 'boolean'
? entry.value === 'true'
: entry.value
}
return out
}
function resolveRunWorkspace(
workflow: WorkflowV1,
settings: AppSettingsV1,
triggerNodeId?: string,
payload?: WorkflowPayload,
scope?: InterpScope
): string {
const triggers = workflow.nodes.filter(
(node) =>
node.type === 'manual-trigger' || node.type === 'schedule-trigger' || node.type === 'webhook-trigger'
)
const trigger = (triggerNodeId ? triggers.find((node) => node.id === triggerNodeId) : undefined) ?? triggers[0]
const rawWorkspace =
trigger && typeof (trigger.config as { workspaceRoot?: unknown }).workspaceRoot === 'string'
? (trigger.config as { workspaceRoot: string }).workspaceRoot
: ''
// The trigger's working directory may reference the run input ({{json.dir}} /
// {{$env.X}}), so the working directory itself can be passed in as a parameter.
const triggerWorkspace = (payload ? interpolate(rawWorkspace, payload, scope) : rawWorkspace).trim()
return triggerWorkspace || settings.workflow.defaultWorkspaceRoot.trim() || settings.workspaceRoot
}
/**
* Resolve where a generate-image node saves its file. Absolute paths are used
* as-is; relative paths resolve against the workspace; empty defaults to
* <workspace>/workflow-images.
*/
function resolveImageOutputDir(workspace: string, configuredRaw: string): string {
const configured = configuredRaw.trim()
if (configured) {
if (isAbsolute(configured)) return resolve(configured)
if (!workspace) throw new Error('Output folder is relative but no workspace is configured.')
return resolve(join(workspace, configured))
}
if (!workspace) {
throw new Error('No workspace configured to save the image — set an output folder on the node.')
}
return join(workspace, 'workflow-images')
}
function summarizeRun(results: WorkflowNodeRunResultV1[]): string {
const lastMeaningful = [...results].reverse().find((result) => result.status === 'success' && result.message.trim())
if (lastMeaningful) return lastMeaningful.message
return `Completed ${results.length} step${results.length === 1 ? '' : 's'}`
}
/** Short description of a workflow for the agent's run_workflow / list_workflows tools. */
function summarizeWorkflowForAgent(workflow: WorkflowV1): string {
const steps = workflow.nodes.filter((node) => node.type === 'ai-agent' || node.type === 'custom').length
const kinds = [...new Set(workflow.nodes.map((node) => node.type))].filter(
(kind) => kind !== 'manual-trigger' && kind !== 'schedule-trigger' && kind !== 'webhook-trigger'
)
return `${workflow.nodes.length} nodes${steps ? `, ${steps} AI step(s)` : ''} — ${kinds.slice(0, 6).join(', ') || 'trigger only'}`
}
// ---------------------------------------------------------------------------
// WorkflowRuntime
// ---------------------------------------------------------------------------
export class WorkflowRuntime {
private readonly deps: ScheduleRuntimeDeps
private scheduler: ReturnType<typeof setInterval> | null = null
private runningWorkflowIds = new Set<string>()
private cancelRequested = new Set<string>()
/** Recursion guard: true while a hook-triggered workflow is running, so its own
* tool calls (via AI-agent nodes) don't re-trigger hooks and loop forever. */
private hookRunActive = false
/** token -> paused human-approval node awaiting a decision. */
private pendingApprovals = new Map<
string,
{ entry: WorkflowPendingApprovalV1; resolve: (decision: WorkflowApprovalDecision) => void }
>()
/** workflowId -> nodeId -> live status, surfaced to the canvas via status(). */
private liveNodeStatus = new Map<string, Map<string, WorkflowNodeRunStatus>>()
/** workflowId -> nodeId -> latest per-node result (input/output/timing), surfaced live during a run. */
private liveNodeResults = new Map<string, Map<string, WorkflowNodeRunResultV1>>()
private powerSaveBlockerId: number | null = null
private webhookServer: Server | null = null
private webhookServerKey = ''
constructor(deps: ScheduleRuntimeDeps) {
this.deps = deps
}
sync(settings: AppSettingsV1): void {
this.startScheduler()
this.syncPowerSaveBlocker(settings)
this.syncWebhookServer(settings)
void this.ensureNextRuns(settings)
}
stop(): void {
if (this.scheduler) {
clearInterval(this.scheduler)
this.scheduler = null
}
this.stopPowerSaveBlocker()
this.closeWebhookServer()
}
private syncWebhookServer(settings: AppSettingsV1): void {
// The same local server hosts webhook-trigger paths, /workflow/internal/* (agent
// tool) and the public POST /workflow/run, so listen whenever workflows are on.
const shouldListen = settings.workflow.enabled && settings.workflow.workflows.length > 0
if (!shouldListen) {
this.closeWebhookServer()
return
}
const key = String(settings.workflow.webhookPort)
if (this.webhookServer && this.webhookServerKey === key) return
this.closeWebhookServer()
const server = createServer((req, res) => {
void this.handleWebhookRequest(req, res)
})
server.on('error', (error) => {
this.deps.logError('workflow-webhook', 'Webhook server failed', {
message: error instanceof Error ? error.message : String(error)
})
if (this.webhookServer === server) this.closeWebhookServer()
})
// Bind to localhost only — never expose the listener to the network.
server.listen(settings.workflow.webhookPort, '127.0.0.1')
this.webhookServer = server
this.webhookServerKey = key
}
private closeWebhookServer(): void {
if (!this.webhookServer) return
const server = this.webhookServer
this.webhookServer = null
this.webhookServerKey = ''
server.close()
}