@pikku/core 0.12.1 → 0.12.3

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 (165) hide show
  1. package/CHANGELOG.md +34 -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/middleware-runner.js +1 -0
  12. package/dist/permissions.js +1 -0
  13. package/dist/pikku-state.js +7 -1
  14. package/dist/schema.js +1 -1
  15. package/dist/services/gateway-service.d.ts +19 -0
  16. package/dist/services/gateway-service.js +1 -0
  17. package/dist/services/in-memory-workflow-service.d.ts +8 -2
  18. package/dist/services/in-memory-workflow-service.js +28 -1
  19. package/dist/services/index.d.ts +2 -0
  20. package/dist/services/index.js +1 -0
  21. package/dist/services/local-gateway-service.d.ts +22 -0
  22. package/dist/services/local-gateway-service.js +51 -0
  23. package/dist/services/workflow-service.d.ts +8 -2
  24. package/dist/testing/index.d.ts +2 -0
  25. package/dist/testing/index.js +1 -0
  26. package/dist/testing/service-tests.d.ts +31 -0
  27. package/dist/testing/service-tests.js +598 -0
  28. package/dist/types/core.types.d.ts +12 -2
  29. package/dist/types/state.types.d.ts +9 -2
  30. package/dist/utils/hash.d.ts +2 -0
  31. package/dist/utils/hash.js +23 -0
  32. package/dist/utils.js +1 -1
  33. package/dist/wirings/ai-agent/agent-dynamic-workflow.d.ts +6 -0
  34. package/dist/wirings/ai-agent/agent-dynamic-workflow.js +348 -0
  35. package/dist/wirings/ai-agent/ai-agent-memory.d.ts +1 -1
  36. package/dist/wirings/ai-agent/ai-agent-memory.js +19 -7
  37. package/dist/wirings/ai-agent/ai-agent-prepare.d.ts +10 -7
  38. package/dist/wirings/ai-agent/ai-agent-prepare.js +141 -48
  39. package/dist/wirings/ai-agent/ai-agent-runner.d.ts +4 -0
  40. package/dist/wirings/ai-agent/ai-agent-runner.js +381 -27
  41. package/dist/wirings/ai-agent/ai-agent-stream.d.ts +7 -2
  42. package/dist/wirings/ai-agent/ai-agent-stream.js +126 -48
  43. package/dist/wirings/ai-agent/ai-agent.types.d.ts +57 -3
  44. package/dist/wirings/ai-agent/index.d.ts +2 -3
  45. package/dist/wirings/ai-agent/index.js +1 -2
  46. package/dist/wirings/channel/channel-handler.d.ts +5 -2
  47. package/dist/wirings/channel/channel-handler.js +16 -2
  48. package/dist/wirings/channel/channel-middleware-runner.js +1 -0
  49. package/dist/wirings/channel/channel.types.d.ts +7 -7
  50. package/dist/wirings/channel/index.d.ts +1 -1
  51. package/dist/wirings/channel/local/local-channel-handler.d.ts +8 -1
  52. package/dist/wirings/channel/local/local-channel-handler.js +22 -3
  53. package/dist/wirings/channel/local/local-channel-runner.js +28 -5
  54. package/dist/wirings/channel/pikku-abstract-channel-handler.d.ts +2 -1
  55. package/dist/wirings/channel/pikku-abstract-channel-handler.js +1 -0
  56. package/dist/wirings/channel/serverless/serverless-channel-runner.js +5 -2
  57. package/dist/wirings/cli/cli-runner.js +13 -2
  58. package/dist/wirings/cli/cli.types.d.ts +1 -0
  59. package/dist/wirings/gateway/gateway-runner.d.ts +24 -0
  60. package/dist/wirings/gateway/gateway-runner.js +325 -0
  61. package/dist/wirings/gateway/gateway.types.d.ts +127 -0
  62. package/dist/wirings/gateway/gateway.types.js +1 -0
  63. package/dist/wirings/gateway/index.d.ts +2 -0
  64. package/dist/wirings/gateway/index.js +1 -0
  65. package/dist/wirings/http/http-routes.js +0 -1
  66. package/dist/wirings/http/http-runner.d.ts +1 -1
  67. package/dist/wirings/http/http-runner.js +28 -3
  68. package/dist/wirings/http/http.types.d.ts +3 -11
  69. package/dist/wirings/http/index.d.ts +2 -1
  70. package/dist/wirings/http/index.js +1 -0
  71. package/dist/wirings/http/pikku-fetch-http-request.d.ts +1 -0
  72. package/dist/wirings/http/pikku-fetch-http-request.js +3 -0
  73. package/dist/wirings/http/pikku-fetch-http-response.d.ts +1 -0
  74. package/dist/wirings/http/pikku-fetch-http-response.js +4 -4
  75. package/dist/wirings/http/web-request.d.ts +12 -0
  76. package/dist/wirings/http/web-request.js +85 -0
  77. package/dist/wirings/mcp/mcp-endpoint-registry.js +1 -1
  78. package/dist/wirings/mcp/mcp-runner.js +13 -1
  79. package/dist/wirings/rpc/rpc-runner.d.ts +30 -6
  80. package/dist/wirings/rpc/rpc-runner.js +36 -14
  81. package/dist/wirings/rpc/rpc-types.d.ts +6 -1
  82. package/dist/wirings/rpc/wire-addon.d.ts +1 -0
  83. package/dist/wirings/rpc/wire-addon.js +1 -1
  84. package/dist/wirings/scheduler/scheduler-runner.js +1 -0
  85. package/dist/wirings/workflow/graph/graph-validation.d.ts +3 -0
  86. package/dist/wirings/workflow/graph/graph-validation.js +175 -0
  87. package/dist/wirings/workflow/graph/index.d.ts +1 -0
  88. package/dist/wirings/workflow/graph/index.js +1 -0
  89. package/dist/wirings/workflow/index.d.ts +1 -1
  90. package/dist/wirings/workflow/pikku-workflow-service.d.ts +8 -2
  91. package/dist/wirings/workflow/pikku-workflow-service.js +1 -2
  92. package/dist/wirings/workflow/workflow.types.d.ts +10 -1
  93. package/package.json +6 -3
  94. package/src/crypto-utils.test.ts +99 -1
  95. package/src/crypto-utils.ts +114 -0
  96. package/src/function/function-runner.ts +5 -5
  97. package/src/function/functions.types.ts +38 -1
  98. package/src/handle-error.test.ts +65 -2
  99. package/src/handle-error.ts +8 -4
  100. package/src/index.ts +14 -0
  101. package/src/middleware-runner.ts +1 -0
  102. package/src/permissions.ts +1 -0
  103. package/src/pikku-state.ts +8 -1
  104. package/src/schema.ts +1 -1
  105. package/src/services/gateway-service.ts +20 -0
  106. package/src/services/in-memory-workflow-service.ts +45 -2
  107. package/src/services/index.ts +2 -0
  108. package/src/services/local-gateway-service.ts +62 -0
  109. package/src/services/workflow-service.ts +12 -1
  110. package/src/testing/index.ts +2 -0
  111. package/src/testing/service-tests.ts +873 -0
  112. package/src/types/core.types.ts +12 -1
  113. package/src/types/state.types.ts +12 -2
  114. package/src/utils/hash.test.ts +68 -0
  115. package/src/utils/hash.ts +26 -0
  116. package/src/utils.ts +1 -1
  117. package/src/wirings/ai-agent/agent-dynamic-workflow.ts +469 -0
  118. package/src/wirings/ai-agent/ai-agent-memory.ts +17 -7
  119. package/src/wirings/ai-agent/ai-agent-prepare.ts +194 -62
  120. package/src/wirings/ai-agent/ai-agent-runner.test.ts +3 -1
  121. package/src/wirings/ai-agent/ai-agent-runner.ts +553 -31
  122. package/src/wirings/ai-agent/ai-agent-stream.test.ts +209 -2
  123. package/src/wirings/ai-agent/ai-agent-stream.ts +195 -91
  124. package/src/wirings/ai-agent/ai-agent.types.ts +57 -3
  125. package/src/wirings/ai-agent/index.ts +3 -5
  126. package/src/wirings/channel/channel-handler.ts +41 -4
  127. package/src/wirings/channel/channel-middleware-runner.ts +1 -0
  128. package/src/wirings/channel/channel.types.ts +12 -7
  129. package/src/wirings/channel/index.ts +1 -0
  130. package/src/wirings/channel/local/local-channel-handler.ts +31 -3
  131. package/src/wirings/channel/local/local-channel-runner.ts +32 -8
  132. package/src/wirings/channel/pikku-abstract-channel-handler.test.ts +2 -0
  133. package/src/wirings/channel/pikku-abstract-channel-handler.ts +8 -1
  134. package/src/wirings/channel/serverless/serverless-channel-runner.ts +5 -2
  135. package/src/wirings/cli/cli-runner.ts +15 -2
  136. package/src/wirings/cli/cli.types.ts +1 -0
  137. package/src/wirings/gateway/gateway-runner.test.ts +474 -0
  138. package/src/wirings/gateway/gateway-runner.ts +411 -0
  139. package/src/wirings/gateway/gateway.types.ts +149 -0
  140. package/src/wirings/gateway/index.ts +13 -0
  141. package/src/wirings/http/http-routes.ts +0 -1
  142. package/src/wirings/http/http-runner.ts +38 -10
  143. package/src/wirings/http/http.types.ts +3 -12
  144. package/src/wirings/http/index.ts +3 -0
  145. package/src/wirings/http/pikku-fetch-http-request.ts +4 -0
  146. package/src/wirings/http/pikku-fetch-http-response.ts +4 -4
  147. package/src/wirings/http/web-request.test.ts +236 -0
  148. package/src/wirings/http/web-request.ts +104 -0
  149. package/src/wirings/mcp/mcp-endpoint-registry.ts +1 -1
  150. package/src/wirings/mcp/mcp-runner.ts +30 -12
  151. package/src/wirings/rpc/rpc-runner.ts +45 -24
  152. package/src/wirings/rpc/rpc-types.ts +6 -1
  153. package/src/wirings/rpc/wire-addon.ts +2 -1
  154. package/src/wirings/scheduler/scheduler-runner.ts +1 -0
  155. package/src/wirings/workflow/graph/graph-validation.test.ts +170 -0
  156. package/src/wirings/workflow/graph/graph-validation.ts +237 -0
  157. package/src/wirings/workflow/graph/index.ts +5 -0
  158. package/src/wirings/workflow/index.ts +1 -0
  159. package/src/wirings/workflow/pikku-workflow-service.ts +14 -3
  160. package/src/wirings/workflow/workflow.types.ts +9 -1
  161. package/tsconfig.tsbuildinfo +1 -1
  162. package/dist/wirings/ai-agent/ai-agent-assistant-ui.d.ts +0 -5
  163. package/dist/wirings/ai-agent/ai-agent-assistant-ui.js +0 -146
  164. package/src/wirings/ai-agent/ai-agent-assistant-ui.test.ts +0 -363
  165. package/src/wirings/ai-agent/ai-agent-assistant-ui.ts +0 -214
