@pikku/core 0.12.0 → 0.12.1

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 (262) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/errors/errors.d.ts +6 -0
  3. package/dist/errors/errors.js +10 -0
  4. package/dist/errors/index.d.ts +1 -0
  5. package/dist/errors/index.js +1 -0
  6. package/dist/function/function-runner.d.ts +3 -3
  7. package/dist/function/function-runner.js +66 -44
  8. package/dist/function/functions.types.d.ts +1 -0
  9. package/dist/handle-error.d.ts +2 -2
  10. package/dist/handle-error.js +2 -2
  11. package/dist/index.d.ts +5 -3
  12. package/dist/index.js +2 -1
  13. package/dist/internal.d.ts +3 -0
  14. package/dist/internal.js +2 -0
  15. package/dist/middleware/auth-bearer.d.ts +1 -1
  16. package/dist/middleware/auth-bearer.js +1 -1
  17. package/dist/middleware/auth-cookie.d.ts +2 -2
  18. package/dist/middleware/auth-cookie.js +1 -1
  19. package/dist/middleware/cors.d.ts +2 -2
  20. package/dist/middleware/cors.js +45 -37
  21. package/dist/middleware-runner.d.ts +1 -1
  22. package/dist/permissions.d.ts +2 -2
  23. package/dist/pikku-state.d.ts +9 -8
  24. package/dist/pikku-state.js +30 -17
  25. package/dist/schema.d.ts +4 -4
  26. package/dist/schema.js +9 -5
  27. package/dist/services/ai-agent-runner-service.d.ts +22 -3
  28. package/dist/services/ai-run-state-service.d.ts +1 -1
  29. package/dist/services/ai-storage-service.d.ts +1 -1
  30. package/dist/services/content-service.d.ts +6 -0
  31. package/dist/services/gopass-secrets.d.ts +1 -1
  32. package/dist/services/gopass-secrets.js +3 -0
  33. package/dist/services/in-memory-ai-run-state-service.d.ts +15 -0
  34. package/dist/services/in-memory-ai-run-state-service.js +44 -0
  35. package/dist/services/in-memory-trigger-service.d.ts +0 -1
  36. package/dist/services/in-memory-trigger-service.js +6 -8
  37. package/dist/services/index.d.ts +3 -2
  38. package/dist/services/index.js +1 -0
  39. package/dist/services/local-content.d.ts +2 -1
  40. package/dist/services/local-content.js +6 -1
  41. package/dist/services/local-secrets.d.ts +2 -2
  42. package/dist/services/local-variables.d.ts +1 -1
  43. package/dist/services/logger-console.d.ts +2 -1
  44. package/dist/services/scheduler-service.d.ts +0 -12
  45. package/dist/services/scheduler-service.js +0 -6
  46. package/dist/services/scoped-secret-service.d.ts +1 -1
  47. package/dist/services/trigger-service.d.ts +0 -7
  48. package/dist/services/user-session-service.d.ts +3 -3
  49. package/dist/services/workflow-service.d.ts +2 -3
  50. package/dist/types/core.types.d.ts +24 -18
  51. package/dist/types/state.types.d.ts +17 -15
  52. package/dist/utils.d.ts +5 -5
  53. package/dist/utils.js +12 -9
  54. package/dist/wirings/ai-agent/ai-agent-assistant-ui.d.ts +5 -0
  55. package/dist/wirings/ai-agent/ai-agent-assistant-ui.js +146 -0
  56. package/dist/wirings/ai-agent/ai-agent-helpers.d.ts +28 -0
  57. package/dist/wirings/ai-agent/ai-agent-helpers.js +40 -0
  58. package/dist/wirings/ai-agent/ai-agent-prepare.d.ts +4 -5
  59. package/dist/wirings/ai-agent/ai-agent-prepare.js +66 -30
  60. package/dist/wirings/ai-agent/ai-agent-registry.d.ts +1 -1
  61. package/dist/wirings/ai-agent/ai-agent-runner.js +107 -8
  62. package/dist/wirings/ai-agent/ai-agent-stream.d.ts +2 -1
  63. package/dist/wirings/ai-agent/ai-agent-stream.js +246 -87
  64. package/dist/wirings/ai-agent/ai-agent.types.d.ts +61 -2
  65. package/dist/wirings/ai-agent/index.d.ts +3 -1
  66. package/dist/wirings/ai-agent/index.js +2 -0
  67. package/dist/wirings/channel/channel-common.d.ts +2 -2
  68. package/dist/wirings/channel/channel-handler.d.ts +3 -3
  69. package/dist/wirings/channel/channel-handler.js +4 -4
  70. package/dist/wirings/channel/channel-runner.d.ts +5 -5
  71. package/dist/wirings/channel/channel-runner.js +3 -2
  72. package/dist/wirings/channel/channel-store.d.ts +1 -1
  73. package/dist/wirings/channel/channel.types.d.ts +4 -6
  74. package/dist/wirings/channel/local/local-channel-runner.d.ts +7 -2
  75. package/dist/wirings/channel/local/local-channel-runner.js +4 -3
  76. package/dist/wirings/channel/local/local-eventhub-service.d.ts +2 -2
  77. package/dist/wirings/channel/log-channels.d.ts +1 -1
  78. package/dist/wirings/channel/pikku-abstract-channel-handler.d.ts +1 -1
  79. package/dist/wirings/channel/serverless/serverless-channel-runner.d.ts +4 -4
  80. package/dist/wirings/channel/serverless/serverless-channel-runner.js +25 -19
  81. package/dist/wirings/cli/channel/cli-channel-runner.d.ts +1 -1
  82. package/dist/wirings/cli/cli-runner.d.ts +2 -2
  83. package/dist/wirings/cli/cli.types.d.ts +3 -3
  84. package/dist/wirings/cli/command-parser.d.ts +1 -1
  85. package/dist/wirings/http/http-runner.d.ts +9 -9
  86. package/dist/wirings/http/http-runner.js +33 -14
  87. package/dist/wirings/http/http.types.d.ts +2 -6
  88. package/dist/wirings/http/log-http-routes.d.ts +1 -1
  89. package/dist/wirings/http/pikku-fetch-http-request.d.ts +1 -1
  90. package/dist/wirings/http/pikku-fetch-http-response.d.ts +2 -2
  91. package/dist/wirings/http/pikku-fetch-http-response.js +6 -1
  92. package/dist/wirings/http/routers/http-router.d.ts +1 -1
  93. package/dist/wirings/http/routers/path-to-regex.d.ts +2 -2
  94. package/dist/wirings/mcp/mcp-endpoint-registry.d.ts +1 -1
  95. package/dist/wirings/mcp/mcp-runner.d.ts +0 -3
  96. package/dist/wirings/mcp/mcp-runner.js +4 -2
  97. package/dist/wirings/mcp/mcp.types.d.ts +2 -2
  98. package/dist/wirings/oauth2/oauth2-client.d.ts +3 -3
  99. package/dist/wirings/oauth2/wire-oauth2-credential.d.ts +1 -1
  100. package/dist/wirings/queue/index.d.ts +1 -1
  101. package/dist/wirings/queue/index.js +1 -1
  102. package/dist/wirings/queue/queue-runner.d.ts +1 -12
  103. package/dist/wirings/queue/queue-runner.js +4 -12
  104. package/dist/wirings/queue/queue.types.d.ts +3 -9
  105. package/dist/wirings/queue/register-queue-helper.d.ts +2 -2
  106. package/dist/wirings/queue/register-queue-helper.js +1 -1
  107. package/dist/wirings/queue/validate-worker-config.d.ts +1 -1
  108. package/dist/wirings/rpc/index.d.ts +2 -0
  109. package/dist/wirings/rpc/index.js +1 -0
  110. package/dist/wirings/rpc/rpc-runner.d.ts +36 -14
  111. package/dist/wirings/rpc/rpc-runner.js +56 -28
  112. package/dist/wirings/rpc/rpc-types.d.ts +14 -2
  113. package/dist/wirings/rpc/wire-addon.d.ts +10 -0
  114. package/dist/wirings/rpc/wire-addon.js +9 -0
  115. package/dist/wirings/scheduler/index.d.ts +1 -1
  116. package/dist/wirings/scheduler/index.js +1 -1
  117. package/dist/wirings/scheduler/log-schedulers.d.ts +1 -1
  118. package/dist/wirings/scheduler/scheduler-runner.d.ts +3 -10
  119. package/dist/wirings/scheduler/scheduler-runner.js +4 -25
  120. package/dist/wirings/scheduler/scheduler.types.d.ts +2 -2
  121. package/dist/wirings/trigger/pikku-trigger-service.d.ts +2 -6
  122. package/dist/wirings/trigger/pikku-trigger-service.js +11 -16
  123. package/dist/wirings/trigger/trigger-runner.d.ts +1 -5
  124. package/dist/wirings/trigger/trigger-runner.js +4 -3
  125. package/dist/wirings/workflow/pikku-workflow-service.d.ts +2 -6
  126. package/dist/wirings/workflow/pikku-workflow-service.js +20 -29
  127. package/dist/wirings/workflow/workflow.types.d.ts +2 -2
  128. package/package.json +2 -1
  129. package/src/crypto-utils.test.ts +116 -0
  130. package/src/errors/error.test.ts +143 -2
  131. package/src/errors/errors.ts +10 -0
  132. package/src/errors/index.ts +1 -0
  133. package/src/function/function-runner.test.ts +2 -2
  134. package/src/function/function-runner.ts +72 -49
  135. package/src/function/functions.types.ts +1 -0
  136. package/src/handle-error.test.ts +361 -0
  137. package/src/handle-error.ts +4 -4
  138. package/src/index.ts +3 -10
  139. package/src/internal.ts +6 -0
  140. package/src/middleware/auth-apikey.test.ts +1 -1
  141. package/src/middleware/auth-bearer.test.ts +1 -1
  142. package/src/middleware/auth-bearer.ts +2 -5
  143. package/src/middleware/auth-cookie.test.ts +1 -1
  144. package/src/middleware/auth-cookie.ts +3 -5
  145. package/src/middleware/cors.test.ts +424 -0
  146. package/src/middleware/cors.ts +14 -6
  147. package/src/middleware/remote-auth.test.ts +488 -0
  148. package/src/middleware-runner.test.ts +1 -1
  149. package/src/middleware-runner.ts +1 -1
  150. package/src/permissions.test.ts +2 -2
  151. package/src/permissions.ts +2 -2
  152. package/src/pikku-state.test.ts +224 -0
  153. package/src/pikku-state.ts +40 -28
  154. package/src/schema.test.ts +198 -6
  155. package/src/schema.ts +11 -7
  156. package/src/services/ai-agent-runner-service.ts +15 -3
  157. package/src/services/ai-run-state-service.ts +1 -1
  158. package/src/services/ai-storage-service.ts +1 -1
  159. package/src/services/content-service.ts +7 -0
  160. package/src/services/gopass-secrets.ts +4 -1
  161. package/src/services/in-memory-ai-run-state-service.ts +73 -0
  162. package/src/services/in-memory-trigger-service.ts +6 -10
  163. package/src/services/in-memory-workflow-service.test.ts +351 -0
  164. package/src/services/index.ts +2 -1
  165. package/src/services/local-content.ts +9 -3
  166. package/src/services/local-secrets.test.ts +80 -0
  167. package/src/services/local-secrets.ts +2 -2
  168. package/src/services/local-variables.test.ts +61 -0
  169. package/src/services/local-variables.ts +1 -1
  170. package/src/services/logger-console.test.ts +118 -0
  171. package/src/services/logger-console.ts +2 -1
  172. package/src/services/scheduler-service.ts +0 -18
  173. package/src/services/scoped-secret-service.test.ts +74 -0
  174. package/src/services/scoped-secret-service.ts +1 -1
  175. package/src/services/trigger-service.ts +0 -21
  176. package/src/services/typed-secret-service.test.ts +93 -0
  177. package/src/services/typed-variables-service.test.ts +73 -0
  178. package/src/services/user-session-service.test.ts +113 -0
  179. package/src/services/user-session-service.ts +3 -3
  180. package/src/services/workflow-service.ts +2 -12
  181. package/src/time-utils.test.ts +1 -1
  182. package/src/types/core.types.ts +25 -19
  183. package/src/types/state.types.ts +24 -15
  184. package/src/utils.test.ts +350 -0
  185. package/src/utils.ts +14 -13
  186. package/src/wirings/ai-agent/ai-agent-assistant-ui.test.ts +363 -0
  187. package/src/wirings/ai-agent/ai-agent-assistant-ui.ts +214 -0
  188. package/src/wirings/ai-agent/ai-agent-helpers.test.ts +152 -0
  189. package/src/wirings/ai-agent/ai-agent-helpers.ts +76 -0
  190. package/src/wirings/ai-agent/ai-agent-model-config.test.ts +115 -0
  191. package/src/wirings/ai-agent/ai-agent-prepare.ts +79 -45
  192. package/src/wirings/ai-agent/ai-agent-registry.ts +1 -1
  193. package/src/wirings/ai-agent/ai-agent-runner.test.ts +245 -3
  194. package/src/wirings/ai-agent/ai-agent-runner.ts +121 -7
  195. package/src/wirings/ai-agent/ai-agent-stream.test.ts +430 -24
  196. package/src/wirings/ai-agent/ai-agent-stream.ts +377 -102
  197. package/src/wirings/ai-agent/ai-agent.types.ts +57 -2
  198. package/src/wirings/ai-agent/index.ts +11 -0
  199. package/src/wirings/channel/channel-common.ts +2 -2
  200. package/src/wirings/channel/channel-handler.ts +13 -9
  201. package/src/wirings/channel/channel-runner.ts +6 -6
  202. package/src/wirings/channel/channel-store.ts +1 -1
  203. package/src/wirings/channel/channel.types.ts +4 -8
  204. package/src/wirings/channel/local/local-channel-runner.test.ts +19 -12
  205. package/src/wirings/channel/local/local-channel-runner.ts +18 -13
  206. package/src/wirings/channel/local/local-eventhub-service.test.ts +2 -2
  207. package/src/wirings/channel/local/local-eventhub-service.ts +2 -2
  208. package/src/wirings/channel/log-channels.ts +1 -1
  209. package/src/wirings/channel/pikku-abstract-channel-handler.ts +1 -1
  210. package/src/wirings/channel/serverless/serverless-channel-runner.ts +37 -32
  211. package/src/wirings/cli/channel/cli-channel-runner.ts +1 -1
  212. package/src/wirings/cli/cli-runner.test.ts +1 -1
  213. package/src/wirings/cli/cli-runner.ts +11 -4
  214. package/src/wirings/cli/cli.types.ts +3 -3
  215. package/src/wirings/cli/command-parser.test.ts +1 -1
  216. package/src/wirings/cli/command-parser.ts +1 -1
  217. package/src/wirings/http/http-routes.test.ts +1 -1
  218. package/src/wirings/http/http-runner.test.ts +9 -17
  219. package/src/wirings/http/http-runner.ts +43 -27
  220. package/src/wirings/http/http.types.ts +1 -14
  221. package/src/wirings/http/log-http-routes.ts +1 -1
  222. package/src/wirings/http/pikku-fetch-http-request.ts +1 -1
  223. package/src/wirings/http/pikku-fetch-http-response.ts +12 -5
  224. package/src/wirings/http/routers/http-router.ts +1 -1
  225. package/src/wirings/http/routers/path-to-regex.test.ts +1 -1
  226. package/src/wirings/http/routers/path-to-regex.ts +4 -3
  227. package/src/wirings/mcp/mcp-endpoint-registry.ts +5 -1
  228. package/src/wirings/mcp/mcp-runner.ts +9 -15
  229. package/src/wirings/mcp/mcp.types.ts +2 -2
  230. package/src/wirings/oauth2/oauth2-client.ts +3 -3
  231. package/src/wirings/oauth2/wire-oauth2-credential.ts +1 -1
  232. package/src/wirings/queue/index.ts +0 -1
  233. package/src/wirings/queue/queue-runner.test.ts +52 -25
  234. package/src/wirings/queue/queue-runner.ts +8 -30
  235. package/src/wirings/queue/queue.types.ts +3 -13
  236. package/src/wirings/queue/register-queue-helper.ts +3 -5
  237. package/src/wirings/queue/validate-worker-config.test.ts +108 -0
  238. package/src/wirings/queue/validate-worker-config.ts +4 -1
  239. package/src/wirings/rpc/index.ts +2 -0
  240. package/src/wirings/rpc/rpc-runner.ts +92 -49
  241. package/src/wirings/rpc/rpc-types.ts +17 -2
  242. package/src/wirings/rpc/wire-addon.ts +20 -0
  243. package/src/wirings/scheduler/index.ts +0 -1
  244. package/src/wirings/scheduler/log-schedulers.ts +1 -1
  245. package/src/wirings/scheduler/scheduler-runner.test.ts +49 -60
  246. package/src/wirings/scheduler/scheduler-runner.ts +9 -56
  247. package/src/wirings/scheduler/scheduler.types.ts +2 -2
  248. package/src/wirings/secret/validate-secret-definitions.test.ts +140 -0
  249. package/src/wirings/trigger/pikku-trigger-service.ts +17 -39
  250. package/src/wirings/trigger/trigger-runner.test.ts +79 -0
  251. package/src/wirings/trigger/trigger-runner.ts +8 -11
  252. package/src/wirings/variable/validate-variable-definitions.test.ts +91 -0
  253. package/src/wirings/workflow/graph/graph-runner.test.ts +14 -22
  254. package/src/wirings/workflow/graph/template.test.ts +49 -0
  255. package/src/wirings/workflow/pikku-workflow-service.test.ts +15 -27
  256. package/src/wirings/workflow/pikku-workflow-service.ts +29 -45
  257. package/src/wirings/workflow/workflow-helpers.test.ts +129 -0
  258. package/src/wirings/workflow/workflow.types.ts +2 -2
  259. package/tsconfig.tsbuildinfo +1 -1
  260. package/dist/wirings/workflow/workflow-utils.d.ts +0 -1
  261. package/dist/wirings/workflow/workflow-utils.js +0 -1
  262. package/src/wirings/workflow/workflow-utils.ts +0 -0
