@pikku/core 0.12.4 → 0.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/dist/dev/hot-reload.d.ts +10 -0
  3. package/dist/dev/hot-reload.js +158 -0
  4. package/dist/middleware-runner.d.ts +1 -0
  5. package/dist/middleware-runner.js +5 -0
  6. package/dist/permissions.d.ts +1 -0
  7. package/dist/permissions.js +5 -0
  8. package/dist/services/in-memory-workflow-service.js +7 -11
  9. package/dist/wirings/ai-agent/ai-agent-prepare.js +16 -1
  10. package/dist/wirings/channel/channel-middleware-runner.d.ts +1 -0
  11. package/dist/wirings/channel/channel-middleware-runner.js +5 -0
  12. package/dist/wirings/workflow/pikku-workflow-service.js +7 -8
  13. package/package.json +3 -2
  14. package/src/crypto-utils.test.ts +214 -0
  15. package/src/crypto-utils.ts +213 -0
  16. package/src/dev/hot-reload.test.ts +484 -0
  17. package/src/dev/hot-reload.ts +212 -0
  18. package/src/errors/error-handler.ts +62 -0
  19. package/src/errors/error.test.ts +195 -0
  20. package/src/errors/errors.ts +374 -0
  21. package/src/errors/index.ts +2 -0
  22. package/src/factory-functions.test.ts +109 -0
  23. package/src/function/function-runner.test.ts +536 -0
  24. package/src/function/function-runner.ts +365 -0
  25. package/src/function/functions.types.ts +304 -0
  26. package/src/function/index.ts +5 -0
  27. package/src/handle-error.test.ts +424 -0
  28. package/src/handle-error.ts +69 -0
  29. package/src/index.ts +118 -0
  30. package/src/internal.ts +6 -0
  31. package/src/middleware/auth-apikey.test.ts +363 -0
  32. package/src/middleware/auth-apikey.ts +47 -0
  33. package/src/middleware/auth-bearer.test.ts +450 -0
  34. package/src/middleware/auth-bearer.ts +72 -0
  35. package/src/middleware/auth-cookie.test.ts +528 -0
  36. package/src/middleware/auth-cookie.ts +80 -0
  37. package/src/middleware/cors.test.ts +424 -0
  38. package/src/middleware/cors.ts +104 -0
  39. package/src/middleware/index.ts +5 -0
  40. package/src/middleware/remote-auth.test.ts +488 -0
  41. package/src/middleware/remote-auth.ts +68 -0
  42. package/src/middleware/timeout.ts +15 -0
  43. package/src/middleware-runner.test.ts +418 -0
  44. package/src/middleware-runner.ts +240 -0
  45. package/src/permissions.test.ts +434 -0
  46. package/src/permissions.ts +327 -0
  47. package/src/pikku-request.ts +23 -0
  48. package/src/pikku-response.ts +5 -0
  49. package/src/pikku-state.test.ts +224 -0
  50. package/src/pikku-state.ts +216 -0
  51. package/src/run-tests-script.test.ts +49 -0
  52. package/src/schema.test.ts +249 -0
  53. package/src/schema.ts +151 -0
  54. package/src/services/ai-agent-runner-service.ts +41 -0
  55. package/src/services/ai-run-state-service.ts +20 -0
  56. package/src/services/ai-storage-service.ts +39 -0
  57. package/src/services/content-service.ts +76 -0
  58. package/src/services/deployment-service.ts +22 -0
  59. package/src/services/gateway-service.ts +20 -0
  60. package/src/services/gopass-secrets.ts +98 -0
  61. package/src/services/in-memory-ai-run-state-service.ts +73 -0
  62. package/src/services/in-memory-trigger-service.ts +64 -0
  63. package/src/services/in-memory-workflow-service.test.ts +351 -0
  64. package/src/services/in-memory-workflow-service.ts +502 -0
  65. package/src/services/index.ts +56 -0
  66. package/src/services/jwt-service.ts +30 -0
  67. package/src/services/local-content.ts +120 -0
  68. package/src/services/local-gateway-service.ts +62 -0
  69. package/src/services/local-secrets.test.ts +80 -0
  70. package/src/services/local-secrets.ts +94 -0
  71. package/src/services/local-variables.test.ts +61 -0
  72. package/src/services/local-variables.ts +39 -0
  73. package/src/services/logger-console.test.ts +118 -0
  74. package/src/services/logger-console.ts +98 -0
  75. package/src/services/logger.ts +57 -0
  76. package/src/services/scheduler-service.ts +86 -0
  77. package/src/services/schema-service.ts +33 -0
  78. package/src/services/scoped-secret-service.test.ts +74 -0
  79. package/src/services/scoped-secret-service.ts +41 -0
  80. package/src/services/secret-service.ts +38 -0
  81. package/src/services/trigger-service.ts +17 -0
  82. package/src/services/typed-secret-service.test.ts +93 -0
  83. package/src/services/typed-secret-service.ts +70 -0
  84. package/src/services/typed-variables-service.test.ts +73 -0
  85. package/src/services/typed-variables-service.ts +81 -0
  86. package/src/services/user-session-service.test.ts +113 -0
  87. package/src/services/user-session-service.ts +86 -0
  88. package/src/services/variables-service.ts +11 -0
  89. package/src/services/workflow-service.ts +95 -0
  90. package/src/testing/index.ts +2 -0
  91. package/src/testing/service-tests.ts +873 -0
  92. package/src/time-utils.test.ts +56 -0
  93. package/src/time-utils.ts +107 -0
  94. package/src/types/core.types.ts +478 -0
  95. package/src/types/state.types.ts +188 -0
  96. package/src/utils/hash.test.ts +68 -0
  97. package/src/utils/hash.ts +26 -0
  98. package/src/utils.test.ts +350 -0
  99. package/src/utils.ts +129 -0
  100. package/src/version.test.ts +80 -0
  101. package/src/version.ts +25 -0
  102. package/src/wirings/ai-agent/agent-dynamic-workflow.ts +469 -0
  103. package/src/wirings/ai-agent/ai-agent-helpers.test.ts +152 -0
  104. package/src/wirings/ai-agent/ai-agent-helpers.ts +76 -0
  105. package/src/wirings/ai-agent/ai-agent-memory.ts +310 -0
  106. package/src/wirings/ai-agent/ai-agent-model-config.test.ts +115 -0
  107. package/src/wirings/ai-agent/ai-agent-model-config.ts +43 -0
  108. package/src/wirings/ai-agent/ai-agent-prepare.ts +659 -0
  109. package/src/wirings/ai-agent/ai-agent-registry.test.ts +37 -0
  110. package/src/wirings/ai-agent/ai-agent-registry.ts +82 -0
  111. package/src/wirings/ai-agent/ai-agent-runner.test.ts +319 -0
  112. package/src/wirings/ai-agent/ai-agent-runner.ts +773 -0
  113. package/src/wirings/ai-agent/ai-agent-stream.test.ts +859 -0
  114. package/src/wirings/ai-agent/ai-agent-stream.ts +1153 -0
  115. package/src/wirings/ai-agent/ai-agent.types.ts +382 -0
  116. package/src/wirings/ai-agent/index.ts +37 -0
  117. package/src/wirings/channel/channel-common.ts +90 -0
  118. package/src/wirings/channel/channel-handler.ts +250 -0
  119. package/src/wirings/channel/channel-middleware-runner.ts +126 -0
  120. package/src/wirings/channel/channel-runner.ts +166 -0
  121. package/src/wirings/channel/channel-store.ts +29 -0
  122. package/src/wirings/channel/channel.types.ts +172 -0
  123. package/src/wirings/channel/define-channel-routes.ts +25 -0
  124. package/src/wirings/channel/eventhub-service.ts +34 -0
  125. package/src/wirings/channel/eventhub-store.ts +13 -0
  126. package/src/wirings/channel/index.ts +24 -0
  127. package/src/wirings/channel/local/index.ts +3 -0
  128. package/src/wirings/channel/local/local-channel-handler.ts +81 -0
  129. package/src/wirings/channel/local/local-channel-runner.test.ts +215 -0
  130. package/src/wirings/channel/local/local-channel-runner.ts +210 -0
  131. package/src/wirings/channel/local/local-eventhub-service.test.ts +95 -0
  132. package/src/wirings/channel/local/local-eventhub-service.ts +101 -0
  133. package/src/wirings/channel/log-channels.ts +20 -0
  134. package/src/wirings/channel/pikku-abstract-channel-handler.test.ts +54 -0
  135. package/src/wirings/channel/pikku-abstract-channel-handler.ts +45 -0
  136. package/src/wirings/channel/serverless/index.ts +5 -0
  137. package/src/wirings/channel/serverless/serverless-channel-runner.ts +289 -0
  138. package/src/wirings/cli/channel/cli-channel-runner.ts +136 -0
  139. package/src/wirings/cli/channel/index.ts +1 -0
  140. package/src/wirings/cli/cli-runner.test.ts +403 -0
  141. package/src/wirings/cli/cli-runner.ts +529 -0
  142. package/src/wirings/cli/cli.types.ts +358 -0
  143. package/src/wirings/cli/command-parser.test.ts +445 -0
  144. package/src/wirings/cli/command-parser.ts +504 -0
  145. package/src/wirings/cli/define-cli-commands.ts +24 -0
  146. package/src/wirings/cli/index.ts +19 -0
  147. package/src/wirings/gateway/gateway-runner.test.ts +474 -0
  148. package/src/wirings/gateway/gateway-runner.ts +411 -0
  149. package/src/wirings/gateway/gateway.types.ts +149 -0
  150. package/src/wirings/gateway/index.ts +13 -0
  151. package/src/wirings/http/http-routes.test.ts +322 -0
  152. package/src/wirings/http/http-routes.ts +197 -0
  153. package/src/wirings/http/http-runner.test.ts +144 -0
  154. package/src/wirings/http/http-runner.ts +588 -0
  155. package/src/wirings/http/http.types.ts +369 -0
  156. package/src/wirings/http/index.ts +28 -0
  157. package/src/wirings/http/log-http-routes.ts +22 -0
  158. package/src/wirings/http/pikku-fetch-http-request.test.ts +237 -0
  159. package/src/wirings/http/pikku-fetch-http-request.ts +170 -0
  160. package/src/wirings/http/pikku-fetch-http-response.test.ts +82 -0
  161. package/src/wirings/http/pikku-fetch-http-response.ts +147 -0
  162. package/src/wirings/http/routers/http-router.ts +13 -0
  163. package/src/wirings/http/routers/path-to-regex.test.ts +319 -0
  164. package/src/wirings/http/routers/path-to-regex.ts +126 -0
  165. package/src/wirings/http/web-request.test.ts +236 -0
  166. package/src/wirings/http/web-request.ts +104 -0
  167. package/src/wirings/mcp/index.ts +27 -0
  168. package/src/wirings/mcp/mcp-endpoint-registry.test.ts +389 -0
  169. package/src/wirings/mcp/mcp-endpoint-registry.ts +159 -0
  170. package/src/wirings/mcp/mcp-runner.ts +323 -0
  171. package/src/wirings/mcp/mcp.types.ts +216 -0
  172. package/src/wirings/node/index.ts +2 -0
  173. package/src/wirings/node/node.types.ts +23 -0
  174. package/src/wirings/oauth2/index.ts +3 -0
  175. package/src/wirings/oauth2/oauth2-client.test.ts +929 -0
  176. package/src/wirings/oauth2/oauth2-client.ts +335 -0
  177. package/src/wirings/oauth2/oauth2.types.ts +69 -0
  178. package/src/wirings/oauth2/wire-oauth2-credential.ts +23 -0
  179. package/src/wirings/queue/index.ts +31 -0
  180. package/src/wirings/queue/queue-runner.test.ts +710 -0
  181. package/src/wirings/queue/queue-runner.ts +192 -0
  182. package/src/wirings/queue/queue.types.ts +189 -0
  183. package/src/wirings/queue/register-queue-helper.ts +60 -0
  184. package/src/wirings/queue/validate-worker-config.test.ts +108 -0
  185. package/src/wirings/queue/validate-worker-config.ts +116 -0
  186. package/src/wirings/rpc/index.ts +4 -0
  187. package/src/wirings/rpc/rpc-runner.ts +460 -0
  188. package/src/wirings/rpc/rpc-types.ts +56 -0
  189. package/src/wirings/rpc/wire-addon.ts +21 -0
  190. package/src/wirings/scheduler/index.ts +11 -0
  191. package/src/wirings/scheduler/log-schedulers.ts +20 -0
  192. package/src/wirings/scheduler/scheduler-runner.test.ts +660 -0
  193. package/src/wirings/scheduler/scheduler-runner.ts +133 -0
  194. package/src/wirings/scheduler/scheduler.types.ts +53 -0
  195. package/src/wirings/secret/index.ts +9 -0
  196. package/src/wirings/secret/secret.types.ts +32 -0
  197. package/src/wirings/secret/validate-secret-definitions.test.ts +140 -0
  198. package/src/wirings/secret/validate-secret-definitions.ts +82 -0
  199. package/src/wirings/trigger/index.ts +10 -0
  200. package/src/wirings/trigger/pikku-trigger-service.ts +112 -0
  201. package/src/wirings/trigger/trigger-runner.test.ts +79 -0
  202. package/src/wirings/trigger/trigger-runner.ts +135 -0
  203. package/src/wirings/trigger/trigger.types.ts +178 -0
  204. package/src/wirings/variable/index.ts +8 -0
  205. package/src/wirings/variable/validate-variable-definitions.test.ts +91 -0
  206. package/src/wirings/variable/validate-variable-definitions.ts +69 -0
  207. package/src/wirings/variable/variable.types.ts +22 -0
  208. package/src/wirings/workflow/dsl/index.ts +31 -0
  209. package/src/wirings/workflow/dsl/workflow-dsl.types.ts +320 -0
  210. package/src/wirings/workflow/dsl/workflow-runner.ts +28 -0
  211. package/src/wirings/workflow/graph/graph-node.ts +222 -0
  212. package/src/wirings/workflow/graph/graph-runner.test.ts +487 -0
  213. package/src/wirings/workflow/graph/graph-runner.ts +816 -0
  214. package/src/wirings/workflow/graph/graph-validation.test.ts +170 -0
  215. package/src/wirings/workflow/graph/graph-validation.ts +237 -0
  216. package/src/wirings/workflow/graph/index.ts +19 -0
  217. package/src/wirings/workflow/graph/template.test.ts +49 -0
  218. package/src/wirings/workflow/graph/template.ts +42 -0
  219. package/src/wirings/workflow/graph/wire-workflow-graph.ts +29 -0
  220. package/src/wirings/workflow/graph/workflow-graph.types.ts +104 -0
  221. package/src/wirings/workflow/index.ts +82 -0
  222. package/src/wirings/workflow/pikku-workflow-service.test.ts +200 -0
  223. package/src/wirings/workflow/pikku-workflow-service.ts +1179 -0
  224. package/src/wirings/workflow/workflow-helpers.test.ts +129 -0
  225. package/src/wirings/workflow/workflow-helpers.ts +79 -0
  226. package/src/wirings/workflow/workflow.types.ts +274 -0
  227. package/tsconfig.json +14 -0
  228. package/tsconfig.tsbuildinfo +1 -0
  229. package/lcov.info +0 -18891
