@pikku/core 0.12.2 → 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 (282) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/crypto-utils.d.ts +10 -0
  3. package/dist/crypto-utils.js +62 -0
  4. package/dist/function/function-runner.js +4 -4
  5. package/dist/function/functions.types.d.ts +26 -1
  6. package/dist/function/functions.types.js +16 -0
  7. package/dist/handle-error.d.ts +1 -1
  8. package/dist/handle-error.js +7 -3
  9. package/dist/index.d.ts +14 -2
  10. package/dist/index.js +1 -1
  11. package/dist/pikku-state.js +3 -1
  12. package/dist/schema.js +1 -1
  13. package/dist/services/in-memory-workflow-service.d.ts +22 -3
  14. package/dist/services/in-memory-workflow-service.js +77 -1
  15. package/dist/services/workflow-service.d.ts +8 -2
  16. package/dist/testing/index.d.ts +2 -0
  17. package/dist/testing/index.js +1 -0
  18. package/dist/testing/service-tests.d.ts +31 -0
  19. package/dist/testing/service-tests.js +598 -0
  20. package/dist/types/core.types.d.ts +9 -1
  21. package/dist/types/state.types.d.ts +4 -2
  22. package/dist/utils/hash.d.ts +2 -0
  23. package/dist/utils/hash.js +23 -0
  24. package/dist/wirings/ai-agent/agent-dynamic-workflow.d.ts +6 -0
  25. package/dist/wirings/ai-agent/agent-dynamic-workflow.js +348 -0
  26. package/dist/wirings/ai-agent/ai-agent-memory.d.ts +1 -1
  27. package/dist/wirings/ai-agent/ai-agent-memory.js +6 -5
  28. package/dist/wirings/ai-agent/ai-agent-prepare.d.ts +10 -7
  29. package/dist/wirings/ai-agent/ai-agent-prepare.js +127 -47
  30. package/dist/wirings/ai-agent/ai-agent-runner.d.ts +4 -0
  31. package/dist/wirings/ai-agent/ai-agent-runner.js +381 -27
  32. package/dist/wirings/ai-agent/ai-agent-stream.d.ts +7 -2
  33. package/dist/wirings/ai-agent/ai-agent-stream.js +109 -46
  34. package/dist/wirings/ai-agent/ai-agent.types.d.ts +22 -1
  35. package/dist/wirings/ai-agent/index.d.ts +1 -2
  36. package/dist/wirings/ai-agent/index.js +1 -2
  37. package/dist/wirings/channel/channel-handler.js +5 -1
  38. package/dist/wirings/channel/channel.types.d.ts +1 -7
  39. package/dist/wirings/channel/local/local-channel-handler.d.ts +1 -1
  40. package/dist/wirings/channel/local/local-channel-handler.js +5 -3
  41. package/dist/wirings/channel/local/local-channel-runner.js +14 -4
  42. package/dist/wirings/channel/serverless/serverless-channel-runner.js +4 -1
  43. package/dist/wirings/cli/cli-runner.js +10 -2
  44. package/dist/wirings/cli/cli.types.d.ts +1 -0
  45. package/dist/wirings/http/http-routes.js +0 -1
  46. package/dist/wirings/http/http-runner.d.ts +1 -1
  47. package/dist/wirings/http/http-runner.js +25 -3
  48. package/dist/wirings/http/http.types.d.ts +3 -11
  49. package/dist/wirings/http/index.d.ts +2 -1
  50. package/dist/wirings/http/index.js +1 -0
  51. package/dist/wirings/http/pikku-fetch-http-request.d.ts +1 -0
  52. package/dist/wirings/http/pikku-fetch-http-request.js +3 -0
  53. package/dist/wirings/http/pikku-fetch-http-response.d.ts +1 -0
  54. package/dist/wirings/http/pikku-fetch-http-response.js +4 -4
  55. package/dist/wirings/http/web-request.d.ts +12 -0
  56. package/dist/wirings/http/web-request.js +85 -0
  57. package/dist/wirings/mcp/mcp-endpoint-registry.js +1 -1
  58. package/dist/wirings/mcp/mcp-runner.js +13 -1
  59. package/dist/wirings/rpc/rpc-runner.d.ts +30 -6
  60. package/dist/wirings/rpc/rpc-runner.js +36 -14
  61. package/dist/wirings/rpc/rpc-types.d.ts +6 -1
  62. package/dist/wirings/rpc/wire-addon.d.ts +1 -0
  63. package/dist/wirings/rpc/wire-addon.js +1 -1
  64. package/dist/wirings/scheduler/scheduler-runner.js +1 -0
  65. package/dist/wirings/workflow/graph/graph-validation.d.ts +3 -0
  66. package/dist/wirings/workflow/graph/graph-validation.js +175 -0
  67. package/dist/wirings/workflow/graph/index.d.ts +1 -0
  68. package/dist/wirings/workflow/graph/index.js +1 -0
  69. package/dist/wirings/workflow/index.d.ts +1 -1
  70. package/dist/wirings/workflow/pikku-workflow-service.d.ts +8 -2
  71. package/dist/wirings/workflow/pikku-workflow-service.js +1 -2
  72. package/dist/wirings/workflow/workflow.types.d.ts +10 -1
  73. package/lcov.info +18891 -0
  74. package/package.json +4 -2
  75. package/dist/wirings/ai-agent/ai-agent-assistant-ui.d.ts +0 -5
  76. package/dist/wirings/ai-agent/ai-agent-assistant-ui.js +0 -168
  77. package/src/crypto-utils.test.ts +0 -116
  78. package/src/crypto-utils.ts +0 -99
  79. package/src/errors/error-handler.ts +0 -62
  80. package/src/errors/error.test.ts +0 -195
  81. package/src/errors/errors.ts +0 -374
  82. package/src/errors/index.ts +0 -2
  83. package/src/factory-functions.test.ts +0 -109
  84. package/src/function/function-runner.test.ts +0 -536
  85. package/src/function/function-runner.ts +0 -365
  86. package/src/function/functions.types.ts +0 -267
  87. package/src/function/index.ts +0 -5
  88. package/src/handle-error.test.ts +0 -361
  89. package/src/handle-error.ts +0 -65
  90. package/src/index.ts +0 -104
  91. package/src/internal.ts +0 -6
  92. package/src/middleware/auth-apikey.test.ts +0 -363
  93. package/src/middleware/auth-apikey.ts +0 -47
  94. package/src/middleware/auth-bearer.test.ts +0 -450
  95. package/src/middleware/auth-bearer.ts +0 -72
  96. package/src/middleware/auth-cookie.test.ts +0 -528
  97. package/src/middleware/auth-cookie.ts +0 -80
  98. package/src/middleware/cors.test.ts +0 -424
  99. package/src/middleware/cors.ts +0 -104
  100. package/src/middleware/index.ts +0 -5
  101. package/src/middleware/remote-auth.test.ts +0 -488
  102. package/src/middleware/remote-auth.ts +0 -68
  103. package/src/middleware/timeout.ts +0 -15
  104. package/src/middleware-runner.test.ts +0 -418
  105. package/src/middleware-runner.ts +0 -234
  106. package/src/permissions.test.ts +0 -434
  107. package/src/permissions.ts +0 -319
  108. package/src/pikku-request.ts +0 -23
  109. package/src/pikku-response.ts +0 -5
  110. package/src/pikku-state.test.ts +0 -224
  111. package/src/pikku-state.ts +0 -214
  112. package/src/run-tests-script.test.ts +0 -49
  113. package/src/schema.test.ts +0 -249
  114. package/src/schema.ts +0 -151
  115. package/src/services/ai-agent-runner-service.ts +0 -41
  116. package/src/services/ai-run-state-service.ts +0 -20
  117. package/src/services/ai-storage-service.ts +0 -39
  118. package/src/services/content-service.ts +0 -76
  119. package/src/services/deployment-service.ts +0 -22
  120. package/src/services/gateway-service.ts +0 -20
  121. package/src/services/gopass-secrets.ts +0 -98
  122. package/src/services/in-memory-ai-run-state-service.ts +0 -73
  123. package/src/services/in-memory-trigger-service.ts +0 -64
  124. package/src/services/in-memory-workflow-service.test.ts +0 -351
  125. package/src/services/in-memory-workflow-service.ts +0 -395
  126. package/src/services/index.ts +0 -56
  127. package/src/services/jwt-service.ts +0 -30
  128. package/src/services/local-content.ts +0 -120
  129. package/src/services/local-gateway-service.ts +0 -62
  130. package/src/services/local-secrets.test.ts +0 -80
  131. package/src/services/local-secrets.ts +0 -94
  132. package/src/services/local-variables.test.ts +0 -61
  133. package/src/services/local-variables.ts +0 -39
  134. package/src/services/logger-console.test.ts +0 -118
  135. package/src/services/logger-console.ts +0 -98
  136. package/src/services/logger.ts +0 -57
  137. package/src/services/scheduler-service.ts +0 -86
  138. package/src/services/schema-service.ts +0 -33
  139. package/src/services/scoped-secret-service.test.ts +0 -74
  140. package/src/services/scoped-secret-service.ts +0 -41
  141. package/src/services/secret-service.ts +0 -38
  142. package/src/services/trigger-service.ts +0 -17
  143. package/src/services/typed-secret-service.test.ts +0 -93
  144. package/src/services/typed-secret-service.ts +0 -70
  145. package/src/services/typed-variables-service.test.ts +0 -73
  146. package/src/services/typed-variables-service.ts +0 -81
  147. package/src/services/user-session-service.test.ts +0 -113
  148. package/src/services/user-session-service.ts +0 -86
  149. package/src/services/variables-service.ts +0 -11
  150. package/src/services/workflow-service.ts +0 -84
  151. package/src/time-utils.test.ts +0 -56
  152. package/src/time-utils.ts +0 -107
  153. package/src/types/core.types.ts +0 -470
  154. package/src/types/state.types.ts +0 -186
  155. package/src/utils.test.ts +0 -350
  156. package/src/utils.ts +0 -129
  157. package/src/version.test.ts +0 -80
  158. package/src/version.ts +0 -25
  159. package/src/wirings/ai-agent/ai-agent-assistant-ui.test.ts +0 -363
  160. package/src/wirings/ai-agent/ai-agent-assistant-ui.ts +0 -238
  161. package/src/wirings/ai-agent/ai-agent-helpers.test.ts +0 -152
  162. package/src/wirings/ai-agent/ai-agent-helpers.ts +0 -76
  163. package/src/wirings/ai-agent/ai-agent-memory.ts +0 -309
  164. package/src/wirings/ai-agent/ai-agent-model-config.test.ts +0 -115
  165. package/src/wirings/ai-agent/ai-agent-model-config.ts +0 -43
  166. package/src/wirings/ai-agent/ai-agent-prepare.ts +0 -522
  167. package/src/wirings/ai-agent/ai-agent-registry.test.ts +0 -37
  168. package/src/wirings/ai-agent/ai-agent-registry.ts +0 -82
  169. package/src/wirings/ai-agent/ai-agent-runner.test.ts +0 -317
  170. package/src/wirings/ai-agent/ai-agent-runner.ts +0 -251
  171. package/src/wirings/ai-agent/ai-agent-stream.test.ts +0 -652
  172. package/src/wirings/ai-agent/ai-agent-stream.ts +0 -1060
  173. package/src/wirings/ai-agent/ai-agent.types.ts +0 -360
  174. package/src/wirings/ai-agent/index.ts +0 -41
  175. package/src/wirings/channel/channel-common.ts +0 -90
  176. package/src/wirings/channel/channel-handler.ts +0 -241
  177. package/src/wirings/channel/channel-middleware-runner.ts +0 -120
  178. package/src/wirings/channel/channel-runner.ts +0 -166
  179. package/src/wirings/channel/channel-store.ts +0 -29
  180. package/src/wirings/channel/channel.types.ts +0 -178
  181. package/src/wirings/channel/define-channel-routes.ts +0 -25
  182. package/src/wirings/channel/eventhub-service.ts +0 -34
  183. package/src/wirings/channel/eventhub-store.ts +0 -13
  184. package/src/wirings/channel/index.ts +0 -24
  185. package/src/wirings/channel/local/index.ts +0 -3
  186. package/src/wirings/channel/local/local-channel-handler.ts +0 -79
  187. package/src/wirings/channel/local/local-channel-runner.test.ts +0 -215
  188. package/src/wirings/channel/local/local-channel-runner.ts +0 -200
  189. package/src/wirings/channel/local/local-eventhub-service.test.ts +0 -95
  190. package/src/wirings/channel/local/local-eventhub-service.ts +0 -101
  191. package/src/wirings/channel/log-channels.ts +0 -20
  192. package/src/wirings/channel/pikku-abstract-channel-handler.test.ts +0 -54
  193. package/src/wirings/channel/pikku-abstract-channel-handler.ts +0 -45
  194. package/src/wirings/channel/serverless/index.ts +0 -5
  195. package/src/wirings/channel/serverless/serverless-channel-runner.ts +0 -286
  196. package/src/wirings/cli/channel/cli-channel-runner.ts +0 -136
  197. package/src/wirings/cli/channel/index.ts +0 -1
  198. package/src/wirings/cli/cli-runner.test.ts +0 -403
  199. package/src/wirings/cli/cli-runner.ts +0 -519
  200. package/src/wirings/cli/cli.types.ts +0 -357
  201. package/src/wirings/cli/command-parser.test.ts +0 -445
  202. package/src/wirings/cli/command-parser.ts +0 -504
  203. package/src/wirings/cli/define-cli-commands.ts +0 -24
  204. package/src/wirings/cli/index.ts +0 -19
  205. package/src/wirings/gateway/gateway-runner.test.ts +0 -474
  206. package/src/wirings/gateway/gateway-runner.ts +0 -411
  207. package/src/wirings/gateway/gateway.types.ts +0 -149
  208. package/src/wirings/gateway/index.ts +0 -13
  209. package/src/wirings/http/http-routes.test.ts +0 -322
  210. package/src/wirings/http/http-routes.ts +0 -198
  211. package/src/wirings/http/http-runner.test.ts +0 -144
  212. package/src/wirings/http/http-runner.ts +0 -563
  213. package/src/wirings/http/http.types.ts +0 -378
  214. package/src/wirings/http/index.ts +0 -25
  215. package/src/wirings/http/log-http-routes.ts +0 -22
  216. package/src/wirings/http/pikku-fetch-http-request.test.ts +0 -237
  217. package/src/wirings/http/pikku-fetch-http-request.ts +0 -166
  218. package/src/wirings/http/pikku-fetch-http-response.test.ts +0 -82
  219. package/src/wirings/http/pikku-fetch-http-response.ts +0 -147
  220. package/src/wirings/http/routers/http-router.ts +0 -13
  221. package/src/wirings/http/routers/path-to-regex.test.ts +0 -319
  222. package/src/wirings/http/routers/path-to-regex.ts +0 -126
  223. package/src/wirings/mcp/index.ts +0 -27
  224. package/src/wirings/mcp/mcp-endpoint-registry.test.ts +0 -389
  225. package/src/wirings/mcp/mcp-endpoint-registry.ts +0 -159
  226. package/src/wirings/mcp/mcp-runner.ts +0 -305
  227. package/src/wirings/mcp/mcp.types.ts +0 -216
  228. package/src/wirings/node/index.ts +0 -2
  229. package/src/wirings/node/node.types.ts +0 -23
  230. package/src/wirings/oauth2/index.ts +0 -3
  231. package/src/wirings/oauth2/oauth2-client.test.ts +0 -929
  232. package/src/wirings/oauth2/oauth2-client.ts +0 -335
  233. package/src/wirings/oauth2/oauth2.types.ts +0 -69
  234. package/src/wirings/oauth2/wire-oauth2-credential.ts +0 -23
  235. package/src/wirings/queue/index.ts +0 -31
  236. package/src/wirings/queue/queue-runner.test.ts +0 -710
  237. package/src/wirings/queue/queue-runner.ts +0 -192
  238. package/src/wirings/queue/queue.types.ts +0 -189
  239. package/src/wirings/queue/register-queue-helper.ts +0 -60
  240. package/src/wirings/queue/validate-worker-config.test.ts +0 -108
  241. package/src/wirings/queue/validate-worker-config.ts +0 -116
  242. package/src/wirings/rpc/index.ts +0 -4
  243. package/src/wirings/rpc/rpc-runner.ts +0 -439
  244. package/src/wirings/rpc/rpc-types.ts +0 -51
  245. package/src/wirings/rpc/wire-addon.ts +0 -20
  246. package/src/wirings/scheduler/index.ts +0 -11
  247. package/src/wirings/scheduler/log-schedulers.ts +0 -20
  248. package/src/wirings/scheduler/scheduler-runner.test.ts +0 -660
  249. package/src/wirings/scheduler/scheduler-runner.ts +0 -132
  250. package/src/wirings/scheduler/scheduler.types.ts +0 -53
  251. package/src/wirings/secret/index.ts +0 -9
  252. package/src/wirings/secret/secret.types.ts +0 -32
  253. package/src/wirings/secret/validate-secret-definitions.test.ts +0 -140
  254. package/src/wirings/secret/validate-secret-definitions.ts +0 -82
  255. package/src/wirings/trigger/index.ts +0 -10
  256. package/src/wirings/trigger/pikku-trigger-service.ts +0 -112
  257. package/src/wirings/trigger/trigger-runner.test.ts +0 -79
  258. package/src/wirings/trigger/trigger-runner.ts +0 -135
  259. package/src/wirings/trigger/trigger.types.ts +0 -178
  260. package/src/wirings/variable/index.ts +0 -8
  261. package/src/wirings/variable/validate-variable-definitions.test.ts +0 -91
  262. package/src/wirings/variable/validate-variable-definitions.ts +0 -69
  263. package/src/wirings/variable/variable.types.ts +0 -22
  264. package/src/wirings/workflow/dsl/index.ts +0 -31
  265. package/src/wirings/workflow/dsl/workflow-dsl.types.ts +0 -320
  266. package/src/wirings/workflow/dsl/workflow-runner.ts +0 -28
  267. package/src/wirings/workflow/graph/graph-node.ts +0 -222
  268. package/src/wirings/workflow/graph/graph-runner.test.ts +0 -487
  269. package/src/wirings/workflow/graph/graph-runner.ts +0 -816
  270. package/src/wirings/workflow/graph/index.ts +0 -14
  271. package/src/wirings/workflow/graph/template.test.ts +0 -49
  272. package/src/wirings/workflow/graph/template.ts +0 -42
  273. package/src/wirings/workflow/graph/wire-workflow-graph.ts +0 -29
  274. package/src/wirings/workflow/graph/workflow-graph.types.ts +0 -104
  275. package/src/wirings/workflow/index.ts +0 -81
  276. package/src/wirings/workflow/pikku-workflow-service.test.ts +0 -200
  277. package/src/wirings/workflow/pikku-workflow-service.ts +0 -1165
  278. package/src/wirings/workflow/workflow-helpers.test.ts +0 -129
  279. package/src/wirings/workflow/workflow-helpers.ts +0 -79
  280. package/src/wirings/workflow/workflow.types.ts +0 -266
  281. package/tsconfig.json +0 -14
  282. package/tsconfig.tsbuildinfo +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikku/core",
