@agentuity/server 0.0.5 → 0.0.6

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 (82) hide show
  1. package/AGENTS.md +29 -96
  2. package/README.md +31 -196
  3. package/dist/config.d.ts +11 -0
  4. package/dist/config.d.ts.map +1 -0
  5. package/dist/config.js +13 -0
  6. package/dist/config.js.map +1 -0
  7. package/dist/index.d.ts +4 -5
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +4 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/server.d.ts +22 -0
  12. package/dist/server.d.ts.map +1 -0
  13. package/dist/server.js +107 -0
  14. package/dist/server.js.map +1 -0
  15. package/package.json +11 -32
  16. package/dist/_config.d.ts +0 -61
  17. package/dist/_config.d.ts.map +0 -1
  18. package/dist/_context.d.ts +0 -33
  19. package/dist/_context.d.ts.map +0 -1
  20. package/dist/_idle.d.ts +0 -7
  21. package/dist/_idle.d.ts.map +0 -1
  22. package/dist/_server.d.ts +0 -17
  23. package/dist/_server.d.ts.map +0 -1
  24. package/dist/_services.d.ts +0 -2
  25. package/dist/_services.d.ts.map +0 -1
  26. package/dist/_util.d.ts +0 -16
  27. package/dist/_util.d.ts.map +0 -1
  28. package/dist/_waituntil.d.ts +0 -20
  29. package/dist/_waituntil.d.ts.map +0 -1
  30. package/dist/agent.d.ts +0 -88
  31. package/dist/agent.d.ts.map +0 -1
  32. package/dist/app.d.ts +0 -24
  33. package/dist/app.d.ts.map +0 -1
  34. package/dist/logger/console.d.ts +0 -50
  35. package/dist/logger/console.d.ts.map +0 -1
  36. package/dist/logger/index.d.ts +0 -4
  37. package/dist/logger/index.d.ts.map +0 -1
  38. package/dist/logger/internal.d.ts +0 -79
  39. package/dist/logger/internal.d.ts.map +0 -1
  40. package/dist/logger/logger.d.ts +0 -41
  41. package/dist/logger/logger.d.ts.map +0 -1
  42. package/dist/logger/user.d.ts +0 -8
  43. package/dist/logger/user.d.ts.map +0 -1
  44. package/dist/logger/util.d.ts +0 -11
  45. package/dist/logger/util.d.ts.map +0 -1
  46. package/dist/otel/config.d.ts +0 -17
  47. package/dist/otel/config.d.ts.map +0 -1
  48. package/dist/otel/console.d.ts +0 -26
  49. package/dist/otel/console.d.ts.map +0 -1
  50. package/dist/otel/fetch.d.ts +0 -12
  51. package/dist/otel/fetch.d.ts.map +0 -1
  52. package/dist/otel/http.d.ts +0 -16
  53. package/dist/otel/http.d.ts.map +0 -1
  54. package/dist/otel/logger.d.ts +0 -36
  55. package/dist/otel/logger.d.ts.map +0 -1
  56. package/dist/otel/otel.d.ts +0 -58
  57. package/dist/otel/otel.d.ts.map +0 -1
  58. package/dist/router.d.ts +0 -37
  59. package/dist/router.d.ts.map +0 -1
  60. package/src/_config.ts +0 -101
  61. package/src/_context.ts +0 -88
  62. package/src/_idle.ts +0 -26
  63. package/src/_server.ts +0 -278
  64. package/src/_services.ts +0 -175
  65. package/src/_util.ts +0 -63
  66. package/src/_waituntil.ts +0 -246
  67. package/src/agent.ts +0 -287
  68. package/src/app.ts +0 -31
  69. package/src/index.ts +0 -5
  70. package/src/logger/console.ts +0 -111
  71. package/src/logger/index.ts +0 -3
  72. package/src/logger/internal.ts +0 -165
  73. package/src/logger/logger.ts +0 -44
  74. package/src/logger/user.ts +0 -11
  75. package/src/logger/util.ts +0 -80
  76. package/src/otel/config.ts +0 -81
  77. package/src/otel/console.ts +0 -56
  78. package/src/otel/fetch.ts +0 -103
  79. package/src/otel/http.ts +0 -51
  80. package/src/otel/logger.ts +0 -238
  81. package/src/otel/otel.ts +0 -317
  82. package/src/router.ts +0 -303