@@ -0,0 +1,127 @@
1
+ import type { CommonWireMeta, CorePikkuMiddleware, CorePikkuMiddlewareGroup } from '../../types/core.types.js';
2
+ import type { CorePikkuFunctionConfig, CorePermissionGroup, CorePikkuPermission } from '../../function/functions.types.js';
3
+ import type { PikkuHTTPRequest } from '../http/http.types.js';
4
+ /**
5
+ * Attachment in gateway messages (images, files, etc.)
6
+ */
7
+ export interface GatewayAttachment {
8
+ type: string;
9
+ url?: string;
10
+ data?: ArrayBuffer | Uint8Array;
11
+ mimeType?: string;
12
+ filename?: string;
13
+ }
14
+ /**
15
+ * Normalized inbound message from any platform
16
+ */
17
+ export interface GatewayInboundMessage {
18
+ /** Platform-specific sender identifier (phone number, Slack user ID, etc.) */
19
+ senderId: string;
20
+ /** Message text content */
21
+ text: string;
22
+ /** Original platform-specific payload */
23
+ raw: unknown;
24
+ /** Optional file/media attachments */
25
+ attachments?: GatewayAttachment[];
26
+ /** Optional platform-specific metadata */
27
+ metadata?: Record<string, unknown>;
28
+ }
29
+ /**
30
+ * Outbound message to send back via the platform
31
+ */
32
+ export interface GatewayOutboundMessage {
33
+ /** Plain text response */
34
+ text?: string;
35
+ /** Platform-specific rich content (Slack blocks, WhatsApp templates, etc.) */
36
+ richContent?: Record<string, unknown>;
37
+ /** Optional file/media attachments */
38
+ attachments?: GatewayAttachment[];
39
+ }
40
+ /**
41
+ * Result of webhook verification (e.g., WhatsApp GET challenge, Slack url_verification)
42
+ */
43
+ export type WebhookVerificationResult = {
44
+ verified: true;
45
+ response: unknown;
46
+ } | {
47
+ verified: false;
48
+ };
49
+ /**
50
+ * Gateway adapter interface — implemented by platform-specific addon packages.
51
+ *
52
+ * Two responsibilities:
53
+ * 1. Parse incoming platform-specific format into normalized GatewayInboundMessage
54
+ * 2. Send outgoing GatewayOutboundMessage via the platform's API
55
+ */
56
+ export interface GatewayAdapter {
57
+ /** Platform name (e.g., 'whatsapp', 'slack', 'telegram') */
58
+ name: string;
59
+ /** Parse platform-specific payload into normalized message. Return null to ignore (e.g., delivery receipts). */
60
+ parse(data: unknown): GatewayInboundMessage | null;
61
+ /** Send a message to a specific sender via the platform's API */
62
+ send(senderId: string, message: GatewayOutboundMessage): Promise<void>;
63
+ /** Initialize the adapter (connect to platform, start listening).
64
+ * Called by GatewayService.start() — the adapter should call onMessage for each incoming event. */
65
+ init(onMessage: (data: unknown) => Promise<void>): Promise<void>;
66
+ /** Tear down the adapter (disconnect, release resources). */
67
+ close(): Promise<void>;
68
+ /** Handle webhook verification challenges (only for webhook type).
69
+ * Receives the data (body or query params) and the Pikku HTTP request for additional inspection. */
70
+ verifyWebhook?(data: unknown, request?: PikkuHTTPRequest): WebhookVerificationResult | Promise<WebhookVerificationResult>;
71
+ }
72
+ /**
73
+ * The gateway wire object available on wire.gateway inside handler functions and middleware
74
+ */
75
+ export interface PikkuGateway {
76
+ /** Name of this gateway instance */
77
+ gatewayName: string;
78
+ /** Platform-specific sender identifier */
79
+ senderId: string;
80
+ /** Platform name from adapter.name */
81
+ platform: string;
82
+ /** Send a proactive message to the sender */
83
+ send(msg: GatewayOutboundMessage): Promise<void>;
84
+ }
85
+ /**
86
+ * Gateway transport type:
87
+ * - 'webhook': Platform POSTs to us (WhatsApp Cloud API, Slack Events API, Telegram webhooks)
88
+ * - 'websocket': Client connects via WebSocket (WebChat, browser widget)
89
+ * - 'listener': Standalone event loop, no route (Baileys, Signal CLI, Matrix sync)
90
+ */
91
+ export type GatewayTransportType = 'webhook' | 'websocket' | 'listener';
92
+ /**
93
+ * Core gateway configuration for wireGateway()
94
+ */
95
+ export type CoreGateway<PikkuFunctionConfig = CorePikkuFunctionConfig<any, any>, PikkuPermission extends CorePikkuPermission = CorePikkuPermission, PikkuMiddleware extends CorePikkuMiddleware = CorePikkuMiddleware> = {
96
+ /** Unique name for this gateway */
97
+ name: string;
98
+ /** Transport type */
99
+ type: GatewayTransportType;
100
+ /** HTTP route for webhook/websocket types */
101
+ route?: string;
102
+ /** The gateway adapter (parse inbound, send outbound) */
103
+ adapter: GatewayAdapter;
104
+ /** The handler function that processes parsed messages */
105
+ func: PikkuFunctionConfig;
106
+ /** Optional middleware chain (e.g., auth) */
107
+ middleware?: CorePikkuMiddlewareGroup<any, any>;
108
+ /** Optional permissions */
109
+ permissions?: CorePermissionGroup | PikkuPermission[];
110
+ /** Optional tags for categorization */
111
+ tags?: string[];
112
+ /** Whether authentication is required (default: true) */
113
+ auth?: boolean;
114
+ };
115
+ /**
116
+ * Metadata for a registered gateway, stored in state
117
+ */
118
+ export type GatewayMeta = CommonWireMeta & {
119
+ name: string;
120
+ type: GatewayTransportType;
121
+ route?: string;
122
+ gateway: true;
123
+ };
124
+ /**
125
+ * All gateway metadata keyed by name
126
+ */
127
+ export type GatewaysMeta = Record<string, GatewayMeta>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export { wireGateway, createListenerMessageHandler } from './gateway-runner.js';
2
+ export type { GatewayAdapter, GatewayAttachment, GatewayInboundMessage, GatewayOutboundMessage, GatewayMeta, GatewaysMeta, GatewayTransportType, CoreGateway, PikkuGateway, WebhookVerificationResult, } from './gateway.types.js';
@@ -0,0 +1 @@
1
+ export { wireGateway, createListenerMessageHandler } from './gateway-runner.js';
@@ -113,7 +113,6 @@ function registerRoute(route, groupConfig) {
113
113
  contentType: route.contentType,
114
114
  timeout: route.timeout,
115
115
  headers: route.headers,
116
- docs: route.docs,
117
116
  sse: route.sse,
118
117
  });
