@oomol-lab/open-flow 0.1.0-beta.75 → 0.1.0-beta.77

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 (146) hide show
  1. package/README.md +3 -1
  2. package/dist/browser/{ContentIcon-FCpKiwjp.js → ContentIcon-VZQO8VZU.js} +9 -6
  3. package/dist/browser/{FlowCanvas-dzRBnlUT.js → FlowCanvas-BNGDMaWr.js} +75 -63
  4. package/dist/browser/{createResourceDialog-BeYDdUl-.js → createResourceDialog-BmtakfVg.js} +63 -57
  5. package/dist/browser/{dialog-ZtpsFbl4.js → dialog-BcFBfRB1.js} +126 -32
  6. package/dist/browser/{exportSvg-DqXw1yf-.js → exportSvg-CG8hEUNk.js} +2 -2
  7. package/dist/browser/{flowChanges-b_5UobFj.js → flowChanges-BGo_4Ypo.js} +6063 -11285
  8. package/dist/browser/{flowWorkspace-ItojZbO4.js → flowWorkspace-BFHGev7s.js} +1065 -2570
  9. package/dist/browser/preview.css +626 -653
  10. package/dist/browser/preview.js +1907 -9663
  11. package/dist/browser/theme.css +117 -263
  12. package/dist/browser/{tooltip-wZJRB9oP.js → tooltip-BAWSUexx.js} +2 -2
  13. package/dist/browser/{typeScriptSession-CSRwWmZm.js → typeScriptSession-CRoezJPN.js} +1 -1
  14. package/dist/browser/ui.css +464 -463
  15. package/dist/browser/ui.js +4 -3
  16. package/dist/browser/workbench.css +9891 -9897
  17. package/dist/browser/workbench.d.ts +6 -2
  18. package/dist/browser/workbench.js +838 -499
  19. package/dist/browser/{workbenchSelect-M441Lz0d.js → workbenchSelect-CjK-xdm3.js} +2 -2
  20. package/dist/command/index.js +48 -50
  21. package/dist/common/authoring.d.ts +5 -5
  22. package/dist/common/authoringExamples.d.ts +3 -2
  23. package/dist/common/authoringSchema.d.ts +26 -4
  24. package/dist/common/connector-proxy.d.ts +1 -1
  25. package/dist/common/control-api-conformance.js +352 -144
  26. package/dist/common/control-api-errors.d.ts +12 -0
  27. package/dist/common/control-api.d.ts +38 -4
  28. package/dist/common/control-api.js +373 -162
  29. package/dist/common/control-requests.d.ts +22 -3
  30. package/dist/common/control-requests.js +268 -28
  31. package/dist/common/cron-trigger.d.ts +2 -1
  32. package/dist/common/decision.d.ts +4 -4
  33. package/dist/common/decision.js +5 -2
  34. package/dist/common/engine-contract.d.ts +6 -1
  35. package/dist/common/event-source-definition.d.ts +1 -1
  36. package/dist/common/event-source-view.d.ts +22 -0
  37. package/dist/common/event-source.d.ts +1 -1
  38. package/dist/common/event-source.js +24 -65
  39. package/dist/common/event-sources.d.ts +0 -21
  40. package/dist/common/flow-authoring.js +90 -20
  41. package/dist/common/flow-change-schema.d.ts +9 -1
  42. package/dist/common/flow-change.d.ts +8 -202
  43. package/dist/common/flow-change.js +96 -24
  44. package/dist/common/flow-encoding.js +89 -21
  45. package/dist/common/flow-input-value.d.ts +1 -1
  46. package/dist/common/flow-model.d.ts +121 -0
  47. package/dist/common/flow-notifications.d.ts +1 -1
  48. package/dist/common/flow-retry.d.ts +2 -4
  49. package/dist/common/flow-semantics.js +161 -80
  50. package/dist/common/flow-state.d.ts +123 -0
  51. package/dist/common/flow-state.js +5852 -0
  52. package/dist/common/flow-workflowReferences.d.ts +8 -0
  53. package/dist/common/flowInspection.d.ts +1 -1
  54. package/dist/common/http-hosts.d.ts +6 -0
  55. package/dist/common/http-request.d.ts +13 -5
  56. package/dist/common/http-request.js +23 -5
  57. package/dist/common/integration-trigger.d.ts +2 -1
  58. package/dist/common/mcp.d.ts +96 -3
  59. package/dist/common/mcp.js +355 -142
  60. package/dist/common/openapi.d.ts +4 -4
  61. package/dist/common/openapi.js +4 -1
  62. package/dist/common/poll-trigger.d.ts +2 -1
  63. package/dist/common/run-events.js +1 -0
  64. package/dist/common/runtime-contract.d.ts +37 -1
  65. package/dist/common/runtime-contract.js +717 -72
  66. package/dist/common/runtime-nodejs-compat.d.ts +44 -0
  67. package/dist/common/runtime-nodejs-compat.js +5870 -0
  68. package/dist/common/scheduler-checkpoint.d.ts +1 -1
  69. package/dist/common/scheduler-node-execution.d.ts +2 -1
  70. package/dist/common/scheduler.d.ts +2 -2
  71. package/dist/common/scheduler.js +76 -6
  72. package/dist/common/state-conformance.d.ts +16 -0
  73. package/dist/common/tags.d.ts +4 -0
  74. package/dist/common/trigger-catalog.d.ts +1 -7
  75. package/dist/common/trigger-config-options.d.ts +1 -1
  76. package/dist/common/trigger-config.d.ts +1 -1
  77. package/dist/common/trigger-contract.d.ts +2 -1
  78. package/dist/common/trigger-localization.d.ts +8 -2
  79. package/dist/common/trigger-model.d.ts +101 -0
  80. package/dist/common/webhook-response.d.ts +1 -1
  81. package/dist/common/webhook-trigger.d.ts +3 -1
  82. package/dist/common/workflow.d.ts +3 -12
  83. package/dist/common/workflow.js +25 -23
  84. package/dist/index.d.ts +52 -14
  85. package/package.json +9 -1
  86. package/src/base/common/json.ts +1 -1
  87. package/src/connector/common/proxy.ts +1 -1
  88. package/src/control/common/api.ts +90 -16
  89. package/src/control/common/authoring.ts +6 -1
  90. package/src/control/common/authoringExamples.ts +8 -0
  91. package/src/control/common/authoringSchema.ts +26 -13
  92. package/src/control/common/authoringTools.ts +1 -1
  93. package/src/control/common/conformance.ts +1 -1
  94. package/src/control/common/connectorDecoders.ts +1 -1
  95. package/src/control/common/errors.ts +6 -0
  96. package/src/control/common/eventSources.ts +2 -29
  97. package/src/control/common/flowDecoders.ts +1 -0
  98. package/src/control/common/mcp.ts +16 -0
  99. package/src/control/common/requests.ts +10 -2
  100. package/src/control/common/tags.ts +20 -0
  101. package/src/control/common/triggerCatalog.ts +1 -8
  102. package/src/decision/common/decision.ts +15 -7
  103. package/src/event-source/common/definition.ts +1 -1
  104. package/src/event-source/common/index.ts +1 -1
  105. package/src/event-source/common/view.ts +20 -0
  106. package/src/execution/common/checkpoint.ts +1 -1
  107. package/src/execution/common/events.ts +3 -0
  108. package/src/execution/common/node-execution.ts +4 -1
  109. package/src/execution/common/scheduler.ts +3 -1
  110. package/src/flow/common/change.ts +60 -193
  111. package/src/flow/common/changeSchema.ts +39 -4
  112. package/src/flow/common/connectionUsage.ts +1 -1
  113. package/src/flow/common/errorHandling.ts +1 -1
  114. package/src/flow/common/inputValue.ts +1 -1
  115. package/src/flow/common/model.ts +130 -0
  116. package/src/flow/common/modules.ts +1 -1
  117. package/src/flow/common/portChanges.ts +1 -1
  118. package/src/flow/common/retry.ts +2 -4
  119. package/src/flow/common/semantics.ts +31 -4
  120. package/src/flow/common/webhookResponse.ts +1 -1
  121. package/src/flow/common/workflowReferences.ts +31 -0
  122. package/src/http/common/authBindings.ts +6 -9
  123. package/src/http/common/hosts.ts +13 -0
  124. package/src/http/common/httpRequest.ts +30 -15
  125. package/src/openapi/common/openapi.ts +9 -5
  126. package/src/{execution → runtime}/common/engineContract.ts +23 -15
  127. package/src/runtime/common/nodejsCompat.ts +275 -0
  128. package/src/runtime/common/nodejsGuest.generated.json +47 -0
  129. package/src/runtime/common/runtime.ts +1254 -0
  130. package/src/state/common/conformance.ts +86 -0
  131. package/src/state/common/state.ts +169 -0
  132. package/src/trigger/common/config.ts +1 -1
  133. package/src/trigger/common/configOptions.ts +1 -1
  134. package/src/trigger/common/contract.ts +2 -1
  135. package/src/trigger/common/cron.ts +2 -1
  136. package/src/trigger/common/integration.ts +2 -1
  137. package/src/trigger/common/model.ts +87 -0
  138. package/src/trigger/common/poll.ts +2 -1
  139. package/src/trigger/common/webhook.ts +3 -1
  140. package/src/trigger/providers/fieldDescriptions.ts +1 -1
  141. package/src/trigger/providers/localization.ts +9 -2
  142. package/src/trigger/providers/remote.ts +1 -1
  143. package/src/types/index.ts +55 -15
  144. package/src/workflow/common/workflow.ts +3 -44
  145. package/src/execution/common/runtime.ts +0 -563
  146. /package/src/{control → connector}/common/providerIconSprite.ts +0 -0