package/AGENTS.md CHANGED
@@ -2,123 +2,56 @@
2
2
 
3
3
  ## Package Overview
4
4
 
5
- Server runtime for building Agentuity applications. Built on Hono framework and optimized for Bun runtime with OpenTelemetry observability.
5
+ Runtime-agnostic server utilities for Node.js and Bun applications. This package provides common server-side utilities that work across both runtimes without using runtime-specific APIs.
6
6
 
7
7
  ## Commands
8
8
 
9
- - **Build**: `bun run build` (compiles for Bun target)
9
+ - **Build**: `bun run build` (compiles TypeScript with tsc)
10
10
  - **Typecheck**: `bun run typecheck` (runs TypeScript type checking)
11
- - **Clean**: `bun run clean` (removes dist/)
11
+ - **Clean**: `rm -rf dist` (removes build artifacts)
12
12
 
13
13
  ## Architecture
14
14
 
15
- - **Runtime**: Bun server runtime
16
- - **Framework**: Hono (lightweight web framework)
17
- - **Build target**: Bun runtime
18
- - **Dependencies**: `@agentuity/core`, Hono, OpenTelemetry
19
- - **Observability**: Built-in OpenTelemetry for logs, traces, and metrics
15
+ - **Runtime**: Node.js and Bun compatible (no runtime-specific code)
16
+ - **Build target**: ESNext with TypeScript declaration files
17
+ - **Exports**: All public APIs exported from `src/index.ts`
18
+ - **Dependencies**: Only @agentuity/core and standard Node.js types
20
19
 
21
20
  ## Structure
22
21
 
23
- ```
22
+ ```text
24
23
  src/
