@pikku/core 0.12.14 → 0.12.16

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 (136) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/errors/errors.d.ts +4 -0
  3. package/dist/errors/errors.js +12 -0
  4. package/dist/function/function-runner.js +2 -1
  5. package/dist/function/functions.types.js +1 -0
  6. package/dist/function/index.d.ts +2 -1
  7. package/dist/function/index.js +1 -0
  8. package/dist/handle-error.d.ts +2 -2
  9. package/dist/handle-error.js +8 -8
  10. package/dist/index.d.ts +2 -3
  11. package/dist/index.js +1 -2
  12. package/dist/middleware/index.d.ts +3 -0
  13. package/dist/middleware/index.js +3 -0
  14. package/dist/middleware/remote-auth.js +5 -2
  15. package/dist/middleware/telemetry.d.ts +47 -0
  16. package/dist/middleware/telemetry.js +106 -0
  17. package/dist/middleware-runner.js +31 -4
  18. package/dist/permissions.d.ts +13 -1
  19. package/dist/permissions.js +51 -0
  20. package/dist/pikku-state.d.ts +0 -1
  21. package/dist/pikku-state.js +1 -4
  22. package/dist/remote.d.ts +10 -0
  23. package/dist/remote.js +32 -0
  24. package/dist/schema.js +2 -0
  25. package/dist/services/deployment-service.d.ts +12 -1
  26. package/dist/services/in-memory-queue-service.d.ts +7 -0
  27. package/dist/services/in-memory-queue-service.js +28 -0
  28. package/dist/services/index.d.ts +4 -1
  29. package/dist/services/index.js +2 -1
  30. package/dist/services/logger-console.d.ts +26 -40
  31. package/dist/services/logger-console.js +102 -46
  32. package/dist/services/logger.d.ts +5 -0
  33. package/dist/services/meta-service.d.ts +175 -0
  34. package/dist/services/meta-service.js +310 -0
  35. package/dist/services/workflow-service.d.ts +6 -1
  36. package/dist/testing/service-tests.js +0 -8
  37. package/dist/types/core.types.d.ts +21 -0
  38. package/dist/types/core.types.js +7 -1
  39. package/dist/types/state.types.d.ts +2 -2
  40. package/dist/wirings/ai-agent/ai-agent-prepare.js +42 -21
  41. package/dist/wirings/ai-agent/ai-agent-registry.js +2 -2
  42. package/dist/wirings/ai-agent/ai-agent-runner.js +18 -1
  43. package/dist/wirings/ai-agent/ai-agent-stream.js +1 -0
  44. package/dist/wirings/ai-agent/ai-agent.types.d.ts +5 -3
  45. package/dist/wirings/channel/channel-runner.js +3 -3
  46. package/dist/wirings/cli/cli-runner.js +5 -3
  47. package/dist/wirings/cli/command-parser.js +7 -3
  48. package/dist/wirings/http/http-runner.d.ts +1 -1
  49. package/dist/wirings/http/http-runner.js +23 -11
  50. package/dist/wirings/http/http.types.d.ts +3 -0
  51. package/dist/wirings/http/pikku-fetch-http-response.d.ts +1 -0
  52. package/dist/wirings/http/pikku-fetch-http-response.js +3 -0
  53. package/dist/wirings/mcp/mcp-runner.js +5 -3
  54. package/dist/wirings/mcp/mcp.types.d.ts +1 -1
  55. package/dist/wirings/queue/queue-runner.d.ts +3 -1
  56. package/dist/wirings/queue/queue-runner.js +7 -3
  57. package/dist/wirings/rpc/rpc-runner.js +56 -90
  58. package/dist/wirings/scheduler/scheduler-runner.d.ts +3 -1
  59. package/dist/wirings/scheduler/scheduler-runner.js +9 -5
  60. package/dist/wirings/trigger/trigger-runner.js +4 -2
  61. package/dist/wirings/workflow/dsl/workflow-runner.d.ts +1 -1
  62. package/dist/wirings/workflow/dsl/workflow-runner.js +6 -9
  63. package/dist/wirings/workflow/graph/graph-runner.d.ts +1 -1
  64. package/dist/wirings/workflow/graph/graph-runner.js +18 -4
  65. package/dist/wirings/workflow/index.d.ts +4 -2
  66. package/dist/wirings/workflow/index.js +4 -2
  67. package/dist/wirings/workflow/pikku-workflow-service.d.ts +16 -4
  68. package/dist/wirings/workflow/pikku-workflow-service.js +216 -24
  69. package/dist/wirings/workflow/workflow-queue-workers.d.ts +40 -0
  70. package/dist/wirings/workflow/workflow-queue-workers.js +41 -0
  71. package/dist/wirings/workflow/workflow.types.d.ts +17 -1
  72. package/package.json +4 -1
  73. package/src/errors/errors.ts +12 -0
  74. package/src/function/function-runner.ts +5 -4
  75. package/src/function/functions.types.ts +1 -0
  76. package/src/function/index.ts +10 -0
  77. package/src/handle-error.test.ts +2 -2
  78. package/src/handle-error.ts +8 -8
  79. package/src/index.ts +2 -2
  80. package/src/middleware/index.ts +3 -0
  81. package/src/middleware/remote-auth.test.ts +4 -4
  82. package/src/middleware/remote-auth.ts +7 -2
  83. package/src/middleware/telemetry.ts +110 -0
  84. package/src/middleware-runner.test.ts +149 -1
  85. package/src/middleware-runner.ts +48 -4
  86. package/src/permissions.ts +70 -0
  87. package/src/pikku-state.test.ts +0 -26
  88. package/src/pikku-state.ts +1 -5
  89. package/src/remote.ts +46 -0
  90. package/src/schema.ts +1 -0
  91. package/src/services/deployment-service.ts +17 -1
  92. package/src/services/in-memory-queue-service.ts +46 -0
  93. package/src/services/index.ts +21 -1
  94. package/src/services/logger-console.ts +127 -47
  95. package/src/services/logger.ts +6 -0
  96. package/src/services/meta-service.ts +523 -0
  97. package/src/services/workflow-service.ts +8 -0
  98. package/src/testing/service-tests.ts +0 -10
  99. package/src/types/core.types.ts +36 -1
  100. package/src/types/state.types.ts +2 -2
  101. package/src/wirings/ai-agent/ai-agent-prepare.ts +51 -40
  102. package/src/wirings/ai-agent/ai-agent-registry.ts +3 -3
  103. package/src/wirings/ai-agent/ai-agent-runner.ts +16 -1
  104. package/src/wirings/ai-agent/ai-agent-stream.ts +8 -0
  105. package/src/wirings/ai-agent/ai-agent.types.ts +5 -3
  106. package/src/wirings/channel/channel-runner.ts +4 -5
  107. package/src/wirings/channel/local/local-channel-runner.test.ts +5 -1
  108. package/src/wirings/cli/cli-runner.test.ts +8 -7
  109. package/src/wirings/cli/cli-runner.ts +6 -4
  110. package/src/wirings/cli/command-parser.ts +8 -3
  111. package/src/wirings/http/http-runner.ts +27 -11
  112. package/src/wirings/http/http.types.ts +3 -0
  113. package/src/wirings/http/pikku-fetch-http-response.ts +4 -0
  114. package/src/wirings/mcp/mcp-runner.ts +7 -9
  115. package/src/wirings/mcp/mcp.types.ts +1 -1
  116. package/src/wirings/queue/queue-runner.test.ts +5 -11
  117. package/src/wirings/queue/queue-runner.ts +11 -3
  118. package/src/wirings/rpc/rpc-runner.ts +82 -115
  119. package/src/wirings/scheduler/scheduler-runner.test.ts +5 -11
  120. package/src/wirings/scheduler/scheduler-runner.ts +13 -5
  121. package/src/wirings/trigger/trigger-runner.test.ts +10 -11
  122. package/src/wirings/trigger/trigger-runner.ts +6 -4
  123. package/src/wirings/workflow/dsl/workflow-runner.ts +11 -10
  124. package/src/wirings/workflow/graph/graph-runner.ts +19 -4
  125. package/src/wirings/workflow/index.ts +17 -6
  126. package/src/wirings/workflow/pikku-workflow-service.ts +284 -24
  127. package/src/wirings/workflow/workflow-queue-workers.ts +85 -0
  128. package/src/wirings/workflow/workflow.types.ts +16 -1
  129. package/tsconfig.tsbuildinfo +1 -1
  130. package/dist/wirings/ai-agent/agent-dynamic-workflow.d.ts +0 -6
  131. package/dist/wirings/ai-agent/agent-dynamic-workflow.js +0 -468
  132. package/dist/wirings/workflow/workflow-helpers.d.ts +0 -36
  133. package/dist/wirings/workflow/workflow-helpers.js +0 -38
  134. package/src/wirings/ai-agent/agent-dynamic-workflow.ts +0 -610
  135. package/src/wirings/workflow/workflow-helpers.test.ts +0 -129
  136. package/src/wirings/workflow/workflow-helpers.ts +0 -79