@@ -0,0 +1,1254 @@
1
+ import type { CodeModule, ConnectorCapability, TaskCapability, JsonValue } from '../../flow/common/model.ts'
2
+
3
+ import { dequal } from 'dequal/lite'
4
+ import { currentEngineContract } from './engineContract.ts'
5
+
6
+ export { currentEngineContract, nodejsEngineContract, findEngineContract, type EngineContract } from './engineContract.ts'
7
+
8
+ /** Serialized into the guest; keep validation and helpers self-contained. */
9
+ export function createState(invoke: (kind: string, payload: JsonValue) => Promise<RuntimeCapabilityResponse>) {
10
+ // Serialized into the guest together with this factory.
11
+ // oxlint-disable-next-line unicorn/consistent-function-scoping
12
+ const invalid = (message: string) => Object.assign(new TypeError(message), { code: 'capability.invalid' })
13
+ const keyOf = (key: unknown) => {
14
+ if (typeof key !== 'string' || key.length === 0 || new TextEncoder().encode(key).length > 256) throw invalid('State keys require 1 to 256 UTF-8 bytes.')
15
+ return key
16
+ }
17
+ const valueOf = (value: unknown): JsonValue => {
18
+ if (value === undefined) throw invalid('State values must be JSON.')
19
+ try {
20
+ return (snapshotRuntimeResult({ value }) as { value: JsonValue }).value
21
+ } catch {
22
+ throw invalid('State values must be JSON.')
23
+ }
24
+ }
25
+ const idsOf = (ids: unknown): (string | number)[] => {
26
+ if (!Array.isArray(ids) || !Array.from(ids).every((id) => typeof id === 'string' || (typeof id === 'number' && Number.isFinite(id))))
27
+ throw invalid('Identities must be strings or finite numbers.')
28
+ return ids
29
+ }
30
+ return {
31
+ state: Object.freeze({
32
+ async get(key: unknown) {
33
+ return ((await invoke('state.get', { key: keyOf(key) })).body as { value: JsonValue }).value
34
+ },
35
+ async set(key: unknown, value: unknown) {
36
+ await invoke('state.set', { key: keyOf(key), value: valueOf(value) })
37
+ },
38
+ async insert(key: unknown, value: unknown) {
39
+ if (value === null) throw invalid('State insert does not accept null.')
40
+ return ((await invoke('state.insert', { key: keyOf(key), value: valueOf(value) })).body as { inserted: boolean }).inserted
41
+ },
42
+ async delete(key: unknown) {
43
+ await invoke('state.delete', { key: keyOf(key) })
44
+ },
45
+ async list() {
46
+ return ((await invoke('state.list', {})).body as { keys: string[] }).keys
47
+ },
48
+ }),
49
+ dedupe: Object.freeze({
50
+ async insert(ids: unknown) {
51
+ return ((await invoke('dedupe.insert', { ids: idsOf(ids) })).body as { inserted: boolean[] }).inserted
52
+ },
53
+ async has(ids: unknown) {
54
+ return ((await invoke('dedupe.has', { ids: idsOf(ids) })).body as { present: boolean[] }).present
55
+ },
56
+ }),
57
+ }
58
+ }
59
+
60
+ export type RuntimeModule = Pick<CodeModule, 'imports' | 'source'>
61
+
62
+ /** Snapshot a Task result before JSON transport can discard or coerce invalid values. */
63
+ export function snapshotRuntimeResult(value: unknown): JsonValue | undefined {
64
+ // This function is also serialized into the isolated runtime; keep it self-contained.
65
+ const parents = new Set<object>()
66
+ const copy = (item: unknown, depth: number): JsonValue => {
67
+ if (depth > 64) throw new Error('Task result exceeds the maximum JSON depth.')
68
+ if (item === null || typeof item == 'string' || typeof item == 'boolean') return item
69
+ if (typeof item == 'number' && Number.isFinite(item)) return item
70
+ if (
71
+ typeof item != 'object' ||
72
+ parents.has(item) ||
73
+ (!Array.isArray(item) && Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null) ||
74
+ Object.getOwnPropertySymbols(item).length > 0
75
+ )
76
+ throw new Error('Task result must contain only JSON values.')
77
+ parents.add(item)
78
+ const result = Array.isArray(item)
79
+ ? Array.from(item, (child) => copy(child, depth + 1))
80
+ : Object.fromEntries(
81
+ Object.entries(item)
82
+ .filter(([, child]) => depth != 0 || child !== undefined)
83
+ .map(([key, child]) => [key, copy(child, depth + 1)]),
84
+ )
85
+ parents.delete(item)
86
+ return result
87
+ }
88
+ return value === undefined ? undefined : copy(value, 0)
89
+ }
90
+
91
+ export const nodejsRuntimeConformanceCases: readonly RuntimeConformanceCase[] = [
92
+ {
93
+ name: 'supports Node builtin imports and asynchronous virtual file operations',
94
+ async verify(harness) {
95
+ const value = await harness.invoke({
96
+ capability: async () => ({ body: null, status: 403 }),
97
+ input: null,
98
+ invocationId: 'nodejs-files',
99
+ program: program(
100
+ harness,
101
+ `import assert from 'node:assert/strict';
102
+ import { Buffer } from 'node:buffer'; import path from 'node:path'; import fs from 'node:fs/promises';
103
+ export default async () => {
104
+ const file = path.join('/tmp', 'conformance.txt');
105
+ await fs.writeFile(file, Buffer.from('你好'));
106
+ const text = await fs.readFile(file, 'utf8');
107
+ assert.equal(text, '你好');
108
+ await fs.unlink(file);
109
+ return { text, bytes: Buffer.byteLength(text) };
110
+ }`,
111
+ ),
112
+ })
113
+ equal(value, { text: '你好', bytes: 6 }, 'Node virtual files')
114
+ },
115
+ },
116
+ {
117
+ name: 'preserves abort reasons and cancels Promise timers',
118
+ async verify(harness) {
119
+ const value = await harness.invoke({
120
+ capability: async () => ({ body: null, status: 403 }),
121
+ input: null,
122
+ invocationId: 'nodejs-abort',
123
+ program: program(
124
+ harness,
125
+ `import { setTimeout } from 'node:timers/promises';
126
+ export default async () => {
127
+ const controller = new AbortController(); const reason = { message: 'stop' };
128
+ const combined = AbortSignal.any([controller.signal]);
129
+ const pending = setTimeout(60000, 'late', { signal: combined });
130
+ controller.abort(reason); controller.abort('ignored');
131
+ let thrown; try { combined.throwIfAborted(); } catch (error) { thrown = error; }
132
+ try { await pending; return false; } catch (error) {
133
+ return { sameReason: combined.reason === reason && thrown === reason, name: error.name };
134
+ }
135
+ }`,
136
+ ),
137
+ })
138
+ equal(value, { sameReason: true, name: 'AbortError' }, 'Node cancellation')
139
+ },
140
+ },
141
+ nodejsCase(
142
+ 'resolves prefixed and bare builtin names to the same module and shares globals with their modules',
143
+ `import { Buffer } from 'node:buffer'; import bare from 'buffer'; import processModule from 'node:process';
144
+ import { URL as ImportedURL, URLSearchParams as ImportedParams } from 'node:url'; import { ReadableStream as ImportedStream } from 'node:stream/web';
145
+ export default () => ({ buffer: Buffer === bare.Buffer && Buffer === globalThis.Buffer, process: process === processModule,
146
+ url: URL === ImportedURL && URLSearchParams === ImportedParams, stream: ReadableStream === ImportedStream,
147
+ cwd: process.cwd(), env: Object.keys(process.env) })`,
148
+ { buffer: true, process: true, url: true, stream: true, cwd: '/tmp', env: [] },
149
+ ),
150
+ nodejsCase(
151
+ 'supports events, string decoding, paths, query strings, URLs and promisify',
152
+ `import { EventEmitter } from 'node:events'; import { StringDecoder } from 'node:string_decoder'; import { Buffer } from 'node:buffer';
153
+ import path from 'node:path'; import qs from 'node:querystring'; import { promisify } from 'node:util';
154
+ export default async () => {
155
+ const emitter = new EventEmitter(); let count = 0; emitter.once('value', (x) => (count += x)); emitter.emit('value', 7); emitter.emit('value', 9);
156
+ const decoder = new StringDecoder('utf8'); const bytes = Buffer.from('你好');
157
+ const incremental = new TextDecoder(); const partial = incremental.decode(new Uint8Array([0xe4, 0xbd]), { stream: true });
158
+ const url = new URL('../文件?a=1', 'https://example.com/a/b'); url.searchParams.append('b', 'x y');
159
+ return { count, text: decoder.write(bytes.subarray(0, 2)) + decoder.end(bytes.subarray(2)), partial, rest: incremental.decode(new Uint8Array([0xa0])),
160
+ path: path.join('/tmp', 'a', '..', 'b'), query: qs.parse('a=1&a=2').a, url: url.href, canParse: URL.canParse('not a url'),
161
+ value: await promisify((callback) => callback(null, 42))() };
162
+ }`,
163
+ {
164
+ count: 7,
165
+ text: '你好',
166
+ partial: '',
167
+ rest: '你',
168
+ path: '/tmp/b',
169
+ query: ['1', '2'],
170
+ url: 'https://example.com/%E6%96%87%E4%BB%B6?a=1&b=x+y',
171
+ canParse: false,
172
+ value: 42,
173
+ },
174
+ ),
175
+ nodejsCase(
176
+ 'encodes Buffers and computes hashes, HMACs, gzip and random values',
177
+ `import { Buffer } from 'node:buffer'; import { createHash, createHmac, randomBytes } from 'node:crypto'; import { gzipSync, gunzipSync, deflateRawSync, inflateRawSync } from 'node:zlib';
178
+ export default () => ({ hex: Buffer.from('你好').toString('hex'), base64: Buffer.from('abc').toString('base64'), latin1: Buffer.from([0xe9]).toString('latin1'),
179
+ utf16: Buffer.from('a', 'utf16le').length, hash: createHash('sha256').update('a').update('bc').digest('hex'),
180
+ md5: createHash('md5').update('abc').digest('base64'), hmac: createHmac('sha256', 'key').update('message').digest('hex'),
181
+ gzip: gunzipSync(gzipSync(Buffer.from('你好'))).toString(), raw: inflateRawSync(deflateRawSync('raw')).toString(),
182
+ random: randomBytes(12).length, uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(crypto.randomUUID()),
183
+ values: crypto.getRandomValues(new Uint8Array(4)).length })`,
184
+ {
185
+ hex: 'e4bda0e5a5bd',
186
+ base64: 'YWJj',
187
+ latin1: 'é',
188
+ utf16: 2,
189
+ hash: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
190
+ md5: 'kAFQmDzST7DWlj99KOF/cg==',
191
+ hmac: '6e9ef29b75fffc5b7abae527d58fdadb2fe42e7219011976917343065f58ed4a',
192
+ gzip: '你好',
193
+ raw: 'raw',
194
+ random: 12,
195
+ uuid: true,
196
+ values: 4,
197
+ },
198
+ ),
199
+ nodejsCase(
200
+ 'provides an invocation-local filesystem with Node error codes',
201
+ `import fs from 'node:fs'; import fsp from 'node:fs/promises';
202
+ export default async () => {
203
+ await fsp.mkdir('/tmp/nested', { recursive: true });
204
+ fs.writeFileSync('/tmp/nested/data', '你好');
205
+ const handle = await fsp.open('/tmp/nested/data', 'r'); const data = await handle.readFile('utf8'); await handle.close();
206
+ await fsp.rename('/tmp/nested/data', '/tmp/nested/moved');
207
+ let missing; try { fs.readFileSync('/etc/passwd'); } catch (error) { missing = error.code; }
208
+ return { data, size: fs.statSync('/tmp/nested/moved').size, entries: fs.readdirSync('/tmp/nested'), missing };
209
+ }`,
210
+ { data: '你好', size: 6, entries: ['moved'], missing: 'ENOENT' },
211
+ ),
212
+ nodejsCase(
213
+ 'runs timers, Node streams, pipelines and Web Streams',
214
+ `import { setTimeout as delay } from 'node:timers/promises'; import { Readable, Writable } from 'node:stream'; import { pipeline } from 'node:stream/promises';
215
+ export default async () => {
216
+ let count = 0; const timer = setInterval(() => { count++; clearInterval(timer) }, 1); const removed = setTimeout(() => { count += 100 }, 1); clearTimeout(removed);
217
+ await delay(10);
218
+ const data = []; for await (const chunk of Readable.from(['a', 'b'])) data.push(chunk);
219
+ let piped = ''; await pipeline(Readable.from(['x', 'y']), new Writable({ write(chunk, _encoding, callback) { piped += chunk.toString(); callback() } }));
220
+ const reader = new ReadableStream({ start(controller) { controller.enqueue('web'); controller.close() } }).getReader();
221
+ return { count, data, piped, web: (await reader.read()).value };
222
+ }`,
223
+ { count: 1, data: ['a', 'b'], piped: 'xy', web: 'web' },
224
+ ),
225
+ nodejsCase(
226
+ 'supports AbortSignal timeout and pre-aborted signals',
227
+ `import { setTimeout as delay } from 'node:timers/promises';
228
+ export default async () => { const timeout = AbortSignal.timeout(1); await delay(10); return { timeout: timeout.reason.name, aborted: AbortSignal.abort().aborted } }`,
229
+ { timeout: 'TimeoutError', aborted: true },
230
+ ),
231
+ nodejsCase(
232
+ 'encodes and decodes text larger than one builtin transfer and creates many decoders',
233
+ `export default () => {
234
+ const text = '你😀a'.repeat(400000); const bytes = new TextEncoder().encode(text);
235
+ const decoder = new TextDecoder(); let streamed = '';
236
+ for (let offset = 0; offset < bytes.length; offset += 1000003) streamed += decoder.decode(bytes.subarray(offset, offset + 1000003), { stream: true });
237
+ streamed += decoder.decode();
238
+ let decoded = 0; for (let index = 0; index < 300; index++) decoded += new TextDecoder().decode(new Uint8Array([0x61])).length;
239
+ return { bytes: bytes.length, whole: new TextDecoder().decode(bytes) === text, streamed: streamed === text, decoded };
240
+ }`,
241
+ { bytes: 3_200_000, whole: true, streamed: true, decoded: 300 },
242
+ ),
243
+ {
244
+ name: 'isolates files, globals and builtin module state between Task invocations',
245
+ async verify(harness) {
246
+ const invoke = async (invocationId: string, source: string) =>
247
+ await harness.invoke({
248
+ capability: async () => ({ body: null, status: 403 }),
249
+ input: null,
250
+ invocationId,
251
+ program: program(harness, source),
252
+ })
253
+ await invoke(
254
+ 'nodejs-isolation-write',
255
+ `import fs from 'node:fs'; import crypto from 'node:crypto';
256
+ export default () => { fs.writeFileSync('/tmp/marker', 'x'); URL.prototype.taskMarker = true; crypto.constants.taskMarker = true; globalThis.taskMarker = true }`,
257
+ )
258
+ const value = await invoke(
259
+ 'nodejs-isolation-read',
260
+ `import fs from 'node:fs'; import crypto from 'node:crypto';
261
+ export default () => ({ file: fs.existsSync('/tmp/marker'), url: 'taskMarker' in URL.prototype, module: 'taskMarker' in crypto.constants, global: 'taskMarker' in globalThis })`,
262
+ )
263
+ equal(value, { file: false, url: false, module: false, global: false }, 'Task isolation')
264
+ },
265
+ },
266
+ ]
267
+
268
+ /** Reference Artifact Host for the guest chunk protocol; deployments own storage, identity and limits. */
269
+ function artifactHost() {
270
+ const chunkBytes = 512 * 1024
271
+ const uploads = new Map<string, Uint8Array[]>()
272
+ const artifacts = new Map<string, Uint8Array>()
273
+ const kinds: string[] = []
274
+ let nextUpload = 0
275
+ const capability = async (call: RuntimeCapabilityCall): Promise<RuntimeCapabilityResponse> => {
276
+ kinds.push(call.kind)
277
+ const payload = call.payload as Readonly<Record<string, JsonValue>>
278
+ if (call.kind == 'artifact.write') {
279
+ const upload = typeof payload.upload == 'string' ? payload.upload : `u${++nextUpload}`
280
+ uploads.set(upload, [...(uploads.get(upload) ?? []), decodeBase64(payload.data!)])
281
+ return { body: { upload }, status: 200 }
282
+ }
283
+ if (call.kind == 'artifact.put') {
284
+ const parts = [...(typeof payload.upload == 'string' ? (uploads.get(payload.upload) ?? []) : []), decodeBase64(payload.data!)]
285
+ const bytes = new Uint8Array(parts.reduce((size, part) => size + part.length, 0))
286
+ parts.reduce((offset, part) => (bytes.set(part, offset), offset + part.length), 0)
287
+ const id = `a${artifacts.size + 1}`
288
+ artifacts.set(id, bytes)
289
+ return {
290
+ body: {
291
+ kind: 'artifact',
292
+ id,
293
+ name: payload.name!,
294
+ size: bytes.length,
295
+ digest: artifactDigest(id),
296
+ ...(payload.mediaType == null ? {} : { mediaType: payload.mediaType }),
297
+ },
298
+ status: 200,
299
+ }
300
+ }
301
+ if (call.kind == 'artifact.read') {
302
+ const bytes = artifacts.get(String(payload.id))!
303
+ const offset = Number(payload.offset)
304
+ return { body: { data: encodeBase64(bytes.subarray(offset, offset + chunkBytes)), size: bytes.length }, status: 200 }
305
+ }
306
+ throw new Error(`Unexpected Capability ${call.kind}.`)
307
+ }
308
+ return { capability, digest: artifactDigest, kinds: () => kinds }
309
+ }
310
+
311
+ function decodeBase64(text: JsonValue): Uint8Array {
312
+ return Uint8Array.from(atob(String(text)), (character) => character.charCodeAt(0))
313
+ }
314
+
315
+ function encodeBase64(bytes: Uint8Array): string {
316
+ return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''))
317
+ }
318
+
319
+ function artifactDigest(id: string): string {
320
+ return `sha256:${id.slice(1).padStart(64, '0')}`
321
+ }
322
+
323
+ function nodejsCase(name: string, source: string, expected: JsonValue): RuntimeConformanceCase {
324
+ return {
325
+ name,
326
+ async verify(harness) {
327
+ const value = await harness.invoke({
328
+ capability: async () => ({ body: null, status: 403 }),
329
+ input: null,
330
+ invocationId: `nodejs-${name}`,
331
+ program: program(harness, source),
332
+ })
333
+ equal(value, expected, name)
334
+ },
335
+ }
336
+ }
337
+
338
+ export interface RuntimeProgram {
339
+ readonly engineContract: string
340
+ readonly engineDigest: string
341
+ readonly entryModuleId: string
342
+ readonly modules: Readonly<Record<string, RuntimeModule>>
343
+ }
344
+
345
+ export interface RuntimeCapabilityCall {
346
+ readonly nodeId?: string
347
+ readonly jobId?: string
348
+ readonly callId: string
349
+ readonly invocationId: string
350
+ readonly kind: string
351
+ readonly payload: JsonValue
352
+ readonly signal: AbortSignal
353
+ }
354
+
355
+ export interface RuntimeCapabilityResponse {
356
+ readonly body: JsonValue
357
+ readonly status: number
358
+ }
359
+
360
+ export interface LlmTaskInvocation {
361
+ readonly input: Readonly<Record<string, JsonValue>>
362
+ readonly invocationId: string
363
+ readonly mode: 'chat' | 'json'
364
+ readonly signal: AbortSignal
365
+ readonly version: 1
366
+ }
367
+
368
+ export type LlmTaskResult =
369
+ | { readonly kind: 'completed'; readonly value: JsonValue; readonly version: 1 }
370
+ | {
371
+ readonly retryable?: boolean
372
+ readonly code: 'llm.output-invalid' | 'llm.unavailable'
373
+ readonly kind: 'failed'
374
+ readonly message: string
375
+ readonly version: 1
376
+ }
377
+
378
+ export type InvokeLlmTask = (invocation: LlmTaskInvocation) => Promise<LlmTaskResult>
379
+
380
+ export interface AgentCheckpoint {
381
+ readonly state: JsonValue
382
+ readonly callId: string
383
+ readonly toolId: string
384
+ readonly input: Readonly<Record<string, JsonValue>>
385
+ readonly rounds: number
386
+ readonly version: 1
387
+ }
388
+
389
+ export type AgentResult = { readonly kind: 'completed'; readonly output: JsonValue } | { readonly kind: 'suspended'; readonly checkpoint: AgentCheckpoint }
390
+
391
+ export interface AgentInvocation {
392
+ readonly input: Readonly<Record<string, JsonValue>>
393
+ readonly invocationId: string
394
+ readonly signal: AbortSignal
395
+ readonly resume?: { readonly action: 'approve' | 'reject'; readonly checkpoint: AgentCheckpoint }
396
+ }
397
+
398
+ export interface RuntimeInvocation {
399
+ readonly capabilities?: readonly TaskCapability[]
400
+ readonly capability: (call: RuntimeCapabilityCall) => Promise<RuntimeCapabilityResponse>
401
+ readonly input: JsonValue
402
+ readonly invocationId: string
403
+ readonly program: RuntimeProgram
404
+ readonly signal?: AbortSignal
405
+ }
406
+
407
+ export interface RuntimeHarness {
408
+ readonly engineDigest: string
409
+ invoke(invocation: RuntimeInvocation): Promise<JsonValue | undefined>
410
+ }
411
+
412
+ export interface RuntimeConformanceCase {
413
+ readonly name: string
414
+ verify(harness: RuntimeHarness): Promise<void>
415
+ }
416
+
417
+ function program(harness: RuntimeHarness, source: string, modules: Readonly<Record<string, RuntimeModule>> = {}): RuntimeProgram {
418
+ return {
419
+ engineContract: currentEngineContract,
420
+ engineDigest: harness.engineDigest,
421
+ entryModuleId: 'main',
422
+ modules: {
423
+ ...modules,
424
+ main: { imports: Object.keys(modules), source },
425
+ },
426
+ }
427
+ }
428
+
429
+ function equal(actual: unknown, expected: unknown, message: string): void {
430
+ if (!dequal(actual, expected)) {
431
+ throw new Error(`${message}: expected ${JSON.stringify(expected)}, received ${JSON.stringify(actual)}.`)
432
+ }
433
+ }
434
+
435
+ async function rejects(operation: Promise<unknown>, pattern: RegExp, message: string): Promise<void> {
436
+ try {
437
+ await operation
438
+ } catch (error) {
439
+ if (pattern.test(error instanceof Error ? error.message : String(error))) return
440
+ throw new Error(`${message}: received ${error instanceof Error ? error.message : String(error)}.`, { cause: error })
441
+ }
442
+ throw new Error(`${message}: operation unexpectedly succeeded.`)
443
+ }
444
+
445
+ export const runtimeConformanceCases: readonly RuntimeConformanceCase[] = [
446
+ {
447
+ name: 'cancels detached State work when its Task finishes',
448
+ async verify(harness) {
449
+ let aborted = false
450
+ const result = await harness.invoke({
451
+ input: null,
452
+ invocationId: 'state-detached',
453
+ capability: async ({ signal }) =>
454
+ await new Promise((resolve) => {
455
+ signal.addEventListener(
456
+ 'abort',
457
+ () => {
458
+ aborted = true
459
+ resolve({ status: 200, body: null })
460
+ },
461
+ { once: true },
462
+ )
463
+ }),
464
+ program: program(
465
+ harness,
466
+ `export default async (_, context) => {
467
+ void context.state.set('detached', 1);
468
+ await new Promise(resolve => setTimeout(resolve, 20));
469
+ return null;
470
+ }`,
471
+ ),
472
+ })
473
+ equal(result, null, 'Detached State Task result')
474
+ equal(aborted, true, 'Detached State cancellation')
475
+ },
476
+ },
477
+ {
478
+ name: 'rejects non-JSON State values and invalid identities before Host dispatch',
479
+ async verify(harness) {
480
+ let calls = 0
481
+ const result = await harness.invoke({
482
+ input: null,
483
+ invocationId: 'state-invalid',
484
+ capability: async () => {
485
+ calls += 1
486
+ return { status: 200, body: null }
487
+ },
488
+ program: program(
489
+ harness,
490
+ `export default async (_, context) => {
491
+ const cyclic = {}; cyclic.self = cyclic;
492
+ const invalid = [undefined, NaN, Infinity, new Date(), { x: undefined }, cyclic, [undefined], { x: () => 1 }];
493
+ const errors = [];
494
+ for (const value of invalid) { try { await context.state.set('key', value); errors.push('accepted'); } catch (e) { errors.push(e.code); } }
495
+ for (const call of [() => context.state.get(''), () => context.state.get('x'.repeat(257)), () => context.state.insert('x', null), () => context.dedupe.insert([NaN]), () => context.dedupe.has([null]), () => context.dedupe.insert(new Array(1))]) {
496
+ try { await call(); errors.push('accepted'); } catch (e) { errors.push(e.code); }
497
+ }
498
+ return errors;
499
+ }`,
500
+ ),
501
+ })
502
+ equal(
503
+ result,
504
+ Array.from({ length: 14 }, () => 'capability.invalid'),
505
+ 'State boundary validation',
506
+ )
507
+ equal(calls, 0, 'State invalid dispatch')
508
+ },
509
+ },
510
+ {
511
+ name: 'rejects Task results that JSON transport would discard or coerce',
512
+ async verify(harness) {
513
+ for (const expression of [
514
+ '{ value: () => 42 }',
515
+ '{ value: Symbol("value") }',
516
+ '{ value: NaN }',
517
+ '{ value: Infinity }',
518
+ '{ value: 1n }',
519
+ '{ value: { nested: undefined } }',
520
+ '{ value: [undefined] }',
521
+ '{ value: Array(1) }',
522
+ '{ value: new Date() }',
523
+ '{ value: { toJSON() { return "hidden" } } }',
524
+ '{ [Symbol("key")]: 1 }',
525
+ '(() => { const value = {}; value.self = value; return { value } })()',
526
+ ]) {
527
+ await rejects(
528
+ harness.invoke({
529
+ capability: async () => ({ body: null, status: 200 }),
530
+ input: null,
531
+ invocationId: 'invalid-task-result',
532
+ program: program(harness, `export default () => (${expression})`),
533
+ }),
534
+ /Task result must contain only JSON values/,
535
+ `Invalid Task result: ${expression}`,
536
+ )
537
+ }
538
+ },
539
+ },
540
+ {
541
+ name: 'snapshots JSON results while preserving missing ports and shared values',
542
+ async verify(harness) {
543
+ const value = await harness.invoke({
544
+ capability: async () => ({ body: null, status: 200 }),
545
+ input: null,
546
+ invocationId: 'json-task-result',
547
+ program: program(
548
+ harness,
549
+ `export default () => {
550
+ const shared = { text: 'hello', values: [1, true, null] };
551
+ return { missing: undefined, nullable: null, first: shared, second: shared };
552
+ }`,
553
+ ),
554
+ })
555
+ const shared = { text: 'hello', values: [1, true, null] }
556
+ equal(value, { nullable: null, first: shared, second: shared }, 'JSON Task result')
557
+ },
558
+ },
559
+ {
560
+ name: 'preserves Action error codes and fixed per-call Connection selection',
561
+ async verify(harness) {
562
+ const declarations: readonly ConnectorCapability[] = [
563
+ {
564
+ kind: 'connector',
565
+ action: 'example.echo',
566
+ connections: [{ connectionId: 'work', alias: 'office' }, { connectionId: 'home' }],
567
+ },
568
+ ]
569
+ const result = await harness.invoke({
570
+ capabilities: declarations,
571
+ capability: async ({ payload }) => {
572
+ const selected = resolveAction(declarations, payload)
573
+ if (selected.input.fail) throw Object.assign(new Error('Provider unavailable.'), { code: 'connector.unavailable' })
574
+ return { body: selected.connectionId ?? null, status: 200 }
575
+ },
576
+ input: null,
577
+ invocationId: 'action-accounts',
578
+ program: program(
579
+ harness,
580
+ `export default async (_, context) => {
581
+ const values = await Promise.all([
582
+ context.actions.example.echo({}, { connectionAlias: 'office' }),
583
+ context.actions['example.echo']({}, { connectionId: 'home' }),
584
+ ])
585
+ try { await context.actions.example.echo({ fail: true }, { connectionId: 'work' }) }
586
+ catch (error) { values.push(error.code) }
587
+ return values
588
+ }`,
589
+ ),
590
+ })
591
+ equal(result, ['work', 'home', 'connector.unavailable'], 'Action selection and recovery')
592
+ },
593
+ },
594
+ {
595
+ name: 'shares Action entries and assigns independent concurrent call identities',
596
+ async verify(harness) {
597
+ const calls: RuntimeCapabilityCall[] = []
598
+ const value = await harness.invoke({
599
+ capabilities: [{ kind: 'connector', action: 'example.echo', connections: [] }],
600
+ capability: async (call) => {
601
+ calls.push(call)
602
+ return { body: call.payload, status: 200 }
603
+ },
604
+ input: null,
605
+ invocationId: 'action-calls',
606
+ program: program(
607
+ harness,
608
+ `export default async (_input, context) => {
609
+ const call = context.actions.example.echo
610
+ return { same: call === context.actions['example.echo'], values: await Promise.all([call({ value: 1 }), call({ value: 2 }), call({ value: 3 })]) }
611
+ }`,
612
+ ),
613
+ })
614
+ equal(value, { same: true, values: [1, 2, 3].map((item) => ({ action: 'example.echo', input: { value: item } })) }, 'Action results')
615
+ equal(new Set(calls.map((call) => call.callId)).size, 3, 'Independent Action identities')
616
+ equal(
617
+ calls.map((call) => call.invocationId),
618
+ ['action-calls', 'action-calls', 'action-calls'],
619
+ 'Task identity',
620
+ )
621
+ },
622
+ },
623
+
624
+ {
625
+ name: 'loads the fixed ESM closure and platform module',
626
+ async verify(harness) {
627
+ const value = await harness.invoke({
628
+ capability: async () => {
629
+ throw new Error('Capability must not be called.')
630
+ },
631
+ input: { value: 6 },
632
+ invocationId: 'module-closure',
633
+ program: program(
634
+ harness,
635
+ `import { double } from './helper.mjs'
636
+ import { engineContract, identity } from 'open-flow:platform'
637
+ export default (input) => ({ engineContract, value: identity(double(input.value)) })`,
638
+ { helper: { imports: [], source: 'export const double = (value) => value * 2' } },
639
+ ),
640
+ })
641
+ equal(value, { engineContract: currentEngineContract, value: 12 }, 'ESM closure result')
642
+ },
643
+ },
644
+ {
645
+ name: 'rejects modules outside the fixed closure',
646
+ async verify(harness) {
647
+ await rejects(
648
+ harness.invoke({
649
+ capability: async () => ({ body: null, status: 200 }),
650
+ input: null,
651
+ invocationId: 'closed-linker',
652
+ program: program(
653
+ harness,
654
+ `import { execSync } from 'node:child_process'
655
+ export default () => execSync('cat /etc/passwd').toString()`,
656
+ ),
657
+ }),
658
+ /invalid|unsupported|cannot import|not part of/i,
659
+ 'Closed linker',
660
+ )
661
+ },
662
+ },
663
+ {
664
+ name: 'copies asynchronous Capability requests and responses',
665
+ async verify(harness) {
666
+ const calls: RuntimeCapabilityCall[] = []
667
+ const value = await harness.invoke({
668
+ capabilities: [{ kind: 'connector', action: 'example.read', connections: [] }],
669
+ capability: async (call) => {
670
+ calls.push(call)
671
+ return { body: { accepted: true, echoed: call.payload }, status: 200 }
672
+ },
673
+ input: { issue: 42 },
674
+ invocationId: 'async-capability',
675
+ program: program(harness, `export default async (input, context) => context.actions.example.read(input)`),
676
+ })
677
+ equal(value, { accepted: true, echoed: { action: 'example.read', input: { issue: 42 } } }, 'Capability result')
678
+ equal(
679
+ calls.map(({ invocationId, kind, payload }) => ({ invocationId, kind, payload })),
680
+ [{ invocationId: 'async-capability', kind: 'connector', payload: { action: 'example.read', input: { issue: 42 } } }],
681
+ 'Capability request',
682
+ )
683
+ },
684
+ },
685
+ {
686
+ name: 'stores and reads Artifacts through bounded chunks',
687
+ async verify(harness) {
688
+ const host = artifactHost()
689
+ const value = await harness.invoke({
690
+ capability: host.capability,
691
+ input: null,
692
+ invocationId: 'artifact-roundtrip',
693
+ program: program(
694
+ harness,
695
+ `export default async (_input, context) => {
696
+ const large = new Uint8Array(1200 * 1024).map((_, index) => index % 251)
697
+ const text = await context.artifact.put('你好', { name: 'greeting.txt', mediaType: 'text/plain' })
698
+ const binary = await context.artifact.put(large, { name: 'data.bin' })
699
+ const empty = await context.artifact.put(new Uint8Array(0), { name: 'empty' })
700
+ const read = await context.artifact.open(binary)
701
+ return { text, binary, empty, greeting: new TextDecoder().decode(await context.artifact.open(text)),
702
+ same: read.length == large.length && read.every((byte, index) => byte == large[index]), emptyLength: (await context.artifact.open(empty)).length }
703
+ }`,
704
+ ),
705
+ })
706
+ const ref = (id: string, name: string, size: number, mediaType?: string) => ({
707
+ kind: 'artifact',
708
+ id,
709
+ name,
710
+ size,
711
+ digest: host.digest(id),
712
+ ...(mediaType == null ? {} : { mediaType }),
713
+ })
714
+ equal(
715
+ value,
716
+ {
717
+ text: ref('a1', 'greeting.txt', 6, 'text/plain'),
718
+ binary: ref('a2', 'data.bin', 1200 * 1024),
719
+ empty: ref('a3', 'empty', 0),
720
+ greeting: '你好',
721
+ same: true,
722
+ emptyLength: 0,
723
+ },
724
+ 'Artifact roundtrip',
725
+ )
726
+ equal(
727
+ host.kinds(),
728
+ [
729
+ 'artifact.put',
730
+ 'artifact.write',
731
+ 'artifact.write',
732
+ 'artifact.put',
733
+ 'artifact.put',
734
+ 'artifact.read',
735
+ 'artifact.read',
736
+ 'artifact.read',
737
+ 'artifact.read',
738
+ 'artifact.read',
739
+ ],
740
+ 'Artifact chunks',
741
+ )
742
+ },
743
+ },
744
+ {
745
+ name: 'rejects invalid Artifact arguments before Host dispatch',
746
+ async verify(harness) {
747
+ const host = artifactHost()
748
+ const value = await harness.invoke({
749
+ capability: host.capability,
750
+ input: null,
751
+ invocationId: 'artifact-invalid',
752
+ program: program(
753
+ harness,
754
+ `export default async (_input, context) => {
755
+ const codes = []
756
+ for (const call of [() => context.artifact.put({}, { name: 'x' }), () => context.artifact.put('x', {}), () => context.artifact.put('x', { name: 'x', mediaType: 1 }), () => context.artifact.open({ id: 'a1' })]) {
757
+ try { await call() } catch (error) { codes.push(error.code) }
758
+ }
759
+ return codes
760
+ }`,
761
+ ),
762
+ })
763
+ equal(
764
+ value,
765
+ Array.from({ length: 4 }, () => 'capability.invalid'),
766
+ 'Artifact validation',
767
+ )
768
+ equal(host.kinds(), [], 'Artifact dispatch')
769
+ },
770
+ },
771
+ {
772
+ name: 'calls declared HTTP hosts through context.fetch',
773
+ async verify(harness) {
774
+ const calls: JsonValue[] = []
775
+ const value = await harness.invoke({
776
+ capability: async (call) => {
777
+ calls.push({ kind: call.kind, payload: call.payload })
778
+ return {
779
+ status: 200,
780
+ body: {
781
+ status: 201,
782
+ statusText: 'Created',
783
+ url: 'https://api.example.com/items?q=1',
784
+ headers: [
785
+ ['content-type', 'application/json'],
786
+ ['x-tag', 'a'],
787
+ ['x-tag', 'b'],
788
+ ],
789
+ body: btoa('{"id":7}'),
790
+ },
791
+ }
792
+ },
793
+ input: null,
794
+ invocationId: 'code-fetch',
795
+ program: program(
796
+ harness,
797
+ `export default async (_input, context) => {
798
+ const response = await context.fetch(new URL('https://api.example.com/items?q=1'), { method: 'post', headers: [['X-Trace', '1']], body: '{"name":"a"}' })
799
+ const json = await response.json()
800
+ let reused; try { await response.text() } catch (error) { reused = error instanceof TypeError }
801
+ const codes = []
802
+ for (const call of [() => context.fetch('https://api.example.com', { method: 'TRACE' }), () => context.fetch('https://api.example.com', { body: 'x' }),
803
+ () => context.fetch('https://api.example.com', { method: 'POST', body: {} }), () => context.fetch('https://api.example.com', { headers: { 'bad header': 'x' } }),
804
+ () => context.fetch('https://api.example.com', { method: 'PUT', body: new Uint8Array(1024 * 1024 + 1) })]) {
805
+ try { await call() } catch (error) { codes.push(error.code) }
806
+ }
807
+ return { status: response.status, ok: response.ok, statusText: response.statusText, url: response.url, redirected: response.redirected, json, reused,
808
+ tag: response.headers.get('X-Tag'), has: response.headers.has('content-type'), names: [...response.headers.keys()], codes, egress: typeof context.egress }
809
+ }`,
810
+ ),
811
+ })
812
+ equal(
813
+ value,
814
+ {
815
+ status: 201,
816
+ ok: true,
817
+ statusText: 'Created',
818
+ url: 'https://api.example.com/items?q=1',
819
+ redirected: false,
820
+ json: { id: 7 },
821
+ reused: true,
822
+ tag: 'a, b',
823
+ has: true,
824
+ names: ['content-type', 'x-tag', 'x-tag'],
825
+ codes: Array.from({ length: 5 }, () => 'capability.invalid'),
826
+ egress: 'undefined',
827
+ },
828
+ 'Fetch response',
829
+ )
830
+ equal(
831
+ calls,
832
+ [
833
+ {
834
+ kind: 'http.fetch',
835
+ payload: {
836
+ url: 'https://api.example.com/items?q=1',
837
+ method: 'POST',
838
+ headers: [
839
+ ['x-trace', '1'],
840
+ ['content-type', 'text/plain;charset=UTF-8'],
841
+ ],
842
+ body: btoa('{"name":"a"}'),
843
+ },
844
+ },
845
+ ],
846
+ 'Fetch request',
847
+ )
848
+ },
849
+ },
850
+ {
851
+ name: 'returns final outputs without exposing intermediate output capability',
852
+ async verify(harness) {
853
+ const value = await harness.invoke({
854
+ capability: async () => {
855
+ throw new Error('Capability must not be called.')
856
+ },
857
+ input: null,
858
+ invocationId: 'final-outputs',
859
+ program: program(
860
+ harness,
861
+ `export default async (_input, context) => ({ available: typeof context.outputs, previous: await context.getPrevious(), value: 1 })`,
862
+ ),
863
+ })
864
+ equal(value, { available: 'undefined', previous: [], value: 1 }, 'Final Task outputs')
865
+ },
866
+ },
867
+ {
868
+ name: 'cancels a pending Capability and the user invocation',
869
+ async verify(harness) {
870
+ const cancellation = new AbortController()
871
+ let capabilityAborted = false
872
+ let capabilityStarted!: () => void
873
+ const started = new Promise<void>((resolve) => {
874
+ capabilityStarted = resolve
875
+ })
876
+ const invoked = harness.invoke({
877
+ capabilities: [{ kind: 'connector', action: 'example.wait', connections: [] }],
878
+ capability: async ({ signal }) => {
879
+ capabilityStarted()
880
+ return await new Promise<RuntimeCapabilityResponse>((_resolve, reject) =>
881
+ signal.addEventListener(
882
+ 'abort',
883
+ () => {
884
+ capabilityAborted = true
885
+ reject(signal.reason)
886
+ },
887
+ { once: true },
888
+ ),
889
+ )
890
+ },
891
+ input: null,
892
+ invocationId: 'canceled-capability',
893
+ program: program(harness, `export default async (_input, context) => context.actions.example.wait({})`),
894
+ signal: cancellation.signal,
895
+ })
896
+ await started
897
+ cancellation.abort(new Error('Invocation canceled.'))
898
+ await rejects(invoked, /cancel|abort|disposed/i, 'Canceled invocation')
899
+ equal(capabilityAborted, true, 'Capability cancellation')
900
+ },
901
+ },
902
+ ]
903
+
904
+ export function createActions(invoke: (payload: JsonValue) => Promise<RuntimeCapabilityResponse>): Readonly<Record<string, unknown>> {
905
+ // Keep validation inside the function serialized into the isolated runtime.
906
+ // eslint-disable-next-line unicorn/consistent-function-scoping
907
+ const json = (value: unknown, parents: Set<object>): void => {
908
+ if (value === null || typeof value == 'string' || typeof value == 'boolean' || (typeof value == 'number' && Number.isFinite(value))) return
909
+ if (
910
+ typeof value != 'object' ||
911
+ parents.has(value) ||
912
+ (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) ||
913
+ Object.getOwnPropertySymbols(value).length > 0
914
+ )
915
+ throw Object.assign(new Error('Action parameters must contain only JSON values.'), { code: 'capability.invalid' })
916
+ parents.add(value)
917
+ for (const child of Array.isArray(value) ? value : Object.values(value)) json(child, parents)
918
+ parents.delete(value)
919
+ }
920
+ const target: Record<string, unknown> = Object.create(null)
921
+ const calls = new Map<string, (input?: JsonValue, options?: JsonValue) => Promise<JsonValue>>()
922
+ const providers = new Map<string, Readonly<Record<string, unknown>>>()
923
+ const actionCall = (action: string): ((input?: JsonValue, options?: JsonValue) => Promise<JsonValue>) => {
924
+ let call = calls.get(action)
925
+ if (call != null) return call
926
+ call = async (input: JsonValue = {}, options?: JsonValue): Promise<JsonValue> => {
927
+ json(input, new Set())
928
+ if (options !== undefined) json(options, new Set())
929
+ const response = await invoke({ action, input, ...(options === undefined ? {} : { options }) })
930
+ return response.body
931
+ }
932
+ calls.set(action, call)
933
+ return call
934
+ }
935
+ target.call = async (action: JsonValue, input: JsonValue = {}, options?: JsonValue): Promise<JsonValue> => {
936
+ if (typeof action != 'string') throw Object.assign(new Error('Action ID must be a string.'), { code: 'capability.invalid' })
937
+ return actionCall(action)(input, options)
938
+ }
939
+ Object.freeze(target)
940
+ return new Proxy(target, {
941
+ get(object, property) {
942
+ if (typeof property != 'string') return Reflect.get(object, property)
943
+ if (Object.hasOwn(object, property)) return object[property]
944
+ if (property.includes('.')) return actionCall(property)
945
+ let methods = providers.get(property)
946
+ if (methods == null) {
947
+ const provider = property
948
+ const providerTarget = Object.freeze(Object.create(null) as Record<string, unknown>)
949
+ methods = new Proxy(providerTarget, {
950
+ get(_object, name) {
951
+ return typeof name == 'string' ? actionCall(`${provider}.${name}`) : undefined
952
+ },
953
+ })
954
+ providers.set(property, methods)
955
+ }
956
+ return methods
957
+ },
958
+ })
959
+ }
960
+
961
+ export function resolveAction(
962
+ declarations: readonly ConnectorCapability[],
963
+ payload: unknown,
964
+ ): { readonly action: string; readonly connectionId?: string; readonly input: Readonly<Record<string, JsonValue>> } {
965
+ const invalid = Object.assign(new Error('The Action request is invalid.'), { code: 'capability.invalid' })
966
+ const denied = Object.assign(new Error('The Action or Connection is unavailable for this Code node.'), { code: 'capability.denied' })
967
+ if (payload == null || typeof payload != 'object' || Array.isArray(payload)) throw invalid
968
+ const source = payload as Record<string, JsonValue>
969
+ if (
970
+ Object.keys(source).some((key) => !['action', 'input', 'options'].includes(key)) ||
971
+ typeof source.action != 'string' ||
972
+ !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_.-]+$/.test(source.action) ||
973
+ source.input == null ||
974
+ typeof source.input != 'object' ||
975
+ Array.isArray(source.input)
976
+ )
977
+ throw invalid
978
+ const permissions = declarations.find((declaration) => 'mode' in declaration)
979
+ const allowed = permissions?.mode == 'independent' ? permissions.actions.find((entry) => entry.action == source.action) : undefined
980
+ if (permissions?.mode == 'independent' && allowed == null) throw denied
981
+ const hints = declarations.flatMap((declaration) => {
982
+ if ('mode' in declaration) return []
983
+ if ('action' in declaration) {
984
+ if (declaration.action != source.action) return []
985
+ return [
986
+ ...declaration.connections.flatMap((connection) =>
987
+ connection.alias == null ? [] : [{ action: declaration.action, connectionId: connection.connectionId, alias: connection.alias }],
988
+ ),
989
+ ...(declaration.connectionId == null ? [] : [{ action: declaration.action, connectionId: declaration.connectionId }]),
990
+ ]
991
+ }
992
+ return declaration.connectionHints?.filter((hint) => hint.action == source.action) ?? []
993
+ })
994
+ let connectionId = hints.find((hint) => hint.alias == null)?.connectionId
995
+ if (Object.hasOwn(source, 'options')) {
996
+ if (source.options == null || typeof source.options != 'object' || Array.isArray(source.options)) throw invalid
997
+ const options = source.options as Record<string, JsonValue>
998
+ const keys = Object.keys(options)
999
+ if (keys.length != 1) throw invalid
1000
+ if (typeof options.connectionId == 'string' && options.connectionId.length > 0 && keys[0] == 'connectionId') {
1001
+ connectionId = options.connectionId
1002
+ } else if (typeof options.connectionAlias == 'string' && options.connectionAlias.length > 0 && keys[0] == 'connectionAlias') {
1003
+ connectionId = hints.find((item) => item.alias == options.connectionAlias)?.connectionId
1004
+ if (connectionId == null) throw denied
1005
+ } else throw invalid
1006
+ }
1007
+ if (permissions?.mode == 'independent') {
1008
+ if (connectionId != null && connectionId != allowed?.connectionId) throw denied
1009
+ connectionId = allowed?.connectionId
1010
+ }
1011
+ if (permissions?.mode == 'shared' && Object.hasOwn(source, 'options') && connectionId == null) throw denied
1012
+ return { action: source.action, input: source.input as Readonly<Record<string, JsonValue>>, ...(connectionId == null ? {} : { connectionId }) }
1013
+ }
1014
+
1015
+ export interface DecisionTaskInvocation {
1016
+ readonly questions: readonly import('../../decision/common/decision.ts').DecisionQuestion[]
1017
+ readonly state: JsonValue
1018
+ readonly invocationId: string
1019
+ readonly signal: AbortSignal
1020
+ readonly version: 1
1021
+ }
1022
+ export type InvokeDecisionTask = (invocation: DecisionTaskInvocation) => Promise<LlmTaskResult>
1023
+
1024
+ /**
1025
+ * Serialized into the sandbox before the Capability helpers that use it; keep it self-contained. Encodes in guest
1026
+ * JavaScript, because Node compatibility `atob`/`btoa` route through bounded Host primitives.
1027
+ */
1028
+ export function createBase64() {
1029
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1030
+ const values = new Uint8Array(128).fill(255)
1031
+ for (let index = 0; index < alphabet.length; index++) values[alphabet.charCodeAt(index)] = index
1032
+ return Object.freeze({
1033
+ encode(bytes: Uint8Array): string {
1034
+ const parts: string[] = []
1035
+ for (let start = 0; start < bytes.length; start += 0x6000) {
1036
+ let text = ''
1037
+ for (let index = start; index < Math.min(start + 0x6000, bytes.length); index += 3) {
1038
+ const value = (bytes[index]! << 16) | ((bytes[index + 1] ?? 0) << 8) | (bytes[index + 2] ?? 0)
1039
+ text +=
1040
+ alphabet[value >> 18]! +
1041
+ alphabet[(value >> 12) & 63]! +
1042
+ (index + 1 < bytes.length ? alphabet[(value >> 6) & 63]! : '=') +
1043
+ (index + 2 < bytes.length ? alphabet[value & 63]! : '=')
1044
+ }
1045
+ parts.push(text)
1046
+ }
1047
+ return parts.join('')
1048
+ },
1049
+ decode(text: unknown): Uint8Array {
1050
+ if (typeof text != 'string' || text.length % 4 != 0) throw new TypeError('Base64 content is invalid.')
1051
+ const padding = text.endsWith('==') ? 2 : text.endsWith('=') ? 1 : 0
1052
+ const bytes = new Uint8Array((text.length / 4) * 3 - padding)
1053
+ for (let index = 0, offset = 0; index < text.length; index += 4) {
1054
+ const digits = [0, 1, 2, 3].map((position) => {
1055
+ const code = text.charCodeAt(index + position)
1056
+ if (code == 61 && index + position >= text.length - padding) return 0
1057
+ const value = code < 128 ? values[code]! : 255
1058
+ if (value == 255) throw new TypeError('Base64 content is invalid.')
1059
+ return value
1060
+ })
1061
+ const value = (digits[0]! << 18) | (digits[1]! << 12) | (digits[2]! << 6) | digits[3]!
1062
+ if (offset < bytes.length) bytes[offset++] = value >> 16
1063
+ if (offset < bytes.length) bytes[offset++] = (value >> 8) & 255
1064
+ if (offset < bytes.length) bytes[offset++] = value & 255
1065
+ }
1066
+ return bytes
1067
+ },
1068
+ })
1069
+ }
1070
+
1071
+ /**
1072
+ * Serialized into the sandbox; keep it self-contained. Transfers bytes as base64 chunks through
1073
+ * `artifact.write`, `artifact.put` and `artifact.read` so each Capability message stays bounded.
1074
+ */
1075
+ export function createArtifacts(
1076
+ invoke: (kind: string, payload: JsonValue) => Promise<RuntimeCapabilityResponse>,
1077
+ { decode, encode }: ReturnType<typeof createBase64> = createBase64(),
1078
+ ) {
1079
+ const chunkBytes = 512 * 1024
1080
+ // Keep helpers inside the function serialized into the isolated runtime.
1081
+ // eslint-disable-next-line unicorn/consistent-function-scoping
1082
+ const invalid = (message: string): Error => Object.assign(new TypeError(message), { code: 'capability.invalid' })
1083
+ return Object.freeze({
1084
+ async put(data: unknown, options: unknown): Promise<JsonValue> {
1085
+ const settings = options as { readonly name?: unknown; readonly mediaType?: unknown } | null
1086
+ if (settings == null || typeof settings != 'object' || typeof settings.name != 'string' || settings.name.length == 0)
1087
+ throw invalid('Artifact name is required.')
1088
+ if (settings.mediaType !== undefined && typeof settings.mediaType != 'string') throw invalid('Artifact mediaType must be a string.')
1089
+ const bytes = typeof data == 'string' ? new TextEncoder().encode(data) : data instanceof Uint8Array ? data : undefined
1090
+ if (bytes == null) throw invalid('Artifact data must be a string or Uint8Array.')
1091
+ const tail = bytes.length == 0 ? 0 : Math.floor((bytes.length - 1) / chunkBytes) * chunkBytes
1092
+ let upload: JsonValue | undefined
1093
+ for (let offset = 0; offset < tail; offset += chunkBytes) {
1094
+ const response = await invoke('artifact.write', {
1095
+ ...(upload === undefined ? {} : { upload }),
1096
+ data: encode(bytes.subarray(offset, offset + chunkBytes)),
1097
+ })
1098
+ upload = (response.body as { readonly upload?: JsonValue } | null)?.upload
1099
+ }
1100
+ const response = await invoke('artifact.put', {
1101
+ ...(upload === undefined ? {} : { upload }),
1102
+ name: settings.name,
1103
+ ...(settings.mediaType === undefined ? {} : { mediaType: settings.mediaType }),
1104
+ data: encode(bytes.subarray(tail)),
1105
+ })
1106
+ return response.body
1107
+ },
1108
+ async open(ref: unknown): Promise<Uint8Array> {
1109
+ const artifact = ref as { readonly kind?: unknown; readonly id?: unknown } | null
1110
+ if (artifact == null || typeof artifact != 'object' || artifact.kind != 'artifact' || typeof artifact.id != 'string')
1111
+ throw invalid('An ArtifactRef is required.')
1112
+ const parts: Uint8Array[] = []
1113
+ let offset = 0
1114
+ let size = 0
1115
+ do {
1116
+ const body = (await invoke('artifact.read', { id: artifact.id, offset })).body as { readonly data?: unknown; readonly size?: unknown } | null
1117
+ const part = decode(body?.data)
1118
+ if (typeof body?.size != 'number' || !Number.isSafeInteger(body.size) || (part.length == 0 && offset < body.size))
1119
+ throw new TypeError('Artifact content is invalid.')
1120
+ size = body.size
1121
+ parts.push(part)
1122
+ offset += part.length
1123
+ } while (offset < size)
1124
+ const bytes = new Uint8Array(offset)
1125
+ let position = 0
1126
+ for (const part of parts) {
1127
+ bytes.set(part, position)
1128
+ position += part.length
1129
+ }
1130
+ return bytes
1131
+ },
1132
+ })
1133
+ }
1134
+
1135
+ /**
1136
+ * Serialized into the sandbox; keep it self-contained. `context.fetch` sends one `http.fetch` Capability call per request.
1137
+ * The Host authorizes the URL against the node's `http` Capability, does not follow redirects and adds no credentials.
1138
+ * Request and response bodies are limited to 1 MiB; the response is a read-only subset of the Fetch `Response`.
1139
+ */
1140
+ export function createFetch(
1141
+ invoke: (kind: string, payload: JsonValue) => Promise<RuntimeCapabilityResponse>,
1142
+ { decode, encode }: ReturnType<typeof createBase64> = createBase64(),
1143
+ ) {
1144
+ const maximumBytes = 1024 * 1024
1145
+ const methods = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
1146
+ // Keep helpers inside the function serialized into the isolated runtime.
1147
+ // eslint-disable-next-line unicorn/consistent-function-scoping
1148
+ const invalid = (message: string): Error => Object.assign(new TypeError(message), { code: 'capability.invalid' })
1149
+ // eslint-disable-next-line unicorn/consistent-function-scoping
1150
+ const headerList = (value: unknown): [string, string][] => {
1151
+ if (value == null) return []
1152
+ const pairs =
1153
+ typeof (value as { [Symbol.iterator]?: unknown })[Symbol.iterator] == 'function'
1154
+ ? Array.from(value as Iterable<unknown>, (pair) => {
1155
+ if (!Array.isArray(pair) || pair.length != 2) throw invalid('Headers must be name/value pairs.')
1156
+ return pair
1157
+ })
1158
+ : typeof value == 'object'
1159
+ ? Object.entries(value as Record<string, unknown>)
1160
+ : undefined
1161
+ if (pairs == null) throw invalid('Headers must be an object or name/value pairs.')
1162
+ return pairs.map(([name, text]) => {
1163
+ if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(String(name))) throw invalid(`Invalid header name "${String(name)}".`)
1164
+ return [String(name).toLowerCase(), String(text)]
1165
+ })
1166
+ }
1167
+ return async function fetch(input: unknown, init: unknown = {}): Promise<unknown> {
1168
+ const options = (init ?? {}) as { readonly method?: unknown; readonly headers?: unknown; readonly body?: unknown; readonly signal?: unknown }
1169
+ if (typeof options != 'object') throw invalid('Fetch options must be an object.')
1170
+ const url = String(input instanceof Object && 'href' in input ? (input as { href: unknown }).href : input)
1171
+ const method = String(options.method ?? 'GET').toUpperCase()
1172
+ if (!methods.has(method)) throw invalid(`Unsupported HTTP method "${method}".`)
1173
+ const headers = headerList(options.headers)
1174
+ const body =
1175
+ options.body == null
1176
+ ? undefined
1177
+ : typeof options.body == 'string'
1178
+ ? new TextEncoder().encode(options.body)
1179
+ : options.body instanceof Uint8Array
1180
+ ? options.body
1181
+ : options.body instanceof ArrayBuffer
1182
+ ? new Uint8Array(options.body)
1183
+ : undefined
1184
+ if (options.body != null && body == null) throw invalid('Fetch body must be a string, Uint8Array or ArrayBuffer.')
1185
+ if (body != null && (method == 'GET' || method == 'HEAD')) throw invalid(`A ${method} request cannot have a body.`)
1186
+ if (body != null && body.length > maximumBytes) throw invalid('Fetch request body exceeds 1 MiB.')
1187
+ if (typeof options.body == 'string' && !headers.some(([name]) => name == 'content-type')) headers.push(['content-type', 'text/plain;charset=UTF-8'])
1188
+ const signal = options.signal as { readonly aborted?: boolean; readonly reason?: unknown; addEventListener?: Function } | undefined
1189
+ if (signal?.aborted) throw signal.reason
1190
+ const request = invoke('http.fetch', { url, method, headers, ...(body == null ? {} : { body: encode(body) }) })
1191
+ const result = (
1192
+ signal?.addEventListener == null
1193
+ ? await request
1194
+ : await Promise.race([request, new Promise<never>((_, reject) => signal.addEventListener!('abort', () => reject(signal.reason), { once: true }))])
1195
+ ).body as { readonly status?: unknown; readonly statusText?: unknown; readonly url?: unknown; readonly headers?: unknown; readonly body?: unknown } | null
1196
+ if (
1197
+ result == null ||
1198
+ typeof result.status != 'number' ||
1199
+ typeof result.url != 'string' ||
1200
+ typeof result.body != 'string' ||
1201
+ !Array.isArray(result.headers) ||
1202
+ result.headers.some((pair) => !Array.isArray(pair) || typeof pair[0] != 'string' || typeof pair[1] != 'string')
1203
+ )
1204
+ throw new TypeError('The HTTP response is invalid.')
1205
+ const status = result.status
1206
+ const entries = result.headers as [string, string][]
1207
+ const content = decode(result.body)
1208
+ let used = false
1209
+ const consume = (): Uint8Array => {
1210
+ if (used) throw new TypeError('Response body has already been used.')
1211
+ used = true
1212
+ return content.slice()
1213
+ }
1214
+ const responseHeaders = Object.freeze({
1215
+ get: (name: string) => {
1216
+ const values = entries.filter(([key]) => key == String(name).toLowerCase()).map(([, value]) => value)
1217
+ return values.length == 0 ? null : values.join(', ')
1218
+ },
1219
+ has: (name: string) => entries.some(([key]) => key == String(name).toLowerCase()),
1220
+ entries: () => entries.map(([name, value]) => [name, value])[Symbol.iterator](),
1221
+ keys: () => entries.map(([name]) => name)[Symbol.iterator](),
1222
+ values: () => entries.map(([, value]) => value)[Symbol.iterator](),
1223
+ forEach: (callback: (value: string, name: string) => void) => entries.forEach(([name, value]) => callback(value, name)),
1224
+ [Symbol.iterator]: () => entries.map(([name, value]) => [name, value])[Symbol.iterator](),
1225
+ })
1226
+ return Object.freeze({
1227
+ status,
1228
+ statusText: typeof result.statusText == 'string' ? result.statusText : '',
1229
+ ok: status >= 200 && status < 300,
1230
+ redirected: false,
1231
+ url: result.url,
1232
+ headers: responseHeaders,
1233
+ get bodyUsed() {
1234
+ return used
1235
+ },
1236
+ bytes: async () => consume(),
1237
+ arrayBuffer: async () => consume().buffer,
1238
+ text: async () => new TextDecoder().decode(consume()),
1239
+ json: async () => JSON.parse(new TextDecoder().decode(consume())) as unknown,
1240
+ })
1241
+ }
1242
+ }
1243
+
1244
+ /** Serialized into the sandbox alongside the strict JSON snapshot helper. */
1245
+ export function createWorkflows(invoke: (payload: JsonValue) => Promise<RuntimeCapabilityResponse>) {
1246
+ return Object.freeze({
1247
+ async call(name: string, input: Readonly<Record<string, JsonValue>> = {}): Promise<JsonValue> {
1248
+ if (typeof name != 'string' || input == null || typeof input != 'object' || Array.isArray(input))
1249
+ throw Object.assign(new Error('Workflow name and input object are required.'), { code: 'capability.invalid' })
1250
+ const value = snapshotRuntimeResult(input)!
1251
+ return (await invoke({ name, input: value })).body
1252
+ },
1253
+ })
1254
+ }