25
- ├── index.ts # Main exports
26
- ├── app.ts # createApp() function
27
- ├── agent.ts # Agent types and defineAgent()
28
- ├── router.ts # createRouter() with extended methods
29
- ├── logger.ts # Logging utilities
30
- ├── _server.ts # Internal server creation
31
- ├── _context.ts # Internal context management
32
- └── _util.ts # Internal utilities
24
+ ├── index.ts # Main entry point, exports all modules
25
+ ├── config.ts # Service URL configuration: ServiceUrls, getServiceUrls
26
+ └── server.ts # Server fetch adapter: createServerFetchAdapter
33
27
  ```
34
28
 
35
29
  ## Code Style
36
30
 
37
- - **Hono patterns** - Follow Hono's context-based API design
38
- - **Type safety** - Extensive use of TypeScript generics
39
- - **Middleware pattern** - Support Hono middleware
40
- - **Async handlers** - All handlers can be async
41
- - **OpenTelemetry** - Use tracer/logger from context
31
+ - **Runtime agnostic** - No Bun-specific or Node-specific APIs
32
+ - **TypeScript-first** - All code is TypeScript
33
+ - **Interface-based** - Prefer interfaces for public APIs
34
+ - **Server-side only** - Not browser compatible
35
+ - **Minimal dependencies** - Keep dependencies lean
42
36
 
43
37
  ## Important Conventions
44
38
 
45
- - **Agent context** - Every agent handler receives `AgentContext` as first parameter
46
- - **Schema validation** - Support StandardSchemaV1 (works with Zod, Valibot, etc.)
47
- - **Streaming support** - Agents can return ReadableStream for streaming responses
48
- - **WebSocket support** - Use `router.websocket()` for WebSocket routes
49
- - **SSE support** - Use `router.sse()` for Server-Sent Events
50
- - **Session tracking** - Each request gets unique sessionId
51
- - **Storage abstractions** - Provide kv, objectstore, stream, vector interfaces
52
-
53
- ## Agent Definition Pattern
54
-
55
- ```typescript
56
- import { defineAgent } from '@agentuity/server';
57
- import { z } from 'zod';
58
-
59
- export default defineAgent({
60
- metadata: {
61
- id: 'unique-id',
62
- identifier: 'folder-name',
63
- name: 'Human Name',
64
- description: 'What it does',
65
- filename: __filename,
66
- version: 'hash-or-version'
67
- },
68
- inputSchema: z.object({ /* ... */ }),
69
- outputSchema: z.object({ /* ... */ }),
70
- handler: async (ctx, input) => {
71
- // ctx.logger, ctx.tracer, ctx.kv, etc.
72
- return output;
73
- }
74
- });
75
- ```
76
-
77
- ## Router Extensions
78
-
79
- The `createRouter()` function returns an extended Hono instance with:
80
-
81
- - **Standard HTTP methods**: `get`, `post`, `put`, `delete`, `patch`
82
- - **Streaming**: `stream(path, handler)` - Returns ReadableStream
83
- - **WebSocket**: `websocket(path, handler)` - WebSocket connections
84
- - **SSE**: `sse(path, handler)` - Server-Sent Events
85
-
86
- ## AgentContext API
87
-
88
- Every agent handler receives:
89
-
90
- ```typescript
91
- interface AgentContext {
92
- logger: Logger; // Structured logger
93
- tracer: Tracer; // OpenTelemetry tracer
94
- sessionId: string; // Unique session ID
95
- kv: KeyValueStorage; // Key-value storage
96
- objectstore: ObjectStorage; // Object storage
97
- stream: StreamStorage; // Stream storage
98
- vector: VectorStorage; // Vector storage
99
- agent: AgentRegistry; // Access other agents
100
- waitUntil: (promise) => void; // Background tasks
101
- }
102
- ```
103
-
104
- ## Observability
105
-
106
- - **Logging**: Use `ctx.logger.info/warn/error()` not console.log
107
- - **Tracing**: Create spans with `ctx.tracer.startSpan()`
108
- - **Metrics**: Access via `c.var.meter` in Hono context
109
- - **Environment**: Metrics/traces sent to OTLP endpoints
39
+ - **No runtime-specific code** - Must work in both Node.js and Bun
40
+ - **No browser APIs** - Server-side only
41
+ - **Shared with runtime** - Common utilities used by @agentuity/runtime
42
+ - **Breaking changes** - Coordinate with @agentuity/runtime package
43
+ - **Standard patterns** - Follow Node.js/Bun common practices
110
44
 
111
45
  ## Testing
112
46
 
113
- - Use Bun's test runner: `bun test`
114
- - Mock storage interfaces (kv, objectstore, etc.)
115
- - Test agent handlers with mock context
116
- - Use Hono's testing utilities for routes
47
+ - Use Bun's built-in test runner: `bun test`
48
+ - Test with both Node.js and Bun when possible
49
+ - Avoid runtime-specific test utilities
117
50
 
118
51
  ## Publishing Checklist
119
52
 
120
- 1. Run `bun run build` to compile for Bun runtime
121
- 2. Verify OpenTelemetry dependencies are correct versions
122
- 3. Test with real Hono server
123
- 4. Must publish **after** @agentuity/core
124
- 5. Ensure React is only in devDependencies (for type checking web components)
53
+ 1. Run `bun run build` to compile
54
+ 2. Verify `dist/` contains `.js` and `.d.ts` files
55
+ 3. Ensure no runtime-specific APIs are used
56
+ 4. Test with both Node.js and Bun if possible
57
+ 5. Must be published **after** @agentuity/core
package/README.md CHANGED
@@ -1,6 +1,12 @@
1
1
  # @agentuity/server
2
2
 
3
- Server runtime for building Agentuity applications with Bun and Hono.
3
+ Server-side utilities for Node.js and Bun applications. This package is runtime-agnostic and contains common utilities that work across both runtimes.
4
+
5
+ ## Features
6
+
7
+ - **Runtime Agnostic**: Works with both Node.js and Bun
8
+ - **Server-side focused**: Not browser compatible
9
+ - **Shared utilities**: Common APIs used by @agentuity/runtime and standalone apps
4
10
 
5
11
  ## Installation
6
12
 
@@ -8,211 +14,40 @@ Server runtime for building Agentuity applications with Bun and Hono.
8
14
  bun add @agentuity/server
9
15
  ```
