digital-workers 2.1.3 → 2.4.0
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/.turbo/turbo-build.log +1 -1
- package/CHANGELOG.md +17 -0
- package/README.md +2 -0
- package/dist/actions.d.ts.map +1 -1
- package/dist/actions.js +33 -21
- package/dist/actions.js.map +1 -1
- package/dist/agent-comms.d.ts.map +1 -1
- package/dist/agent-comms.js +36 -25
- package/dist/agent-comms.js.map +1 -1
- package/dist/approve.d.ts +40 -8
- package/dist/approve.d.ts.map +1 -1
- package/dist/approve.js +86 -20
- package/dist/approve.js.map +1 -1
- package/dist/ask.d.ts +38 -7
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +85 -25
- package/dist/ask.js.map +1 -1
- package/dist/browse.d.ts +223 -0
- package/dist/browse.d.ts.map +1 -0
- package/dist/browse.js +392 -0
- package/dist/browse.js.map +1 -0
- package/dist/capability-tiers.js +3 -3
- package/dist/capability-tiers.js.map +1 -1
- package/dist/cascade-context.d.ts +28 -28
- package/dist/client.d.ts +162 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +64 -0
- package/dist/client.js.map +1 -0
- package/dist/decide.d.ts +42 -6
- package/dist/decide.d.ts.map +1 -1
- package/dist/decide.js +54 -11
- package/dist/decide.js.map +1 -1
- package/dist/do.d.ts +36 -7
- package/dist/do.d.ts.map +1 -1
- package/dist/do.js +82 -39
- package/dist/do.js.map +1 -1
- package/dist/error-escalation.d.ts.map +1 -1
- package/dist/error-escalation.js +38 -38
- package/dist/error-escalation.js.map +1 -1
- package/dist/generate.d.ts +48 -7
- package/dist/generate.d.ts.map +1 -1
- package/dist/generate.js +49 -8
- package/dist/generate.js.map +1 -1
- package/dist/goals.d.ts +10 -9
- package/dist/goals.d.ts.map +1 -1
- package/dist/goals.js +30 -24
- package/dist/goals.js.map +1 -1
- package/dist/image.d.ts +189 -0
- package/dist/image.d.ts.map +1 -0
- package/dist/image.js +528 -0
- package/dist/image.js.map +1 -0
- package/dist/index.d.ts +49 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +58 -2
- package/dist/index.js.map +1 -1
- package/dist/is.d.ts +45 -10
- package/dist/is.d.ts.map +1 -1
- package/dist/is.js +56 -21
- package/dist/is.js.map +1 -1
- package/dist/kpis.d.ts +24 -15
- package/dist/kpis.d.ts.map +1 -1
- package/dist/kpis.js +16 -14
- package/dist/kpis.js.map +1 -1
- package/dist/load-balancing.d.ts.map +1 -1
- package/dist/load-balancing.js +124 -38
- package/dist/load-balancing.js.map +1 -1
- package/dist/logger.d.ts +76 -0
- package/dist/logger.d.ts.map +1 -0
- package/dist/logger.js +39 -0
- package/dist/logger.js.map +1 -0
- package/dist/notify.d.ts +38 -9
- package/dist/notify.d.ts.map +1 -1
- package/dist/notify.js +72 -17
- package/dist/notify.js.map +1 -1
- package/dist/role.d.ts +5 -4
- package/dist/role.d.ts.map +1 -1
- package/dist/role.js +13 -10
- package/dist/role.js.map +1 -1
- package/dist/runtime.d.ts +310 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +510 -0
- package/dist/runtime.js.map +1 -0
- package/dist/team.d.ts +11 -6
- package/dist/team.d.ts.map +1 -1
- package/dist/team.js +22 -15
- package/dist/team.js.map +1 -1
- package/dist/transports/email.d.ts +318 -0
- package/dist/transports/email.d.ts.map +1 -0
- package/dist/transports/email.js +779 -0
- package/dist/transports/email.js.map +1 -0
- package/dist/transports/slack.d.ts +515 -0
- package/dist/transports/slack.d.ts.map +1 -0
- package/dist/transports/slack.js +844 -0
- package/dist/transports/slack.js.map +1 -0
- package/dist/transports.d.ts.map +1 -1
- package/dist/transports.js +44 -25
- package/dist/transports.js.map +1 -1
- package/dist/types.d.ts +141 -19
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +5 -0
- package/dist/types.js.map +1 -1
- package/dist/utils/id.d.ts +19 -0
- package/dist/utils/id.d.ts.map +1 -0
- package/dist/utils/id.js +21 -0
- package/dist/utils/id.js.map +1 -0
- package/dist/video.d.ts +203 -0
- package/dist/video.d.ts.map +1 -0
- package/dist/video.js +528 -0
- package/dist/video.js.map +1 -0
- package/dist/worker.d.ts +343 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.js +698 -0
- package/dist/worker.js.map +1 -0
- package/package.json +32 -14
- package/src/actions.ts +39 -30
- package/src/agent-comms.ts +54 -92
- package/src/approve.ts +91 -20
- package/src/ask.ts +99 -25
- package/src/browse.ts +627 -0
- package/src/capability-tiers.ts +5 -5
- package/src/client.ts +221 -0
- package/src/decide.ts +81 -35
- package/src/do.ts +98 -52
- package/src/error-escalation.ts +55 -67
- package/src/generate.ts +52 -18
- package/src/goals.ts +36 -27
- package/src/image.ts +816 -0
- package/src/index.ts +187 -2
- package/src/is.ts +59 -25
- package/src/kpis.ts +41 -36
- package/src/load-balancing.ts +132 -46
- package/src/logger.ts +93 -0
- package/src/notify.ts +78 -17
- package/src/role.ts +30 -20
- package/src/runtime.ts +796 -0
- package/src/team.ts +24 -19
- package/src/transports/email.ts +1160 -0
- package/src/transports/slack.ts +1320 -0
- package/src/transports.ts +58 -43
- package/src/types.ts +174 -46
- package/src/utils/id.ts +21 -0
- package/src/video.ts +906 -0
- package/src/worker.ts +1007 -0
- package/test/approve.test.ts +305 -0
- package/test/ask.test.ts +274 -0
- package/test/browse.test.ts +361 -0
- package/test/decide.test.ts +252 -0
- package/test/do.test.ts +144 -0
- package/test/error-logging.test.ts +357 -0
- package/test/generate.test.ts +319 -0
- package/test/image.test.ts +398 -0
- package/test/is.test.ts +287 -0
- package/test/load-balancing-safety.test.ts +404 -0
- package/test/notify.test.ts +434 -0
- package/test/primitives.test.ts +320 -0
- package/test/runtime-integration.test.ts +892 -0
- package/test/transports/crypto.test.ts +230 -0
- package/test/transports/email.test.ts +866 -0
- package/test/transports/id-generation.test.ts +91 -0
- package/test/transports/slack.test.ts +760 -0
- package/test/type-safety.test.ts +834 -0
- package/test/types.test.ts +60 -2
- package/test/video.test.ts +530 -0
- package/test/worker.test.ts +1433 -0
- package/tsconfig.json +4 -1
- package/vitest.config.ts +42 -0
- package/wrangler.jsonc +36 -0
- package/LICENSE +0 -21
- package/src/actions.js +0 -436
- package/src/approve.js +0 -234
- package/src/ask.js +0 -226
- package/src/decide.js +0 -244
- package/src/do.js +0 -227
- package/src/generate.js +0 -298
- package/src/goals.js +0 -205
- package/src/index.js +0 -68
- package/src/is.js +0 -317
- package/src/kpis.js +0 -270
- package/src/notify.js +0 -219
- package/src/role.js +0 -110
- package/src/team.js +0 -130
- package/src/transports.js +0 -357
- package/src/types.js +0 -71
package/tsconfig.json
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"extends": "../../tsconfig.base.json",
|
|
3
3
|
"compilerOptions": {
|
|
4
|
+
"module": "ESNext",
|
|
5
|
+
"moduleResolution": "bundler",
|
|
4
6
|
"rootDir": "src",
|
|
5
|
-
"outDir": "dist"
|
|
7
|
+
"outDir": "dist",
|
|
8
|
+
"types": ["@cloudflare/workers-types"]
|
|
6
9
|
},
|
|
7
10
|
"include": ["src/**/*"],
|
|
8
11
|
"exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"]
|
package/vitest.config.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config'
|
|
2
|
+
|
|
3
|
+
export default defineWorkersConfig({
|
|
4
|
+
test: {
|
|
5
|
+
// CRITICAL: Limit concurrency to prevent resource exhaustion
|
|
6
|
+
maxConcurrency: 1,
|
|
7
|
+
maxWorkers: 1,
|
|
8
|
+
minWorkers: 1,
|
|
9
|
+
fileParallelism: false,
|
|
10
|
+
|
|
11
|
+
poolOptions: {
|
|
12
|
+
workers: {
|
|
13
|
+
wrangler: { configPath: './wrangler.jsonc' },
|
|
14
|
+
miniflare: {
|
|
15
|
+
compatibilityDate: '2025-01-20',
|
|
16
|
+
compatibilityFlags: ['nodejs_compat_v2'],
|
|
17
|
+
durableObjects: {
|
|
18
|
+
WORKER_STATE: 'WorkerStateDO',
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
|
|
24
|
+
include: ['src/**/*.test.ts', 'test/**/*.test.ts'],
|
|
25
|
+
testTimeout: 60000, // AI calls can take time
|
|
26
|
+
hookTimeout: 30000,
|
|
27
|
+
|
|
28
|
+
// Coverage configuration
|
|
29
|
+
coverage: {
|
|
30
|
+
provider: 'v8',
|
|
31
|
+
reporter: ['text', 'json', 'html'],
|
|
32
|
+
include: ['src/**/*.ts'],
|
|
33
|
+
exclude: ['**/*.test.ts', '**/__tests__/**', '**/node_modules/**'],
|
|
34
|
+
thresholds: {
|
|
35
|
+
statements: 65,
|
|
36
|
+
branches: 60,
|
|
37
|
+
functions: 60,
|
|
38
|
+
lines: 65,
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
})
|
package/wrangler.jsonc
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
// Wrangler configuration for digital-workers worker tests
|
|
3
|
+
// Used by @cloudflare/vitest-pool-workers for testing
|
|
4
|
+
|
|
5
|
+
"name": "digital-workers",
|
|
6
|
+
"main": "src/worker.ts",
|
|
7
|
+
"compatibility_date": "2025-01-20",
|
|
8
|
+
"compatibility_flags": ["nodejs_compat_v2"],
|
|
9
|
+
|
|
10
|
+
// AI binding for Cloudflare Workers AI
|
|
11
|
+
// Enables real AI Gateway access in tests
|
|
12
|
+
"ai": {
|
|
13
|
+
"binding": "AI"
|
|
14
|
+
},
|
|
15
|
+
|
|
16
|
+
// Durable Objects for worker state management
|
|
17
|
+
"durable_objects": {
|
|
18
|
+
"bindings": [
|
|
19
|
+
{ "name": "WORKER_STATE", "class_name": "WorkerStateDO" }
|
|
20
|
+
]
|
|
21
|
+
},
|
|
22
|
+
|
|
23
|
+
// Migrations for Durable Objects
|
|
24
|
+
"migrations": [
|
|
25
|
+
{ "tag": "v1", "new_classes": ["WorkerStateDO"] }
|
|
26
|
+
],
|
|
27
|
+
|
|
28
|
+
// The default export (DigitalWorkersService) extends WorkerEntrypoint
|
|
29
|
+
// All public methods are automatically exposed via RPC
|
|
30
|
+
|
|
31
|
+
// Environment variables for AI Gateway
|
|
32
|
+
// These are loaded from .dev.vars or .env in local development
|
|
33
|
+
"vars": {
|
|
34
|
+
// Placeholder - actual values come from .dev.vars
|
|
35
|
+
}
|
|
36
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 .org.ai
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
package/src/actions.js
DELETED
|
@@ -1,436 +0,0 @@
|
|
|
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
|
-
}
|