services-as-software 0.1.0 → 2.0.1

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 (78) hide show
  1. package/.turbo/turbo-build.log +5 -0
  2. package/CHANGELOG.md +10 -0
  3. package/README.md +235 -225
  4. package/dist/client.d.ts +25 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/client.js +103 -0
  7. package/dist/client.js.map +1 -0
  8. package/dist/endpoint.d.ts +102 -0
  9. package/dist/endpoint.d.ts.map +1 -0
  10. package/dist/endpoint.js +96 -0
  11. package/dist/endpoint.js.map +1 -0
  12. package/dist/entities/billing.d.ts +60 -0
  13. package/dist/entities/billing.d.ts.map +1 -0
  14. package/dist/entities/billing.js +954 -0
  15. package/dist/entities/billing.js.map +1 -0
  16. package/dist/entities/customers.d.ts +45 -0
  17. package/dist/entities/customers.d.ts.map +1 -0
  18. package/dist/entities/customers.js +679 -0
  19. package/dist/entities/customers.js.map +1 -0
  20. package/dist/entities/delivery.d.ts +59 -0
  21. package/dist/entities/delivery.d.ts.map +1 -0
  22. package/dist/entities/delivery.js +890 -0
  23. package/dist/entities/delivery.js.map +1 -0
  24. package/dist/entities/index.d.ts +114 -0
  25. package/dist/entities/index.d.ts.map +1 -0
  26. package/dist/entities/index.js +89 -0
  27. package/dist/entities/index.js.map +1 -0
  28. package/dist/entities/operations.d.ts +59 -0
  29. package/dist/entities/operations.d.ts.map +1 -0
  30. package/dist/entities/operations.js +1010 -0
  31. package/dist/entities/operations.js.map +1 -0
  32. package/dist/entities/orchestration.d.ts +52 -0
  33. package/dist/entities/orchestration.d.ts.map +1 -0
  34. package/dist/entities/orchestration.js +883 -0
  35. package/dist/entities/orchestration.js.map +1 -0
  36. package/dist/entities/services.d.ts +50 -0
  37. package/dist/entities/services.d.ts.map +1 -0
  38. package/dist/entities/services.js +805 -0
  39. package/dist/entities/services.js.map +1 -0
  40. package/dist/helpers.d.ts +362 -0
  41. package/dist/helpers.d.ts.map +1 -0
  42. package/dist/helpers.js +400 -0
  43. package/dist/helpers.js.map +1 -0
  44. package/dist/index.d.ts +17 -215
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +18 -172
  47. package/dist/index.js.map +1 -0
  48. package/dist/provider.d.ts +85 -0
  49. package/dist/provider.d.ts.map +1 -0
  50. package/dist/provider.js +158 -0
  51. package/dist/provider.js.map +1 -0
  52. package/dist/service.d.ts +43 -0
  53. package/dist/service.d.ts.map +1 -0
  54. package/dist/service.js +206 -0
  55. package/dist/service.js.map +1 -0
  56. package/dist/types.d.ts +469 -0
  57. package/dist/types.d.ts.map +1 -0
  58. package/dist/types.js +5 -0
  59. package/dist/types.js.map +1 -0
  60. package/examples/client-usage.ts +82 -0
  61. package/examples/translation-service.ts +227 -0
  62. package/package.json +24 -38
  63. package/src/client.ts +132 -0
  64. package/src/endpoint.ts +144 -0
  65. package/src/entities/billing.ts +1037 -0
  66. package/src/entities/customers.ts +740 -0
  67. package/src/entities/delivery.ts +974 -0
  68. package/src/entities/index.ts +157 -0
  69. package/src/entities/operations.ts +1099 -0
  70. package/src/entities/orchestration.ts +956 -0
  71. package/src/entities/services.ts +872 -0
  72. package/src/helpers.ts +474 -0
  73. package/src/index.ts +97 -0
  74. package/src/provider.ts +183 -0
  75. package/src/service.test.ts +195 -0
  76. package/src/service.ts +266 -0
  77. package/src/types.ts +543 -0
  78. package/tsconfig.json +9 -0