10
16
 
11
- ## Overview
12
-
13
- `@agentuity/server` provides the server-side runtime for Agentuity applications. Built on [Hono](https://hono.dev/) and optimized for [Bun](https://bun.sh/), it enables you to create type-safe agents with automatic routing, validation, and observability.
14
-
15
- ## Quick Start
16
-
17
- ### Creating an Application
18
-
19
- ```typescript
20
- import { createApp } from '@agentuity/server';
21
-
22
- const { app, server, logger } = createApp();
23
-
24
- // Start the server
25
- server.listen(3000);
26
- logger.info('Server running on http://localhost:3000');
27
- ```
28
-
29
- ### Defining an Agent
30
-
31
- ```typescript
32
- import { type AgentContext, createAgent } from '@agentuity/server';
33
- import { z } from 'zod';
34
-
35
- const agent = createAgent({
36
- schema: {
37
- input: z.object({
38
- message: z.string()
39
- }),
40
- output: z.object({
41
- response: z.string()
42
- }),
43
- },
44
- handler: async (ctx: AgentContext, input) => {
45
- ctx.logger.info('Processing message:', input.message);
46
- return { response: `You said: ${input.message}` };
47
- },
48
- });
49
-
50
- export default agent;
51
- ```
52
-
53
- ### Creating Custom Routes
54
-
55
- ```typescript
56
- import { createRouter } from '@agentuity/server';
57
-
58
- const router = createRouter();
59
-
60
- router.get('/hello', (c) => {
61
- return c.json({ message: 'Hello, world!' });
62
- });
63
-
64
- router.post('/data', async (c) => {
65
- const body = await c.req.json();
66
- return c.json({ received: body });
67
- });
68
-
69
- export default router;
70
- ```
71
-
72
- ### Streaming Responses
73
-
74
- ```typescript
75
- router.stream('/events', async (c) => {
76
- return new ReadableStream({
77
- start(controller) {
78
- controller.enqueue('Event 1\n');
79
- controller.enqueue('Event 2\n');
80
- controller.close();
81
- }
82
- });
83
- });
84
- ```
85
-
86
- ### WebSocket Support
87
-
88
- ```typescript
89
- router.websocket('/chat', (c) => (ws) => {
90
- ws.onOpen(() => {
91
- console.log('Client connected');
92
- });
93
-
94
- ws.onMessage((event) => {
95
- const data = JSON.parse(event.data);
96
- ws.send(JSON.stringify({ echo: data }));
97
- });
98
-
99
- ws.onClose(() => {
100
- console.log('Client disconnected');
101
- });
102
- });
103
- ```
104
-
105
- ### Server-Sent Events (SSE)
17
+ ## Usage
106
18
 
107
19
  ```typescript
108
- router.sse('/updates', (c) => async (stream) => {
109
- for (let i = 0; i < 10; i++) {
110
- await stream.writeSSE({
111
- data: JSON.stringify({ count: i }),
112
- event: 'update'
113
- });
114
- await stream.sleep(1000);
115
- }
116
- });
117
- ```
118
-
119
- ## API Reference
120
-
121
- ### createApp(config?)
122
-
123
- Creates a new Agentuity application instance.
124
-
125
- **Returns:**
126
- - `app` - Hono application instance
127
- - `server` - Server instance with `listen()` method
128
- - `logger` - Structured logger
129
-
130
- ### createAgent(config)
131
-
132
- Creates a type-safe agent with input/output validation.
20
+ import { getServiceUrls, type ServiceUrls } from '@agentuity/server';
133
21
 
134
- **Config:**
135
- - `schema.input?` - Schema for input validation (Zod, Valibot, etc.)
136
- - `schema.output?` - Schema for output validation
137
- - `handler` - Agent handler function `(ctx: AgentContext, input) => output`
22
+ // Get service URLs from environment variables
23
+ const urls: ServiceUrls = getServiceUrls();
138
24
 
139
- ### createRouter()
140
-
141
- Creates a new router for defining custom API routes.
142
-
143
- **Methods:**
144
- - `get/post/put/delete/patch` - HTTP method handlers
145
- - `stream(path, handler)` - Streaming response handler
146
- - `websocket(path, handler)` - WebSocket handler
147
- - `sse(path, handler)` - Server-Sent Events handler
148
-
149
- ### AgentContext
150
-
151
- Context object available in agent handlers:
152
-
153
- ```typescript
154
- interface AgentContext {
155
- logger: Logger; // Structured logger
156
- tracer: Tracer; // OpenTelemetry tracer
157
- sessionId: string; // Unique session ID
158
- kv: KeyValueStorage; // Key-value storage
159
- objectstore: ObjectStorage; // Object storage
160
- stream: StreamStorage; // Stream storage
161
- vector: VectorStorage; // Vector storage
162
- agent: AgentRegistry; // Access to other agents
163
- waitUntil: (promise) => void; // Defer cleanup tasks
164
- }
25
+ console.log(urls.keyvalue); // https://agentuity.ai (or AGENTUITY_KEYVALUE_URL)
26
+ console.log(urls.objectstore); // https://agentuity.ai (or AGENTUITY_OBJECTSTORE_URL)
27
+ console.log(urls.stream); // https://streams.agentuity.cloud (or AGENTUITY_STREAM_URL)
28
+ console.log(urls.vector); // https://agentuity.ai (or AGENTUITY_VECTOR_URL)
165
29
  ```
166
30
 
167
- ## Storage Services
168
-
169
- Agentuity provides built-in storage abstractions:
170
-
171
- - **KeyValueStorage** - Simple key-value storage
172
- - **ObjectStorage** - Object/blob storage
173
- - **StreamStorage** - Streaming data storage
174
- - **VectorStorage** - Vector embeddings storage
175
-
176
- Access these via the agent context:
31
+ ### Server Fetch Adapter
177
32
 
178
33
  ```typescript
179
- const agent = createAgent({
180
- schema: {
181
- output: z.object({ value: z.string().optional() }),
182
- },
183
- handler: async (ctx, input) => {
184
- await ctx.kv.set('key', 'value');
185
- const value = await ctx.kv.get('key');
186
- return { value };
187
- },
188
- });
189
- ```
190
-
191
- ## Observability
34
+ import { createServerFetchAdapter } from '@agentuity/server';
192
35
 
193
- Built-in OpenTelemetry support for logging, tracing, and metrics:
194
-
195
- ```typescript
196
- const agent = createAgent({
197
- schema: {
198
- output: z.object({ success: z.boolean() }),
199
- },
200
- handler: async (ctx, input) => {
201
- ctx.logger.info('Processing request');
202
-
203
- const span = ctx.tracer.startSpan('custom-operation');
204
- // ... do work ...
205
- span.end();
206
-
207
- return { success: true };
208
- },
36
+ const adapter = createServerFetchAdapter({
37
+ headers: {
38
+ Authorization: 'Bearer YOUR_TOKEN',
39
+ 'User-Agent': 'My App/1.0',
40
+ },
41
+ onBefore: async (url, options, callback) => {
42
+ console.log('Making request to:', url);
43
+ await callback();
44
+ },
45
+ onAfter: async (url, options, response, err) => {
46
+ console.log('Request completed:', url, response.response.status);
47
+ },
209
48
  });
210
49
  ```
211
50
 
212
- ## TypeScript
213
-
214
- Fully typed with TypeScript. Input and output types are automatically inferred from your schemas.
215
-
216
- ## License
51
+ ## Development
217
52
 
218
- MIT
53
+ See [AGENTS.md](./AGENTS.md) for development guidelines.
@@ -0,0 +1,11 @@
1
+ export interface ServiceUrls {
2
+ keyvalue: string;
3
+ objectstore: string;
4
+ stream: string;
5
+ vector: string;
6
+ }
7
+ /**
8
+ * Get service URLs from environment variables with fallback defaults
9
+ */
10
+ export declare function getServiceUrls(): ServiceUrls;
11
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,wBAAgB,cAAc,IAAI,WAAW,CAS5C"}
package/dist/config.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Get service URLs from environment variables with fallback defaults
3
+ */
4
+ export function getServiceUrls() {
5
+ const transportUrl = process.env.AGENTUITY_TRANSPORT_URL || 'https://agentuity.ai';
6
+ return {
7
+ keyvalue: process.env.AGENTUITY_KEYVALUE_URL || transportUrl,
8
+ objectstore: process.env.AGENTUITY_OBJECTSTORE_URL || transportUrl,
9
+ stream: process.env.AGENTUITY_STREAM_URL || 'https://streams.agentuity.cloud',
10
+ vector: process.env.AGENTUITY_VECTOR_URL || transportUrl,
11
+ };
12
+ }
13
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAOA;;GAEG;AACH,MAAM,UAAU,cAAc;IAC7B,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,uBAAuB,IAAI,sBAAsB,CAAC;IAEnF,OAAO;QACN,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,sBAAsB,IAAI,YAAY;QAC5D,WAAW,EAAE,OAAO,CAAC,GAAG,CAAC,yBAAyB,IAAI,YAAY;QAClE,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,iCAAiC;QAC7E,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,YAAY;KACxD,CAAC;AACH,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- export * from './agent';
2
- export * from './app';
3
- export * from './router';
4
- export type { Logger } from './logger';
5
- export { getApp } from './_server';
1
+ export * from './config';
2
+ export * from './server';
3
+ export type { FetchAdapter, FetchRequest, FetchResponse, FetchSuccessResponse, FetchErrorResponse, Body, ServiceException, } from '@agentuity/core';
4
+ export { buildUrl, toServiceException, toPayload, fromResponse } from '@agentuity/core';
6
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,OAAO,CAAC;AACtB,cAAc,UAAU,CAAC;AACzB,YAAY,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,YAAY,EACX,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,oBAAoB,EACpB,kBAAkB,EAClB,IAAI,EACJ,gBAAgB,GAChB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './config';
2
+ export * from './server';
3
+ export { buildUrl, toServiceException, toPayload, fromResponse } from '@agentuity/core';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AAUzB,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,22 @@
1
+ import type { FetchRequest, FetchResponse, FetchAdapter } from '@agentuity/core';
2
+ import { ServiceException } from '@agentuity/core';
3
+ interface ServiceAdapterConfig {
4
+ headers: Record<string, string>;
5
+ onBefore?: (url: string, options: FetchRequest, invoke: () => Promise<void>) => Promise<void>;
6
+ onAfter?: <T>(url: string, options: FetchRequest, response: FetchResponse<T>, err?: ServiceException) => Promise<void>;
7
+ }
8
+ declare class ServerFetchAdapter implements FetchAdapter {
9
+ #private;
10
+ constructor(config: ServiceAdapterConfig);
11
+ private _invoke;
12
+ invoke<T>(url: string, options?: FetchRequest): Promise<FetchResponse<T>>;
13
+ }
14
+ /**
15
+ * Create a Server Side Fetch Adapter to allow the server to add headers and track outgoing requests
16
+ *
17
+ * @param config the service config
18
+ * @returns
19
+ */
20
+ export declare function createServerFetchAdapter(config: ServiceAdapterConfig): ServerFetchAdapter;
21
+ export {};
22
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,YAAY,EAEZ,aAAa,EACb,YAAY,EACZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,gBAAgB,EAAoC,MAAM,iBAAiB,CAAC;AAErF,UAAU,oBAAoB;IAC7B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9F,OAAO,CAAC,EAAE,CAAC,CAAC,EACX,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,YAAY,EACrB,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC,EAC1B,GAAG,CAAC,EAAE,gBAAgB,KAClB,OAAO,CAAC,IAAI,CAAC,CAAC;CACnB;AAED,cAAM,kBAAmB,YAAW,YAAY;;gBAGnC,MAAM,EAAE,oBAAoB;YAG1B,OAAO;IA2Df,MAAM,CAAC,CAAC,EACb,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,YAAiC,GACxC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;CAmC5B;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,oBAAoB,sBAEpE"}
package/dist/server.js ADDED
@@ -0,0 +1,107 @@
1
+ import { toServiceException, fromResponse } from '@agentuity/core';
2
+ class ServerFetchAdapter {
3
+ #config;
4
+ constructor(config) {
5
+ this.#config = config;
6
+ }
7
+ async _invoke(url, options) {
8
+ const headers = {
9
+ ...options.headers,
10
+ ...this.#config.headers,
11
+ };
12
+ if (options.contentType) {
13
+ headers['Content-Type'] = options.contentType;
14
+ }
15
+ else if (typeof options.body === 'string' ||
16
+ options.body instanceof Uint8Array ||
17
+ options.body instanceof ArrayBuffer) {
18
+ headers['Content-Type'] = 'application/octet-stream';
19
+ }
20
+ const res = await fetch(url, {
21
+ method: options.method ?? 'POST',
22
+ body: options.body,
23
+ headers,
24
+ signal: options.signal,
25
+ ...(options.duplex ? { duplex: options.duplex } : {}),
26
+ });
27
+ if (res.ok) {
28
+ switch (res.status) {
29
+ case 100:
30
+ case 101:
31
+ case 102:
32
+ case 204:
33
+ case 304:
34
+ return {
35
+ ok: true,
36
+ data: undefined,
37
+ response: res,
38
+ };
39
+ default:
40
+ break;
41
+ }
42
+ if (options?.binary) {
43
+ return {
44
+ ok: true,
45
+ data: undefined,
46
+ response: res,
47
+ };
48
+ }
49
+ const data = await fromResponse(res);
50
+ return {
51
+ ok: true,
52
+ data,
53
+ response: res,
54
+ };
55
+ }
56
+ if (res.status === 404) {
57
+ return {
58
+ ok: false,
59
+ response: res,
60
+ };
61
+ }
62
+ const err = await toServiceException(res);
63
+ throw err;
64
+ }
65
+ async invoke(url, options = { method: 'POST' }) {
66
+ if (this.#config.onBefore) {
67
+ let result = undefined;
68
+ let err = undefined;
69
+ await this.#config.onBefore(url, options, async () => {
70
+ try {
71
+ result = await this._invoke(url, options);
72
+ if (this.#config.onAfter) {
73
+ await this.#config.onAfter(url, options, result);
74
+ }
75
+ }
76
+ catch (ex) {
77
+ err = ex;
78
+ if (this.#config.onAfter) {
79
+ await this.#config.onAfter(url, options, {
80
+ ok: false,
81
+ response: new Response(err.message ?? String(err), {
82
+ status: err.statusCode ?? 500,
83
+ }),
84
+ }, err);
85
+ }
86
+ }
87
+ });
88
+ if (err) {
89
+ throw err;
90
+ }
91
+ return result;
92
+ }
93
+ else {
94
+ return await this._invoke(url, options);
95
+ }
96
+ }
97
+ }
98
+ /**
99
+ * Create a Server Side Fetch Adapter to allow the server to add headers and track outgoing requests
100
+ *
101
+ * @param config the service config
102
+ * @returns
103
+ */
104
+ export function createServerFetchAdapter(config) {
105
+ return new ServerFetchAdapter(config);
106
+ }
107
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAMA,OAAO,EAAoB,kBAAkB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAarF,MAAM,kBAAkB;IACvB,OAAO,CAAuB;IAE9B,YAAY,MAA4B;QACvC,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACvB,CAAC;IACO,KAAK,CAAC,OAAO,CAAI,GAAW,EAAE,OAAqB;QAC1D,MAAM,OAAO,GAAG;YACf,GAAG,OAAO,CAAC,OAAO;YAClB,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO;SACvB,CAAC;QACF,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;YACzB,OAAO,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC;QAC/C,CAAC;aAAM,IACN,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ;YAChC,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