@pikku/core 0.12.3 → 0.12.4

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 (218) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/services/in-memory-workflow-service.d.ts +15 -2
  3. package/dist/services/in-memory-workflow-service.js +49 -0
  4. package/lcov.info +18891 -0
  5. package/package.json +1 -1
  6. package/src/crypto-utils.test.ts +0 -214
  7. package/src/crypto-utils.ts +0 -213
  8. package/src/errors/error-handler.ts +0 -62
  9. package/src/errors/error.test.ts +0 -195
  10. package/src/errors/errors.ts +0 -374
  11. package/src/errors/index.ts +0 -2
  12. package/src/factory-functions.test.ts +0 -109
  13. package/src/function/function-runner.test.ts +0 -536
  14. package/src/function/function-runner.ts +0 -365
  15. package/src/function/functions.types.ts +0 -304
  16. package/src/function/index.ts +0 -5
  17. package/src/handle-error.test.ts +0 -424
  18. package/src/handle-error.ts +0 -69
  19. package/src/index.ts +0 -118
  20. package/src/internal.ts +0 -6
  21. package/src/middleware/auth-apikey.test.ts +0 -363
  22. package/src/middleware/auth-apikey.ts +0 -47
  23. package/src/middleware/auth-bearer.test.ts +0 -450
  24. package/src/middleware/auth-bearer.ts +0 -72
  25. package/src/middleware/auth-cookie.test.ts +0 -528
  26. package/src/middleware/auth-cookie.ts +0 -80
  27. package/src/middleware/cors.test.ts +0 -424
  28. package/src/middleware/cors.ts +0 -104
  29. package/src/middleware/index.ts +0 -5
  30. package/src/middleware/remote-auth.test.ts +0 -488
  31. package/src/middleware/remote-auth.ts +0 -68
  32. package/src/middleware/timeout.ts +0 -15
  33. package/src/middleware-runner.test.ts +0 -418
  34. package/src/middleware-runner.ts +0 -234
  35. package/src/permissions.test.ts +0 -434
  36. package/src/permissions.ts +0 -319
  37. package/src/pikku-request.ts +0 -23
  38. package/src/pikku-response.ts +0 -5
  39. package/src/pikku-state.test.ts +0 -224
  40. package/src/pikku-state.ts +0 -216
  41. package/src/run-tests-script.test.ts +0 -49
  42. package/src/schema.test.ts +0 -249
  43. package/src/schema.ts +0 -151
  44. package/src/services/ai-agent-runner-service.ts +0 -41
  45. package/src/services/ai-run-state-service.ts +0 -20
  46. package/src/services/ai-storage-service.ts +0 -39
  47. package/src/services/content-service.ts +0 -76
  48. package/src/services/deployment-service.ts +0 -22
  49. package/src/services/gateway-service.ts +0 -20
  50. package/src/services/gopass-secrets.ts +0 -98
  51. package/src/services/in-memory-ai-run-state-service.ts +0 -73
  52. package/src/services/in-memory-trigger-service.ts +0 -64
  53. package/src/services/in-memory-workflow-service.test.ts +0 -351
  54. package/src/services/in-memory-workflow-service.ts +0 -438
  55. package/src/services/index.ts +0 -56
  56. package/src/services/jwt-service.ts +0 -30
  57. package/src/services/local-content.ts +0 -120
  58. package/src/services/local-gateway-service.ts +0 -62
  59. package/src/services/local-secrets.test.ts +0 -80
  60. package/src/services/local-secrets.ts +0 -94
  61. package/src/services/local-variables.test.ts +0 -61
  62. package/src/services/local-variables.ts +0 -39
  63. package/src/services/logger-console.test.ts +0 -118
  64. package/src/services/logger-console.ts +0 -98
  65. package/src/services/logger.ts +0 -57
  66. package/src/services/scheduler-service.ts +0 -86
  67. package/src/services/schema-service.ts +0 -33
  68. package/src/services/scoped-secret-service.test.ts +0 -74
  69. package/src/services/scoped-secret-service.ts +0 -41
  70. package/src/services/secret-service.ts +0 -38
  71. package/src/services/trigger-service.ts +0 -17
  72. package/src/services/typed-secret-service.test.ts +0 -93
  73. package/src/services/typed-secret-service.ts +0 -70
  74. package/src/services/typed-variables-service.test.ts +0 -73
  75. package/src/services/typed-variables-service.ts +0 -81
  76. package/src/services/user-session-service.test.ts +0 -113
  77. package/src/services/user-session-service.ts +0 -86
  78. package/src/services/variables-service.ts +0 -11
  79. package/src/services/workflow-service.ts +0 -95
  80. package/src/testing/index.ts +0 -2
  81. package/src/testing/service-tests.ts +0 -873
  82. package/src/time-utils.test.ts +0 -56
  83. package/src/time-utils.ts +0 -107
  84. package/src/types/core.types.ts +0 -478
  85. package/src/types/state.types.ts +0 -188
  86. package/src/utils/hash.test.ts +0 -68
  87. package/src/utils/hash.ts +0 -26
  88. package/src/utils.test.ts +0 -350
  89. package/src/utils.ts +0 -129
  90. package/src/version.test.ts +0 -80
  91. package/src/version.ts +0 -25
  92. package/src/wirings/ai-agent/agent-dynamic-workflow.ts +0 -469
  93. package/src/wirings/ai-agent/ai-agent-helpers.test.ts +0 -152
  94. package/src/wirings/ai-agent/ai-agent-helpers.ts +0 -76
  95. package/src/wirings/ai-agent/ai-agent-memory.ts +0 -310
  96. package/src/wirings/ai-agent/ai-agent-model-config.test.ts +0 -115
  97. package/src/wirings/ai-agent/ai-agent-model-config.ts +0 -43
  98. package/src/wirings/ai-agent/ai-agent-prepare.ts +0 -636
  99. package/src/wirings/ai-agent/ai-agent-registry.test.ts +0 -37
  100. package/src/wirings/ai-agent/ai-agent-registry.ts +0 -82
  101. package/src/wirings/ai-agent/ai-agent-runner.test.ts +0 -319
  102. package/src/wirings/ai-agent/ai-agent-runner.ts +0 -773
  103. package/src/wirings/ai-agent/ai-agent-stream.test.ts +0 -859
  104. package/src/wirings/ai-agent/ai-agent-stream.ts +0 -1153
  105. package/src/wirings/ai-agent/ai-agent.types.ts +0 -382
  106. package/src/wirings/ai-agent/index.ts +0 -37
  107. package/src/wirings/channel/channel-common.ts +0 -90
  108. package/src/wirings/channel/channel-handler.ts +0 -250
  109. package/src/wirings/channel/channel-middleware-runner.ts +0 -120
  110. package/src/wirings/channel/channel-runner.ts +0 -166
  111. package/src/wirings/channel/channel-store.ts +0 -29
  112. package/src/wirings/channel/channel.types.ts +0 -172
  113. package/src/wirings/channel/define-channel-routes.ts +0 -25
  114. package/src/wirings/channel/eventhub-service.ts +0 -34
  115. package/src/wirings/channel/eventhub-store.ts +0 -13
  116. package/src/wirings/channel/index.ts +0 -24
  117. package/src/wirings/channel/local/index.ts +0 -3
  118. package/src/wirings/channel/local/local-channel-handler.ts +0 -81
  119. package/src/wirings/channel/local/local-channel-runner.test.ts +0 -215
  120. package/src/wirings/channel/local/local-channel-runner.ts +0 -210
  121. package/src/wirings/channel/local/local-eventhub-service.test.ts +0 -95
  122. package/src/wirings/channel/local/local-eventhub-service.ts +0 -101
  123. package/src/wirings/channel/log-channels.ts +0 -20
  124. package/src/wirings/channel/pikku-abstract-channel-handler.test.ts +0 -54
  125. package/src/wirings/channel/pikku-abstract-channel-handler.ts +0 -45
  126. package/src/wirings/channel/serverless/index.ts +0 -5
  127. package/src/wirings/channel/serverless/serverless-channel-runner.ts +0 -289
  128. package/src/wirings/cli/channel/cli-channel-runner.ts +0 -136
  129. package/src/wirings/cli/channel/index.ts +0 -1
  130. package/src/wirings/cli/cli-runner.test.ts +0 -403
  131. package/src/wirings/cli/cli-runner.ts +0 -529
  132. package/src/wirings/cli/cli.types.ts +0 -358
  133. package/src/wirings/cli/command-parser.test.ts +0 -445
  134. package/src/wirings/cli/command-parser.ts +0 -504
  135. package/src/wirings/cli/define-cli-commands.ts +0 -24
  136. package/src/wirings/cli/index.ts +0 -19
  137. package/src/wirings/gateway/gateway-runner.test.ts +0 -474
  138. package/src/wirings/gateway/gateway-runner.ts +0 -411
  139. package/src/wirings/gateway/gateway.types.ts +0 -149
  140. package/src/wirings/gateway/index.ts +0 -13
  141. package/src/wirings/http/http-routes.test.ts +0 -322
  142. package/src/wirings/http/http-routes.ts +0 -197
  143. package/src/wirings/http/http-runner.test.ts +0 -144
  144. package/src/wirings/http/http-runner.ts +0 -588
  145. package/src/wirings/http/http.types.ts +0 -369
  146. package/src/wirings/http/index.ts +0 -28
  147. package/src/wirings/http/log-http-routes.ts +0 -22
  148. package/src/wirings/http/pikku-fetch-http-request.test.ts +0 -237
  149. package/src/wirings/http/pikku-fetch-http-request.ts +0 -170
  150. package/src/wirings/http/pikku-fetch-http-response.test.ts +0 -82
  151. package/src/wirings/http/pikku-fetch-http-response.ts +0 -147
  152. package/src/wirings/http/routers/http-router.ts +0 -13
  153. package/src/wirings/http/routers/path-to-regex.test.ts +0 -319
  154. package/src/wirings/http/routers/path-to-regex.ts +0 -126
  155. package/src/wirings/http/web-request.test.ts +0 -236
  156. package/src/wirings/http/web-request.ts +0 -104
  157. package/src/wirings/mcp/index.ts +0 -27
  158. package/src/wirings/mcp/mcp-endpoint-registry.test.ts +0 -389
  159. package/src/wirings/mcp/mcp-endpoint-registry.ts +0 -159
  160. package/src/wirings/mcp/mcp-runner.ts +0 -323
  161. package/src/wirings/mcp/mcp.types.ts +0 -216
  162. package/src/wirings/node/index.ts +0 -2
  163. package/src/wirings/node/node.types.ts +0 -23
  164. package/src/wirings/oauth2/index.ts +0 -3
  165. package/src/wirings/oauth2/oauth2-client.test.ts +0 -929
  166. package/src/wirings/oauth2/oauth2-client.ts +0 -335
  167. package/src/wirings/oauth2/oauth2.types.ts +0 -69
  168. package/src/wirings/oauth2/wire-oauth2-credential.ts +0 -23
  169. package/src/wirings/queue/index.ts +0 -31
  170. package/src/wirings/queue/queue-runner.test.ts +0 -710
  171. package/src/wirings/queue/queue-runner.ts +0 -192
  172. package/src/wirings/queue/queue.types.ts +0 -189
  173. package/src/wirings/queue/register-queue-helper.ts +0 -60
  174. package/src/wirings/queue/validate-worker-config.test.ts +0 -108
  175. package/src/wirings/queue/validate-worker-config.ts +0 -116
  176. package/src/wirings/rpc/index.ts +0 -4
  177. package/src/wirings/rpc/rpc-runner.ts +0 -460
  178. package/src/wirings/rpc/rpc-types.ts +0 -56
  179. package/src/wirings/rpc/wire-addon.ts +0 -21
  180. package/src/wirings/scheduler/index.ts +0 -11
  181. package/src/wirings/scheduler/log-schedulers.ts +0 -20
  182. package/src/wirings/scheduler/scheduler-runner.test.ts +0 -660
  183. package/src/wirings/scheduler/scheduler-runner.ts +0 -133
  184. package/src/wirings/scheduler/scheduler.types.ts +0 -53
  185. package/src/wirings/secret/index.ts +0 -9
  186. package/src/wirings/secret/secret.types.ts +0 -32
  187. package/src/wirings/secret/validate-secret-definitions.test.ts +0 -140
  188. package/src/wirings/secret/validate-secret-definitions.ts +0 -82
  189. package/src/wirings/trigger/index.ts +0 -10
  190. package/src/wirings/trigger/pikku-trigger-service.ts +0 -112
  191. package/src/wirings/trigger/trigger-runner.test.ts +0 -79
  192. package/src/wirings/trigger/trigger-runner.ts +0 -135
  193. package/src/wirings/trigger/trigger.types.ts +0 -178
  194. package/src/wirings/variable/index.ts +0 -8
  195. package/src/wirings/variable/validate-variable-definitions.test.ts +0 -91
  196. package/src/wirings/variable/validate-variable-definitions.ts +0 -69
  197. package/src/wirings/variable/variable.types.ts +0 -22
  198. package/src/wirings/workflow/dsl/index.ts +0 -31
  199. package/src/wirings/workflow/dsl/workflow-dsl.types.ts +0 -320
  200. package/src/wirings/workflow/dsl/workflow-runner.ts +0 -28
  201. package/src/wirings/workflow/graph/graph-node.ts +0 -222
  202. package/src/wirings/workflow/graph/graph-runner.test.ts +0 -487
  203. package/src/wirings/workflow/graph/graph-runner.ts +0 -816
  204. package/src/wirings/workflow/graph/graph-validation.test.ts +0 -170
  205. package/src/wirings/workflow/graph/graph-validation.ts +0 -237
  206. package/src/wirings/workflow/graph/index.ts +0 -19
  207. package/src/wirings/workflow/graph/template.test.ts +0 -49
  208. package/src/wirings/workflow/graph/template.ts +0 -42
  209. package/src/wirings/workflow/graph/wire-workflow-graph.ts +0 -29
  210. package/src/wirings/workflow/graph/workflow-graph.types.ts +0 -104
  211. package/src/wirings/workflow/index.ts +0 -82
  212. package/src/wirings/workflow/pikku-workflow-service.test.ts +0 -200
  213. package/src/wirings/workflow/pikku-workflow-service.ts +0 -1176
  214. package/src/wirings/workflow/workflow-helpers.test.ts +0 -129
  215. package/src/wirings/workflow/workflow-helpers.ts +0 -79
  216. package/src/wirings/workflow/workflow.types.ts +0 -274
  217. package/tsconfig.json +0 -14
  218. package/tsconfig.tsbuildinfo +0 -1