@@ -1,610 +0,0 @@
1
- import type { AIAgentToolDef } from './ai-agent.types.js'
2
- import { pikkuState, getSingletonServices } from '../../pikku-state.js'
3
- import { canonicalJSON, hashString } from '../../utils/hash.js'
4
- import type { WorkflowRuntimeMeta } from '../workflow/workflow.types.js'
5
- import { runWorkflowGraph } from '../workflow/graph/graph-runner.js'
6
- import type { StreamContext } from './ai-agent-prepare.js'
7
- import type { PikkuWire, CoreUserSession } from '../../types/core.types.js'
8
- import { ContextAwareRPCService, resolveNamespace } from '../rpc/rpc-runner.js'
9
- import { createMiddlewareSessionWireProps } from '../../services/user-session-service.js'
10
- import type { SessionService } from '../../services/user-session-service.js'
11
- import {
12
- validateWorkflowWiring,
13
- computeEntryNodeIds,
14
- } from '../workflow/graph/graph-validation.js'
15
-
16
- function formatSchemaType(schema: any, depth = 0): string {
17
- if (!schema) return 'any'
18
- if (schema.enum)
19
- return schema.enum.map((v: any) => JSON.stringify(v)).join(' | ')
20
- if (schema.type === 'array') {
21
- const itemType = schema.items
22
- ? formatSchemaType(schema.items, depth + 1)
23
- : 'any'
24
- return `${itemType}[]`
25
- }
26
- if (schema.type === 'object' && schema.properties) {
27
- if (depth > 1) return 'object'
28
- const fields = Object.entries(schema.properties)
29
- .map(([k, v]: [string, any]) => `${k}: ${formatSchemaType(v, depth + 1)}`)
30
- .join(', ')
31
- return `{${fields}}`
32
- }
33
- return schema.type || 'any'
34
- }
35
-
36
- function resolveToolMetaForWorkflow(toolName: string): {
37
- fnMeta: any
38
- inputSchema: any
39
- outputSchema: any
40
- schemas: Map<string, any>
41
- } | null {
42
- const resolved = toolName.includes(':') ? resolveNamespace(toolName) : null
43
- let fnMeta: any
44
- let schemas: Map<string, any>
45
-
46
- if (resolved) {
47
- fnMeta = pikkuState(resolved.package, 'function', 'meta')[resolved.function]
48
- schemas = pikkuState(resolved.package, 'misc', 'schemas')
49
- } else {
50
- const rpcMeta = pikkuState(null, 'rpc', 'meta')
51
- const pikkuFuncId = rpcMeta[toolName]
52
- if (!pikkuFuncId) return null
53
- fnMeta = pikkuState(null, 'function', 'meta')[pikkuFuncId]
54
- schemas = pikkuState(null, 'misc', 'schemas')
55
- }
56
-
57
- if (!fnMeta) return null
58
-
59
- const inputSchema = fnMeta.inputSchemaName
60
- ? schemas.get(fnMeta.inputSchemaName)
61
- : null
62
- const outputSchema = fnMeta.outputSchemaName
63
- ? schemas.get(fnMeta.outputSchemaName)
64
- : null
65
-
66
- return { fnMeta, inputSchema, outputSchema, schemas }
67
- }
68
-
69
- function buildDetailedToolSchemas(toolNames: string[]): string {
70
- const lines: string[] = []
71
- for (const toolName of toolNames) {
72
- const meta = resolveToolMetaForWorkflow(toolName)
73
- if (!meta) continue
74
- const { inputSchema, outputSchema } = meta
75
-
76
- const inputProps = inputSchema?.properties
77
- ? Object.entries(inputSchema.properties)
78
- .map(
79
- ([k, v]: [string, any]) =>
80
- `${k}${inputSchema.required?.includes(k) ? '' : '?'}: ${formatSchemaType(v)}`
81
- )
82
- .join(', ')
83
- : ''
84
- const outputPaths = outputSchema ? collectOutputPaths(outputSchema) : []
85
-
86
- lines.push(
87
- `**${toolName}**\n` +
88
- ` input: {${inputProps}}\n` +
89
- (outputPaths.length > 0
90
- ? ` output paths: ${outputPaths.join(', ')}`
91
- : ` output: void`)
92
- )
93
- }
94
- return lines.join('\n')
95
- }
96
-
97
- function collectOutputPaths(schema: any, prefix = ''): string[] {
98
- if (!schema?.properties) return []
99
- const paths: string[] = []
100
- for (const [key, prop] of Object.entries(schema.properties) as [
101
- string,
102
- any,
103
- ][]) {
104
- const path = prefix ? `${prefix}.${key}` : key
105
- const type = prop.type || 'any'
106
- if (prop.type === 'object' && prop.properties) {
107
- paths.push(...collectOutputPaths(prop, path))
108
- } else {
109
- paths.push(`${path}: ${type}`)
110
- }
111
- }
112
- return paths
113
- }
114
-
115
- export function buildDynamicWorkflowInstructions(
116
- tools: string[],
117
- mode: 'read' | 'always' | 'ask'
118
- ): string {
119
- if (mode === 'read') {
120
- return (
121
- '\n\n## Existing Workflows\n\n' +
122
- 'You can list and execute previously saved workflows using listAgentWorkflows and executeAgentWorkflow.\n' +
123
- "Use listAgentWorkflows to discover what's available, then executeAgentWorkflow to run them."
124
- )
125
- }
126
-
127
- const modeGuidance =
128
- mode === 'always'
129
- ? 'When a user requests a complex multi-step task, prefer creating a workflow over making sequential tool calls.\n' +
130
- 'Check if a suitable workflow already exists with listAgentWorkflows first.\n' +
131
- 'If none exists, create one with createAgentWorkflow, save with saveAgentWorkflow, then execute.\n\n'
132
- : 'When you receive a request that would benefit from a reusable multi-step workflow,\n' +
133
- 'suggest creating one to the user. Explain the benefits (reusability, reliability,\n' +
134
- 'can run in background) and wait for confirmation before creating.\n' +
135
- 'Do NOT create workflows automatically — always propose and get user approval first.\n' +
136
- 'For one-off tasks, just use the tools directly.\n\n'
137
-
138
- const toolSummaryLines: string[] = []
139
-
140
- for (const toolName of tools) {
141
- const meta = resolveToolMetaForWorkflow(toolName)
142
- if (!meta) continue
143
- const { fnMeta, inputSchema, outputSchema } = meta
144
-
145
- const desc = fnMeta.description || fnMeta.title || ''
146
- const inputFields = inputSchema?.properties
147
- ? Object.keys(inputSchema.properties).join(', ')
148
- : ''
149
- const outputFields = outputSchema?.properties
150
- ? Object.keys(outputSchema.properties).join(', ')
151
- : ''
152
-
153
- toolSummaryLines.push(
154
- `| \`${toolName}\` | ${desc || '-'} | ${inputFields || '-'} | ${outputFields || '-'} |`
155
- )
156
- }
157
-
158
- const sections: string[] = [
159
- '\n\n## Workflow Creation\n',
160
- modeGuidance,
161
-
162
- '### When to Create a Workflow\n' +
163
- 'Create a workflow when:\n' +
164
- '- The task has 2+ steps with data dependencies between them\n' +
165
- '- The task will be repeated (workflows are reusable)\n' +
166
- '- Steps can fail independently and need error handling\n' +
167
- '- Steps can run in parallel for better performance\n' +
168
- 'Do NOT create a workflow for single tool calls — just call the tool directly.\n',
169
-
170
- '### Process\n' +
171
- '1. Check if a suitable workflow exists: `listAgentWorkflows`\n' +
172
- '2. If the request is too vague to build a reliable workflow, ask the user to be more specific. For example, if a user says "make a workflow that does stuff with my data" — ask them what steps they need and what data flows between them.\n' +
173
- '3. Plan the graph: identify steps, dependencies, parallel paths, and failure modes\n' +
174
- '4. Create and validate: `createAgentWorkflow` — if validation fails, fix the errors and retry\n' +
175
- '5. Present the workflow to the user and get approval\n' +
176
- '6. Activate: `saveAgentWorkflow`\n' +
177
- '7. Run: `executeAgentWorkflow`\n',
178
-
179
- '### Available Tools\n' +
180
- '| Tool | Description | Input fields | Output fields |\n' +
181
- '|------|-------------|-------------|---------------|\n' +
182
- toolSummaryLines.join('\n') +
183
- '\n\n' +
184
- 'Full schemas (input types, output paths) are returned by `createAgentWorkflow` after validation.\n',
185
-
186
- '### Graph Format Reference\n\n' +
187
- '**Node:** `{ rpcName, input?, next?, onError? }`\n\n' +
188
- '**Data wiring (input field values):**\n' +
189
- '- `{"$ref": "trigger", "path": "fieldName"}` — extract field from trigger input (ALWAYS include `path`)\n' +
190
- '- `{"$ref": "nodeId", "path": "fieldName"}` — extract field from a previous node\'s output (ALWAYS include `path`)\n' +
191
- '- `path` supports dot notation for nested fields — use the "output paths" listed above to find the correct path\n' +
192
- '- Example: if a tool\'s output paths show `todo.id: string`, use `{"$ref": "nodeId", "path": "todo.id"}`\n' +
193
- '- `{"$template": {"parts": ["Hello ", "!"], "expressions": [{"$ref": "trigger", "path": "name"}]}}` — string interpolation\n' +
194
- '- Static values passed directly: `{"count": 10}`\n\n' +
195
- '**Flow control (`next`):**\n' +
196
- '- `"next": "b"` — sequential\n' +
197
- '- `"next": ["b", "c"]` — parallel fan-out\n' +
198
- '- `"next": {"ok": "b", "fail": "c"}` — conditional branch (node calls `graph.branch("ok")` at runtime)\n' +
199
- '- Omit `next` for terminal nodes. Entry nodes are auto-detected.\n\n' +
200
- '**Error handling:**\n' +
201
- '- `"onError": "handler"` — route to error handler on failure\n' +
202
- '- Error handler receives `{ error: { message: string } }` as input\n' +
203
- '- Without `onError`, a node failure fails the entire workflow\n\n' +
204
- '**Sub-workflows:** if `rpcName` matches an existing workflow name, it runs as a child workflow with its own execution context.\n\n' +
205
- '**Trigger input:** the workflow receives input when executed. Entry nodes extract fields via `$ref: "trigger"`. Document what fields your workflow expects in the `description`.\n',
206
-
207
- '### Design Principles\n' +
208
- '1. **Map dependencies first** — before writing nodes, identify which steps depend on which outputs\n' +
209
- '2. **Parallelize independent work** — steps with no data dependency should fan out via array `next`\n' +
210
- '3. **Add error handlers for external calls** — any node calling an external service should have `onError`\n' +
211
- "4. **Minimize blast radius** — isolate risky nodes so their failure doesn't cascade\n" +
212
- '5. **Name nodes by intent** — `fetchUsers`, `sendAlert` not `step1`, `step2`\n' +
213
- '6. **Keep graphs shallow** — prefer wide parallel graphs over deep sequential chains when possible\n',
214
-
215
- '### Common Mistakes\n' +
216
- '- `{"$ref": "trigger"}` without `path` — passes entire object, use `{"$ref": "trigger", "path": "field"}`\n' +
217
- '- Wrong path depth: if output paths show `todo.id`, use `"path": "todo.id"` not `"path": "id"`\n' +
218
- '- Type mismatch: wiring a string output to a number input\n' +
219
- '- Dangling `onError`/`next` references to nodes not in the graph\n' +
220
- '- Cycles: if A→B→A, there are no entry nodes\n',
221
-
222
- '### Examples\n\n' +
223
- '**Sequential with nested output path (if addTodo output paths show `todo.id`):**\n' +
224
- '```json\n{"add":{"rpcName":"addTodo","input":{"title":{"$ref":"trigger","path":"title"}},"next":"complete"},"complete":{"rpcName":"completeTodo","input":{"id":{"$ref":"add","path":"todo.id"}}}}\n```\n\n' +
225
- '**Error handling:**\n' +
226
- '```json\n{"deploy":{"rpcName":"deploy","input":{"env":{"$ref":"trigger","path":"env"}},"next":"notify","onError":"rollback"},"notify":{"rpcName":"alert","input":{"message":"Deployed"}},"rollback":{"rpcName":"rollback","input":{},"next":"alertFail"},"alertFail":{"rpcName":"alert","input":{"message":"Rolled back"}}}\n```\n\n' +
227
- '**Parallel fan-out:**\n' +
228
- '```json\n{"fetchA":{"rpcName":"getA","input":{},"next":"combine"},"fetchB":{"rpcName":"getB","input":{},"next":"combine"},"combine":{"rpcName":"graph:merge","input":{"items":[{"$ref":"fetchA","path":"data"},{"$ref":"fetchB","path":"data"}]}}}\n```',
229
- ]
230
-
231
- return sections.join('\n')
232
- }
233
-
234
- export function buildWorkflowTools(
235
- agentName: string,
236
- packageName: string | null,
237
- toolNames: string[],
238
- mode: 'read' | 'always' | 'ask',
239
- streamContext?: StreamContext,
240
- sessionService?: SessionService<CoreUserSession>
241
- ): AIAgentToolDef[] {
242
- const tools: AIAgentToolDef[] = []
243
-
244
- if (mode !== 'read') {
245
- tools.push({
246
- name: 'createAgentWorkflow',
247
- description:
248
- 'Validate and create a draft workflow DAG that chains tools together. The graph is validated for wiring correctness and type compatibility. Call saveAgentWorkflow to activate it after the user approves.',
249
- inputSchema: {
250
- type: 'object',
251
- properties: {
252
- name: {
253
- type: 'string',
254
- description:
255
- 'Short name for the workflow (will be prefixed with ai:{agentName}:)',
256
- },
257
- description: {
258
- type: 'string',
259
- description: 'What this workflow does',
260
- },
261
- nodes: {
262
- type: 'string',
263
- description:
264
- 'JSON string of nodeId→node map. Node fields: rpcName (tool name), input (use $ref+path to wire data), next (flow control), onError (error routing). Must have 2+ nodes.',
265
- },
266
- },
267
- required: ['name', 'nodes'],
268
- },
269
- execute: async (input: unknown) => {
270
- const raw = input as {
271
- name: string
272
- description?: string
273
- nodes: string | Record<string, any>
274
- }
275
- const name = raw.name.replace(/[^a-zA-Z0-9_-]/g, '-')
276
- let nodes: Record<string, any>
277
- if (typeof raw.nodes === 'string') {
278
- try {
279
- nodes = JSON.parse(raw.nodes)
280
- } catch {
281
- return { error: 'Invalid JSON in nodes field' }
282
- }
283
- } else {
284
- nodes = raw.nodes
285
- }
286
-
287
- if (Object.keys(nodes).length < 2) {
288
- return {
289
- error:
290
- 'A workflow must have at least 2 nodes. A single node is just a tool call — use the tool directly instead.',
291
- }
292
- }
293
-
294
- const usedTools = [
295
- ...new Set(
296
- Object.values(nodes)
297
- .map((n: any) => n.rpcName)
298
- .filter(Boolean)
299
- ),
300
- ]
301
- const toolSchemas = buildDetailedToolSchemas(usedTools)
302
-
303
- const validationErrors = validateWorkflowWiring(nodes, toolNames)
304
- if (validationErrors.length > 0) {
305
- return {
306
- error: 'Workflow validation failed',
307
- errors: validationErrors,
308
- toolSchemas,
309
- }
310
- }
311
-
312
- const entryNodeIds = computeEntryNodeIds(nodes)
313
- if (entryNodeIds.length === 0) {
314
- return {
315
- error:
316
- 'No entry nodes found. Every node is referenced by another node, creating a cycle.',
317
- }
318
- }
319
-
320
- const fullName = `ai:${agentName}:${name}`
321
-
322
- const graphHash = hashString(canonicalJSON({ nodes, entryNodeIds }))
323
- const graph: WorkflowRuntimeMeta = {
324
- name: fullName,
325
- pikkuFuncId: fullName,
326
- source: 'ai-agent',
327
- description: raw.description,
328
- nodes,
329
- entryNodeIds,
330
- graphHash,
331
- }
332
-
333
- const singletonServices = getSingletonServices()
334
- if (!singletonServices?.workflowService) {
335
- return { error: 'Workflow service not available' }
336
- }
337
-
338
- await singletonServices.workflowService.upsertWorkflowVersion(
339
- fullName,
340
- graphHash,
341
- graph,
342
- 'ai-agent',
343
- 'draft'
344
- )
345
-
346
- return {
347
- valid: true,
348
- workflowName: fullName,
349
- graphHash,
350
- entryNodes: entryNodeIds,
351
- nodeCount: Object.keys(nodes).length,
352
- toolSchemas,
353
- message: `Workflow '${fullName}' validated and saved as draft. Check the toolSchemas to verify your $ref paths match the output paths. Then present this to the user and call saveAgentWorkflow to activate it.`,
354
- }
355
- },
356
- })
357
-
358
- tools.push({
359
- name: 'saveAgentWorkflow',
360
- description:
361
- 'Activate a previously created draft workflow so it can be executed. Requires user approval.',
362
- inputSchema: {
363
- type: 'object',
364
- properties: {
365
- name: {
366
- type: 'string',
367
- description:
368
- 'Full workflow name returned by createAgentWorkflow (e.g. ai:agentName:myWorkflow)',
369
- },
370
- graphHash: {
371
- type: 'string',
372
- description: 'Graph hash returned by createAgentWorkflow',
373
- },
374
- },
375
- required: ['name', 'graphHash'],
376
- },
377
- needsApproval: true,
378
- approvalDescriptionFn: async (input: unknown) => {
379
- const raw = input as { name: string; graphHash: string }
380
- const fullName = raw.name.startsWith(`ai:${agentName}:`)
381
- ? raw.name
382
- : `ai:${agentName}:${raw.name}`
383
-
384
- const singletonServices = getSingletonServices()
385
- if (!singletonServices?.workflowService) {
386
- return `Activate workflow '${fullName}'`
387
- }
388
-
389
- const version =
390
- await singletonServices.workflowService.getWorkflowVersion(
391
- fullName,
392
- raw.graphHash
393
- )
394
- if (version) {
395
- const graph = version.graph as WorkflowRuntimeMeta
396
- if (graph.nodes) {
397
- const desc = graph.description ? `\n${graph.description}` : ''
398
- return `Activate workflow '${fullName}' (${Object.keys(graph.nodes).length} nodes)${desc}`
399
- }
400
- }
401
- return `Activate workflow '${fullName}'`
402
- },
403
- execute: async (input: unknown) => {
404
- const raw = input as { name: string; graphHash: string }
405
- const fullName = raw.name.startsWith(`ai:${agentName}:`)
406
- ? raw.name
407
- : `ai:${agentName}:${raw.name}`
408
-
409
- const singletonServices = getSingletonServices()
410
- if (!singletonServices?.workflowService) {
411
- return { error: 'Workflow service not available' }
412
- }
413
-
414
- const version =
415
- await singletonServices.workflowService.getWorkflowVersion(
416
- fullName,
417
- raw.graphHash
418
- )
419
- if (!version) {
420
- return {
421
- error: `Workflow '${fullName}' with hash '${raw.graphHash}' not found. Use createAgentWorkflow first.`,
422
- }
423
- }
424
-
425
- await singletonServices.workflowService.updateWorkflowVersionStatus(
426
- fullName,
427
- raw.graphHash,
428
- 'active'
429
- )
430
-
431
- const graph = version.graph as WorkflowRuntimeMeta
432
- const allMeta = pikkuState(null, 'workflows', 'meta')
433
- allMeta[fullName] = graph
434
-
435
- if (streamContext) {
436
- streamContext.channel.send({
437
- type: 'workflow-created',
438
- workflowName: fullName,
439
- graph,
440
- })
441
- }
442
-
443
- return {
444
- success: true,
445
- workflowName: fullName,
446
- message: `Workflow '${fullName}' activated and ready to execute.`,
447
- }
448
- },
449
- })
450
- } // end if (mode !== 'read')
451
-
452
- tools.push({
453
- name: 'listAgentWorkflows',
454
- description:
455
- 'List previously saved workflows for this agent that can be executed.',
456
- inputSchema: {
457
- type: 'object',
458
- properties: {},
459
- },
460
- execute: async () => {
461
- const singletonServices = getSingletonServices()
462
- if (!singletonServices?.workflowService) {
463
- return { error: 'Workflow service not available' }
464
- }
465
-
466
- const results: Array<{
467
- name: string
468
- description?: string
469
- graphHash?: string
470
- }> = []
471
-
472
- const allMeta = pikkuState(null, 'workflows', 'meta')
473
- const prefix = `ai:${agentName}:`
474
- for (const [name, meta] of Object.entries(allMeta)) {
475
- if (name.startsWith(prefix) && meta.source === 'ai-agent') {
476
- results.push({
477
- name,
478
- description: meta.description,
479
- graphHash: meta.graphHash,
480
- })
481
- }
482
- }
483
-
484
- if (results.length === 0) {
485
- const persisted =
486
- await singletonServices.workflowService.getAIGeneratedWorkflows(
487
- agentName
488
- )
489
- for (const wf of persisted) {
490
- results.push({
491
- name: wf.workflowName,
492
- graphHash: wf.graphHash,
493
- })
494
- }
495
- }
496
-
497
- return { workflows: results }
498
- },
499
- })
500
-
501
- tools.push({
502
- name: 'executeAgentWorkflow',
503
- description: 'Execute a previously saved workflow with the given input.',
504
- inputSchema: {
505
- type: 'object',
506
- properties: {
507
- name: {
508
- type: 'string',
509
- description:
510
- 'Workflow name (will be auto-prefixed with ai:{agentName}: if needed)',
511
- },
512
- input: {
513
- type: 'object',
514
- description: 'Input data for the workflow trigger',
515
- },
516
- },
517
- required: ['name'],
518
- },
519
- needsApproval: true,
520
- approvalDescriptionFn: async (input: unknown) => {
521
- const { name, input: workflowInput } = input as {
522
- name: string
523
- input?: Record<string, any>
524
- }
525
- const fullName = name.startsWith(`ai:${agentName}:`)
526
- ? name
527
- : `ai:${agentName}:${name}`
528
- const inputStr = workflowInput
529
- ? `\nInput: ${JSON.stringify(workflowInput)}`
530
- : ''
531
- return `Execute workflow '${fullName}'${inputStr}`
532
- },
533
- execute: async (toolInput: unknown) => {
534
- const { name, input: workflowInput } = toolInput as {
535
- name: string
536
- input?: Record<string, any>
537
- }
538
-
539
- const fullName = name.startsWith(`ai:${agentName}:`)
540
- ? name
541
- : `ai:${agentName}:${name}`
542
-
543
- const singletonServices = getSingletonServices()
544
- if (!singletonServices?.workflowService) {
545
- return { error: 'Workflow service not available' }
546
- }
547
-
548
- const allMeta = pikkuState(null, 'workflows', 'meta')
549
- if (!allMeta[fullName]) {
550
- return {
551
- error: `Workflow '${fullName}' not found. Use listAgentWorkflows to see available workflows, or createAgentWorkflow to make a new one.`,
552
- }
553
- }
554
-
555
- const workflowService = singletonServices.workflowService as any
556
-
557
- const wire: PikkuWire = sessionService
558
- ? { ...createMiddlewareSessionWireProps(sessionService) }
559
- : {}
560
- const rpcService = new ContextAwareRPCService(singletonServices, wire, {
561
- sessionService,
562
- })
563
-
564
- const { runId } = await runWorkflowGraph(
565
- workflowService,
566
- fullName,
567
- workflowInput ?? {},
568
- rpcService,
569
- true,
570
- undefined,
571
- { type: 'ai-agent' }
572
- )
573
-
574
- const maxWait = 45000
575
- const startTime = Date.now()
576
- let pollInterval = 100
577
- while (Date.now() - startTime < maxWait) {
578
- const run = await workflowService.getRun(runId)
579
- if (!run) {
580
- return { error: `Workflow run '${runId}' not found` }
581
- }
582
- if (
583
- run.status === 'completed' ||
584
- run.status === 'failed' ||
585
- run.status === 'cancelled' ||
586
- run.status === 'suspended'
587
- ) {
588
- if (run.status === 'failed') {
589
- return {
590
- error: `Workflow failed: ${run.error?.message || 'Unknown error'}`,
591
- runId,
592
- }
593
- }
594
- return { result: run.output, runId, status: run.status }
595
- }
596
- await new Promise((resolve) => setTimeout(resolve, pollInterval))
597
- pollInterval = Math.min(pollInterval * 1.5, 2000)
598
- }
599
-
600
- return {
601
- runId,
602
- status: 'running',
603
- message:
604
- 'Workflow is still running after timeout. It will continue in the background.',
605
- }
606
- },
607
- })
608
-
609
- return tools
610
- }