@@ -4,7 +4,12 @@ import assert from 'node:assert/strict'
4
4
  import { resetPikkuState, pikkuState } from '../../pikku-state.js'
5
5
  import { streamAIAgent } from './ai-agent-stream.js'
6
6
  import { ToolApprovalRequired } from './ai-agent-prepare.js'
7
- import type { CoreAIAgent, AIStreamEvent } from './ai-agent.types.js'
7
+ import type {
8
+ CoreAIAgent,
9
+ AIStreamEvent,
10
+ PikkuAIMiddlewareHooks,
11
+ } from './ai-agent.types.js'
12
+ import type { AIAgentStepResult } from '../../services/ai-agent-runner-service.js'
8
13
 
9
14
  beforeEach(() => {
10
15
  resetPikkuState()
@@ -30,6 +35,17 @@ const addTestAgent = (agentName: string) => {
30
35
  })
31
36
  }
32
37
 
38
+ const makeStepResult = (
39
+ overrides?: Partial<AIAgentStepResult>
40
+ ): AIAgentStepResult => ({
41
+ text: '',
42
+ toolCalls: [],
43
+ toolResults: [],
44
+ usage: { inputTokens: 0, outputTokens: 0 },
45
+ finishReason: 'stop',
46
+ ...overrides,
47
+ })
48
+
33
49
  describe('streamAIAgent', () => {
34
50
  test('marks run as failed and emits error/done when stream runner throws', async () => {
35
51
  addTestAgent('failing-stream-agent')
@@ -37,7 +53,7 @@ describe('streamAIAgent', () => {
37
53
  const updates: Array<{ runId: string; patch: unknown }> = []
38
54
  const events: AIStreamEvent[] = []
39
55
 
40
- const singletonServices = {
56
+ const mockServices = {
41
57
  logger: {
42
58
  info: () => {},
43
59
  warn: () => {},
@@ -57,6 +73,8 @@ describe('streamAIAgent', () => {
57
73
  },
58
74
  } as any
59
75
 
76
+ pikkuState(null, 'package', 'singletonServices', mockServices)
77
+
60
78
  await streamAIAgent(
61
79
  'failing-stream-agent',
62
80
  {
@@ -73,23 +91,76 @@ describe('streamAIAgent', () => {
73
91
  },
74
92
  close: () => {},
75
93
  },
76
- { singletonServices }
94
+ {}
77
95
  )
78
96
 
79
97
  assert.deepEqual(updates, [{ runId: 'run-1', patch: { status: 'failed' } }])
80
98
  assert.deepEqual(
81
99
  events.map((event) => event.type),
82
- ['error', 'done']
100
+ ['step-start', 'error', 'done']
101
+ )
102
+ })
103
+
104
+ test('completes normally when stream returns no tool calls', async () => {
105
+ addTestAgent('simple-stream-agent')
106
+
107
+ const updates: Array<{ runId: string; patch: unknown }> = []
108
+ const events: AIStreamEvent[] = []
109
+
110
+ const mockServices = {
111
+ logger: {
112
+ info: () => {},
113
+ warn: () => {},
114
+ error: () => {},
115
+ debug: () => {},
116
+ },
117
+ aiAgentRunner: {
118
+ stream: async (): Promise<AIAgentStepResult> => {
119
+ return makeStepResult({ text: 'Hello world' })
120
+ },
121
+ },
122
+ aiRunState: {
123
+ createRun: async () => 'run-simple',
124
+ updateRun: async (runId: string, patch: unknown) => {
125
+ updates.push({ runId, patch })
126
+ },
127
+ },
128
+ } as any
129
+
130
+ pikkuState(null, 'package', 'singletonServices', mockServices)
131
+
132
+ await streamAIAgent(
133
+ 'simple-stream-agent',
134
+ {
135
+ message: 'hello',
136
+ threadId: 'thread-simple',
137
+ resourceId: 'resource-simple',
138
+ },
139
+ {
140
+ channelId: 'channel-simple',
141
+ openingData: undefined,
142
+ state: 'open',
143
+ send: (event: AIStreamEvent) => {
144
+ events.push(event)
145
+ },
146
+ close: () => {},
147
+ },
148
+ {}
83
149
  )
150
+
151
+ assert.deepEqual(updates, [
152
+ { runId: 'run-simple', patch: { status: 'completed' } },
153
+ ])
154
+ assert.ok(events.some((e) => e.type === 'done'))
84
155
  })
85
156
 
86
- test('suspends run and emits approval request when tool approval is required (no throw)', async () => {
157
+ test('suspends run when tool needs approval (needsApproval flag)', async () => {
87
158
  addTestAgent('approval-stream-agent')
88
159
 
89
160
  const updates: Array<{ runId: string; patch: unknown }> = []
90
161
  const events: AIStreamEvent[] = []
91
162
 
92
- const singletonServices = {
163
+ const mockServices = {
93
164
  logger: {
94
165
  info: () => {},
95
166
  warn: () => {},
@@ -97,8 +168,16 @@ describe('streamAIAgent', () => {
97
168
  debug: () => {},
98
169
  },
99
170
  aiAgentRunner: {
100
- stream: async () => {
101
- throw new ToolApprovalRequired('tool-call-1', 'tool-x', { id: 1 })
171
+ stream: async (): Promise<AIAgentStepResult> => {
172
+ return makeStepResult({
173
+ toolCalls: [
174
+ {
175
+ toolCallId: 'tool-call-1',
176
+ toolName: 'tool-x',
177
+ args: { id: 1 },
178
+ },
179
+ ],
180
+ })
102
181
  },
103
182
  },
104
183
  aiRunState: {
@@ -109,8 +188,25 @@ describe('streamAIAgent', () => {
109
188
  },
110
189
  } as any
111
190
 
191
+ pikkuState(null, 'package', 'singletonServices', mockServices)
192
+
193
+ const agentName = 'approval-stream-agent'
194
+ const agent = pikkuState(null, 'agent', 'agents').get(agentName)!
195
+ agent.tools = ['tool-x']
196
+ pikkuState(null, 'agent', 'agents').set(agentName, agent)
197
+ pikkuState(null, 'agent', 'agentsMeta')[agentName].tools = ['tool-x']
198
+ pikkuState(null, 'rpc', 'meta')['tool-x'] = 'tool-x'
199
+ pikkuState(null, 'function', 'meta')['tool-x'] = {
200
+ description: 'test tool',
201
+ requiresApproval: true,
202
+ }
203
+ pikkuState(null, 'misc', 'schemas').set('ToolXInput', {
204
+ type: 'object',
205
+ properties: { id: { type: 'number' } },
206
+ })
207
+
112
208
  await streamAIAgent(
113
- 'approval-stream-agent',
209
+ agentName,
114
210
  {
115
211
  message: 'hello',
116
212
  threadId: 'thread-2',
@@ -125,7 +221,7 @@ describe('streamAIAgent', () => {
125
221
  },
126
222
  close: () => {},
127
223
  },
128
- { singletonServices },
224
+ {},
129
225
  undefined,
130
226
  { requiresToolApproval: 'all' }
131
227
  )
@@ -157,18 +253,20 @@ describe('streamAIAgent', () => {
157
253
  assert.deepEqual(approvalEvent.args, { id: 1 })
158
254
 
159
255
  assert.deepEqual(
160
- events.map((event) => event.type),
256
+ events
257
+ .filter((e) => e.type === 'approval-request' || e.type === 'done')
258
+ .map((e) => e.type),
161
259
  ['approval-request', 'done']
162
260
  )
163
261
  })
164
262
 
165
- test('suspends with agent-call type when agentRunId is present', async () => {
263
+ test('suspends with agent-call type when sub-agent returns approval sentinel', async () => {
166
264
  addTestAgent('parent-agent')
167
265
 
168
266
  const updates: Array<{ runId: string; patch: unknown }> = []
169
267
  const events: AIStreamEvent[] = []
170
268
 
171
- const singletonServices = {
269
+ const mockServices = {
172
270
  logger: {
173
271
  info: () => {},
174
272
  warn: () => {},
@@ -176,16 +274,30 @@ describe('streamAIAgent', () => {
176
274
  debug: () => {},
177
275
  },
178
276
  aiAgentRunner: {
179
- stream: async () => {
180
- throw new ToolApprovalRequired(
181
- 'tool-call-2',
182
- 'sub-agent',
183
- { message: 'hi' },
184
- undefined,
185
- 'deleteTodo',
186
- { todoId: '2' },
187
- 'sub-run-1'
188
- )
277
+ stream: async (): Promise<AIAgentStepResult> => {
278
+ return makeStepResult({
279
+ toolCalls: [
280
+ {
281
+ toolCallId: 'tool-call-2',
282
+ toolName: 'sub-agent',
283
+ args: { message: 'hi' },
284
+ },
285
+ ],
286
+ toolResults: [
287
+ {
288
+ toolCallId: 'tool-call-2',
289
+ toolName: 'sub-agent',
290
+ result: {
291
+ __approvalRequired: true,
292
+ toolName: 'sub-agent',
293
+ args: { message: 'hi' },
294
+ displayToolName: 'deleteTodo',
295
+ displayArgs: { todoId: '2' },
296
+ agentRunId: 'sub-run-1',
297
+ },
298
+ },
299
+ ],
300
+ })
189
301
  },
190
302
  },
191
303
  aiRunState: {
@@ -196,6 +308,8 @@ describe('streamAIAgent', () => {
196
308
  },
197
309
  } as any
198
310
 
311
+ pikkuState(null, 'package', 'singletonServices', mockServices)
312
+
199
313
  await streamAIAgent(
200
314
  'parent-agent',
201
315
  {
@@ -212,7 +326,7 @@ describe('streamAIAgent', () => {
212
326
  },
213
327
  close: () => {},
214
328
  },
215
- { singletonServices }
329
+ {}
216
330
  )
217
331
 
218
332
  assert.deepEqual(updates, [
@@ -243,4 +357,296 @@ describe('streamAIAgent', () => {
243
357
  assert.equal(approvalEvent.toolName, 'deleteTodo')
244
358
  assert.deepEqual(approvalEvent.args, { todoId: '2' })
245
359
  })
360
+
361
+ test('loops through multiple steps when tools are called', async () => {
362
+ addTestAgent('multi-step-agent')
363
+
364
+ const updates: Array<{ runId: string; patch: unknown }> = []
365
+ const events: AIStreamEvent[] = []
366
+ let callCount = 0
367
+
368
+ const mockServices = {
369
+ logger: {
370
+ info: () => {},
371
+ warn: () => {},
372
+ error: () => {},
373
+ debug: () => {},
374
+ },
375
+ aiAgentRunner: {
376
+ stream: async (): Promise<AIAgentStepResult> => {
377
+ callCount++
378
+ if (callCount === 1) {
379
+ return makeStepResult({
380
+ text: 'Calling tool...',
381
+ toolCalls: [
382
+ { toolCallId: 'tc-1', toolName: 'myTool', args: { q: 'test' } },
383
+ ],
384
+ toolResults: [
385
+ {
386
+ toolCallId: 'tc-1',
387
+ toolName: 'myTool',
388
+ result: 'tool result',
389
+ },
390
+ ],
391
+ finishReason: 'tool-calls',
392
+ })
393
+ }
394
+ return makeStepResult({ text: 'Final answer', finishReason: 'stop' })
395
+ },
396
+ },
397
+ aiRunState: {
398
+ createRun: async () => 'run-multi',
399
+ updateRun: async (runId: string, patch: unknown) => {
400
+ updates.push({ runId, patch })
401
+ },
402
+ },
403
+ } as any
404
+
405
+ pikkuState(null, 'package', 'singletonServices', mockServices)
406
+
407
+ await streamAIAgent(
408
+ 'multi-step-agent',
409
+ {
410
+ message: 'hello',
411
+ threadId: 'thread-multi',
412
+ resourceId: 'resource-multi',
413
+ },
414
+ {
415
+ channelId: 'channel-multi',
416
+ openingData: undefined,
417
+ state: 'open',
418
+ send: (event: AIStreamEvent) => {
419
+ events.push(event)
420
+ },
421
+ close: () => {},
422
+ },
423
+ {}
424
+ )
425
+
426
+ assert.equal(callCount, 2)
427
+ assert.deepEqual(updates, [
428
+ { runId: 'run-multi', patch: { status: 'completed' } },
429
+ ])
430
+ assert.ok(events.some((e) => e.type === 'done'))
431
+ })
432
+
433
+ test('afterStep hook is called for each stream step', async () => {
434
+ addTestAgent('afterstep-stream-agent')
435
+
436
+ const afterStepCalls: unknown[] = []
437
+ const middleware: PikkuAIMiddlewareHooks = {
438
+ afterStep: async (_services, ctx) => {
439
+ afterStepCalls.push(ctx)
440
+ },
441
+ }
442
+ const agent = pikkuState(null, 'agent', 'agents').get(
443
+ 'afterstep-stream-agent'
444
+ )!
445
+ agent.aiMiddleware = [middleware] as any
446
+ pikkuState(null, 'agent', 'agents').set('afterstep-stream-agent', agent)
447
+
448
+ let callCount = 0
449
+ const events: AIStreamEvent[] = []
450
+
451
+ const mockServices = {
452
+ logger: {
453
+ info: () => {},
454
+ warn: () => {},
455
+ error: () => {},
456
+ debug: () => {},
457
+ },
458
+ aiAgentRunner: {
459
+ stream: async (): Promise<AIAgentStepResult> => {
460
+ callCount++
461
+ if (callCount === 1) {
462
+ return makeStepResult({
463
+ text: 'step1',
464
+ toolCalls: [
465
+ { toolCallId: 'tc-1', toolName: 'myTool', args: { q: 'x' } },
466
+ ],
467
+ toolResults: [
468
+ { toolCallId: 'tc-1', toolName: 'myTool', result: 'ok' },
469
+ ],
470
+ usage: { inputTokens: 10, outputTokens: 5 },
471
+ finishReason: 'tool-calls',
472
+ })
473
+ }
474
+ return makeStepResult({
475
+ text: 'final',
476
+ finishReason: 'stop',
477
+ })
478
+ },
479
+ },
480
+ aiRunState: {
481
+ createRun: async () => 'run-as',
482
+ updateRun: async () => {},
483
+ },
484
+ } as any
485
+
486
+ pikkuState(null, 'package', 'singletonServices', mockServices)
487
+
488
+ await streamAIAgent(
489
+ 'afterstep-stream-agent',
490
+ { message: 'hi', threadId: 't-as', resourceId: 'r-as' },
491
+ {
492
+ channelId: 'c-as',
493
+ openingData: undefined,
494
+ state: 'open',
495
+ send: (event: AIStreamEvent) => events.push(event),
496
+ close: () => {},
497
+ },
498
+ {}
499
+ )
500
+
501
+ assert.equal(afterStepCalls.length, 2)
502
+ assert.equal((afterStepCalls[0] as any).stepNumber, 0)
503
+ assert.equal((afterStepCalls[0] as any).finishReason, 'tool-calls')
504
+ assert.equal((afterStepCalls[1] as any).stepNumber, 1)
505
+ assert.equal((afterStepCalls[1] as any).text, 'final')
506
+ })
507
+
508
+ test('onError hook is called when stream throws', async () => {
509
+ addTestAgent('onerror-stream-agent')
510
+
511
+ const onErrorCalls: unknown[] = []
512
+ const middleware: PikkuAIMiddlewareHooks = {
513
+ onError: async (_services, ctx) => {
514
+ onErrorCalls.push(ctx)
515
+ },
516
+ }
517
+ const agent = pikkuState(null, 'agent', 'agents').get(
518
+ 'onerror-stream-agent'
519
+ )!
520
+ agent.aiMiddleware = [middleware] as any
521
+ pikkuState(null, 'agent', 'agents').set('onerror-stream-agent', agent)
522
+
523
+ const events: AIStreamEvent[] = []
524
+ const mockServices = {
525
+ logger: {
526
+ info: () => {},
527
+ warn: () => {},
528
+ error: () => {},
529
+ debug: () => {},
530
+ },
531
+ aiAgentRunner: {
532
+ stream: async () => {
533
+ throw new Error('stream boom')
534
+ },
535
+ },
536
+ aiRunState: {
537
+ createRun: async () => 'run-oe',
538
+ updateRun: async () => {},
539
+ },
540
+ } as any
541
+
542
+ pikkuState(null, 'package', 'singletonServices', mockServices)
543
+
544
+ await streamAIAgent(
545
+ 'onerror-stream-agent',
546
+ { message: 'hi', threadId: 't-oe', resourceId: 'r-oe' },
547
+ {
548
+ channelId: 'c-oe',
549
+ openingData: undefined,
550
+ state: 'open',
551
+ send: (event: AIStreamEvent) => events.push(event),
552
+ close: () => {},
553
+ },
554
+ {}
555
+ )
556
+
557
+ assert.equal(onErrorCalls.length, 1)
558
+ assert.equal((onErrorCalls[0] as any).error.message, 'stream boom')
559
+ assert.ok(events.some((e) => e.type === 'error'))
560
+ assert.ok(events.some((e) => e.type === 'done'))
561
+ })
562
+
563
+ test('beforeToolCall and afterToolCall hooks fire for tool executions', async () => {
564
+ addTestAgent('toolhooks-stream-agent')
565
+
566
+ const hookCalls: { hook: string; ctx: any }[] = []
567
+ const middleware: PikkuAIMiddlewareHooks = {
568
+ beforeToolCall: async (_services, ctx) => {
569
+ hookCalls.push({ hook: 'before', ctx })
570
+ return { args: { ...ctx.args, injected: true } }
571
+ },
572
+ afterToolCall: async (_services, ctx) => {
573
+ hookCalls.push({ hook: 'after', ctx })
574
+ return { result: `modified:${ctx.result}` }
575
+ },
576
+ }
577
+ const agentName = 'toolhooks-stream-agent'
578
+ const agent = pikkuState(null, 'agent', 'agents').get(agentName)!
579
+ agent.aiMiddleware = [middleware] as any
580
+ agent.tools = ['myTool']
581
+ pikkuState(null, 'agent', 'agents').set(agentName, agent)
582
+ pikkuState(null, 'agent', 'agentsMeta')[agentName].tools = ['myTool']
583
+ pikkuState(null, 'rpc', 'meta')['myTool'] = 'myTool'
584
+ pikkuState(null, 'function', 'meta')['myTool'] = {
585
+ description: 'test tool',
586
+ }
587
+
588
+ const events: AIStreamEvent[] = []
589
+ let callCount = 0
590
+
591
+ const mockServices = {
592
+ logger: {
593
+ info: () => {},
594
+ warn: () => {},
595
+ error: () => {},
596
+ debug: () => {},
597
+ },
598
+ aiAgentRunner: {
599
+ stream: async (
600
+ params: any,
601
+ _channel: any
602
+ ): Promise<AIAgentStepResult> => {
603
+ callCount++
604
+ if (callCount === 1) {
605
+ const tool = params.tools.find((t: any) => t.name === 'myTool')
606
+ if (tool) {
607
+ try {
608
+ await tool.execute({ q: 'test' })
609
+ } catch {
610
+ // runPikkuFunc not fully mocked; hooks still fire
611
+ }
612
+ }
613
+ return makeStepResult({
614
+ text: 'done',
615
+ finishReason: 'stop',
616
+ })
617
+ }
618
+ return makeStepResult({ text: 'done', finishReason: 'stop' })
619
+ },
620
+ },
621
+ aiRunState: {
622
+ createRun: async () => 'run-th',
623
+ updateRun: async () => {},
624
+ },
625
+ } as any
626
+
627
+ pikkuState(null, 'package', 'singletonServices', mockServices)
628
+ pikkuState(null, 'package', 'createWireServices', () => ({}))
629
+
630
+ await streamAIAgent(
631
+ agentName,
632
+ { message: 'hi', threadId: 't-th', resourceId: 'r-th' },
633
+ {
634
+ channelId: 'c-th',
635
+ openingData: undefined,
636
+ state: 'open',
637
+ send: (event: AIStreamEvent) => events.push(event),
638
+ close: () => {},
639
+ },
640
+ {}
641
+ )
642
+
643
+ assert.equal(hookCalls.length, 2)
644
+ assert.equal(hookCalls[0].hook, 'before')
645
+ assert.equal(hookCalls[0].ctx.toolName, 'myTool')
646
+ assert.deepEqual(hookCalls[0].ctx.args, { q: 'test' })
647
+ assert.equal(hookCalls[1].hook, 'after')
648
+ assert.equal(hookCalls[1].ctx.toolName, 'myTool')
649
+ assert.deepEqual(hookCalls[1].ctx.args, { q: 'test', injected: true })
650
+ assert.ok(hookCalls[1].ctx.durationMs >= 0)
651
+ })
246
652
  })