@@ -1,636 +0,0 @@
1
- import type { PikkuWire, CoreUserSession } from '../../types/core.types.js'
2
- import type {
3
- CoreAIAgent,
4
- AIAgentInput,
5
- AIAgentToolDef,
6
- AIContentPart,
7
- AIMessage,
8
- AIStreamChannel,
9
- AIStreamEvent,
10
- PikkuAIMiddlewareHooks,
11
- } from './ai-agent.types.js'
12
- import type { AIAgentRunnerParams } from '../../services/ai-agent-runner-service.js'
13
- import { PikkuError } from '../../errors/error-handler.js'
14
- import { pikkuState, getSingletonServices } from '../../pikku-state.js'
15
- import { createMiddlewareSessionWireProps } from '../../services/user-session-service.js'
16
- import type { SessionService } from '../../services/user-session-service.js'
17
- import { randomUUID } from 'crypto'
18
- import { streamAIAgent } from './ai-agent-stream.js'
19
- import { runAIAgent } from './ai-agent-runner.js'
20
- import {
21
- resolveNamespace,
22
- ContextAwareRPCService,
23
- } from '../../wirings/rpc/rpc-runner.js'
24
- import { buildDynamicWorkflowInstructions, buildWorkflowTools } from './agent-dynamic-workflow.js'
25
- import {
26
- resolveMemoryServices,
27
- loadContextMessages,
28
- trimMessages,
29
- } from './ai-agent-memory.js'
30
- import { resolveModelConfig } from './ai-agent-model-config.js'
31
-
32
- export type RunAIAgentParams = {
33
- sessionService?: SessionService<CoreUserSession>
34
- }
35
-
36
- export type StreamAIAgentOptions = {
37
- requiresToolApproval?: 'all' | 'explicit' | false
38
- }
39
-
40
- export class ToolApprovalRequired extends PikkuError {
41
- public readonly toolCallId: string
42
- public readonly toolName: string
43
- public readonly args: unknown
44
- public reason?: string
45
- public readonly displayToolName?: string
46
- public readonly displayArgs?: unknown
47
- public readonly agentRunId?: string
48
-
49
- constructor(
50
- toolCallId: string,
51
- toolName: string,
52
- args: unknown,
53
- reason?: string,
54
- displayToolName?: string,
55
- displayArgs?: unknown,
56
- agentRunId?: string
57
- ) {
58
- super(`Tool '${displayToolName ?? toolName}' requires approval`)
59
- this.toolCallId = toolCallId
60
- this.toolName = toolName
61
- this.args = args
62
- this.reason = reason
63
- this.displayToolName = displayToolName
64
- this.displayArgs = displayArgs
65
- this.agentRunId = agentRunId
66
- }
67
- }
68
-
69
- export type StreamContext = {
70
- channel: AIStreamChannel
71
- options?: StreamAIAgentOptions
72
- delegateState?: { delegated: boolean }
73
- }
74
-
75
- export const resolveAgent = (
76
- agentName: string
77
- ): { agent: CoreAIAgent; packageName: string | null; resolvedName: string } => {
78
- const mainAgent = pikkuState(null, 'agent', 'agents').get(agentName)
79
- if (mainAgent) {
80
- return { agent: mainAgent, packageName: null, resolvedName: agentName }
81
- }
82
-
83
- const colonIndex = agentName.indexOf(':')
84
- if (colonIndex !== -1) {
85
- const namespace = agentName.substring(0, colonIndex)
86
- const localName = agentName.substring(colonIndex + 1)
87
- const addons = pikkuState(null, 'addons', 'packages')
88
- const pkgConfig = addons.get(namespace)
89
- if (pkgConfig) {
90
- const extAgent = pikkuState(pkgConfig.package, 'agent', 'agents').get(
91
- localName
92
- )
93
- if (extAgent) {
94
- return {
95
- agent: extAgent,
96
- packageName: pkgConfig.package,
97
- resolvedName: localName,
98
- }
99
- }
100
- }
101
- }
102
-
103
- throw new Error(`AI agent not found: ${agentName}`)
104
- }
105
-
106
- export async function buildInstructions(
107
- agentName: string,
108
- packageName: string | null
109
- ): Promise<string> {
110
- const meta = pikkuState(packageName, 'agent', 'agentsMeta')[agentName]
111
- const rawInstructions = meta?.instructions ?? ''
112
- let instructions = Array.isArray(rawInstructions)
113
- ? rawInstructions.join('\n')
114
- : rawInstructions
115
-
116
- if (meta?.agents?.length) {
117
- instructions +=
118
- '\n\nWhen calling a sub-agent, provide a short session name that describes the task. ' +
119
- 'Use the same session name to continue a previous conversation with that agent. ' +
120
- 'Use a new session name for a new independent task. ' +
121
- 'When a request involves multiple actions for the same domain, combine them into a single sub-agent call rather than making separate calls.'
122
- }
123
-
124
- if (meta?.dynamicWorkflows && meta.tools?.length) {
125
- instructions += buildDynamicWorkflowInstructions(meta.tools, meta.dynamicWorkflows)
126
- }
127
-
128
- return instructions
129
- }
130
-
131
- export type ScopedChannel = AIStreamChannel & {
132
- approvals: Array<{
133
- toolCallId: string
134
- toolName: string
135
- args: unknown
136
- runId: string
137
- }>
138
- }
139
-
140
- export function createScopedChannel(
141
- parent: AIStreamChannel,
142
- agentName: string,
143
- session: string
144
- ): ScopedChannel {
145
- const capturedApprovals: ScopedChannel['approvals'] = []
146
-
147
- return {
148
- channelId: `${parent.channelId}:${agentName}:${session}`,
149
- openingData: parent.openingData,
150
- get state() {
151
- return parent.state
152
- },
153
- get approvals() {
154
- return capturedApprovals
155
- },
156
- close: () => {},
157
- sendBinary: (data) => parent.sendBinary(data),
158
- send: (event: AIStreamEvent) => {
159
- if (event.type === 'done') return
160
- if (event.type === 'approval-request') {
161
- capturedApprovals.push({
162
- toolCallId: event.toolCallId,
163
- toolName: event.toolName,
164
- args: event.args,
165
- runId: (event as any).runId,
166
- })
167
- return
168
- }
169
- if (
170
- event.type === 'step-start' ||
171
- event.type === 'text-delta' ||
172
- event.type === 'reasoning-delta' ||
173
- event.type === 'tool-call' ||
174
- event.type === 'tool-result' ||
175
- event.type === 'usage' ||
176
- event.type === 'error' ||
177
- event.type === 'workflow-created'
178
- ) {
179
- parent.send({ ...event, agent: agentName, session } as AIStreamEvent)
180
- } else {
181
- parent.send(event)
182
- }
183
- },
184
- }
185
- }
186
-
187
- export async function buildToolDefs(
188
- params: RunAIAgentParams,
189
- agentSessionMap: Map<string, string>,
190
- resourceId: string,
191
- agentName: string,
192
- packageName: string | null,
193
- streamContext?: StreamContext,
194
- aiMiddlewares?: PikkuAIMiddlewareHooks[],
195
- agentMode?: 'delegate' | 'supervise'
196
- ): Promise<{ tools: AIAgentToolDef[]; missingRpcs: string[] }> {
197
- const singletonServices = getSingletonServices()
198
- const tools: AIAgentToolDef[] = []
199
- const missingRpcs: string[] = []
200
- const approvalPolicy =
201
- streamContext?.options?.requiresToolApproval ?? 'explicit'
202
-
203
- const meta = pikkuState(packageName, 'agent', 'agentsMeta')[agentName]
204
- if (!meta) return { tools, missingRpcs }
205
-
206
- const metaTools = meta.tools
207
- const metaAgents = meta.agents
208
-
209
- if (metaTools?.length) {
210
- for (const toolName of metaTools) {
211
- let fnMeta: any
212
- let resolvedPkg: string | null = null
213
- let schemas: Map<string, any>
214
-
215
- const resolved = toolName.includes(':')
216
- ? resolveNamespace(toolName)
217
- : null
218
-
219
- let pikkuFuncId: string | undefined
220
-
221
- if (resolved) {
222
- resolvedPkg = resolved.package
223
- pikkuFuncId = resolved.function
224
- fnMeta = pikkuState(resolvedPkg, 'function', 'meta')[pikkuFuncId]
225
- schemas = pikkuState(resolvedPkg, 'misc', 'schemas')
226
- } else {
227
- const rpcMeta = pikkuState(null, 'rpc', 'meta')
228
- pikkuFuncId = rpcMeta[toolName]
229
- if (!pikkuFuncId) {
230
- missingRpcs.push(toolName)
231
- continue
232
- }
233
- fnMeta = pikkuState(null, 'function', 'meta')[pikkuFuncId]
234
- schemas = pikkuState(null, 'misc', 'schemas')
235
- }
236
-
237
- if (!fnMeta) {
238
- missingRpcs.push(toolName)
239
- continue
240
- }
241
-
242
- const inputSchemaName = fnMeta?.inputSchemaName
243
- let inputSchema = inputSchemaName
244
- ? schemas.get(inputSchemaName)
245
- : undefined
246
- if (
247
- !inputSchema ||
248
- (typeof inputSchema === 'object' &&
249
- inputSchema.type === 'object' &&
250
- !inputSchema.properties)
251
- ) {
252
- inputSchema = { type: 'object', properties: {} }
253
- }
254
-
255
- const needsApproval =
256
- approvalPolicy === 'all' ||
257
- (approvalPolicy === 'explicit' && fnMeta?.approvalRequired)
258
-
259
- // Build approvalDescriptionFn if the function has an approvalDescription configured
260
- let approvalDescriptionFn:
261
- | ((input: unknown) => Promise<string>)
262
- | undefined
263
- if (needsApproval && pikkuFuncId) {
264
- const funcConfig = pikkuState(resolvedPkg, 'function', 'functions').get(
265
- pikkuFuncId
266
- )
267
- if (funcConfig?.approvalDescription) {
268
- const descFn = funcConfig.approvalDescription
269
- const capturedPkg = resolvedPkg
270
- approvalDescriptionFn = async (input: unknown) => {
271
- let services = singletonServices
272
- if (capturedPkg) {
273
- const pkgServices = pikkuState(
274
- capturedPkg,
275
- 'package',
276
- 'singletonServices'
277
- )
278
- if (pkgServices) {
279
- services = pkgServices
280
- }
281
- }
282
- return descFn(services, input)
283
- }
284
- }
285
- }
286
-
287
- tools.push({
288
- name: toolName.replaceAll(':', '__'),
289
- description: fnMeta?.description || fnMeta?.title || toolName,
290
- inputSchema,
291
- needsApproval: needsApproval || undefined,
292
- approvalDescriptionFn,
293
- execute: async (toolInput: unknown) => {
294
- const wire: PikkuWire = params.sessionService
295
- ? { ...createMiddlewareSessionWireProps(params.sessionService) }
296
- : {}
297
- const rpcService = new ContextAwareRPCService(
298
- singletonServices,
299
- wire,
300
- { sessionService: params.sessionService }
301
- )
302
- return rpcService.rpc(toolName, toolInput)
303
- },
304
- })
305
- }
306
- }
307
-
308
- if (metaAgents?.length) {
309
- const allAgentsMeta = pikkuState(null, 'agent', 'agentsMeta')
310
-
311
- for (const subAgentName of metaAgents) {
312
- const subMeta = allAgentsMeta[subAgentName]
313
- if (!subMeta) {
314
- singletonServices.logger.warn(
315
- `Sub-agent '${subAgentName}' not found in agent registry`
316
- )
317
- continue
318
- }
319
-
320
- tools.push({
321
- name: subAgentName,
322
- description: subMeta.description,
323
- inputSchema: {
324
- type: 'object',
325
- properties: {
326
- message: { type: 'string' },
327
- session: {
328
- type: 'string',
329
- description: 'Short session label for thread continuity',
330
- },
331
- },
332
- required: ['message', 'session'],
333
- },
334
- execute: async (toolInput: unknown) => {
335
- const { message, session } = toolInput as {
336
- message: string
337
- session: string
338
- }
339
- const sessionKey = `${subAgentName}::${session}`
340
- let threadId = agentSessionMap.get(sessionKey)
341
- if (!threadId) {
342
- threadId = randomUUID()
343
- agentSessionMap.set(sessionKey, threadId)
344
- }
345
-
346
- if (streamContext) {
347
- const isDelegate = agentMode !== 'supervise'
348
- if (isDelegate && streamContext.delegateState) {
349
- streamContext.delegateState.delegated = true
350
- }
351
- const { channel } = streamContext
352
- channel.send({
353
- type: 'agent-call',
354
- agentName: subAgentName,
355
- session,
356
- input: message,
357
- })
358
- const subChannel = createScopedChannel(
359
- channel,
360
- subAgentName,
361
- session
362
- )
363
- // In supervise mode, suppress sub-agent text from reaching the client.
364
- // Approvals still flow through normally.
365
- const effectiveChannel = isDelegate
366
- ? subChannel
367
- : {
368
- ...subChannel,
369
- send: (event: AIStreamEvent) => {
370
- if (
371
- event.type === 'text-delta' ||
372
- event.type === 'reasoning-delta'
373
- )
374
- return
375
- subChannel.send(event)
376
- },
377
- }
378
- const resultText = await streamAIAgent(
379
- subAgentName,
380
- { message, threadId, resourceId },
381
- effectiveChannel,
382
- params,
383
- agentSessionMap,
384
- streamContext.options
385
- )
386
- if (subChannel.approvals.length > 0) {
387
- return {
388
- __approvalRequired: true,
389
- toolName: subAgentName,
390
- args: toolInput,
391
- agentRunId: subChannel.approvals[0].runId,
392
- subApprovals: subChannel.approvals,
393
- }
394
- }
395
- channel.send({
396
- type: 'agent-result',
397
- agentName: subAgentName,
398
- session,
399
- result: resultText,
400
- })
401
- return resultText
402
- }
403
-
404
- // No stream context: sub-agent runs non-streaming
405
- const result = await runAIAgent(
406
- subAgentName,
407
- { message, threadId, resourceId },
408
- params,
409
- agentSessionMap
410
- )
411
- return result.object ?? result.text
412
- },
413
- })
414
- }
415
- }
416
-
417
- if (meta.dynamicWorkflows) {
418
- const workflowTools = buildWorkflowTools(
419
- agentName,
420
- packageName,
421
- meta.tools ?? [],
422
- meta.dynamicWorkflows,
423
- streamContext,
424
- params.sessionService
425
- )
426
- tools.push(...workflowTools)
427
- }
428
-
429
- const hasToolHooks = aiMiddlewares?.some(
430
- (mw) => mw.beforeToolCall || mw.afterToolCall
431
- )
432
- if (hasToolHooks) {
433
- for (const tool of tools) {
434
- const originalExecute = tool.execute
435
- tool.execute = async (toolInput: unknown) => {
436
- const toolCallId = randomUUID()
437
- let args = (toolInput ?? {}) as Record<string, unknown>
438
-
439
- for (const mw of aiMiddlewares!) {
440
- if (mw.beforeToolCall) {
441
- const beforeResult = await mw.beforeToolCall(singletonServices, {
442
- toolName: tool.name,
443
- toolCallId,
444
- args,
445
- })
446
- if (beforeResult && 'args' in beforeResult) {
447
- args = beforeResult.args
448
- }
449
- }
450
- }
451
-
452
- const startTime = Date.now()
453
- let result: unknown
454
- let execError: unknown
455
- try {
456
- result = await originalExecute(args)
457
- } catch (err) {
458
- execError = err
459
- result = err instanceof Error ? err.message : String(err)
460
- }
461
- const durationMs = Date.now() - startTime
462
-
463
- for (let i = aiMiddlewares!.length - 1; i >= 0; i--) {
464
- const mw = aiMiddlewares![i]
465
- if (mw.afterToolCall) {
466
- const afterResult = await mw.afterToolCall(singletonServices, {
467
- toolName: tool.name,
468
- toolCallId,
469
- args,
470
- result,
471
- durationMs,
472
- })
473
- if (afterResult && 'result' in afterResult) {
474
- result = afterResult.result
475
- }
476
- }
477
- }
478
-
479
- if (execError) throw execError
480
- return result
481
- }
482
- }
483
- }
484
-
485
- return { tools, missingRpcs }
486
- }
487
-
488
- export async function prepareAgentRun(
489
- agentName: string,
490
- input: AIAgentInput,
491
- params: RunAIAgentParams,
492
- agentSessionMap: Map<string, string>,
493
- streamContext?: StreamContext
494
- ) {
495
- const singletonServices = getSingletonServices()
496
- const { agent, packageName, resolvedName } = resolveAgent(agentName)
497
-
498
- const agentRunner = singletonServices.aiAgentRunner
499
- if (!agentRunner) {
500
- throw new Error('AIAgentRunnerService not available in singletonServices')
501
- }
502
-
503
- if (agent.dynamicWorkflows && singletonServices.workflowService) {
504
- const persisted =
505
- await singletonServices.workflowService.getAIGeneratedWorkflows(
506
- resolvedName
507
- )
508
- const allMeta = pikkuState(null, 'workflows', 'meta')
509
- for (const wf of persisted) {
510
- if (!allMeta[wf.workflowName]) {
511
- allMeta[wf.workflowName] = wf.graph
512
- }
513
- }
514
- }
515
-
516
- const { storage } = resolveMemoryServices(agent, singletonServices)
517
- const memoryConfig = agent.memory
518
- const threadId = input.threadId
519
-
520
- const agentsMeta = pikkuState(packageName, 'agent', 'agentsMeta')
521
- const meta = agentsMeta[resolvedName]
522
- const outputSchemaName = meta?.outputSchema
523
- const outputSchema = outputSchemaName
524
- ? pikkuState(packageName, 'misc', 'schemas').get(outputSchemaName)
525
- : undefined
526
-
527
- const workingMemorySchemaName = meta?.workingMemorySchema ?? null
528
- const workingMemoryJsonSchema = workingMemorySchemaName
529
- ? pikkuState(packageName, 'misc', 'schemas').get(workingMemorySchemaName)
530
- : undefined
531
-
532
- if (storage) {
533
- try {
534
- await storage.getThread(threadId)
535
- } catch {
536
- await storage.createThread(input.resourceId, { threadId })
537
- }
538
- }
539
-
540
- let messages: AIMessage[] = []
541
- if (storage) {
542
- messages = await storage.getMessages(threadId, {
543
- lastN: memoryConfig?.lastMessages ?? 20,
544
- })
545
- }
546
-
547
- const contextMessages = await loadContextMessages(
548
- memoryConfig,
549
- storage,
550
- input,
551
- workingMemoryJsonSchema
552
- )
553
-
554
- const userContent: AIMessage['content'] = input.attachments?.length
555
- ? [
556
- { type: 'text' as const, text: input.message },
557
- ...input.attachments.map(
558
- (a) =>
559
- ({
560
- type: a.type,
561
- data: a.data,
562
- url: a.url,
563
- mediaType: a.mediaType,
564
- ...(a.filename ? { filename: a.filename } : {}),
565
- }) as AIContentPart
566
- ),
567
- ]
568
- : input.message
569
-
570
- const userMessage: AIMessage = {
571
- id: randomUUID(),
572
- role: 'user',
573
- content: userContent,
574
- createdAt: new Date(),
575
- }
576
-
577
- const allMessages = [...contextMessages, ...messages, userMessage]
578
- const trimmedMessages = trimMessages(allMessages)
579
-
580
- const aiMiddlewares: PikkuAIMiddlewareHooks[] = agent.aiMiddleware ?? []
581
-
582
- const { tools, missingRpcs } = await buildToolDefs(
583
- params,
584
- agentSessionMap,
585
- input.resourceId,
586
- resolvedName,
587
- packageName,
588
- streamContext,
589
- aiMiddlewares,
590
- agent.agentMode
591
- )
592
-
593
- const instructions = await buildInstructions(resolvedName, packageName)
594
-
595
- const resolved = resolveModelConfig(resolvedName, agent)
596
-
597
- // Per-request overrides
598
- if (input.model) {
599
- resolved.model = resolveModelConfig(resolvedName, {
600
- ...agent,
601
- model: input.model,
602
- }).model
603
- }
604
- if (input.temperature !== undefined) {
605
- resolved.temperature = input.temperature
606
- }
607
-
608
- const maxSteps = resolved.maxSteps ?? 10
609
-
610
- const runnerParams: AIAgentRunnerParams = {
611
- model: resolved.model,
612
- temperature: resolved.temperature,
613
- instructions,
614
- messages: trimmedMessages,
615
- tools,
616
- maxSteps: 1,
617
- toolChoice: agent.toolChoice ?? 'auto',
618
- outputSchema,
619
- }
620
-
621
- return {
622
- agent,
623
- packageName,
624
- resolvedName,
625
- agentRunner,
626
- storage,
627
- memoryConfig,
628
- threadId,
629
- userMessage,
630
- runnerParams,
631
- maxSteps,
632
- missingRpcs,
633
- workingMemoryJsonSchema,
634
- workingMemorySchemaName,
635
- }
636
- }
@@ -1,37 +0,0 @@
1
- import { describe, test } from 'node:test'
2
- import assert from 'node:assert/strict'
3
-
4
- import { approveAIAgent } from './ai-agent-registry.js'
5
-
6
- describe('approveAIAgent', () => {
7
- test('rejects approval when run agent does not match expected agent', async () => {
8
- const aiRunState = {
9
- getRun: async () => ({
10
- runId: 'run-1',
11
- agentName: 'internal-agent',
12
- threadId: 'thread-1',
13
- resourceId: 'resource-1',
14
- status: 'suspended',
15
- pendingApprovals: [],
16
- usage: { inputTokens: 0, outputTokens: 0, model: 'test-model' },
17
- createdAt: new Date(),
18
- updatedAt: new Date(),
19
- }),
20
- updateRun: async () => {},
21
- } as any
22
-
23
- await assert.rejects(
24
- () =>
25
- approveAIAgent(
26
- aiRunState,
27
- 'run-1',
28
- [{ toolCallId: 'call-1', approved: true }],
29
- 'public-agent'
30
- ),
31
- {
32
- message:
33
- "Run run-1 belongs to agent 'internal-agent', not 'public-agent'",
34
- }
35
- )
36
- })
37
- })