@@ -0,0 +1,5 @@
1
+
2
+ 
3
+ > services-as-software@2.0.1 build /Users/nathanclevenger/projects/primitives.org.ai/packages/services-as-software
4
+ > tsc
5
+
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # services-as-software
2
+
3
+ ## 2.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies
8
+ - ai-database@2.0.1
9
+ - ai-functions@2.0.1
10
+ - digital-workers@2.0.1
package/README.md CHANGED
@@ -1,302 +1,312 @@
1
1
  # services-as-software
2
2
 
3
- Define services with objectives, key results, and various pricing models for the agentic services architecture.
3
+ Primitives for building AI-powered services that operate as software. Services are a superset of digital-workers with a payment/business overlay, capable of crossing company/business boundaries.
4
4
 
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- npm install services-as-software
9
- # or
10
- yarn add services-as-software
11
- # or
12
8
  pnpm add services-as-software
13
9
  ```
14
10
 
15
- ## Overview
11
+ ## Quick Start
16
12
 
17
- The `services-as-software` package enables defining services with clear objectives, measurable key results, and support for multiple pricing models. It allows Functions, Workflows, and Agents to be offered as Services with appropriate pricing and business models.
18
-
19
- ## Usage
13
+ ```typescript
14
+ import { Service, POST, GET } from 'services-as-software'
20
15
 
