digital-workers 2.0.2 → 2.1.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # digital-workers
2
2
 
3
+ ## 2.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [6beb531]
8
+ - ai-functions@2.1.1
9
+ - ai-workflows@2.1.1
10
+
11
+ ## 2.0.3
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies
16
+ - rpc.do@0.2.0
17
+ - ai-functions@2.0.3
18
+ - ai-workflows@2.0.3
19
+
3
20
  ## 2.0.2
4
21
 
5
22
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "digital-workers",
3
- "version": "2.0.2",
3
+ "version": "2.1.1",
4
4
  "description": "Common abstract interface over AI Agents and Humans",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -20,9 +20,8 @@
20
20
  "clean": "rm -rf dist"
21
21
  },
22
22
  "dependencies": {
23
- "ai-functions": "2.0.2",
24
- "ai-workflows": "2.0.2",
25
- "rpc.do": "^0.1.0"
23
+ "ai-functions": "2.1.1",
24
+ "ai-workflows": "2.1.1"
26
25
  },
27
26
  "keywords": [
28
27
  "ai",
package/src/actions.js ADDED
@@ -0,0 +1,436 @@
1
+ /**
2
+ * Worker Actions - Workflow Integration
3
+ *
4
+ * Worker actions (notify, ask, approve, decide, do) are durable workflow actions
5
+ * that integrate with ai-workflows. They can be invoked via:
6
+ *
7
+ * 1. `$.do('Worker.notify', data)` - Durable action
8
+ * 2. `$.send('Worker.notify', data)` - Fire and forget
9
+ * 3. `$.notify(target, message)` - Convenience method (when using withWorkers)
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+ // ============================================================================
14
+ // Action Handlers
15
+ // ============================================================================
16
+ /**
17
+ * Handle Worker.notify action
18
+ */
19
+ export async function handleNotify(data, $) {
20
+ const { object: target, message, via, priority = 'normal' } = data;
21
+ // Resolve target to get contacts
22
+ const { contacts, recipients } = resolveTarget(target);
23
+ // Determine which channels to use
24
+ const channels = resolveChannels(via, contacts, priority);
25
+ if (channels.length === 0) {
26
+ return {
27
+ sent: false,
28
+ via: [],
29
+ sentAt: new Date(),
30
+ messageId: generateId('msg'),
31
+ };
32
+ }
33
+ // Send to each channel
34
+ const delivery = await Promise.all(channels.map(async (channel) => {
35
+ try {
36
+ await sendToChannel(channel, message, contacts, { priority });
37
+ return { channel, status: 'sent' };
38
+ }
39
+ catch (error) {
40
+ return {
41
+ channel,
42
+ status: 'failed',
43
+ error: error instanceof Error ? error.message : 'Unknown error',
44
+ };
45
+ }
46
+ }));
47
+ const sent = delivery.some((d) => d.status === 'sent');
48
+ const result = {
49
+ sent,
50
+ via: channels,
51
+ recipients,
52
+ sentAt: new Date(),
53
+ messageId: generateId('msg'),
54
+ delivery,
55
+ };
56
+ // Emit result event
57
+ if (sent) {
58
+ await $.send('Worker.notified', { ...data, result });
59
+ }
60
+ return result;
61
+ }
62
+ /**
63
+ * Handle Worker.ask action
64
+ */
65
+ export async function handleAsk(data, $) {
66
+ const { object: target, question, via, schema, timeout } = data;
67
+ // Resolve target
68
+ const { contacts, recipients } = resolveTarget(target);
69
+ const recipient = recipients[0];
70
+ // Determine channel
71
+ const channel = resolveChannel(via, contacts);
72
+ if (!channel) {
73
+ throw new Error('No valid channel available for ask action');
74
+ }
75
+ // Send question and wait for response
76
+ const answer = await sendQuestion(channel, question, contacts, { schema, timeout });
77
+ const result = {
78
+ answer,
79
+ answeredBy: recipient,
80
+ answeredAt: new Date(),
81
+ via: channel,
82
+ };
83
+ // Emit result event
84
+ await $.send('Worker.answered', { ...data, result });
85
+ return result;
86
+ }
87
+ /**
88
+ * Handle Worker.approve action
89
+ */
90
+ export async function handleApprove(data, $) {
91
+ const { object: target, request, via, context, timeout, escalate } = data;
92
+ // Resolve target
93
+ const { contacts, recipients } = resolveTarget(target);
94
+ const approver = recipients[0];
95
+ // Determine channel
96
+ const channel = resolveChannel(via, contacts);
97
+ if (!channel) {
98
+ throw new Error('No valid channel available for approve action');
99
+ }
100
+ // Send approval request and wait for response
101
+ const response = await sendApprovalRequest(channel, request, contacts, {
102
+ context,
103
+ timeout,
104
+ escalate,
105
+ });
106
+ const result = {
107
+ approved: response.approved,
108
+ approvedBy: approver,
109
+ approvedAt: new Date(),
110
+ notes: response.notes,
111
+ via: channel,
112
+ };
113
+ // Emit result event
114
+ await $.send(result.approved ? 'Worker.approved' : 'Worker.rejected', { ...data, result });
115
+ return result;
116
+ }
117
+ /**
118
+ * Handle Worker.decide action
119
+ */
120
+ export async function handleDecide(data, $) {
121
+ const { options, context, criteria } = data;
122
+ // Use AI to make decision
123
+ const result = await makeDecision(options, context, criteria);
124
+ // Emit result event
125
+ await $.send('Worker.decided', { ...data, result });
126
+ return result;
127
+ }
128
+ /**
129
+ * Handle Worker.do action
130
+ */
131
+ export async function handleDo(data, $) {
132
+ const { object: target, instruction, timeout, maxRetries = 3 } = data;
133
+ const startTime = Date.now();
134
+ const steps = [];
135
+ let lastError;
136
+ let result;
137
+ // Retry loop
138
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
139
+ try {
140
+ steps.push({
141
+ action: attempt === 0 ? 'start' : `retry_${attempt}`,
142
+ result: { instruction },
143
+ timestamp: new Date(),
144
+ });
145
+ // Execute the task (this would integrate with agent execution)
146
+ result = await executeTask(target, instruction, { timeout });
147
+ steps.push({
148
+ action: 'complete',
149
+ result,
150
+ timestamp: new Date(),
151
+ });
152
+ const doResult = {
153
+ result: result,
154
+ success: true,
155
+ duration: Date.now() - startTime,
156
+ steps,
157
+ };
158
+ await $.send('Worker.done', { ...data, result: doResult });
159
+ return doResult;
160
+ }
161
+ catch (error) {
162
+ lastError = error instanceof Error ? error : new Error(String(error));
163
+ steps.push({
164
+ action: 'error',
165
+ result: { error: lastError.message, attempt },
166
+ timestamp: new Date(),
167
+ });
168
+ }
169
+ }
170
+ // All retries failed
171
+ const failResult = {
172
+ result: undefined,
173
+ success: false,
174
+ error: lastError?.message,
175
+ duration: Date.now() - startTime,
176
+ steps,
177
+ };
178
+ await $.send('Worker.failed', { ...data, result: failResult });
179
+ return failResult;
180
+ }
181
+ // ============================================================================
182
+ // Workflow Extension
183
+ // ============================================================================
184
+ /**
185
+ * Register Worker action handlers with a workflow
186
+ *
187
+ * @example
188
+ * ```ts
189
+ * import { Workflow } from 'ai-workflows'
190
+ * import { registerWorkerActions } from 'digital-workers'
191
+ *
192
+ * const workflow = Workflow($ => {
193
+ * registerWorkerActions($)
194
+ *
195
+ * $.on.Expense.submitted(async (expense, $) => {
196
+ * const approval = await $.do('Worker.approve', {
197
+ * actor: 'system',
198
+ * object: manager,
199
+ * request: `Expense: $${expense.amount}`,
200
+ * via: 'slack',
201
+ * })
202
+ * })
203
+ * })
204
+ * ```
205
+ */
206
+ export function registerWorkerActions($) {
207
+ // Register action handlers using the proxy pattern
208
+ // The $ context provides event registration via $.on[Namespace][event]
209
+ const on = $.on;
210
+ if (on.Worker) {
211
+ on.Worker.notify?.(handleNotify);
212
+ on.Worker.ask?.(handleAsk);
213
+ on.Worker.approve?.(handleApprove);
214
+ on.Worker.decide?.(handleDecide);
215
+ on.Worker.do?.(handleDo);
216
+ }
217
+ }
218
+ /**
219
+ * Extend WorkflowContext with convenience methods for worker actions
220
+ *
221
+ * @example
222
+ * ```ts
223
+ * const workflow = Workflow($ => {
224
+ * const worker$ = withWorkers($)
225
+ *
226
+ * $.on.Expense.submitted(async (expense) => {
227
+ * await worker$.notify(finance, `New expense: ${expense.amount}`)
228
+ *
229
+ * const approval = await worker$.approve(
230
+ * `Expense: $${expense.amount}`,
231
+ * manager,
232
+ * { via: 'slack' }
233
+ * )
234
+ * })
235
+ * })
236
+ * ```
237
+ */
238
+ export function withWorkers($) {
239
+ const workerContext = {
240
+ async notify(target, message, options = {}) {
241
+ return $.do('Worker.notify', {
242
+ actor: 'system',
243
+ object: target,
244
+ action: 'notify',
245
+ message,
246
+ ...options,
247
+ });
248
+ },
249
+ async ask(target, question, options = {}) {
250
+ return $.do('Worker.ask', {
251
+ actor: 'system',
252
+ object: target,
253
+ action: 'ask',
254
+ question,
255
+ ...options,
256
+ });
257
+ },
258
+ async approve(request, target, options = {}) {
259
+ // Convert ActionTarget to a suitable actor reference
260
+ const actor = typeof target === 'string'
261
+ ? target
262
+ : 'id' in target
263
+ ? { id: target.id, type: 'type' in target ? target.type : undefined, name: 'name' in target ? target.name : undefined }
264
+ : 'system';
265
+ return $.do('Worker.approve', {
266
+ actor,
267
+ object: target,
268
+ action: 'approve',
269
+ request,
270
+ ...options,
271
+ });
272
+ },
273
+ async decide(options) {
274
+ return $.do('Worker.decide', {
275
+ actor: 'ai',
276
+ object: 'decision',
277
+ action: 'decide',
278
+ ...options,
279
+ });
280
+ },
281
+ };
282
+ return { ...$, ...workerContext };
283
+ }
284
+ // ============================================================================
285
+ // Standalone Functions (for use outside workflows)
286
+ // ============================================================================
287
+ /**
288
+ * Send a notification (standalone, non-durable)
289
+ */
290
+ export async function notify(target, message, options = {}) {
291
+ const { contacts, recipients } = resolveTarget(target);
292
+ const channels = resolveChannels(options.via, contacts, options.priority || 'normal');
293
+ if (channels.length === 0) {
294
+ return { sent: false, via: [], messageId: generateId('msg') };
295
+ }
296
+ const delivery = await Promise.all(channels.map(async (channel) => {
297
+ try {
298
+ await sendToChannel(channel, message, contacts, { priority: options.priority });
299
+ return { channel, status: 'sent' };
300
+ }
301
+ catch (error) {
302
+ return { channel, status: 'failed', error: String(error) };
303
+ }
304
+ }));
305
+ return {
306
+ sent: delivery.some((d) => d.status === 'sent'),
307
+ via: channels,
308
+ recipients,
309
+ sentAt: new Date(),
310
+ messageId: generateId('msg'),
311
+ delivery,
312
+ };
313
+ }
314
+ /**
315
+ * Ask a question (standalone, non-durable)
316
+ */
317
+ export async function ask(target, question, options = {}) {
318
+ const { contacts, recipients } = resolveTarget(target);
319
+ const channel = resolveChannel(options.via, contacts);
320
+ if (!channel) {
321
+ throw new Error('No valid channel available');
322
+ }
323
+ const answer = await sendQuestion(channel, question, contacts, options);
324
+ return {
325
+ answer,
326
+ answeredBy: recipients[0],
327
+ answeredAt: new Date(),
328
+ via: channel,
329
+ };
330
+ }
331
+ /**
332
+ * Request approval (standalone, non-durable)
333
+ */
334
+ export async function approve(request, target, options = {}) {
335
+ const { contacts, recipients } = resolveTarget(target);
336
+ const channel = resolveChannel(options.via, contacts);
337
+ if (!channel) {
338
+ throw new Error('No valid channel available');
339
+ }
340
+ const response = await sendApprovalRequest(channel, request, contacts, options);
341
+ return {
342
+ approved: response.approved,
343
+ approvedBy: recipients[0],
344
+ approvedAt: new Date(),
345
+ notes: response.notes,
346
+ via: channel,
347
+ };
348
+ }
349
+ /**
350
+ * Make a decision (standalone, non-durable)
351
+ */
352
+ export async function decide(options) {
353
+ return makeDecision(options.options, options.context, options.criteria);
354
+ }
355
+ // ============================================================================
356
+ // Internal Helpers
357
+ // ============================================================================
358
+ function resolveTarget(target) {
359
+ if (typeof target === 'string') {
360
+ return { contacts: {}, recipients: [{ id: target }] };
361
+ }
362
+ if ('contacts' in target) {
363
+ const recipients = 'members' in target
364
+ ? target.members
365
+ : [{ id: target.id, type: target.type, name: target.name }];
366
+ return { contacts: target.contacts, recipients };
367
+ }
368
+ return { contacts: {}, recipients: [target] };
369
+ }
370
+ function resolveChannels(via, contacts, priority) {
371
+ if (via) {
372
+ const requested = Array.isArray(via) ? via : [via];
373
+ return requested.filter((c) => contacts[c] !== undefined);
374
+ }
375
+ const available = Object.keys(contacts);
376
+ if (available.length === 0)
377
+ return [];
378
+ const firstChannel = available[0];
379
+ if (!firstChannel)
380
+ return [];
381
+ if (priority === 'urgent') {
382
+ const urgentChannels = ['slack', 'sms', 'phone'];
383
+ const urgent = available.filter((c) => urgentChannels.includes(c));
384
+ return urgent.length > 0 ? urgent : [firstChannel];
385
+ }
386
+ return [firstChannel];
387
+ }
388
+ function resolveChannel(via, contacts) {
389
+ if (via) {
390
+ const channel = Array.isArray(via) ? via[0] : via;
391
+ if (channel && contacts[channel] !== undefined)
392
+ return channel;
393
+ }
394
+ const available = Object.keys(contacts);
395
+ const first = available[0];
396
+ return first ?? null;
397
+ }
398
+ async function sendToChannel(channel, message, contacts, options) {
399
+ // In a real implementation, this would send via Slack API, SendGrid, Twilio, etc.
400
+ await new Promise((resolve) => setTimeout(resolve, 10));
401
+ }
402
+ async function sendQuestion(channel, question, contacts, options) {
403
+ // In a real implementation, this would send the question and wait for response
404
+ await new Promise((resolve) => setTimeout(resolve, 10));
405
+ return 'Pending response...';
406
+ }
407
+ async function sendApprovalRequest(channel, request, contacts, options) {
408
+ // In a real implementation, this would send approval request and wait
409
+ await new Promise((resolve) => setTimeout(resolve, 10));
410
+ return { approved: false, notes: 'Pending approval...' };
411
+ }
412
+ async function makeDecision(options, context, criteria) {
413
+ if (options.length === 0) {
414
+ throw new Error('At least one option is required for a decision');
415
+ }
416
+ // In a real implementation, this would use AI to make a decision
417
+ // For now, return first option with mock data
418
+ const choice = options[0];
419
+ return {
420
+ choice,
421
+ reasoning: 'Decision pending...',
422
+ confidence: 0.5,
423
+ alternatives: options.slice(1).map((opt, i) => ({
424
+ option: opt,
425
+ score: 50 - i * 10,
426
+ })),
427
+ };
428
+ }
429
+ async function executeTask(target, instruction, options) {
430
+ // In a real implementation, this would execute the task via the target worker
431
+ await new Promise((resolve) => setTimeout(resolve, 10));
432
+ return { completed: true, instruction };
433
+ }
434
+ function generateId(prefix) {
435
+ return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
436
+ }
package/src/approve.js ADDED
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Approval request functionality for digital workers
3
+ */
4
+ /**
5
+ * Request approval from a worker or team
6
+ *
7
+ * Routes approval requests through the specified channel and waits for a response.
8
+ *
9
+ * @param request - What is being requested for approval
10
+ * @param target - The worker or team to request approval from
11
+ * @param options - Approval options
12
+ * @returns Promise resolving to approval result
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * // Request approval from a worker
17
+ * const result = await approve('Expense: $500 for AWS', manager, {
18
+ * via: 'slack',
19
+ * context: { amount: 500, category: 'Infrastructure' },
20
+ * })
21
+ *
22
+ * if (result.approved) {
23
+ * console.log(`Approved by ${result.approvedBy?.name}`)
24
+ * }
25
+ *
26
+ * // Request approval from a team
27
+ * const result = await approve('Deploy v2.1.0 to production', opsTeam, {
28
+ * via: 'slack',
29
+ * })
30
+ * ```
31
+ */
32
+ export async function approve(request, target, options = {}) {
33
+ const { via, timeout, context, escalate = false } = options;
34
+ // Resolve target to get contacts and approver info
35
+ const { contacts, approver } = resolveTarget(target);
36
+ // Determine which channel to use
37
+ const channel = resolveChannel(via, contacts);
38
+ if (!channel) {
39
+ throw new Error('No valid channel available for approval request');
40
+ }
41
+ // Send the approval request and wait for response
42
+ const response = await sendApprovalRequest(channel, request, contacts, {
43
+ timeout,
44
+ context,
45
+ approver,
46
+ escalate,
47
+ });
48
+ return {
49
+ approved: response.approved,
50
+ approvedBy: approver,
51
+ approvedAt: new Date(),
52
+ notes: response.notes,
53
+ via: channel,
54
+ };
55
+ }
56
+ /**
57
+ * Request approval with structured decision context
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * const result = await approve.withContext(
62
+ * 'Migrate to new database',
63
+ * cto,
64
+ * {
65
+ * pros: ['Better performance', 'Lower cost'],
66
+ * cons: ['Migration effort', 'Downtime required'],
67
+ * risks: ['Data loss', 'Service disruption'],
68
+ * mitigations: ['Backup strategy', 'Staged rollout'],
69
+ * },
70
+ * { via: 'email' }
71
+ * )
72
+ * ```
73
+ */
74
+ approve.withContext = async (request, target, decision, options = {}) => {
75
+ return approve(request, target, {
76
+ ...options,
77
+ context: {
78
+ ...options.context,
79
+ decision,
80
+ },
81
+ });
82
+ };
83
+ /**
84
+ * Request batch approval for multiple items
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * const results = await approve.batch([
89
+ * 'Expense: $500 for AWS',
90
+ * 'Expense: $200 for office supplies',
91
+ * 'Expense: $1000 for conference ticket',
92
+ * ], finance, { via: 'email' })
93
+ *
94
+ * const approved = results.filter(r => r.approved)
95
+ * ```
96
+ */
97
+ approve.batch = async (requests, target, options = {}) => {
98
+ return Promise.all(requests.map((request) => approve(request, target, options)));
99
+ };
100
+ /**
101
+ * Request approval with a deadline
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * const result = await approve.withDeadline(
106
+ * 'Release v2.0',
107
+ * manager,
108
+ * new Date('2024-01-15T17:00:00Z'),
109
+ * { via: 'slack' }
110
+ * )
111
+ * ```
112
+ */
113
+ approve.withDeadline = async (request, target, deadline, options = {}) => {
114
+ const timeout = deadline.getTime() - Date.now();
115
+ return approve(request, target, {
116
+ ...options,
117
+ timeout: Math.max(0, timeout),
118
+ context: {
119
+ ...options.context,
120
+ deadline: deadline.toISOString(),
121
+ },
122
+ });
123
+ };
124
+ /**
125
+ * Request approval from multiple approvers (any one can approve)
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * const result = await approve.any(
130
+ * 'Urgent: Production fix',
131
+ * [alice, bob, charlie],
132
+ * { via: 'slack' }
133
+ * )
134
+ * ```
135
+ */
136
+ approve.any = async (request, targets, options = {}) => {
137
+ // Race all approval requests - first to respond wins
138
+ return Promise.race(targets.map((target) => approve(request, target, options)));
139
+ };
140
+ /**
141
+ * Request approval from multiple approvers (all must approve)
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * const result = await approve.all(
146
+ * 'Major infrastructure change',
147
+ * [cto, vpe, securityLead],
148
+ * { via: 'email' }
149
+ * )
150
+ * ```
151
+ */
152
+ approve.all = async (request, targets, options = {}) => {
153
+ const results = await Promise.all(targets.map((target) => approve(request, target, options)));
154
+ const allApproved = results.every((r) => r.approved);
155
+ return {
156
+ approved: allApproved,
157
+ approvedAt: new Date(),
158
+ notes: allApproved
159
+ ? 'All approvers approved'
160
+ : `${results.filter((r) => !r.approved).length} rejection(s)`,
161
+ approvals: results,
162
+ };
163
+ };
164
+ // ============================================================================
165
+ // Internal Helpers
166
+ // ============================================================================
167
+ /**
168
+ * Resolve an action target to contacts and approver
169
+ */
170
+ function resolveTarget(target) {
171
+ if (typeof target === 'string') {
172
+ return {
173
+ contacts: {},
174
+ approver: { id: target },
175
+ };
176
+ }
177
+ if ('contacts' in target) {
178
+ // Worker or Team
179
+ let approver;
180
+ if ('members' in target) {
181
+ // Team - use lead or first member
182
+ approver = target.lead ?? target.members[0] ?? { id: target.id };
183
+ }
184
+ else {
185
+ // Worker
186
+ approver = { id: target.id, type: target.type, name: target.name };
187
+ }
188
+ return {
189
+ contacts: target.contacts,
190
+ approver,
191
+ };
192
+ }
193
+ // WorkerRef
194
+ return {
195
+ contacts: {},
196
+ approver: target,
197
+ };
198
+ }
199
+ /**
200
+ * Determine which channel to use
201
+ */
202
+ function resolveChannel(via, contacts) {
203
+ if (via) {
204
+ const requested = Array.isArray(via) ? via[0] : via;
205
+ if (requested && contacts[requested] !== undefined) {
206
+ return requested;
207
+ }
208
+ }
209
+ // Default to first available
210
+ const available = Object.keys(contacts);
211
+ const first = available[0];
212
+ return first ?? null;
213
+ }
214
+ /**
215
+ * Send an approval request to a channel and wait for response
216
+ */
217
+ async function sendApprovalRequest(channel, request, contacts, options) {
218
+ const contact = contacts[channel];
219
+ if (!contact) {
220
+ throw new Error(`No ${channel} contact configured`);
221
+ }
222
+ // In a real implementation, this would:
223
+ // 1. Format the request for the channel (Slack blocks, email HTML, etc.)
224
+ // 2. Send via the appropriate API
225
+ // 3. Wait for response (polling, webhook, interactive message, etc.)
226
+ // 4. Handle timeout and escalation
227
+ // For now, simulate a pending response
228
+ await new Promise((resolve) => setTimeout(resolve, 10));
229
+ // Return a placeholder - real impl would wait for actual response
230
+ return {
231
+ approved: false,
232
+ notes: 'Approval pending - waiting for response',
233
+ };
234
+ }