3
- "version": "0.12.2",
3
+ "version": "0.12.4",
4
4
  "author": "yasser.fadl@gmail.com",
5
5
  "license": "MIT",
6
6
  "module": "dist/index.js",
@@ -41,8 +41,10 @@
41
41
  "./services": "./dist/services/index.js",
42
42
  "./services/local-content": "./dist/services/local-content.js",
43
43
  "./services/gopass-secrets": "./dist/services/gopass-secrets.js",
44
+ "./crypto-utils": "./dist/crypto-utils.js",
44
45
  "./internal": "./dist/internal.js",
45
- "./schema": "./dist/schema.js"
46
+ "./schema": "./dist/schema.js",
47
+ "./testing": "./dist/testing/index.js"
46
48
  },
47
49
  "dependencies": {
48
50
  "@standard-schema/spec": "^1.1.0",
@@ -1,5 +0,0 @@
1
- import type { AIStreamChannel, AIAgentInput } from './ai-agent.types.js';
2
- export declare function createAssistantUIChannel(parent: AIStreamChannel): AIStreamChannel;
3
- export declare function parseAssistantUIInput(input: Record<string, unknown>, defaults?: {
4
- resourceId?: string;
5
- }): AIAgentInput;
@@ -1,168 +0,0 @@
1
- import { randomUUID } from 'crypto';
2
- export function createAssistantUIChannel(parent) {
3
- const messageId = randomUUID();
4
- let started = false;
5
- let totalInputTokens = 0;
6
- let totalOutputTokens = 0;
7
- let pendingToolResults = [];
8
- let hasToolCalls = false;
9
- let hasPendingApproval = false;
10
- const sendChunk = (chunk) => {
11
- parent.send(chunk);
12
- };
13
- const ensureStarted = () => {
14
- if (!started) {
15
- started = true;
16
- sendChunk({ type: 'start', messageId });
17
- }
18
- };
19
- const flushToolResults = () => {
20
- for (const chunk of pendingToolResults) {
21
- sendChunk(chunk);
22
- }
23
- pendingToolResults = [];
24
- };
25
- return {
26
- channelId: parent.channelId,
27
- openingData: parent.openingData,
28
- get state() {
29
- return parent.state;
30
- },
31
- close: () => parent.close(),
32
- sendBinary: (data) => parent.sendBinary(data),
33
- send: (event) => {
34
- switch (event.type) {
35
- case 'text-delta':
36
- ensureStarted();
37
- sendChunk({ type: 'text-delta', textDelta: event.text });
38
- break;
39
- case 'reasoning-delta':
40
- ensureStarted();
41
- sendChunk({ type: 'reasoning-delta', delta: event.text });
42
- break;
43
- case 'audio-delta':
44
- ensureStarted();
45
- sendChunk({ type: 'audio-delta', data: event });
46
- break;
47
- case 'audio-done':
48
- ensureStarted();
49
- sendChunk({ type: 'audio-done', data: event });
50
- break;
51
- case 'tool-call':
52
- ensureStarted();
53
- hasToolCalls = true;
54
- sendChunk({
55
- type: 'tool-call-start',
56
- id: event.toolCallId,
57
- toolCallId: event.toolCallId,
58
- toolName: event.toolName,
59
- });
60
- sendChunk({
61
- type: 'tool-call-delta',
62
- argsText: typeof event.args === 'string'
63
- ? event.args
64
- : JSON.stringify(event.args),
65
- });
66
- sendChunk({ type: 'tool-call-end' });
67
- break;
68
- case 'tool-result':
69
- ensureStarted();
70
- pendingToolResults.push({
71
- type: 'tool-result',
72
- toolCallId: event.toolCallId,
73
- result: event.result,
74
- });
75
- break;
76
- case 'agent-call':
77
- case 'agent-result':
78
- break;
79
- case 'usage': {
80
- ensureStarted();
81
- totalInputTokens += event.tokens.input;
82
- totalOutputTokens += event.tokens.output;
83
- const hasPending = pendingToolResults.length > 0;
84
- sendChunk({
85
- type: 'finish-step',
86
- finishReason: hasToolCalls ? 'tool-calls' : 'stop',
87
- usage: {
88
- promptTokens: event.tokens.input,
89
- completionTokens: event.tokens.output,
90
- },
91
- isContinued: hasPending,
92
- });
93
- flushToolResults();
94
- hasToolCalls = false;
95
- break;
96
- }
97
- case 'error':
98
- ensureStarted();
99
- sendChunk({ type: 'error', errorText: event.message });
100
- break;
101
- case 'approval-request':
102
- ensureStarted();
103
- hasPendingApproval = true;
104
- sendChunk({ type: 'data-approval-request', data: event });
105
- break;
106
- case 'suspended':
107
- ensureStarted();
108
- sendChunk({ type: 'data-suspended', data: event });
109
- break;
110
- case 'done':
111
- ensureStarted();
112
- flushToolResults();
113
- sendChunk({
114
- type: 'finish',
115
- finishReason: hasPendingApproval ? 'tool-calls' : 'stop',
116
- usage: {
117
- promptTokens: totalInputTokens,
118
- completionTokens: totalOutputTokens,
119
- },
120
- });
121
- parent.send('[DONE]');
122
- parent.close();
123
- break;
124
- }
125
- },
126
- };
127
- }
128
- export function parseAssistantUIInput(input, defaults) {
129
- const messages = input.messages;
130
- if (!messages || !Array.isArray(messages) || messages.length === 0) {
131
- throw new Error('assistant-ui input must contain a non-empty messages array');
132
- }
133
- const lastUserMessage = [...messages].reverse().find((m) => m.role === 'user');
134
- if (!lastUserMessage) {
135
- throw new Error('No user message found in assistant-ui input');
136
- }
137
- let messageText;
138
- let attachments;
139
- const extractFromParts = (parts) => {
140
- const textParts = parts.filter((p) => p.type === 'text');
141
- messageText = textParts.map((p) => String(p.text)).join(' ') || '';
142
- const nonTextParts = parts.filter((p) => p.type === 'image' || p.type === 'file');
143
- if (nonTextParts.length > 0) {
144
- attachments = nonTextParts.map((p) => ({
145
- type: p.type,
146
- data: p.data,
147
- url: p.url,
148
- mediaType: p.mediaType,
149
- filename: p.filename,
150
- }));
151
- }
152
- };
153
- if (typeof lastUserMessage.content === 'string') {
154
- messageText = lastUserMessage.content;
155
- }
156
- else if (Array.isArray(lastUserMessage.parts)) {
157
- extractFromParts(lastUserMessage.parts);
158
- }
159
- else if (Array.isArray(lastUserMessage.content)) {
160
- extractFromParts(lastUserMessage.content);
161
- }
162
- else {
163
- messageText = '';
164
- }
165
- const threadId = input.threadId ?? input.id ?? randomUUID();
166
- const resourceId = defaults?.resourceId ?? 'default';
167
- return { message: messageText, threadId, resourceId, attachments };
168
- }
@@ -1,116 +0,0 @@
1
- import { describe, test } from 'node:test'
2
- import assert from 'node:assert'
3
- import { encryptJSON, decryptJSON } from './crypto-utils.js'
4
-
5
- describe('encryptJSON / decryptJSON', () => {
6
- const secret = 'test-secret-key-for-encryption'
7
-
8
- test('should round-trip a simple object', async () => {
9
- const original = { hello: 'world', num: 42 }
10
- const encrypted = await encryptJSON(secret, original)
11
- const decrypted = await decryptJSON(secret, encrypted)
12
- assert.deepStrictEqual(decrypted, original)
13
- })
14
-
15
- test('should round-trip a string value', async () => {
16
- const original = 'just a string'
17
- const encrypted = await encryptJSON(secret, original)
18
- const decrypted = await decryptJSON(secret, encrypted)
19
- assert.strictEqual(decrypted, original)
20
- })
21
-
22
- test('should round-trip a number', async () => {
23
- const original = 12345
24
- const encrypted = await encryptJSON(secret, original)
25
- const decrypted = await decryptJSON(secret, encrypted)
26
- assert.strictEqual(decrypted, original)
27
- })
28
-
29
- test('should round-trip null', async () => {
30
- const encrypted = await encryptJSON(secret, null)
31
- const decrypted = await decryptJSON(secret, encrypted)
32
- assert.strictEqual(decrypted, null)
33
- })
34
-
35
- test('should round-trip a boolean', async () => {
36
- const encrypted = await encryptJSON(secret, true)
37
- const decrypted = await decryptJSON(secret, encrypted)
38
- assert.strictEqual(decrypted, true)
39
- })
40
-
41
- test('should round-trip a nested object', async () => {
42
- const original = { user: { id: 1, roles: ['admin', 'user'] }, active: true }
43
- const encrypted = await encryptJSON(secret, original)
44
- const decrypted = await decryptJSON(secret, encrypted)
45
- assert.deepStrictEqual(decrypted, original)
46
- })
47
-
48
- test('should round-trip an array', async () => {
49
- const original = [1, 'two', { three: 3 }]
50
- const encrypted = await encryptJSON(secret, original)
51
- const decrypted = await decryptJSON(secret, encrypted)
52
- assert.deepStrictEqual(decrypted, original)
53
- })
54
-
55
- test('should produce different ciphertexts for same input (random IV)', async () => {
56
- const value = { same: 'data' }
57
- const enc1 = await encryptJSON(secret, value)
58
- const enc2 = await encryptJSON(secret, value)
59
- assert.notStrictEqual(enc1, enc2)
60
- })
61
-
62
- test('should produce a base64url string (no +, /, or = characters)', async () => {
63
- const encrypted = await encryptJSON(secret, { test: 'base64url' })
64
- assert.ok(!/[+/=]/.test(encrypted), `Expected base64url, got: ${encrypted}`)
65
- })
66
-
67
- test('should fail to decrypt with wrong secret', async () => {
68
- const encrypted = await encryptJSON(secret, { data: 'sensitive' })
69
- await assert.rejects(
70
- () => decryptJSON('wrong-secret', encrypted),
71
- (err: any) => err instanceof Error
72
- )
73
- })
74
-
75
- test('should reject an invalid encrypted payload (too short)', async () => {
76
- await assert.rejects(() => decryptJSON(secret, 'dG9vc2hvcnQ'), {
77
- message: 'Invalid encrypted payload',
78
- })
79
- })
80
-
81
- test('should reject empty string', async () => {
82
- await assert.rejects(() => decryptJSON(secret, ''), {
83
- message: 'Invalid encrypted payload',
84
- })
85
- })
86
-
87
- test('should reject corrupted ciphertext', async () => {
88
- const encrypted = await encryptJSON(secret, { data: 'test' })
89
- const corrupted = encrypted.slice(0, -4) + 'XXXX'
90
- await assert.rejects(
91
- () => decryptJSON(secret, corrupted),
92
- (err: any) => err instanceof Error
93
- )
94
- })
95
-
96
- test('should handle unicode content', async () => {
97
- const original = { emoji: '🎉', japanese: 'こんにちは', arabic: 'مرحبا' }
98
- const encrypted = await encryptJSON(secret, original)
99
- const decrypted = await decryptJSON(secret, encrypted)
100
- assert.deepStrictEqual(decrypted, original)
101
- })
102
-
103
- test('should handle empty object', async () => {
104
- const original = {}
105
- const encrypted = await encryptJSON(secret, original)
106
- const decrypted = await decryptJSON(secret, encrypted)
107
- assert.deepStrictEqual(decrypted, original)
108
- })
109
-
110
- test('should handle large payload', async () => {
111
- const original = { data: 'x'.repeat(10000) }
112
- const encrypted = await encryptJSON(secret, original)
113
- const decrypted = await decryptJSON(secret, encrypted)
114
- assert.deepStrictEqual(decrypted, original)
115
- })
116
- })
@@ -1,99 +0,0 @@
1
- const encoder = new TextEncoder()
2
- const decoder = new TextDecoder()
3
-
4
- const getSubtle = () => {
5
- const crypto = globalThis.crypto
6
- if (!crypto?.subtle) {
7
- throw new Error('WebCrypto not available')
8
- }
9
- return crypto.subtle
10
- }
11
-
12
- const base64Encode = (bytes: Uint8Array): string => {
13
- if (typeof Buffer !== 'undefined') {
14
- return Buffer.from(bytes).toString('base64')
15
- }
16
- let binary = ''
17
- for (let i = 0; i < bytes.length; i++) {
18
- binary += String.fromCharCode(bytes[i]!)
19
- }
20
- return btoa(binary)
21
- }
22
-
23
- const base64Decode = (input: string): Uint8Array => {
24
- if (typeof Buffer !== 'undefined') {
25
- return new Uint8Array(Buffer.from(input, 'base64'))
26
- }
27
- const binary = atob(input)
28
- const bytes = new Uint8Array(binary.length)
29
- for (let i = 0; i < binary.length; i++) {
30
- bytes[i] = binary.charCodeAt(i)
31
- }
32
- return bytes
33
- }
34
-
35
- const toBase64Url = (bytes: Uint8Array): string => {
36
- return base64Encode(bytes)
37
- .replace(/\+/g, '-')
38
- .replace(/\//g, '_')
39
- .replace(/=+$/g, '')
40
- }
41
-
42
- const fromBase64Url = (input: string): Uint8Array => {
43
- let base64 = input.replace(/-/g, '+').replace(/_/g, '/')
44
- while (base64.length % 4 !== 0) base64 += '='
45
- return base64Decode(base64)
46
- }
47
-
48
- const deriveKey = async (secret: string): Promise<CryptoKey> => {
49
- const subtle = getSubtle()
50
- const hash = await subtle.digest('SHA-256', encoder.encode(secret))
51
- return subtle.importKey('raw', hash, { name: 'AES-GCM' }, false, [
52
- 'encrypt',
53
- 'decrypt',
54
- ])
55
- }
56
-
57
- export const encryptJSON = async (
58
- secret: string,
59
- value: unknown
60
- ): Promise<string> => {
61
- const crypto = globalThis.crypto
62
- if (!crypto?.getRandomValues) {
63
- throw new Error('WebCrypto not available')
64
- }
65
- const subtle = getSubtle()
66
- const iv = crypto.getRandomValues(new Uint8Array(12))
67
- const key = await deriveKey(secret)
68
- const plaintext = encoder.encode(JSON.stringify(value))
69
- const encrypted = await subtle.encrypt(
70
- { name: 'AES-GCM', iv },
71
- key,
72
- plaintext
73
- )
74
- const cipherBytes = new Uint8Array(encrypted)
75
- const out = new Uint8Array(iv.length + cipherBytes.length)
76
- out.set(iv, 0)
77
- out.set(cipherBytes, iv.length)
78
- return toBase64Url(out)
79
- }
80
-
81
- export const decryptJSON = async <T>(
82
- secret: string,
83
- token: string
84
- ): Promise<T> => {
85
- const subtle = getSubtle()
86
- const data = fromBase64Url(token)
87
- if (data.length < 13) {
88
- throw new Error('Invalid encrypted payload')
89
- }
90
- const iv = data.slice(0, 12)
91
- const ciphertext = data.slice(12)
92
- const key = await deriveKey(secret)
93
- const decrypted = await subtle.decrypt(
94
- { name: 'AES-GCM', iv },
95
- key,
96
- ciphertext
97
- )
98
- return JSON.parse(decoder.decode(new Uint8Array(decrypted))) as T
99
- }
@@ -1,62 +0,0 @@
1
- import { pikkuState } from '../pikku-state.js'
2
-
3
- /**
4
- * Base class for custom errors.
5
- * @extends {Error}
6
- */
7
- export class PikkuError extends Error {
8
- /**
9
- * Creates an instance of PikkuError.
10
- * @param message - The error message.
11
- */
12
- constructor(message: string = 'An error occurred') {
13
- super(message)
14
- Object.setPrototypeOf(this, new.target.prototype)
15
- }
16
- }
17
-
18
- /**
19
- * Interface for error details.
20
- */
21
- export interface ErrorDetails {
22
- status: number
23
- message: string
24
- mcpCode?: number
25
- }
26
-
27
- /**
28
- * Adds an error to the API errors map.
29
- * @param error - The error to add.
30
- * @param details - The details of the error.
31
- */
32
- export const addError = (error: any, { status, message }: ErrorDetails) => {
33
- pikkuState(null, 'misc', 'errors').set(error, { status, message })
34
- }
35
-
36
- /**
37
- * Adds multiple errors to the API errors map.
38
- * @param errors - An array of errors and their details.
39
- */
40
- export const addErrors = (
41
- errors: Array<[error: any, details: ErrorDetails]>
42
- ) => {
43
- errors.forEach((error) => {
44
- addError(error[0], error[1])
45
- })
46
- }
47
-
48
- /**
49
- * Retrieves the error response for a given error.
50
- * @param error - The error to get the response for.
51
- * @returns An object containing the status and message, or undefined if the error is not found.
52
- */
53
- export const getErrorResponse = (
54
- error: Error
55
- ): { status: number; message: string; mcpCode?: number } | undefined => {
56
- const errors = Array.from(pikkuState(null, 'misc', 'errors').entries())
57
- const foundError = errors.find(([e]) => e.name === error.constructor.name)
58
- if (foundError) {
59
- return foundError[1]
60
- }
61
- return pikkuState(null, 'misc', 'errors').get(error)
62
- }
@@ -1,195 +0,0 @@
1
- import { test, describe } from 'node:test'
2
- import assert from 'assert'
3
- import {
4
- getErrorResponse,
5
- addError,
6
- addErrors,
7
- PikkuError,
8
- } from './error-handler.js'
9
- import {
10
- BadRequestError,
11
- UnauthorizedError,
12
- MissingSessionError,
13
- InvalidSessionError,
14
- PaymentRequiredError,
15
- ForbiddenError,
16
- InvalidOriginError,
17
- NotFoundError,
18
- MethodNotAllowedError,
19
- NotAcceptableError,
20
- ProxyAuthenticationRequiredError,
21
- RequestTimeoutError,
22
- ConflictError,
23
- GoneError,
24
- LengthRequiredError,
25
- PreconditionFailedError,
26
- PayloadTooLargeError,
27
- URITooLongError,
28
- UnsupportedMediaTypeError,
29
- RangeNotSatisfiableError,
30
- ExpectationFailedError,
31
- UnprocessableContentError,
32
- LockedError,
33
- TooManyRequestsError,
34
- InternalServerError,
35
- NotImplementedError,
36
- BadGatewayError,
37
- ServiceUnavailableError,
38
- GatewayTimeoutError,
39
- HTTPVersionNotSupportedError,
40
- MaxComputeTimeReachedError,
41
- MissingSchemaError,
42
- InvalidMiddlewareWireError,
43
- PikkuMissingMetaError,
44
- } from './errors.js'
45
-
46
- describe('PikkuError', () => {
47
- test('should create error with default message', () => {
48
- const error = new PikkuError()
49
- assert.strictEqual(error.message, 'An error occurred')
50
- })
51
-
52
- test('should create error with custom message', () => {
53
- const error = new PikkuError('custom message')
54
- assert.strictEqual(error.message, 'custom message')
55
- })
56
-
57
- test('should be instance of Error', () => {
58
- const error = new PikkuError()
59
- assert.ok(error instanceof Error)
60
- })
61
-
62
- test('should be instance of PikkuError', () => {
63
- const error = new PikkuError()
64
- assert.ok(error instanceof PikkuError)
65
- })
66
-
67
- test('subclasses should be instanceof PikkuError', () => {
68
- assert.ok(new BadRequestError() instanceof PikkuError)
69
- assert.ok(new NotFoundError() instanceof PikkuError)
70
- assert.ok(new ForbiddenError() instanceof PikkuError)
71
- })
72
- })
73
-
74
- describe('getErrorResponse', () => {
75
- test('should return the correct error response for BadRequestError', () => {
76
- const error = new BadRequestError()
77
- const response = getErrorResponse(error)
78
- assert.deepStrictEqual(response, {
79
- status: 400,
80
- message:
81
- 'The server cannot or will not process the request due to client error (e.g., malformed request syntax).',
82
- })
83
- })
84
-
85
- test('should return the correct error response for NotFoundError', () => {
86
- const error = new NotFoundError()
87
- const response = getErrorResponse(error)
88
- assert.deepStrictEqual(response, {
89
- status: 404,
90
- message: 'The server cannot find the requested resource.',
91
- })
92
- })
93
-
94
- test('should return the correct error response for ForbiddenError', () => {
95
- const error = new ForbiddenError()
96
- const response = getErrorResponse(error)
97
- assert.deepStrictEqual(response, {
98
- status: 403,
99
- message:
100
- 'The client does not have permission to access the requested resource.',
101
- })
102
- })
103
-
104
- test('should return undefined for an unknown error', () => {
105
- class UnknownError extends Error {}
106
- const error = new UnknownError()
107
- const response = getErrorResponse(error)
108
- assert.strictEqual(response, undefined)
109
- })
110
-
111
- test('should return the correct error response for a custom error added to apiErrors', () => {
112
- class CustomError extends Error {}
113
- const customError = new CustomError()
114
- const customErrorDetails = { status: 400, message: 'Custom Error' }
115
-
116
- // Add the custom error to the apiErrors map
117
- addError(CustomError, customErrorDetails)
118
-
119
- const response = getErrorResponse(customError)
120
- assert.deepStrictEqual(response, customErrorDetails)
121
- })
122
- })
123
-
124
- describe('addErrors', () => {
125
- test('should register multiple errors at once', () => {
126
- class ErrA extends Error {}
127
- class ErrB extends Error {}
128
- addErrors([
129
- [ErrA, { status: 450, message: 'Error A' }],
130
- [ErrB, { status: 451, message: 'Error B' }],
131
- ])
132
- assert.deepStrictEqual(getErrorResponse(new ErrA()), {
133
- status: 450,
134
- message: 'Error A',
135
- })
136
- assert.deepStrictEqual(getErrorResponse(new ErrB()), {
137
- status: 451,
138
- message: 'Error B',
139
- })
140
- })
141
- })
142
-
143
- describe('all built-in error classes', () => {
144
- const errorCases: [string, any, number][] = [
145
- ['InvalidMiddlewareWireError', InvalidMiddlewareWireError, 500],
146
- ['PikkuMissingMetaError', PikkuMissingMetaError, 500],
147
- ['BadRequestError', BadRequestError, 400],
148
- ['UnauthorizedError', UnauthorizedError, 401],
149
- ['MissingSessionError', MissingSessionError, 401],
150
- ['InvalidSessionError', InvalidSessionError, 401],
151
- ['PaymentRequiredError', PaymentRequiredError, 402],
152
- ['ForbiddenError', ForbiddenError, 403],
153
- ['InvalidOriginError', InvalidOriginError, 403],
154
- ['NotFoundError', NotFoundError, 404],
155
- ['MethodNotAllowedError', MethodNotAllowedError, 405],
156
- ['NotAcceptableError', NotAcceptableError, 406],
157
- ['ProxyAuthenticationRequiredError', ProxyAuthenticationRequiredError, 407],
158
- ['RequestTimeoutError', RequestTimeoutError, 408],
159
- ['ConflictError', ConflictError, 409],
160
- ['GoneError', GoneError, 410],
161
- ['LengthRequiredError', LengthRequiredError, 411],
162
- ['PreconditionFailedError', PreconditionFailedError, 412],
163
- ['PayloadTooLargeError', PayloadTooLargeError, 413],
164
- ['URITooLongError', URITooLongError, 414],
165
- ['UnsupportedMediaTypeError', UnsupportedMediaTypeError, 415],
166
- ['RangeNotSatisfiableError', RangeNotSatisfiableError, 416],
167
- ['ExpectationFailedError', ExpectationFailedError, 417],
168
- ['UnprocessableContentError', UnprocessableContentError, 422],
169
- ['LockedError', LockedError, 423],
170
- ['TooManyRequestsError', TooManyRequestsError, 429],
171
- ['InternalServerError', InternalServerError, 500],
172
- ['NotImplementedError', NotImplementedError, 501],
173
- ['BadGatewayError', BadGatewayError, 502],
174
- ['ServiceUnavailableError', ServiceUnavailableError, 503],
175
- ['GatewayTimeoutError', GatewayTimeoutError, 504],
176
- ['HTTPVersionNotSupportedError', HTTPVersionNotSupportedError, 505],
177
- ['MaxComputeTimeReachedError', MaxComputeTimeReachedError, 524],
178
- ['MissingSchemaError', MissingSchemaError, 500],
179
- ]
180
-
181
- for (const [name, ErrorClass, expectedStatus] of errorCases) {
182
- test(`${name} should map to status ${expectedStatus}`, () => {
183
- const error = new ErrorClass()
184
- const response = getErrorResponse(error)
185
- assert.ok(response, `Expected error response for ${name}`)
186
- assert.strictEqual(response!.status, expectedStatus)
187
- assert.ok(response!.message.length > 0)
188
- })
189
-
190
- test(`${name} should be instance of PikkuError`, () => {
191
- const error = new ErrorClass()
192
- assert.ok(error instanceof PikkuError)
193
- })
194
- }
195
- })