21
- ### Basic Service Definition
16
+ // Define a service
17
+ const translationService = Service({
18
+ name: 'translation-service',
19
+ version: '1.0.0',
20
+ description: 'AI-powered translation service',
22
21
 
23
- ```typescript
24
- import { Service } from 'services-as-software'
25
-
26
- const myService = Service({
27
- name: 'Content Generation Service',
28
- description: 'AI-powered content generation for marketing teams',
29
- objective: {
30
- description: 'Provide high-quality content generation that increases marketing efficiency',
31
- keyResults: [],
32
- },
33
- keyResults: [
34
- {
35
- description: 'Reduce content creation time',
36
- target: 50,
37
- currentValue: 0,
38
- unit: 'percent',
39
- },
40
- {
41
- description: 'Maintain content quality score',
42
- target: 8,
43
- currentValue: 0,
44
- unit: 'rating',
45
- },
46
- ],
22
+ // Pricing configuration
47
23
  pricing: {
48
- model: 'cost-based',
49
- costBase: 10,
50
- fixedCosts: 5,
51
- variableCosts: 2,
24
+ model: 'per-use',
25
+ pricePerUnit: 0.01,
26
+ currency: 'USD',
52
27
  },
53
- implementation: {
54
- type: 'function',
55
- id: 'content-generator-123',
56
- },
57
- })
58
28
 
59
- // Register the service
60
- const registeredService = await myService.register()
61
-
62
- // Calculate price
63
- const price = myService.calculatePrice({ quantity: 5 })
64
-
65
- // Track progress towards key results
66
- myService.trackProgress({
67
- 'Reduce content creation time': 30,
68
- 'Maintain content quality score': 9,
29
+ // Service endpoints
30
+ endpoints: [
31
+ POST({
32
+ name: 'translate',
33
+ path: '/translate',
34
+ handler: async (input) => {
35
+ return {
36
+ translatedText: `Translated: ${input.text}`,
37
+ confidence: 0.95,
38
+ }
39
+ },
40
+ }),
41
+ ],
69
42
  })
70
43
 
71
- // Check if objective is achieved
72
- const achieved = myService.isObjectiveAchieved()
44
+ // Use the service
45
+ const result = await translationService.call('translate', {
46
+ text: 'Hello, world!',
47
+ to: 'es',
48
+ })
73
49
  ```
74
50
 
75
- ### Pricing Models
51
+ ## Core Primitives
76
52
 
77
- The package supports four pricing models:
53
+ ### Service Creation
78
54
 
79
- #### 1. Cost-based Pricing
55
+ - **`Service(definition)`** - Define a service with endpoints, pricing, and business logic
56
+ - **`Endpoint(config)`** - Create a service endpoint
57
+ - **`POST()`, `GET()`, `PUT()`, `DELETE()`, `PATCH()`** - HTTP method helpers
80
58
 
81
- ```typescript
82
- const service = Service({
83
- // ...other properties
84
- pricing: {
85
- model: 'cost-based',
86
- costBase: 100,
87
- fixedCosts: 50,
88
- variableCosts: 10,
89
- },
90
- })
91
-
92
- // Calculate price for 5 units
93
- const price = service.calculatePrice({ quantity: 5 }) // 200 (100 + 50 + 10*5)
94
- ```
59
+ ### Client & Providers
95
60
 
96
- #### 2. Margin-based Pricing
61
+ - **`Client(config)`** - Connect to a remote service
62
+ - **`Provider(config)`** - Manage multiple services
63
+ - **`providers.aws()`, `providers.gcp()`, `providers.azure()`** - Pre-configured cloud providers
97
64
 
98
- ```typescript
99
- const service = Service({
100
- // ...other properties
101
- pricing: {
102
- model: 'margin-based',
103
- costBase: 100,
104
- marginPercentage: 20,
105
- },
106
- })
65
+ ### Service Operations
107
66
 
108
- // Calculate price for 2 units
109
- const price = service.calculatePrice({ quantity: 2 }) // 240 (100*2 + 20% margin)
110
- ```
67
+ - **`ask()`** - Ask a question helper
68
+ - **`deliver()`** - Deliver results helper
69
+ - **`do()`** - Execute a task helper
70
+ - **`every()`** - Scheduled recurring tasks helper
71
+ - **`generate()`** - Generate content helper
72
+ - **`is()`** - Type checking/validation helper
73
+ - **`notify()`** - Send notifications helper
74
+ - **`on()`** - Event handlers helper
75
+ - **`order()`** - Place an order helper
76
+ - **`queue()`** - Queue management helper
77
+ - **`quote()`** - Request a quote helper
78
+ - **`subscribe()`** - Subscription management helper
111
79
 
112
- #### 3. Activity-based Pricing
80
+ ### Business Metrics
113
81
 
114
- ```typescript
115
- const service = Service({
116
- // ...other properties
117
- pricing: {
118
- model: 'activity-based',
119
- activities: [
120
- { name: 'research', rate: 50 },
121
- { name: 'writing', rate: 100 },
122
- { name: 'editing', rate: 30 },
123
- ],
124
- },
125
- })
82
+ - **`entitlements()`** - Access entitlements helper
83
+ - **`kpis()`** - Key performance indicators helper
84
+ - **`okrs()`** - Objectives and key results helper
85
+ - **`Plan()`** - Create subscription plans
86
+ - **`KPI()`** - Define KPIs
87
+ - **`OKR()`** - Define OKRs
126
88
 
127
- // Calculate price based on activities performed
128
- const price = service.calculatePrice({
129
- activities: {
130
- research: 2,
131
- writing: 1,
132
- editing: 3,
133
- },
134
- }) // 290 (50*2 + 100*1 + 30*3)
135
- ```
89
+ ## Examples
136
90
 
137
- #### 4. Outcome-based Pricing
91
+ ### Creating a Service
138
92
 
139
93
  ```typescript
94
+ import { Service, Endpoint, POST } from 'services-as-software'
95
+
140
96
  const service = Service({
141
- // ...other properties
142
- pricing: {
143
- model: 'outcome-based',
144
- outcomes: [
145
- { metric: 'conversion-rate', targetValue: 5, price: 500 },
146
- { metric: 'engagement', targetValue: 10000, price: 300 },
147
- ],
148
- },
149
- })
97
+ name: 'my-service',
98
+ version: '1.0.0',
150
99
 
151
- // Calculate price based on achieved outcomes
152
- const price = service.calculatePrice({
153
- outcomes: {
154
- 'conversion-rate': 6.5,
155
- engagement: 8000,
100
+ // Pricing
101
+ pricing: {
102
+ model: 'subscription',
103
+ basePrice: 49.99,
104
+ currency: 'USD',
105
+ interval: 'monthly',
156
106
  },
157
- }) // 500 (only conversion-rate target was met)
158
- ```
159
107
 
160
- ### Offering Functions as Services
108
+ // Endpoints
109
+ endpoints: [
110
+ POST({
111
+ name: 'process',
112
+ handler: async (input, context) => {
113
+ // Your logic here
114
+ return { processed: true }
115
+ },
116
+ }),
117
+ ],
161
118
 
162
- ```typescript
163
- import { Service } from 'services-as-software'
119
+ // Subscription plans
120
+ plans: [
121
+ {
122
+ id: 'pro',
123
+ name: 'Pro Plan',
124
+ pricing: { model: 'subscription', basePrice: 49.99, currency: 'USD', interval: 'monthly' },
125
+ entitlements: ['api-access', 'priority-support'],
126
+ features: ['Unlimited API calls', '24/7 support'],
127
+ },
128
+ ],
164
129
 
165
- const functionAsService = Service({
166
- name: 'Text Summarization',
167
- objective: {
168
- description: 'Provide accurate text summarization',
169
- keyResults: [],
170
- },
171
- keyResults: [
130
+ // KPIs
131
+ kpis: [
172
132
  {
173
- description: 'Summarization accuracy',
174
- target: 90,
175
- unit: 'percent',
133
+ id: 'daily-requests',
134
+ name: 'Daily Requests',
135
+ calculate: async () => 1000,
136
+ target: 1500,
176
137
  },
177
138
  ],
178
- pricing: {
179
- model: 'cost-based',
180
- costBase: 5,
181
- variableCosts: 0.01,
182
- },
183
- implementation: {
184
- type: 'function',
185
- id: 'text-summarizer-function',
186
- },
187
139
  })
188
140
  ```
189
141
 
190
- ### Offering Workflows as Services
142
+ ### Using a Client
191
143
 
192
144
  ```typescript
193
- import { Service } from 'services-as-software'
145
+ import { Client } from 'services-as-software'
194
146
 
195
- const workflowAsService = Service({
196
- name: 'Content Production Pipeline',
197
- objective: {
198
- description: 'End-to-end content production',
199
- keyResults: [],
200
- },
201
- keyResults: [
202
- {
203
- description: 'Average production time',
204
- target: 24,
205
- unit: 'hours',
206
- },
207
- ],
208
- pricing: {
209
- model: 'activity-based',
210
- activities: [
211
- { name: 'research', rate: 100 },
212
- { name: 'writing', rate: 200 },
213
- { name: 'editing', rate: 50 },
214
- { name: 'publishing', rate: 30 },
215
- ],
216
- },
217
- implementation: {
218
- type: 'workflow',
219
- id: 'content-production-workflow',
147
+ const client = Client({
148
+ url: 'https://api.example.com/service',
149
+ auth: {
150
+ type: 'api-key',
151
+ credentials: { apiKey: 'your-key' },
220
152
  },
221
153
  })
154
+
155
+ const result = await client.do('translate', { text: 'Hello', to: 'es' })
222
156
  ```
223
157
 
224
- ### Offering Agents as Services
158
+ ### Using Providers
225
159
 
226
160
  ```typescript
227
- import { Service } from 'services-as-software'
161
+ import { providers } from 'services-as-software'
228
162
 
229
- const agentAsService = Service({
230
- name: 'Customer Support Agent',
231
- objective: {
232
- description: 'Provide excellent customer support',
233
- keyResults: [],
234
- },
235
- keyResults: [
236
- {
237
- description: 'Customer satisfaction score',
238
- target: 4.5,
239
- unit: 'rating',
240
- },
241
- {
242
- description: 'First response time',
243
- target: 5,
244
- unit: 'minutes',
245
- },
246
- ],
247
- pricing: {
248
- model: 'outcome-based',
249
- outcomes: [
250
- { metric: 'resolution-rate', targetValue: 95, price: 1000 },
251
- { metric: 'satisfaction-score', targetValue: 4.8, price: 500 },
252
- ],
253
- },
254
- implementation: {
255
- type: 'agent',
256
- id: 'customer-support-agent',
257
- },
163
+ const aws = providers.aws({
164
+ accessKeyId: 'key',
165
+ secretAccessKey: 'secret',
166
+ region: 'us-east-1',
258
167
  })
168
+
169
+ const translate = aws.service('translate')
170
+ const result = await translate.do('translate', { text: 'Hello', to: 'es' })
259
171
  ```
260
172
 
261
- ## API Reference
173
+ ## Features
174
+
175
+ - **Type-safe** - Full TypeScript support with comprehensive types
176
+ - **Pricing Models** - Support for free, fixed, per-use, subscription, tiered, and custom pricing
177
+ - **Authentication** - Built-in support for API keys, OAuth, JWT, and Basic auth
178
+ - **Rate Limiting** - Endpoint-level rate limiting configuration
179
+ - **Usage Tracking** - Track service usage for billing and analytics
180
+ - **Subscription Management** - Built-in subscription and entitlement support
181
+ - **Business Metrics** - KPIs and OKRs for monitoring service health
182
+ - **Event System** - Register event handlers for service events
183
+ - **Scheduled Tasks** - Cron-based recurring task support
184
+ - **Multi-Provider** - Connect to AWS, GCP, Azure, and custom providers
185
+
186
+ ## Entity Definitions (Nouns)
187
+
188
+ This package provides comprehensive entity definitions for AI-delivered productized services, following the Noun pattern from `ai-database`. Each entity includes properties, relationships, actions, and events.
189
+
190
+ ### Entity Categories
191
+
192
+ | Category | Entities |
193
+ |----------|----------|
194
+ | **Services** | ProductizedService, ServiceOffering, ServicePlan, ServiceInstance, ServiceExecution |
195
+ | **Delivery** | AgentDelivery, AutonomyLevel, EscalationRule, ConfidenceThreshold, HumanHandoff, QualityGate |
196
+ | **Billing** | ServiceQuote, ServiceOrder, ServiceSubscription, Usage, Invoice, Payment |
197
+ | **Operations** | SLA, SLO, ServiceIncident, SupportTicket, ServiceFeedback, ServiceMetric |
198
+ | **Customers** | ServiceCustomer, ServiceEntitlement, CustomerUsage, CustomerSegment |
199
+ | **Orchestration** | ServiceWorkflow, WorkflowStep, ServiceTask, ServiceQueue, ServiceWorker |
262
200
 
263
- ### Service Function
201
+ ### Using Entity Definitions
264
202
 
265
203
  ```typescript
266
- function Service(definition: ServiceDefinition): ServiceObject
204
+ import {
205
+ ProductizedService,
206
+ AgentDelivery,
207
+ EscalationRule,
208
+ ServiceEntities,
209
+ DeliveryEntities,
210
+ } from 'services-as-software'
211
+
212
+ // Access individual entities
213
+ console.log(ProductizedService.singular) // 'productized-service'
214
+ console.log(ProductizedService.actions) // ['create', 'update', 'publish', 'execute', ...]
215
+
216
+ // Access entity collections
217
+ const allServices = ServiceEntities
218
+ const allDelivery = DeliveryEntities
267
219
  ```
268
220
 
269
- Creates a service with the given definition.
221
+ ### AI Delivery Entities
270
222
 
271
- ### ServiceDefinition
223
+ The delivery entities capture the key semantics of AI-delivered services:
272
224
 
273
225
  ```typescript
274
- interface ServiceDefinition {
275
- name: string
276
- description?: string
277
- objective: Objective
278
- keyResults: KeyResult[]
279
- pricing: ServicePricing
280
- implementation: ImplementationDetails
281
- metadata?: Record<string, any>
226
+ const AgentDelivery: Noun = {
227
+ singular: 'agent-delivery',
228
+ plural: 'agent-deliveries',
229
+ description: 'AI agent configuration for autonomous service delivery',
230
+
231
+ properties: {
232
+ name: { type: 'string', description: 'Agent name' },
233
+ model: { type: 'string', description: 'AI model identifier' },
234
+ autonomyLevel: {
235
+ type: 'string',
236
+ examples: ['full', 'supervised', 'assisted', 'advisory']
237
+ },
238
+ confidenceThreshold: {
239
+ type: 'number',
240
+ description: 'Min confidence for autonomous action (0-1)'
241
+ },
242
+ escalationTriggers: {
243
+ type: 'string',
244
+ array: true,
245
+ description: 'Conditions that trigger escalation'
246
+ },
247
+ // ... more properties
248
+ },
249
+
250
+ relationships: {
251
+ service: { type: 'ProductizedService', description: 'Parent service' },
252
+ escalationRules: { type: 'EscalationRule[]', description: 'Escalation rules' },
253
+ qualityGates: { type: 'QualityGate[]', description: 'Quality gates' },
254
+ },
255
+
256
+ actions: ['create', 'update', 'activate', 'pause', 'train', 'evaluate', 'escalate'],
257
+ events: ['created', 'updated', 'activated', 'paused', 'trained', 'evaluated', 'escalated'],
282
258
  }
283
259
  ```
284
260
 
285
- ### Pricing Models
261
+ ### Productized Service Entity
286
262
 
287
263
  ```typescript
288
- type PricingModel = 'cost-based' | 'margin-based' | 'activity-based' | 'outcome-based'
264
+ const ProductizedService: Noun = {
265
+ singular: 'productized-service',
266
+ plural: 'productized-services',
267
+ description: 'A service packaged and delivered as software',
268
+
269
+ properties: {
270
+ name: { type: 'string', description: 'Service name' },
271
+ deliveryModel: {
272
+ type: 'string',
273
+ examples: ['autonomous', 'assisted', 'supervised', 'manual']
274
+ },
275
+ autonomyLevel: { type: 'number', description: 'AI autonomy level (1-5)' },
276
+ confidenceThreshold: {
277
+ type: 'number',
278
+ description: 'Min confidence for auto-completion'
279
+ },
280
+ escalationPolicy: {
281
+ type: 'string',
282
+ examples: ['immediate', 'queue', 'scheduled', 'manual']
283
+ },
284
+ // ... more properties
285
+ },
289
286
 
290
- type ServicePricing = CostBasedPricing | MarginBasedPricing | ActivityBasedPricing | OutcomeBasedPricing
287
+ relationships: {
288
+ plans: { type: 'ServicePlan[]', description: 'Pricing plans' },
289
+ agent: { type: 'AgentDelivery', description: 'AI agent for delivery' },
290
+ sla: { type: 'SLA', description: 'Service level agreement' },
291
+ workflows: { type: 'ServiceWorkflow[]', description: 'Service workflows' },
292
+ },
293
+
294
+ actions: ['create', 'update', 'publish', 'execute', 'escalate', 'complete'],
295
+ events: ['created', 'updated', 'published', 'executed', 'escalated', 'completed'],
296
+ }
291
297
  ```
292
298
 
293
- ## Integration with Existing Services
299
+ ## Architecture
294
300
 
295
- The `services-as-software` package is designed to work with the existing services ecosystem:
301
+ Services-as-software provides a complete framework for building and consuming services:
296
302
 
297
- - Integrates with the `services.do` SDK for service registration
298
- - Extends the business model concepts from `Business-as-Code`
299
- - Compatible with Functions, Workflows, and Agents collections
303
+ ```
304
+ Service Definition Service Instance Client Access
305
+ ↓ ↓ ↓
306
+ Endpoints Event Handlers HTTP/RPC
307
+ Pricing Scheduled Tasks Authentication
308
+ Plans KPIs/OKRs Rate Limiting
309
+ ```
300
310
 
301
311
  ## License
302
312
 
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Service client for connecting to remote services
3
+ */
4
+ import type { ServiceClient, ClientConfig } from './types.js';
5
+ /**
6
+ * Create a client to connect to a remote service
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const client = Client({
11
+ * url: 'https://api.example.com/translation',
12
+ * auth: {
13
+ * type: 'api-key',
14
+ * credentials: { apiKey: process.env.API_KEY },
15
+ * },
16
+ * })
17
+ *
18
+ * const result = await client.do('translate', {
19
+ * text: 'Hello world',
20
+ * to: 'es',
21
+ * })
22
+ * ```
23
+ */
24
+ export declare function Client(config: ClientConfig): ServiceClient;
25
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EACV,aAAa,EACb,YAAY,EAOb,MAAM,YAAY,CAAA;AAEnB;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,MAAM,CAAC,MAAM,EAAE,YAAY,GAAG,aAAa,CAiG1D"}
package/dist/client.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Service client for connecting to remote services
3
+ */
4
+ /**
5
+ * Create a client to connect to a remote service
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const client = Client({
10
+ * url: 'https://api.example.com/translation',
11
+ * auth: {
12
+ * type: 'api-key',
13
+ * credentials: { apiKey: process.env.API_KEY },
14
+ * },
15
+ * })
16
+ *
17
+ * const result = await client.do('translate', {
18
+ * text: 'Hello world',
19
+ * to: 'es',
20
+ * })
21
+ * ```
22
+ */
23
+ export function Client(config) {
24
+ const baseUrl = config.url || '';
25
+ const headers = {
26
+ 'Content-Type': 'application/json',
27
+ ...config.headers,
28
+ };
29
+ // Add auth headers
30
+ if (config.auth) {
31
+ switch (config.auth.type) {
32
+ case 'api-key':
33
+ headers['Authorization'] = `Bearer ${config.auth.credentials.apiKey || config.auth.credentials.token}`;
34
+ break;
35
+ case 'basic':
36
+ const basicAuth = Buffer.from(`${config.auth.credentials.username}:${config.auth.credentials.password}`).toString('base64');
37
+ headers['Authorization'] = `Basic ${basicAuth}`;
38
+ break;
39
+ case 'jwt':
40
+ headers['Authorization'] = `Bearer ${config.auth.credentials.token}`;
41
+ break;
42
+ // OAuth would require more complex flow
43
+ }
44
+ }
45
+ /**
46
+ * Make an HTTP request to the service
47
+ */
48
+ async function request(endpoint, body) {
49
+ const url = `${baseUrl}/${endpoint.replace(/^\//, '')}`;
50
+ const response = await fetch(url, {
51
+ method: 'POST',
52
+ headers,
53
+ body: body ? JSON.stringify(body) : undefined,
54
+ signal: config.timeout ? AbortSignal.timeout(config.timeout) : undefined,
55
+ });
56
+ if (!response.ok) {
57
+ throw new Error(`Service request failed: ${response.status} ${response.statusText}`);
58
+ }
59
+ return response.json();
60
+ }
61
+ return {
62
+ async ask(question, context) {
63
+ const result = await request('ask', { question, context });
64
+ return result.answer;
65
+ },
66
+ async deliver(orderId, results) {
67
+ await request('deliver', { orderId, results });
68
+ },
69
+ async do(action, input) {
70
+ return request('do', { action, input });
71
+ },
72
+ async generate(prompt, options) {
73
+ return request('generate', { prompt, options });
74
+ },
75
+ async is(value, type) {
76
+ const result = await request('is', { value, type });
77
+ return result.result;
78
+ },
79
+ async notify(notification) {
80
+ await request('notify', notification);
81
+ },
82
+ async order(product, quantity) {
83
+ return request('order', { product, quantity });
84
+ },
85
+ async quote(product, quantity) {
86
+ return request('quote', { product, quantity });
87
+ },
88
+ async subscribe(planId) {
89
+ return request('subscribe', { planId });
90
+ },
91
+ async entitlements() {
92
+ const result = await request('entitlements', {});
93
+ return result.entitlements;
94
+ },
95
+ async kpis() {
96
+ return request('kpis', {});
97
+ },
98
+ async okrs() {
99
+ return request('okrs', {});
100
+ },
101
+ };
102
+ }
103
+ //# sourceMappingURL=client.js.map