119
118
  }
@@ -136,4 +136,4 @@ export declare const pikkuFetch: <In, Out>(request: Request | PikkuHTTPRequest,
136
136
  * @param {RunHTTPWiringOptions} options - Options such as singleton services, session handling, and error configuration.
137
137
  * @returns {Promise<Out | void>} The output from the route handler or void if an error occurred.
138
138
  */
139
- export declare const fetchData: <In, Out>(request: Request | PikkuHTTPRequest, response: PikkuHTTPResponse, { skipUserSession, respondWith404, logWarningsForStatusCodes, coerceDataFromSchema, bubbleErrors, generateRequestId, }?: RunHTTPWiringOptions) => Promise<Out | void>;
139
+ export declare const fetchData: <In, Out>(request: Request | PikkuHTTPRequest, response: PikkuHTTPResponse, { skipUserSession, respondWith404, logWarningsForStatusCodes, coerceDataFromSchema, bubbleErrors, exposeErrors, generateRequestId, }?: RunHTTPWiringOptions) => Promise<Out | void>;
@@ -7,6 +7,7 @@ import { pikkuState } from '../../pikku-state.js';
7
7
  import { PikkuFetchHTTPResponse } from './pikku-fetch-http-response.js';
8
8
  import { PikkuFetchHTTPRequest } from './pikku-fetch-http-request.js';
9
9
  import { addFunction, runPikkuFunc } from '../../function/function-runner.js';
10
+ import { applyWebResponse } from './web-request.js';
10
11
  import { httpRouter } from './routers/http-router.js';
11
12
  import { validateSchema } from '../../schema.js';
12
13
  import { runMiddleware } from '../../middleware-runner.js';
@@ -240,6 +241,9 @@ const executeRoute = async (services, matchedRoute, http, options) => {
240
241
  send: (data) => {
241
242
  response.arrayBuffer(isSerializable(data) ? JSON.stringify(data) : data);
242
243
  },
244
+ sendBinary: (data) => {
245
+ response.arrayBuffer(data);
246
+ },
243
247
  close: () => {
244
248
  channel.state = 'closed';
245
249
  response.close?.();
@@ -268,9 +272,13 @@ const executeRoute = async (services, matchedRoute, http, options) => {
268
272
  tags: route.tags,
269
273
  wire,
270
274
  sessionService: userSession,
275
+ packageName: meta.packageName,
271
276
  });
272
277
  if (!matchedRoute.route.sse) {
273
- if (result === undefined || result === null) {
278
+ if (result instanceof Response) {
279
+ await applyWebResponse(http.response, result);
280
+ }
281
+ else if (result === undefined || result === null) {
274
282
  http?.response?.status(204);
275
283
  }
276
284
  else if (route.returnsJSON === false) {
@@ -338,7 +346,7 @@ export const pikkuFetch = async (request, params = {}) => {
338
346
  * @param {RunHTTPWiringOptions} options - Options such as singleton services, session handling, and error configuration.
339
347
  * @returns {Promise<Out | void>} The output from the route handler or void if an error occurred.
340
348
  */
341
- export const fetchData = async (request, response, { skipUserSession = false, respondWith404 = true, logWarningsForStatusCodes = [], coerceDataFromSchema = true, bubbleErrors = false, generateRequestId, } = {}) => {
349
+ export const fetchData = async (request, response, { skipUserSession = false, respondWith404 = true, logWarningsForStatusCodes = [], coerceDataFromSchema = true, bubbleErrors = false, exposeErrors = false, generateRequestId, } = {}) => {
342
350
  const singletonServices = getSingletonServices();
343
351
  const createWireServices = getCreateWireServices();
344
352
  let wireServices;
@@ -386,7 +394,24 @@ export const fetchData = async (request, response, { skipUserSession = false, re
386
394
  return result;
387
395
  }
388
396
  catch (e) {
389
- handleHTTPError(e, http, requestId, singletonServices.logger, logWarningsForStatusCodes, respondWith404, bubbleErrors);
397
+ if (matchedRoute?.route.sse) {
398
+ // For SSE routes, send error through the stream since the response is already in stream mode
399
+ singletonServices.logger.error(e instanceof Error ? e.message : e);
400
+ try {
401
+ response.arrayBuffer(JSON.stringify({
402
+ type: 'error',
403
+ errorText: e instanceof Error ? e.message : String(e),
404
+ }));
405
+ response.arrayBuffer('[DONE]');
406
+ }
407
+ catch (streamErr) {
408
+ singletonServices.logger.error(`SSE error while sending error payload: ${streamErr instanceof Error ? streamErr.message : String(streamErr)}`);
409
+ }
410
+ response.close?.();
411
+ }
412
+ else {
413
+ handleHTTPError(e, http, requestId, singletonServices.logger, logWarningsForStatusCodes, respondWith404, bubbleErrors, exposeErrors);
414
+ }
390
415
  }
391
416
  finally {
392
417
  // Clean up any session-specific services created during processing
@@ -1,6 +1,5 @@
1
1
  import type { SerializeOptions } from 'cookie';
2
2
  import type { StandardSchemaV1 } from '@standard-schema/spec';
3
- import type { PikkuError } from '../../errors/error-handler.js';
4
3
  import type { CorePikkuMiddleware, CommonWireMeta } from '../../types/core.types.js';
5
4
  import type { CorePikkuFunction, CorePikkuFunctionSessionless, CorePikkuPermission, CorePermissionGroup, CorePikkuFunctionConfig } from '../../function/functions.types.js';
6
5
  type ExtractHTTPWiringParams<S extends string> = S extends `${string}:${infer Param}/${infer Rest}` ? Param | ExtractHTTPWiringParams<`/${Rest}`> : S extends `${string}:${infer Param}` ? Param : never;
@@ -16,6 +15,7 @@ export type RunHTTPWiringOptions = Partial<{
16
15
  logWarningsForStatusCodes: number[];
17
16
  coerceDataFromSchema: boolean;
18
17
  bubbleErrors: boolean;
18
+ exposeErrors: boolean;
19
19
  generateRequestId: () => string;
20
20
  }>;
21
21
  /**
@@ -27,15 +27,6 @@ export type HTTPMethod = 'post' | 'get' | 'delete' | 'patch' | 'head' | 'put' |
27
27
  * Uses Standard Schema interface - works with Zod, Valibot, ArkType, Effect Schema, etc.
28
28
  */
29
29
  export type HTTPHeadersSchema = StandardSchemaV1<Record<string, string | string[] | undefined>>;
30
- /**
31
- * Documentation config for OpenAPI generation
32
- */
33
- export type HTTPRouteDocsConfig = {
34
- description?: string;
35
- response?: string;
36
- errors?: Array<typeof PikkuError>;
37
- tags?: string[];
38
- };
39
30
  /**
40
31
  * Common HTTP route configuration shared between wireHTTP and wireHTTPRoutes
41
32
  */
@@ -44,7 +35,6 @@ export type HTTPRouteBaseConfig = {
44
35
  timeout?: number;
45
36
  tags?: string[];
46
37
  headers?: HTTPHeadersSchema;
47
- docs?: HTTPRouteDocsConfig;
48
38
  };
49
39
  /**
50
40
  * Represents an API HTTP wiring without a function, including metadata such as content type, route, and timeout settings.
@@ -167,6 +157,7 @@ export interface PikkuHTTPRequest<In = unknown> {
167
157
  data(): Promise<In>;
168
158
  json(): Promise<unknown>;
169
159
  arrayBuffer(): Promise<ArrayBuffer>;
160
+ headers(): Record<string, string>;
170
161
  header(headerName: string): string | null;
171
162
  cookie(name?: string): string | null;
172
163
  params(): Partial<Record<string, string | string[]>>;
@@ -179,6 +170,7 @@ export interface PikkuHTTPResponse<Out = unknown> {
179
170
  header(name: string, value: string | string[]): this;
180
171
  arrayBuffer(data: ArrayBuffer | ArrayBufferView | Blob | string | FormData | URLSearchParams | ReadableStream): this;
181
172
  json(data: Out): this;
173
+ send?(data: string | ArrayBuffer | Buffer): this;
182
174
  redirect(location: string, status?: number): this;
183
175
  close?: () => void;
184
176
  setMode?: (mode: 'stream') => void;
@@ -3,4 +3,5 @@ export { PikkuFetchHTTPResponse } from './pikku-fetch-http-response.js';
3
3
  export { logRoutes } from './log-http-routes.js';
4
4
  export { fetch, fetchData, wireHTTP, addHTTPMiddleware, addHTTPPermission, } from './http-runner.js';
5
5
  export { wireHTTPRoutes, defineHTTPRoutes } from './http-routes.js';
6
- export type { AssertHTTPWiringParams, CoreHTTPFunctionWiring, HTTPMethod, HTTPRouteBaseConfig, HTTPWiringsMeta, PikkuHTTPRequest, PikkuHTTPResponse, PikkuQuery, RunHTTPWiringOptions, } from './http.types.js';
6
+ export { toWebRequest, applyWebResponse } from './web-request.js';
7
+ export type { AssertHTTPWiringParams, CoreHTTPFunctionWiring, HTTPMethod, HTTPRouteBaseConfig, HTTPRouteContract, HTTPRouteMap, HTTPWiringsMeta, PikkuHTTPRequest, PikkuHTTPResponse, PikkuQuery, RunHTTPWiringOptions, } from './http.types.js';
@@ -3,3 +3,4 @@ export { PikkuFetchHTTPResponse } from './pikku-fetch-http-response.js';
3
3
  export { logRoutes } from './log-http-routes.js';
4
4
  export { fetch, fetchData, wireHTTP, addHTTPMiddleware, addHTTPPermission, } from './http-runner.js';
5
5
  export { wireHTTPRoutes, defineHTTPRoutes } from './http-routes.js';
6
+ export { toWebRequest, applyWebResponse } from './web-request.js';
@@ -20,6 +20,7 @@ export declare class PikkuFetchHTTPRequest<In = unknown> implements PikkuHTTPReq
20
20
  * @returns A promise that resolves to the raw request body.
21
21
  */
22
22
  arrayBuffer(): Promise<ArrayBuffer>;
23
+ headers(): Record<string, string>;
23
24
  /**
24
25
  * Retrieves the value of a specific header.
25
26
  * @param headerName - The name of the header to retrieve.
@@ -35,6 +35,9 @@ export class PikkuFetchHTTPRequest {
35
35
  arrayBuffer() {
36
36
  return this.request.arrayBuffer();
37
37
  }
38
+ headers() {
39
+ return Object.fromEntries(this.request.headers.entries());
40
+ }
38
41
  /**
39
42
  * Retrieves the value of a specific header.
40
43
  * @param headerName - The name of the header to retrieve.
@@ -10,6 +10,7 @@ export declare class PikkuFetchHTTPResponse implements PikkuHTTPResponse {
10
10
  json(data: unknown): this;
11
11
  text(content: string): this;
12
12
  html(content: string): this;
13
+ send(data: any): this;
13
14
  redirect(location: string, status?: number): this;
14
15
  close(): this;
15
16
  toResponse(args?: Record<string, any>): Response;
@@ -71,10 +71,10 @@ export class PikkuFetchHTTPResponse {
71
71
  }
72
72
  return this;
73
73
  }
74
- // public body(body: BodyInit): this {
75
- // this.#body = body
76
- // return this
77
- // }
74
+ send(data) {
75
+ this.#body = data;
76
+ return this;
77
+ }
78
78
  redirect(location, status = 302) {
79
79
  if (!location.startsWith('/') &&
80
80
  !location.startsWith('https://') &&
@@ -0,0 +1,12 @@
1
+ import type { PikkuHTTPRequest } from './http.types.js';
2
+ import type { PikkuHTTPResponse } from './http.types.js';
3
+ /**
4
+ * Converts a PikkuHTTPRequest into a Web API Request.
5
+ * Useful for bridging Pikku routes to libraries that expect standard Web Request objects.
6
+ */
7
+ export declare function toWebRequest(req: PikkuHTTPRequest, baseUrl?: string): Request;
8
+ /**
9
+ * Applies a Web API Response to a PikkuHTTPResponse.
10
+ * Copies status, headers (including Set-Cookie), redirects, and body.
11
+ */
12
+ export declare function applyWebResponse(res: PikkuHTTPResponse, webResponse: Response): Promise<void>;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Converts a PikkuHTTPRequest into a Web API Request.
3
+ * Useful for bridging Pikku routes to libraries that expect standard Web Request objects.
4
+ */
5
+ export function toWebRequest(req, baseUrl) {
6
+ const url = new URL(req.path(), baseUrl ?? `http://${req.header('host') ?? 'localhost'}`);
7
+ const query = req.query();
8
+ for (const [key, value] of Object.entries(query)) {
9
+ if (value != null) {
10
+ url.searchParams.set(key, String(value));
11
+ }
12
+ }
13
+ const headers = new Headers(req.headers());
14
+ const method = req.method().toUpperCase();
15
+ const hasBody = !['GET', 'HEAD', 'OPTIONS'].includes(method);
16
+ if (!hasBody) {
17
+ return new Request(url, { method, headers });
18
+ }
19
+ return new Request(url, {
20
+ method,
21
+ headers,
22
+ body: new ReadableStream({
23
+ async start(controller) {
24
+ try {
25
+ const buffer = await req.arrayBuffer();
26
+ if (buffer.byteLength > 0) {
27
+ controller.enqueue(new Uint8Array(buffer));
28
+ }
29
+ else {
30
+ // arrayBuffer may be empty if body was pre-parsed (e.g., Express middleware)
31
+ const contentType = (headers.get('content-type') || '').toLowerCase();
32
+ const parsed = await req.json();
33
+ if (parsed &&
34
+ typeof parsed === 'object' &&
35
+ Object.keys(parsed).length > 0) {
36
+ let reconstructed;
37
+ if (contentType.includes('application/x-www-form-urlencoded')) {
38
+ reconstructed = new URLSearchParams(parsed).toString();
39
+ }
40
+ else {
41
+ reconstructed = JSON.stringify(parsed);
42
+ }
43
+ controller.enqueue(new TextEncoder().encode(reconstructed));
44
+ }
45
+ }
46
+ }
47
+ catch {
48
+ // Empty body
49
+ }
50
+ controller.close();
51
+ },
52
+ }),
53
+ // @ts-ignore - duplex is needed for streaming body in Node.js
54
+ duplex: 'half',
55
+ });
56
+ }
57
+ const SKIP_RESPONSE_HEADERS = new Set(['content-length', 'transfer-encoding']);
58
+ /**
59
+ * Applies a Web API Response to a PikkuHTTPResponse.
60
+ * Copies status, headers (including Set-Cookie), redirects, and body.
61
+ */
62
+ export async function applyWebResponse(res, webResponse) {
63
+ res.status(webResponse.status);
64
+ webResponse.headers.forEach((value, name) => {
65
+ const lower = name.toLowerCase();
66
+ if (SKIP_RESPONSE_HEADERS.has(lower)) {
67
+ return;
68
+ }
69
+ if (lower === 'location') {
70
+ res.redirect(value, webResponse.status);
71
+ }
72
+ else {
73
+ res.header(name, value);
74
+ }
75
+ });
76
+ const body = await webResponse.text();
77
+ if (body) {
78
+ if (res.send) {
79
+ res.send(body);
80
+ }
81
+ else {
82
+ res.arrayBuffer(body);
83
+ }
84
+ }
85
+ }
@@ -12,7 +12,7 @@ export class MCPEndpointRegistry {
12
12
  name: tool.name,
13
13
  title: tool.title,
14
14
  description: tool.description,
15
- inputSchema: tool.parameters,
15
+ inputSchema: tool.parameters ?? { type: 'object' },
16
16
  outputSchema: tool.returns,
17
17
  enabled: tool.enabled !== undefined ? tool.enabled : true,
18
18
  });
@@ -2,6 +2,7 @@ import { getErrorResponse } from '../../errors/error-handler.js';
2
2
  import { closeWireServices } from '../../utils.js';
3
3
  import { pikkuState, getSingletonServices, getCreateWireServices, } from '../../pikku-state.js';
4
4
  import { addFunction, runPikkuFunc } from '../../function/function-runner.js';
5
+ import { resolveNamespace } from '../rpc/rpc-runner.js';
5
6
  import { BadRequestError, NotFoundError, PikkuMissingMetaError, } from '../../errors/errors.js';
6
7
  import { PikkuSessionService, createMiddlewareSessionWireProps, } from '../../services/user-session-service.js';
7
8
  export class MCPError extends Error {
@@ -115,7 +116,17 @@ async function runMCPPikkuFunc(request, type, name, mcp, pikkuFuncId, { mcp: mcp
115
116
  else if (type === 'prompt') {
116
117
  meta = pikkuState(null, 'mcp', 'promptsMeta')[name];
117
118
  }
118
- let result = await runPikkuFunc('mcp', `${type}:${name}`, pikkuFuncId, {
119
+ // Resolve namespaced function IDs (e.g., 'swaggerPetstore:findPetsByStatus')
120
+ let resolvedFuncName = pikkuFuncId;
121
+ let resolvedPackageName = meta?.packageName ?? null;
122
+ if (pikkuFuncId.includes(':')) {
123
+ const resolved = resolveNamespace(pikkuFuncId);
124
+ if (resolved) {
125
+ resolvedFuncName = resolved.function;
126
+ resolvedPackageName = resolved.package;
127
+ }
128
+ }
129
+ let result = await runPikkuFunc('mcp', `${type}:${name}`, resolvedFuncName, {
119
130
  singletonServices,
120
131
  createWireServices,
121
132
  data: () => request.params,
@@ -126,6 +137,7 @@ async function runMCPPikkuFunc(request, type, name, mcp, pikkuFuncId, { mcp: mcp
126
137
  tags: mcp?.tags,
127
138
  wire,
128
139
  sessionService: mcpSessionService,
140
+ packageName: resolvedPackageName,
129
141
  });
130
142
  if (type === 'tool' && meta?.outputSchema !== 'MCPToolResponse') {
131
143
  result = [{ type: 'text', text: JSON.stringify(result) }];
@@ -2,13 +2,18 @@ import type { CoreServices, PikkuWire } from '../../types/core.types.js';
2
2
  import type { SessionService } from '../../services/user-session-service.js';
3
3
  import type { CoreUserSession } from '../../types/core.types.js';
4
4
  import { PikkuError } from '../../errors/error-handler.js';
5
- import type { PikkuRPC } from './rpc-types.js';
5
+ import type { PikkuRPC, ResolvedFunction } from './rpc-types.js';
6
6
  export declare class RPCNotFoundError extends PikkuError {
7
7
  readonly rpcName: string;
8
8
  constructor(rpcName: string);
9
9
  }
10
10
  import type { AIAgentInput } from '../ai-agent/ai-agent.types.js';
11
11
  import type { StreamAIAgentOptions } from '../ai-agent/ai-agent-prepare.js';
12
+ /**
13
+ * Resolve a namespaced function reference to package and function names
14
+ * Uses pikkuState to look up the namespace -> package mapping
15
+ */
16
+ export declare const resolveNamespace: (namespacedFunction: string) => ResolvedFunction | null;
12
17
  export declare class ContextAwareRPCService {
13
18
  private services;
14
19
  private wire;
@@ -39,6 +44,14 @@ export declare class ContextAwareRPCService {
39
44
  }>;
40
45
  get agent(): {
41
46
  run: (agentName: string, input: AIAgentInput) => Promise<{
47
+ status?: "suspended" | undefined;
48
+ pendingApprovals?: {
49
+ toolCallId: string;
50
+ toolName: string;
51
+ args: unknown;
52
+ reason?: string;
53
+ runId: string;
54
+ }[] | undefined;
42
55
  runId: string;
43
56
  result: {};
44
57
  usage: {
@@ -50,7 +63,9 @@ export declare class ContextAwareRPCService {
50
63
  message: string;
51
64
  threadId: string;
52
65
  resourceId: string;
53
- } | Record<string, unknown>, options?: StreamAIAgentOptions) => Promise<void>;
66
+ model?: string;
67
+ temperature?: number;
68
+ }, options?: StreamAIAgentOptions) => Promise<void>;
54
69
  resume: (runId: string, input: {
55
70
  toolCallId: string;
56
71
  approved: boolean;
@@ -59,11 +74,20 @@ export declare class ContextAwareRPCService {
59
74
  toolCallId: string;
60
75
  approved: boolean;
61
76
  }[], expectedAgentName?: string) => Promise<{
62
- status: "resumed" | "suspended";
77
+ status?: "suspended" | undefined;
78
+ pendingApprovals?: {
79
+ toolCallId: string;
80
+ toolName: string;
81
+ args: unknown;
82
+ reason?: string;
83
+ runId: string;
84
+ }[] | undefined;
63
85
  runId: string;
64
- approved: string[];
65
- rejected: string[];
66
- remainingApprovals: number;
86
+ result: {};
87
+ usage: {
88
+ inputTokens: number;
89
+ outputTokens: number;
90
+ };
67
91
  }>;
68
92
  };
69
93
  remote<In = any, Out = any>(funcName: string, data: In): Promise<Out>;