@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,773 @@
1
+ import type {
2
+ AIAgentInput,
3
+ AIAgentOutput,
4
+ AIAgentStep,
5
+ AIAgentMemoryConfig,
6
+ CoreAIAgent,
7
+ PikkuAIMiddlewareHooks,
8
+ AgentRunState,
9
+ } from './ai-agent.types.js'
10
+ import type {
11
+ AIAgentStepResult,
12
+ AIAgentRunnerParams,
13
+ AIAgentRunnerService,
14
+ } from '../../services/ai-agent-runner-service.js'
15
+ import type { AIStorageService } from '../../services/ai-storage-service.js'
16
+ import type { AIRunStateService } from '../../services/ai-run-state-service.js'
17
+
18
+ import {
19
+ saveMessages,
20
+ resolveMemoryServices,
21
+ loadContextMessages,
22
+ trimMessages,
23
+ } from './ai-agent-memory.js'
24
+ import {
25
+ prepareAgentRun,
26
+ resolveAgent,
27
+ buildInstructions,
28
+ buildToolDefs,
29
+ type RunAIAgentParams,
30
+ } from './ai-agent-prepare.js'
31
+ import { checkForApprovals, appendStepMessages } from './ai-agent-stream.js'
32
+ import { pikkuState, getSingletonServices } from '../../pikku-state.js'
33
+ import { resolveModelConfig } from './ai-agent-model-config.js'
34
+ import { randomUUID } from 'crypto'
35
+
36
+ export async function runAIAgent(
37
+ agentName: string,
38
+ input: AIAgentInput,
39
+ params: RunAIAgentParams,
40
+ agentSessionMap?: Map<string, string>
41
+ ): Promise<AIAgentOutput> {
42
+ const sessionMap = agentSessionMap ?? new Map<string, string>()
43
+
44
+ const {
45
+ agent,
46
+ agentRunner,
47
+ storage,
48
+ memoryConfig,
49
+ threadId,
50
+ userMessage,
51
+ runnerParams,
52
+ maxSteps,
53
+ missingRpcs,
54
+ workingMemoryJsonSchema,
55
+ workingMemorySchemaName,
56
+ } = await prepareAgentRun(agentName, input, params, sessionMap)
57
+
58
+ const singletonServices = getSingletonServices()
59
+ const { aiRunState } = singletonServices
60
+ if (!aiRunState) {
61
+ throw new Error('AIRunStateService not available in singletonServices')
62
+ }
63
+
64
+ if (missingRpcs.length > 0) {
65
+ const runId = await aiRunState.createRun({
66
+ agentName,
67
+ threadId,
68
+ resourceId: input.resourceId,
69
+ status: 'suspended',
70
+ suspendReason: 'rpc-missing',
71
+ missingRpcs,
72
+ usage: { inputTokens: 0, outputTokens: 0, model: agent.model },
73
+ createdAt: new Date(),
74
+ updatedAt: new Date(),
75
+ })
76
+ return {
77
+ runId,
78
+ text: '',
79
+ threadId,
80
+ steps: [],
81
+ usage: { inputTokens: 0, outputTokens: 0 },
82
+ }
83
+ }
84
+
85
+ const aiMiddlewares: PikkuAIMiddlewareHooks[] = agent.aiMiddleware ?? []
86
+
87
+ let modifiedMessages = runnerParams.messages
88
+ let modifiedInstructions = runnerParams.instructions
89
+ for (const mw of aiMiddlewares) {
90
+ if (mw.modifyInput) {
91
+ const result = await mw.modifyInput(singletonServices, {
92
+ messages: modifiedMessages,
93
+ instructions: modifiedInstructions,
94
+ })
95
+ modifiedMessages = result.messages
96
+ modifiedInstructions = result.instructions
97
+ }
98
+ }
99
+ runnerParams.messages = modifiedMessages
100
+ runnerParams.instructions = modifiedInstructions
101
+
102
+ const runId = await aiRunState.createRun({
103
+ agentName,
104
+ threadId,
105
+ resourceId: input.resourceId,
106
+ status: 'running',
107
+ usage: { inputTokens: 0, outputTokens: 0, model: agent.model },
108
+ createdAt: new Date(),
109
+ updatedAt: new Date(),
110
+ })
111
+
112
+ try {
113
+ const accumulatedSteps: AIAgentStep[] = []
114
+ const totalUsage = { inputTokens: 0, outputTokens: 0 }
115
+ let lastStepResult: AIAgentStepResult | null = null
116
+
117
+ for (let step = 0; step < maxSteps; step++) {
118
+ if (agent.prepareStep) {
119
+ let stopped = false
120
+ await agent.prepareStep({
121
+ stepNumber: step,
122
+ messages: runnerParams.messages,
123
+ tools: runnerParams.tools,
124
+ toolChoice: runnerParams.toolChoice,
125
+ model: runnerParams.model,
126
+ stop: () => {
127
+ stopped = true
128
+ },
129
+ })
130
+ if (stopped) break
131
+ }
132
+
133
+ const stepResult = await agentRunner.run(runnerParams)
134
+ lastStepResult = stepResult
135
+
136
+ totalUsage.inputTokens += stepResult.usage.inputTokens
137
+ totalUsage.outputTokens += stepResult.usage.outputTokens
138
+
139
+ for (const mw of aiMiddlewares) {
140
+ if (mw.afterStep) {
141
+ await mw.afterStep(singletonServices, {
142
+ stepNumber: step,
143
+ text: stepResult.text,
144
+ toolCalls: stepResult.toolCalls,
145
+ toolResults: stepResult.toolResults,
146
+ usage: stepResult.usage,
147
+ finishReason: stepResult.finishReason,
148
+ })
149
+ }
150
+ }
151
+
152
+ accumulatedSteps.push({
153
+ usage: stepResult.usage,
154
+ toolCalls: stepResult.toolCalls.map((tc) => {
155
+ const tr = stepResult.toolResults.find(
156
+ (r) => r.toolCallId === tc.toolCallId
157
+ )
158
+ return {
159
+ name: tc.toolName,
160
+ args: tc.args as Record<string, unknown>,
161
+ result:
162
+ typeof tr?.result === 'string'
163
+ ? tr.result
164
+ : JSON.stringify(tr?.result ?? ''),
165
+ }
166
+ }),
167
+ })
168
+
169
+ if (stepResult.toolCalls.length === 0) break
170
+
171
+ const approvalsNeeded = checkForApprovals(
172
+ stepResult,
173
+ runnerParams.tools,
174
+ runId
175
+ )
176
+ if (approvalsNeeded.length > 0) {
177
+ for (const approval of approvalsNeeded) {
178
+ const toolDef = runnerParams.tools.find(
179
+ (t) => t.name === approval.toolName
180
+ )
181
+ if (toolDef?.approvalDescriptionFn && !approval.reason) {
182
+ try {
183
+ approval.reason = await toolDef.approvalDescriptionFn(
184
+ approval.args
185
+ )
186
+ } catch {
187
+ // If description generation fails, continue without it
188
+ }
189
+ }
190
+ }
191
+
192
+ const pendingApprovals = approvalsNeeded.map((a) =>
193
+ a.agentRunId
194
+ ? {
195
+ type: 'agent-call' as const,
196
+ toolCallId: a.toolCallId,
197
+ agentName: a.toolName,
198
+ agentRunId: a.agentRunId,
199
+ displayToolName: a.displayToolName ?? a.toolName,
200
+ displayArgs: a.displayArgs ?? a.args,
201
+ }
202
+ : {
203
+ type: 'tool-call' as const,
204
+ toolCallId: a.toolCallId,
205
+ toolName: a.toolName,
206
+ args: a.args,
207
+ }
208
+ )
209
+
210
+ const completedStepsForSave = accumulatedSteps.slice(0, -1)
211
+ await saveMessages(
212
+ storage,
213
+ threadId,
214
+ input.resourceId,
215
+ memoryConfig,
216
+ userMessage,
217
+ { text: '', steps: completedStepsForSave },
218
+ {
219
+ workingMemoryJsonSchema,
220
+ workingMemorySchemaName,
221
+ logger: singletonServices.logger,
222
+ schemaService: singletonServices.schema,
223
+ }
224
+ )
225
+
226
+ if (storage) {
227
+ await storage.saveMessages(threadId, [
228
+ {
229
+ id: randomUUID(),
230
+ role: 'assistant',
231
+ toolCalls: stepResult.toolCalls.map((tc) => ({
232
+ id: tc.toolCallId,
233
+ name: tc.toolName,
234
+ args: tc.args as Record<string, unknown>,
235
+ })),
236
+ createdAt: new Date(),
237
+ },
238
+ ])
239
+ }
240
+
241
+ await aiRunState.updateRun(runId, {
242
+ status: 'suspended',
243
+ suspendReason: 'approval',
244
+ pendingApprovals,
245
+ usage: { ...totalUsage, model: agent.model },
246
+ })
247
+
248
+ const suspendedFinalText = lastStepResult?.text ?? ''
249
+ return {
250
+ runId,
251
+ text: suspendedFinalText,
252
+ threadId,
253
+ steps: accumulatedSteps,
254
+ usage: totalUsage,
255
+ status: 'suspended',
256
+ pendingApprovals: approvalsNeeded.map((a) => ({
257
+ toolCallId: a.toolCallId,
258
+ toolName: a.displayToolName ?? a.toolName,
259
+ args: a.displayArgs ?? a.args,
260
+ reason: a.reason,
261
+ runId,
262
+ })),
263
+ }
264
+ }
265
+
266
+ appendStepMessages(runnerParams, stepResult)
267
+ }
268
+
269
+ const finalText = lastStepResult?.text ?? ''
270
+ const finalObject = lastStepResult?.object
271
+
272
+ const result = {
273
+ text: finalText,
274
+ steps: accumulatedSteps,
275
+ }
276
+
277
+ const responseText = await saveMessages(
278
+ storage,
279
+ threadId,
280
+ input.resourceId,
281
+ memoryConfig,
282
+ userMessage,
283
+ result,
284
+ {
285
+ workingMemoryJsonSchema,
286
+ workingMemorySchemaName,
287
+ logger: singletonServices.logger,
288
+ schemaService: singletonServices.schema,
289
+ }
290
+ )
291
+
292
+ let outputText = responseText
293
+ let outputMessages = runnerParams.messages
294
+ for (let i = aiMiddlewares.length - 1; i >= 0; i--) {
295
+ const mw = aiMiddlewares[i]
296
+ if (mw.modifyOutput) {
297
+ const modResult = await mw.modifyOutput(singletonServices, {
298
+ text: outputText,
299
+ messages: outputMessages,
300
+ usage: totalUsage,
301
+ })
302
+ outputText = modResult.text
303
+ outputMessages = modResult.messages
304
+ }
305
+ }
306
+
307
+ await aiRunState.updateRun(runId, {
308
+ status: 'completed',
309
+ usage: { ...totalUsage, model: agent.model },
310
+ })
311
+
312
+ return {
313
+ runId,
314
+ text: outputText,
315
+ object: finalObject,
316
+ threadId,
317
+ steps: accumulatedSteps,
318
+ usage: totalUsage,
319
+ }
320
+ } catch (error) {
321
+ for (const mw of aiMiddlewares) {
322
+ if (mw.onError) {
323
+ try {
324
+ await mw.onError(singletonServices, {
325
+ error: error instanceof Error ? error : new Error(String(error)),
326
+ stepNumber: -1,
327
+ messages: runnerParams.messages,
328
+ })
329
+ } catch {
330
+ // onError hooks must not affect error flow
331
+ }
332
+ }
333
+ }
334
+ await aiRunState.updateRun(runId, {
335
+ status: 'failed',
336
+ errorMessage: error instanceof Error ? error.message : String(error),
337
+ })
338
+ throw error
339
+ }
340
+ }
341
+
342
+ export async function resumeAIAgentSync(
343
+ runId: string,
344
+ approvals: { toolCallId: string; approved: boolean }[],
345
+ params: RunAIAgentParams,
346
+ expectedAgentName?: string
347
+ ): Promise<AIAgentOutput> {
348
+ const singletonServices = getSingletonServices()
349
+ const { aiRunState } = singletonServices
350
+ if (!aiRunState) {
351
+ throw new Error('AIRunStateService not available in singletonServices')
352
+ }
353
+
354
+ const run = await aiRunState.getRun(runId)
355
+ if (!run) throw new Error(`No run found for runId ${runId}`)
356
+ if (expectedAgentName && run.agentName !== expectedAgentName) {
357
+ throw new Error(
358
+ `Run ${runId} belongs to agent '${run.agentName}', not '${expectedAgentName}'`
359
+ )
360
+ }
361
+ if (run.status !== 'suspended') {
362
+ throw new Error(`Run ${runId} is not suspended (status: ${run.status})`)
363
+ }
364
+
365
+ const { agent, packageName, resolvedName } = resolveAgent(run.agentName)
366
+ const { storage } = resolveMemoryServices(agent, singletonServices)
367
+ const memoryConfig = agent.memory
368
+ const agentRunner = singletonServices.aiAgentRunner
369
+ if (!agentRunner) {
370
+ throw new Error('AIAgentRunnerService not available')
371
+ }
372
+
373
+ const approvedIds = new Set(
374
+ approvals.filter((a) => a.approved).map((a) => a.toolCallId)
375
+ )
376
+ const rejectedIds = new Set(
377
+ approvals.filter((a) => !a.approved).map((a) => a.toolCallId)
378
+ )
379
+
380
+ const savedPendingApprovals = [...(run.pendingApprovals ?? [])]
381
+
382
+ for (const { toolCallId, approved } of approvals) {
383
+ await aiRunState.resolveApproval(
384
+ toolCallId,
385
+ approved ? 'approved' : 'denied'
386
+ )
387
+ }
388
+
389
+ const { tools } = await buildToolDefs(
390
+ params,
391
+ new Map<string, string>(),
392
+ run.resourceId,
393
+ resolvedName,
394
+ packageName,
395
+ undefined,
396
+ agent.aiMiddleware ?? []
397
+ )
398
+
399
+ const toolCallMessages: {
400
+ toolCallId: string
401
+ toolName: string
402
+ args: any
403
+ result: string
404
+ }[] = []
405
+
406
+ for (const pending of savedPendingApprovals) {
407
+ if (pending.type !== 'tool-call') continue
408
+
409
+ const toolCallId = pending.toolCallId
410
+ let resultStr: string
411
+
412
+ if (rejectedIds.has(toolCallId)) {
413
+ resultStr =
414
+ 'The user explicitly declined this action. Inform them that it was declined and do not retry.'
415
+ } else if (approvedIds.has(toolCallId)) {
416
+ const matchingTool = tools.find((t) => t.name === pending.toolName)
417
+ if (!matchingTool) {
418
+ throw new Error(
419
+ `Tool "${pending.toolName}" not found in agent definition`
420
+ )
421
+ }
422
+ const toolArgs =
423
+ typeof pending.args === 'string'
424
+ ? JSON.parse(pending.args)
425
+ : pending.args
426
+ try {
427
+ const toolResult = await matchingTool.execute(toolArgs)
428
+ resultStr =
429
+ typeof toolResult === 'string'
430
+ ? toolResult
431
+ : JSON.stringify(toolResult)
432
+ } catch (err) {
433
+ resultStr = `Error: ${err instanceof Error ? err.message : String(err)}`
434
+ }
435
+ } else {
436
+ continue
437
+ }
438
+
439
+ toolCallMessages.push({
440
+ toolCallId,
441
+ toolName: pending.toolName,
442
+ args:
443
+ typeof pending.args === 'string'
444
+ ? JSON.parse(pending.args)
445
+ : pending.args,
446
+ result: resultStr,
447
+ })
448
+ }
449
+
450
+ if (storage && toolCallMessages.length > 0) {
451
+ await storage.saveMessages(run.threadId, [
452
+ {
453
+ id: randomUUID(),
454
+ role: 'tool',
455
+ toolResults: toolCallMessages.map((tc) => ({
456
+ id: tc.toolCallId,
457
+ name: tc.toolName,
458
+ result: tc.result,
459
+ })),
460
+ createdAt: new Date(),
461
+ },
462
+ ])
463
+ }
464
+
465
+ await aiRunState.updateRun(runId, { status: 'running' })
466
+
467
+ return continueAfterToolResultSync(
468
+ run,
469
+ agent,
470
+ packageName,
471
+ resolvedName,
472
+ storage,
473
+ memoryConfig,
474
+ agentRunner,
475
+ params,
476
+ aiRunState
477
+ )
478
+ }
479
+
480
+ async function continueAfterToolResultSync(
481
+ run: AgentRunState,
482
+ agent: CoreAIAgent,
483
+ packageName: string | null,
484
+ resolvedName: string,
485
+ storage: AIStorageService | undefined,
486
+ memoryConfig: AIAgentMemoryConfig | undefined,
487
+ agentRunner: AIAgentRunnerService,
488
+ params: RunAIAgentParams,
489
+ aiRunState: AIRunStateService
490
+ ): Promise<AIAgentOutput> {
491
+ const singletonServices = getSingletonServices()
492
+ const agentsMeta = pikkuState(packageName, 'agent', 'agentsMeta')
493
+ const meta = agentsMeta[resolvedName]
494
+ const workingMemorySchemaName = meta?.workingMemorySchema ?? null
495
+
496
+ const messages = storage
497
+ ? await storage.getMessages(run.threadId, {
498
+ lastN: memoryConfig?.lastMessages ?? 20,
499
+ })
500
+ : []
501
+
502
+ const workingMemoryJsonSchema = workingMemorySchemaName
503
+ ? pikkuState(packageName, 'misc', 'schemas').get(workingMemorySchemaName)
504
+ : undefined
505
+
506
+ const contextMessages = await loadContextMessages(
507
+ memoryConfig,
508
+ storage,
509
+ { message: '', threadId: run.threadId, resourceId: run.resourceId },
510
+ workingMemoryJsonSchema
511
+ )
512
+
513
+ const allMessages = [...contextMessages, ...messages]
514
+ const trimmedMessages = trimMessages(allMessages)
515
+
516
+ const instructions = await buildInstructions(resolvedName, packageName)
517
+
518
+ const aiMiddlewares: PikkuAIMiddlewareHooks[] = agent.aiMiddleware ?? []
519
+ let modifiedMessages = trimmedMessages
520
+ let modifiedInstructions = instructions
521
+ for (const mw of aiMiddlewares) {
522
+ if (mw.modifyInput) {
523
+ const result = await mw.modifyInput(singletonServices, {
524
+ messages: modifiedMessages,
525
+ instructions: modifiedInstructions,
526
+ })
527
+ modifiedMessages = result.messages
528
+ modifiedInstructions = result.instructions
529
+ }
530
+ }
531
+
532
+ const { tools: resumeTools } = await buildToolDefs(
533
+ params,
534
+ new Map<string, string>(),
535
+ run.resourceId,
536
+ resolvedName,
537
+ packageName,
538
+ undefined,
539
+ aiMiddlewares
540
+ )
541
+
542
+ const resolved = resolveModelConfig(resolvedName, agent)
543
+ const maxSteps = resolved.maxSteps ?? 10
544
+
545
+ const runnerParams: AIAgentRunnerParams = {
546
+ model: resolved.model,
547
+ temperature: resolved.temperature,
548
+ instructions: modifiedInstructions,
549
+ messages: modifiedMessages,
550
+ tools: resumeTools,
551
+ maxSteps: 1,
552
+ toolChoice: (agent.toolChoice ?? 'auto') as 'auto' | 'required' | 'none',
553
+ outputSchema: meta?.outputSchema
554
+ ? pikkuState(packageName, 'misc', 'schemas').get(meta.outputSchema)
555
+ : undefined,
556
+ }
557
+
558
+ try {
559
+ const accumulatedSteps: AIAgentStep[] = []
560
+ const totalUsage = { inputTokens: 0, outputTokens: 0 }
561
+ let lastStepResult: AIAgentStepResult | null = null
562
+
563
+ for (let step = 0; step < maxSteps; step++) {
564
+ const stepResult = await agentRunner.run(runnerParams)
565
+ lastStepResult = stepResult
566
+
567
+ totalUsage.inputTokens += stepResult.usage.inputTokens
568
+ totalUsage.outputTokens += stepResult.usage.outputTokens
569
+
570
+ for (const mw of aiMiddlewares) {
571
+ if (mw.afterStep) {
572
+ await mw.afterStep(singletonServices, {
573
+ stepNumber: step,
574
+ text: stepResult.text,
575
+ toolCalls: stepResult.toolCalls,
576
+ toolResults: stepResult.toolResults,
577
+ usage: stepResult.usage,
578
+ finishReason: stepResult.finishReason,
579
+ })
580
+ }
581
+ }
582
+
583
+ accumulatedSteps.push({
584
+ usage: stepResult.usage,
585
+ toolCalls: stepResult.toolCalls.map((tc) => {
586
+ const tr = stepResult.toolResults.find(
587
+ (r) => r.toolCallId === tc.toolCallId
588
+ )
589
+ return {
590
+ name: tc.toolName,
591
+ args: tc.args as Record<string, unknown>,
592
+ result:
593
+ typeof tr?.result === 'string'
594
+ ? tr.result
595
+ : JSON.stringify(tr?.result ?? ''),
596
+ }
597
+ }),
598
+ })
599
+
600
+ if (stepResult.toolCalls.length === 0) break
601
+
602
+ const approvalsNeeded = checkForApprovals(
603
+ stepResult,
604
+ runnerParams.tools,
605
+ run.runId
606
+ )
607
+ if (approvalsNeeded.length > 0) {
608
+ for (const approval of approvalsNeeded) {
609
+ const toolDef = runnerParams.tools.find(
610
+ (t) => t.name === approval.toolName
611
+ )
612
+ if (toolDef?.approvalDescriptionFn && !approval.reason) {
613
+ try {
614
+ approval.reason = await toolDef.approvalDescriptionFn(
615
+ approval.args
616
+ )
617
+ } catch {
618
+ // ignore
619
+ }
620
+ }
621
+ }
622
+
623
+ const pendingApprovals = approvalsNeeded.map((a) =>
624
+ a.agentRunId
625
+ ? {
626
+ type: 'agent-call' as const,
627
+ toolCallId: a.toolCallId,
628
+ agentName: a.toolName,
629
+ agentRunId: a.agentRunId,
630
+ displayToolName: a.displayToolName ?? a.toolName,
631
+ displayArgs: a.displayArgs ?? a.args,
632
+ }
633
+ : {
634
+ type: 'tool-call' as const,
635
+ toolCallId: a.toolCallId,
636
+ toolName: a.toolName,
637
+ args: a.args,
638
+ }
639
+ )
640
+
641
+ const completedSteps = accumulatedSteps.slice(0, -1)
642
+ if (completedSteps.length > 0) {
643
+ await saveMessages(
644
+ storage,
645
+ run.threadId,
646
+ run.resourceId,
647
+ memoryConfig,
648
+ null,
649
+ { text: '', steps: completedSteps },
650
+ {
651
+ workingMemoryJsonSchema,
652
+ workingMemorySchemaName,
653
+ logger: singletonServices.logger,
654
+ schemaService: singletonServices.schema,
655
+ }
656
+ )
657
+ }
658
+
659
+ if (storage) {
660
+ await storage.saveMessages(run.threadId, [
661
+ {
662
+ id: randomUUID(),
663
+ role: 'assistant',
664
+ toolCalls: stepResult.toolCalls.map((tc) => ({
665
+ id: tc.toolCallId,
666
+ name: tc.toolName,
667
+ args: tc.args as Record<string, unknown>,
668
+ })),
669
+ createdAt: new Date(),
670
+ },
671
+ ])
672
+ }
673
+
674
+ await aiRunState.updateRun(run.runId, {
675
+ status: 'suspended',
676
+ suspendReason: 'approval',
677
+ pendingApprovals,
678
+ usage: { ...totalUsage, model: agent.model },
679
+ })
680
+
681
+ const suspendedText = lastStepResult?.text ?? ''
682
+ return {
683
+ runId: run.runId,
684
+ text: suspendedText,
685
+ threadId: run.threadId,
686
+ steps: accumulatedSteps,
687
+ usage: totalUsage,
688
+ status: 'suspended',
689
+ pendingApprovals: approvalsNeeded.map((a) => ({
690
+ toolCallId: a.toolCallId,
691
+ toolName: a.displayToolName ?? a.toolName,
692
+ args: a.displayArgs ?? a.args,
693
+ reason: a.reason,
694
+ runId: run.runId,
695
+ })),
696
+ }
697
+ }
698
+
699
+ appendStepMessages(runnerParams, stepResult)
700
+ }
701
+
702
+ const finalText = lastStepResult?.text ?? ''
703
+ const finalObject = lastStepResult?.object
704
+
705
+ const result = {
706
+ text: finalText,
707
+ steps: accumulatedSteps,
708
+ }
709
+
710
+ const responseText = await saveMessages(
711
+ storage,
712
+ run.threadId,
713
+ run.resourceId,
714
+ memoryConfig,
715
+ null as any,
716
+ result,
717
+ {
718
+ workingMemoryJsonSchema,
719
+ workingMemorySchemaName,
720
+ logger: singletonServices.logger,
721
+ schemaService: singletonServices.schema,
722
+ }
723
+ )
724
+
725
+ let outputText = responseText
726
+ let outputMessages = runnerParams.messages
727
+ for (let i = aiMiddlewares.length - 1; i >= 0; i--) {
728
+ const mw = aiMiddlewares[i]
729
+ if (mw.modifyOutput) {
730
+ const modResult = await mw.modifyOutput(singletonServices, {
731
+ text: outputText,
732
+ messages: outputMessages,
733
+ usage: totalUsage,
734
+ })
735
+ outputText = modResult.text
736
+ outputMessages = modResult.messages
737
+ }
738
+ }
739
+
740
+ await aiRunState.updateRun(run.runId, {
741
+ status: 'completed',
742
+ usage: { ...totalUsage, model: agent.model },
743
+ })
744
+
745
+ return {
746
+ runId: run.runId,
747
+ text: outputText,
748
+ object: finalObject,
749
+ threadId: run.threadId,
750
+ steps: accumulatedSteps,
751
+ usage: totalUsage,
752
+ }
753
+ } catch (error) {
754
+ for (const mw of aiMiddlewares) {
755
+ if (mw.onError) {
756
+ try {
757
+ await mw.onError(singletonServices, {
758
+ error: error instanceof Error ? error : new Error(String(error)),
759
+ stepNumber: -1,
760
+ messages: runnerParams.messages,
761
+ })
762
+ } catch {
763
+ // ignore
764
+ }
765
+ }
766
+ }
767
+ await aiRunState.updateRun(run.runId, {
768
+ status: 'failed',
769
+ errorMessage: error instanceof Error ? error.message : String(error),
770
+ })
771
+ throw error
772
+ }
773
+ }