@@ -0,0 +1,502 @@
1
+ import { randomUUID } from 'crypto'
2
+ import { PikkuWorkflowService } from '../wirings/workflow/pikku-workflow-service.js'
3
+ import type { SerializedError } from '../types/core.types.js'
4
+ import type {
5
+ WorkflowRun,
6
+ WorkflowRunService,
7
+ WorkflowRunWire,
8
+ StepState,
9
+ WorkflowStatus,
10
+ WorkflowVersionStatus,
11
+ WorkflowStepOptions,
12
+ } from '../wirings/workflow/workflow.types.js'
13
+
14
+ interface InternalStepData {
15
+ rpcName: string | null
16
+ data: any
17
+ stepName: string
18
+ }
19
+
20
+ /**
21
+ * In-memory implementation of WorkflowService for inline-only execution
22
+ *
23
+ * This is a lightweight workflow service that stores all state in memory.
24
+ * It only supports inline execution (no queue workers) and is ideal for:
25
+ * - CLI tools that need workflow-like step orchestration
26
+ * - Testing and development
27
+ * - Single-process applications without persistence requirements
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * const workflowService = new InMemoryWorkflowService()
32
+ * await workflowService.startWorkflow('myWorkflow', input, { type: 'cli' }, rpc, { inline: true })
33
+ * ```
34
+ */
35
+ export class InMemoryWorkflowService
36
+ extends PikkuWorkflowService
37
+ implements WorkflowRunService
38
+ {
39
+ private runs = new Map<string, WorkflowRun>()
40
+ private steps = new Map<string, StepState>() // keyed by `${runId}:${stepName}`
41
+ private stepData = new Map<string, InternalStepData>() // keyed by stepId
42
+ private stepHistory = new Map<
43
+ string,
44
+ Array<StepState & { stepName: string }>
45
+ >() // keyed by runId
46
+ private runState = new Map<string, Record<string, unknown>>() // keyed by runId
47
+ private branchKeys = new Map<string, string>() // keyed by stepId
48
+ private workflowVersions = new Map<
49
+ string,
50
+ { graph: any; source: string; status: WorkflowVersionStatus }
51
+ >() // keyed by `${name}:${graphHash}`
52
+
53
+ async createRun(
54
+ workflowName: string,
55
+ input: any,
56
+ inline: boolean,
57
+ graphHash: string,
58
+ wire: WorkflowRunWire
59
+ ): Promise<string> {
60
+ const runId = randomUUID()
61
+ const now = new Date()
62
+
63
+ const run: WorkflowRun = {
64
+ id: runId,
65
+ workflow: workflowName,
66
+ status: 'running',
67
+ input,
68
+ inline,
69
+ graphHash,
70
+ wire,
71
+ createdAt: now,
72
+ updatedAt: now,
73
+ }
74
+
75
+ this.runs.set(runId, run)
76
+ this.stepHistory.set(runId, [])
77
+ this.runState.set(runId, {})
78
+
79
+ if (inline) {
80
+ this.registerInlineRun(runId)
81
+ }
82
+
83
+ return runId
84
+ }
85
+
86
+ async getRun(id: string): Promise<WorkflowRun | null> {
87
+ return this.runs.get(id) || null
88
+ }
89
+
90
+ async getRunHistory(
91
+ runId: string
92
+ ): Promise<Array<StepState & { stepName: string }>> {
93
+ return this.stepHistory.get(runId) || []
94
+ }
95
+
96
+ async updateRunStatus(
97
+ id: string,
98
+ status: WorkflowStatus,
99
+ output?: any,
100
+ error?: SerializedError
101
+ ): Promise<void> {
102
+ const run = this.runs.get(id)
103
+ if (run) {
104
+ run.status = status
105
+ run.updatedAt = new Date()
106
+ if (output !== undefined) run.output = output
107
+ if (error !== undefined) run.error = error
108
+ }
109
+ }
110
+
111
+ async insertStepState(
112
+ runId: string,
113
+ stepName: string,
114
+ rpcName: string | null,
115
+ data: any,
116
+ stepOptions?: WorkflowStepOptions
117
+ ): Promise<StepState> {
118
+ const stepId = randomUUID()
119
+ const now = new Date()
120
+
121
+ const step: StepState & { stepName: string } = {
122
+ stepId,
123
+ status: 'pending',
124
+ attemptCount: 1,
125
+ retries: stepOptions?.retries,
126
+ retryDelay: stepOptions?.retryDelay,
127
+ createdAt: now,
128
+ updatedAt: now,
129
+ stepName,
130
+ }
131
+
132
+ const key = `${runId}:${stepName}`
133
+ this.steps.set(key, step)
134
+ this.stepData.set(stepId, { rpcName, data, stepName })
135
+
136
+ // Add to history (same reference so mutations are reflected)
137
+ const history = this.stepHistory.get(runId) || []
138
+ history.push(step)
139
+ this.stepHistory.set(runId, history)
140
+
141
+ return step
142
+ }
143
+
144
+ async getStepState(runId: string, stepName: string): Promise<StepState> {
145
+ const key = `${runId}:${stepName}`
146
+ const step = this.steps.get(key)
147
+ if (!step) {
148
+ throw new Error(
149
+ `Step not found: runId=${runId}, stepName=${stepName}. Use insertStepState to create it.`
150
+ )
151
+ }
152
+ return step
153
+ }
154
+
155
+ async setStepRunning(stepId: string): Promise<void> {
156
+ for (const step of this.steps.values()) {
157
+ if (step.stepId === stepId) {
158
+ step.status = 'running'
159
+ step.runningAt = new Date()
160
+ step.updatedAt = new Date()
161
+ break
162
+ }
163
+ }
164
+ }
165
+
166
+ async setStepScheduled(stepId: string): Promise<void> {
167
+ for (const step of this.steps.values()) {
168
+ if (step.stepId === stepId) {
169
+ step.status = 'scheduled'
170
+ step.scheduledAt = new Date()
171
+ step.updatedAt = new Date()
172
+ break
173
+ }
174
+ }
175
+ }
176
+
177
+ async setStepResult(stepId: string, result: any): Promise<void> {
178
+ for (const step of this.steps.values()) {
179
+ if (step.stepId === stepId) {
180
+ step.status = 'succeeded'
181
+ step.result = result
182
+ step.succeededAt = new Date()
183
+ step.updatedAt = new Date()
184
+ break
185
+ }
186
+ }
187
+ }
188
+
189
+ async setStepError(stepId: string, error: Error): Promise<void> {
190
+ for (const step of this.steps.values()) {
191
+ if (step.stepId === stepId) {
192
+ step.status = 'failed'
193
+ step.error = {
194
+ name: error.name,
195
+ message: error.message,
196
+ stack: error.stack,
197
+ }
198
+ step.failedAt = new Date()
199
+ step.updatedAt = new Date()
200
+ break
201
+ }
202
+ }
203
+ }
204
+
205
+ async createRetryAttempt(
206
+ failedStepId: string,
207
+ status: 'pending' | 'running'
208
+ ): Promise<StepState> {
209
+ // Find the failed step
210
+ let failedStep: StepState | undefined
211
+ let runId: string | undefined
212
+ let stepName: string | undefined
213
+
214
+ for (const [key, step] of this.steps.entries()) {
215
+ if (step.stepId === failedStepId) {
216
+ failedStep = step
217
+ const parts = key.split(':')
218
+ runId = parts[0]
219
+ stepName = parts.slice(1).join(':')
220
+ break
221
+ }
222
+ }
223
+
224
+ if (!failedStep || !runId || !stepName) {
225
+ throw new Error(`Step not found: ${failedStepId}`)
226
+ }
227
+
228
+ const failedStepData = this.stepData.get(failedStepId)
229
+ const newStepId = randomUUID()
230
+ const now = new Date()
231
+
232
+ const newStep: StepState & { stepName: string } = {
233
+ stepId: newStepId,
234
+ status,
235
+ attemptCount: failedStep.attemptCount + 1,
236
+ retries: failedStep.retries,
237
+ retryDelay: failedStep.retryDelay,
238
+ createdAt: now,
239
+ updatedAt: now,
240
+ stepName: stepName,
241
+ }
242
+
243
+ if (status === 'running') {
244
+ newStep.runningAt = now
245
+ }
246
+
247
+ const key = `${runId}:${stepName}`
248
+ this.steps.set(key, newStep)
249
+
250
+ // Copy step data to new step
251
+ if (failedStepData) {
252
+ this.stepData.set(newStepId, { ...failedStepData })
253
+ }
254
+
255
+ // Add to history (same reference so mutations are reflected)
256
+ const history = this.stepHistory.get(runId) || []
257
+ history.push(newStep)
258
+ this.stepHistory.set(runId, history)
259
+
260
+ return newStep
261
+ }
262
+
263
+ async listRuns(options?: {
264
+ workflowName?: string
265
+ status?: string
266
+ limit?: number
267
+ offset?: number
268
+ }): Promise<WorkflowRun[]> {
269
+ let runs = Array.from(this.runs.values())
270
+ if (options?.workflowName) {
271
+ runs = runs.filter((r) => r.workflow === options.workflowName)
272
+ }
273
+ if (options?.status) {
274
+ runs = runs.filter((r) => r.status === options.status)
275
+ }
276
+ runs.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
277
+ const offset = options?.offset ?? 0
278
+ const limit = options?.limit ?? runs.length
279
+ return runs.slice(offset, offset + limit)
280
+ }
281
+
282
+ async getRunSteps(
283
+ runId: string
284
+ ): Promise<
285
+ Array<StepState & { stepName: string; rpcName?: string; data?: any }>
286
+ > {
287
+ const history = this.stepHistory.get(runId) || []
288
+ return history.map((step) => {
289
+ const stepDataEntry = this.stepData.get(step.stepId)
290
+ return {
291
+ ...step,
292
+ rpcName: stepDataEntry?.rpcName ?? undefined,
293
+ data: stepDataEntry?.data,
294
+ }
295
+ })
296
+ }
297
+
298
+ async getDistinctWorkflowNames(): Promise<string[]> {
299
+ const names = new Set<string>()
300
+ for (const run of this.runs.values()) {
301
+ names.add(run.workflow)
302
+ }
303
+ return Array.from(names)
304
+ }
305
+
306
+ async deleteRun(id: string): Promise<boolean> {
307
+ const existed = this.runs.has(id)
308
+ this.runs.delete(id)
309
+ this.stepHistory.delete(id)
310
+ this.runState.delete(id)
311
+ const prefix = `${id}:`
312
+ for (const key of this.steps.keys()) {
313
+ if (key.startsWith(prefix)) {
314
+ const step = this.steps.get(key)
315
+ if (step) {
316
+ this.stepData.delete(step.stepId)
317
+ this.branchKeys.delete(step.stepId)
318
+ }
319
+ this.steps.delete(key)
320
+ }
321
+ }
322
+ return existed
323
+ }
324
+
325
+ async withRunLock<T>(_id: string, fn: () => Promise<T>): Promise<T> {
326
+ // In-memory service doesn't need locking for inline execution
327
+ return fn()
328
+ }
329
+
330
+ async withStepLock<T>(
331
+ _runId: string,
332
+ _stepName: string,
333
+ fn: () => Promise<T>
334
+ ): Promise<T> {
335
+ // In-memory service doesn't need locking for inline execution
336
+ return fn()
337
+ }
338
+
339
+ async close(): Promise<void> {
340
+ // Clear all in-memory state
341
+ this.runs.clear()
342
+ this.steps.clear()
343
+ this.stepData.clear()
344
+ this.stepHistory.clear()
345
+ this.runState.clear()
346
+ this.branchKeys.clear()
347
+ this.workflowVersions.clear()
348
+ }
349
+
350
+ // Graph workflow methods
351
+
352
+ async getCompletedGraphState(runId: string): Promise<{
353
+ completedNodeIds: string[]
354
+ failedNodeIds: string[]
355
+ branchKeys: Record<string, string>
356
+ }> {
357
+ const completedNodeIds: string[] = []
358
+ const failedNodeIds: string[] = []
359
+ const prefix = `${runId}:`
360
+ for (const [key, step] of this.steps.entries()) {
361
+ if (!key.startsWith(prefix)) continue
362
+ const nodeId = key.substring(prefix.length)
363
+ if (step.status === 'succeeded') {
364
+ completedNodeIds.push(nodeId)
365
+ } else if (step.status === 'failed') {
366
+ const maxAttempts = (step.retries ?? 0) + 1
367
+ if (step.attemptCount >= maxAttempts) {
368
+ failedNodeIds.push(nodeId)
369
+ }
370
+ }
371
+ }
372
+
373
+ const branchKeys: Record<string, string> = {}
374
+ for (const [stepId, branchKey] of this.branchKeys.entries()) {
375
+ const stepData = this.stepData.get(stepId)
376
+ if (stepData) {
377
+ branchKeys[stepData.stepName] = branchKey
378
+ }
379
+ }
380
+
381
+ return { completedNodeIds, failedNodeIds, branchKeys }
382
+ }
383
+
384
+ async getNodesWithoutSteps(
385
+ runId: string,
386
+ nodeIds: string[]
387
+ ): Promise<string[]> {
388
+ const existingSteps = new Set<string>()
389
+ const prefix = `${runId}:`
390
+ for (const [key] of this.steps.entries()) {
391
+ if (key.startsWith(prefix)) {
392
+ existingSteps.add(key.substring(prefix.length))
393
+ }
394
+ }
395
+ return nodeIds.filter((id) => !existingSteps.has(id))
396
+ }
397
+
398
+ async getNodeResults(
399
+ runId: string,
400
+ nodeIds: string[]
401
+ ): Promise<Record<string, any>> {
402
+ const results: Record<string, any> = {}
403
+ for (const nodeId of nodeIds) {
404
+ const key = `${runId}:${nodeId}`
405
+ const step = this.steps.get(key)
406
+ if (step?.result !== undefined) {
407
+ results[nodeId] = step.result
408
+ }
409
+ }
410
+ return results
411
+ }
412
+
413
+ async setBranchKey(
414
+ runId: string,
415
+ nodeId: string,
416
+ branchKey: string
417
+ ): Promise<void> {
418
+ const key = `${runId}:${nodeId}`
419
+ const step = this.steps.get(key)
420
+ if (step) {
421
+ this.branchKeys.set(step.stepId, branchKey)
422
+ }
423
+ }
424
+
425
+ async setBranchTaken(stepId: string, branchKey: string): Promise<void> {
426
+ this.branchKeys.set(stepId, branchKey)
427
+ }
428
+
429
+ async updateRunState(
430
+ runId: string,
431
+ name: string,
432
+ value: unknown
433
+ ): Promise<void> {
434
+ const state = this.runState.get(runId) || {}
435
+ state[name] = value
436
+ this.runState.set(runId, state)
437
+ }
438
+
439
+ async getRunState(runId: string): Promise<Record<string, unknown>> {
440
+ return this.runState.get(runId) || {}
441
+ }
442
+
443
+ async upsertWorkflowVersion(
444
+ name: string,
445
+ graphHash: string,
446
+ graph: any,
447
+ source: string,
448
+ status?: WorkflowVersionStatus
449
+ ): Promise<void> {
450
+ this.workflowVersions.set(`${name}:${graphHash}`, {
451
+ graph,
452
+ source,
453
+ status: status ?? 'active',
454
+ })
455
+ }
456
+
457
+ async updateWorkflowVersionStatus(
458
+ name: string,
459
+ graphHash: string,
460
+ status: WorkflowVersionStatus
461
+ ): Promise<void> {
462
+ const key = `${name}:${graphHash}`
463
+ const version = this.workflowVersions.get(key)
464
+ if (version) {
465
+ version.status = status
466
+ }
467
+ }
468
+
469
+ async getWorkflowVersion(
470
+ name: string,
471
+ graphHash: string
472
+ ): Promise<{ graph: any; source: string } | null> {
473
+ const version = this.workflowVersions.get(`${name}:${graphHash}`)
474
+ if (!version) return null
475
+ return { graph: version.graph, source: version.source }
476
+ }
477
+
478
+ async getAIGeneratedWorkflows(
479
+ agentName?: string
480
+ ): Promise<Array<{ workflowName: string; graphHash: string; graph: any }>> {
481
+ const results: Array<{
482
+ workflowName: string
483
+ graphHash: string
484
+ graph: any
485
+ }> = []
486
+ const prefix = agentName ? `ai:${agentName}:` : 'ai:'
487
+ for (const [key, value] of this.workflowVersions) {
488
+ if (value.source !== 'ai-agent' || value.status !== 'active') continue
489
+ const separatorIdx = key.lastIndexOf(':')
490
+ const wfName = key.substring(0, separatorIdx)
491
+ const hash = key.substring(separatorIdx + 1)
492
+ if (wfName.startsWith(prefix)) {
493
+ results.push({
494
+ workflowName: wfName,
495
+ graphHash: hash,
496
+ graph: value.graph,
497
+ })
498
+ }
499
+ }
500
+ return results
501
+ }
502
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @module @pikku/core
3
+ */
4
+
5
+ export { LogLevel } from './logger.js'
6
+ export { ScopedSecretService } from './scoped-secret-service.js'
7
+ export {
8
+ PikkuSessionService,
9
+ createMiddlewareSessionWireProps,
10
+ createFunctionSessionWireProps,
11
+ } from './user-session-service.js'
12
+ export { TypedSecretService } from './typed-secret-service.js'
13
+ export { TypedVariablesService } from './typed-variables-service.js'
14
+ export { LocalSecretService } from './local-secrets.js'
15
+ export { LocalVariablesService } from './local-variables.js'
16
+ export { ConsoleLogger } from './logger-console.js'
17
+ export { InMemoryWorkflowService } from './in-memory-workflow-service.js'
18
+ export { InMemoryTriggerService } from './in-memory-trigger-service.js'
19
+ export { InMemoryAIRunStateService } from './in-memory-ai-run-state-service.js'
20
+ export { LocalGatewayService } from './local-gateway-service.js'
21
+ export type { ContentService } from './content-service.js'
22
+ export type { JWTService } from './jwt-service.js'
23
+ export type { Logger } from './logger.js'
24
+ export type { SecretService } from './secret-service.js'
25
+ export type { VariablesService } from './variables-service.js'
26
+ export type { SchemaService } from './schema-service.js'
27
+ export type { SessionService } from './user-session-service.js'
28
+ export type {
29
+ ScheduledTaskSummary,
30
+ ScheduledTaskInfo,
31
+ SchedulerService,
32
+ } from './scheduler-service.js'
33
+ export type { TriggerService } from './trigger-service.js'
34
+ export type { GatewayService } from './gateway-service.js'
35
+ export type {
36
+ DeploymentService,
37
+ DeploymentConfig,
38
+ DeploymentInfo,
39
+ DeploymentServiceConfig,
40
+ } from './deployment-service.js'
41
+ export type { AIStorageService } from './ai-storage-service.js'
42
+ export type {
43
+ AIAgentRunnerParams,
44
+ AIAgentRunnerResult,
45
+ AIAgentStepResult,
46
+ AIAgentRunnerService,
47
+ } from './ai-agent-runner-service.js'
48
+ export type {
49
+ CreateRunInput,
50
+ AIRunStateService,
51
+ } from './ai-run-state-service.js'
52
+ export type {
53
+ CredentialStatus,
54
+ CredentialMeta,
55
+ } from './typed-secret-service.js'
56
+ export type { VariableStatus, VariableMeta } from './typed-variables-service.js'
@@ -0,0 +1,30 @@
1
+ import type { RelativeTimeInput } from '../time-utils.js'
2
+
3
+ /**
4
+ * Interface for handling JSON Web Tokens (JWT).
5
+ */
6
+ export interface JWTService {
7
+ /**
8
+ * Encodes a payload into a JWT.
9
+ * @param expiresIn - The expiration time of the token.
10
+ * @param payload - The payload to encode.
11
+ * @returns A promise that resolves to the encoded JWT.
12
+ */
13
+ encode: <T extends any>(
14
+ expiresIn: RelativeTimeInput,
15
+ payload: T
16
+ ) => Promise<string>
17
+
18
+ /**
19
+ * Decodes a JWT into its payload.
20
+ * @param hash - The JWT to decode.
21
+ * @param invalidHashError - An optional error to throw if the hash is invalid.
22
+ * @param debug - An optional flag for debugging.
23
+ * @returns A promise that resolves to the decoded payload.
24
+ */
25
+ decode: <T>(
26
+ hash: string,
27
+ invalidHashError?: Error,
28
+ debug?: boolean
29
+ ) => Promise<T>
30
+ }
@@ -0,0 +1,120 @@
1
+ import { createReadStream, createWriteStream, promises } from 'fs'
2
+ import { mkdir, readFile } from 'fs/promises'
3
+ import type { ContentService, Logger } from '@pikku/core/services'
4
+ import { pipeline } from 'stream/promises'
5
+ import type { Readable } from 'stream'
6
+
7
+ export interface LocalContentConfig {
8
+ localFileUploadPath: string
9
+ uploadUrlPrefix: string
10
+ assetUrlPrefix: string
11
+ server?: string
12
+ sizeLimit?: string
13
+ }
14
+
15
+ export class LocalContent implements ContentService {
16
+ constructor(
17
+ private config: LocalContentConfig,
18
+ private logger: Logger
19
+ ) {}
20
+
21
+ public async init() {}
22
+
23
+ public async signURL(url: string): Promise<string> {
24
+ return `${url}?signed=true`
25
+ }
26
+
27
+ public async signContentKey(assetKey: string): Promise<string> {
28
+ return this.config.server
29
+ ? `${this.config.server}${this.config.assetUrlPrefix}/${assetKey}?signed=true`
30
+ : `${this.config.assetUrlPrefix}/${assetKey}?signed=true`
31
+ }
32
+
33
+ public async getUploadURL(assetKey: string) {
34
+ this.logger.debug(`Going to upload with key: ${assetKey}`)
35
+ return {
36
+ uploadUrl: `${this.config.uploadUrlPrefix}/${assetKey}`,
37
+ assetKey,
38
+ }
39
+ }
40
+
41
+ public async writeFile(
42
+ assetKey: string,
43
+ stream: ReadableStream | NodeJS.ReadableStream
44
+ ): Promise<boolean> {
45
+ this.logger.debug(`Writing file: ${assetKey}`)
46
+
47
+ const path = `${this.config.localFileUploadPath}/${assetKey}`
48
+
49
+ try {
50
+ await this.createDirectoryForFile(path)
51
+ const fileStream = createWriteStream(path)
52
+ // Use pipeline to properly manage stream piping and errors
53
+ await pipeline(stream as Readable, fileStream)
54
+ return true
55
+ } catch (e) {
56
+ console.error(e)
57
+ this.logger.error(`Error writing content ${assetKey}`, e)
58
+ return false
59
+ }
60
+ }
61
+
62
+ public async copyFile(
63
+ assetKey: string,
64
+ fromAbsolutePath: string
65
+ ): Promise<boolean> {
66
+ this.logger.debug(`Writing file: ${assetKey}`)
67
+ try {
68
+ const path = `${this.config.localFileUploadPath}/${assetKey}`
69
+ await this.createDirectoryForFile(path)
70
+ await promises.copyFile(fromAbsolutePath, path)
71
+ } catch (e) {
72
+ console.error(e)
73
+ this.logger.error(`Error inserting content ${assetKey}`, e)
74
+ }
75
+ return false
76
+ }
77
+
78
+ public async readFile(
79
+ assetKey: string
80
+ ): Promise<ReadableStream | NodeJS.ReadableStream> {
81
+ this.logger.debug(`Getting key: ${assetKey}`)
82
+
83
+ const filePath = `${this.config.localFileUploadPath}/${assetKey}`
84
+
85
+ try {
86
+ const stream = createReadStream(filePath)
87
+ // Handle early stream errors (like file not found, permission denied, etc.)
88
+ stream.on('error', (err) => {
89
+ this.logger.error(`Error getting content ${assetKey}`, err)
90
+ })
91
+
92
+ return stream
93
+ } catch (e) {
94
+ this.logger.error(`Error setting up stream for ${assetKey}`, e)
95
+ throw e
96
+ }
97
+ }
98
+
99
+ public async readFileAsBuffer(assetKey: string): Promise<Buffer> {
100
+ const filePath = `${this.config.localFileUploadPath}/${assetKey}`
101
+ this.logger.debug(`Reading file as buffer: ${assetKey}`)
102
+ return readFile(filePath)
103
+ }
104
+
105
+ public async deleteFile(assetKey: string): Promise<boolean> {
106
+ this.logger.debug(`deleting key: ${assetKey}`)
107
+ try {
108
+ await promises.unlink(`${this.config.localFileUploadPath}/${assetKey}`)
109
+ return true
110
+ } catch (e: any) {
111
+ this.logger.error(`Error deleting content ${assetKey}`, e)
112
+ }
113
+ return false
114
+ }
115
+
116
+ private async createDirectoryForFile(path: string): Promise<void> {
117
+ const dir = path.split('/').slice(0, -1).join('/')
118
+ await mkdir(dir, { recursive: true })
119
+ }
120
+ }