@nathanstephenson/flow 0.1.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.
Files changed (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,343 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { constants, mkdirSync, openSync, closeSync, readFileSync, fstatSync, writeFileSync, realpathSync } from 'node:fs';
3
+ import { resolve, relative, isAbsolute } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import ts from 'typescript';
6
+ import { getQuickJS } from 'quickjs-emscripten';
7
+ import { libraries } from "./runtime-libs.js";
8
+ const LIMIT = 100_000;
9
+ const controller = new AbortController();
10
+ let stop = () => { controller.abort(); };
11
+ let lease = setTimeout(() => stop(), 3000);
12
+ const lines = createInterface({ input: process.stdin });
13
+ let started = false;
14
+ lines.on('close', () => stop());
15
+ lines.on('line', line => {
16
+ clearTimeout(lease);
17
+ lease = setTimeout(() => stop(), 3000);
18
+ if (started)
19
+ return;
20
+ started = true;
21
+ void (process.argv.includes('--docker-supervisor') ? dockerSupervisor(JSON.parse(line)) : run(JSON.parse(line))).then(output => finish({ output }), error => finish({ error: error instanceof Error ? error.message : String(error) }));
22
+ });
23
+ function finish(result) {
24
+ clearTimeout(lease);
25
+ process.stdout.write(JSON.stringify(result) + '\n', () => process.exit(0));
26
+ }
27
+ async function dockerSupervisor(config) {
28
+ const child = spawn(config.docker, config.args, { stdio: ['pipe', 'pipe', 'pipe'] });
29
+ let output = '', error = '', stopped = false;
30
+ stop = () => { stopped = true; controller.abort(); child.kill('SIGKILL'); };
31
+ const deadline = setTimeout(stop, config.request.timeout);
32
+ child.stdin.on('error', () => { });
33
+ child.stdin.write(JSON.stringify(config.request) + '\n');
34
+ const heartbeat = setInterval(() => { if (!stopped)
35
+ child.stdin.write('\n'); }, 500);
36
+ child.stdout.setEncoding('utf8').on('data', (chunk) => { output += chunk; });
37
+ child.stderr.setEncoding('utf8').on('data', (chunk) => { error = (error + chunk).slice(-1000); });
38
+ try {
39
+ const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); });
40
+ if (stopped || code !== 0)
41
+ throw new Error(`Docker runtime stopped (${code}): ${error}`);
42
+ const result = JSON.parse(output);
43
+ if (Object.hasOwn(result, 'error'))
44
+ throw new Error(result.error);
45
+ return result.output;
46
+ }
47
+ finally {
48
+ clearInterval(heartbeat);
49
+ clearTimeout(deadline);
50
+ clearTimeout(lease);
51
+ await new Promise((resolve, reject) => {
52
+ const cleanup = spawn(config.docker, ['--host', 'unix:///var/run/docker.sock', 'rm', '--force', config.name], { stdio: ['ignore', 'ignore', 'pipe'], timeout: 5000, killSignal: 'SIGKILL' });
53
+ let error = '';
54
+ cleanup.stderr.on('data', (chunk) => { error = (error + chunk.toString()).slice(-1000); });
55
+ cleanup.once('error', reject);
56
+ cleanup.once('close', code => code === 0 || error.includes('No such container') ? resolve() : reject(new Error(`Docker container cleanup failed: ${error}`)));
57
+ });
58
+ }
59
+ }
60
+ async function run(request) {
61
+ const timer = setTimeout(() => stop(), request.timeout);
62
+ try {
63
+ if (request.kind === 'shell')
64
+ return await shell(request);
65
+ return process.argv.includes('--guest') ? await guest(request) : await supervisedGuest(request);
66
+ }
67
+ finally {
68
+ clearTimeout(timer);
69
+ }
70
+ }
71
+ function supervisedGuest(request) {
72
+ return new Promise((resolve, reject) => {
73
+ const child = spawn(process.execPath, ['--max-old-space-size=128', process.argv[1], '--guest'], { env: { PATH: '/usr/bin:/bin' }, stdio: ['pipe', 'pipe', 'pipe'] });
74
+ let killTimer;
75
+ stop = () => { if (controller.signal.aborted)
76
+ return; controller.abort(); child.stdin.end(); killTimer = setTimeout(() => child.kill('SIGKILL'), 500); };
77
+ let output = '', error = '';
78
+ child.stdin.on('error', () => { });
79
+ child.stdin.write(JSON.stringify(request) + '\n');
80
+ const heartbeat = setInterval(() => { if (!controller.signal.aborted)
81
+ child.stdin.write('\n'); }, 500);
82
+ child.stdout.setEncoding('utf8').on('data', (chunk) => { output += chunk; });
83
+ child.stderr.setEncoding('utf8').on('data', (chunk) => { error = (error + chunk).slice(-1000); });
84
+ child.once('error', reject);
85
+ child.once('close', code => {
86
+ clearInterval(heartbeat);
87
+ clearTimeout(killTimer);
88
+ if (code !== 0 || controller.signal.aborted) {
89
+ reject(new Error(`Guest stopped: ${error}`));
90
+ return;
91
+ }
92
+ try {
93
+ const result = JSON.parse(output);
94
+ if (result.error)
95
+ reject(new Error(result.error));
96
+ else
97
+ resolve(result.output);
98
+ }
99
+ catch (error) {
100
+ reject(error);
101
+ }
102
+ });
103
+ });
104
+ }
105
+ function shell(request) {
106
+ return new Promise((resolveResult, reject) => {
107
+ const child = spawn('/bin/bash', ['--noprofile', '--norc', '-c', 'IFS= read -r -d \'\' OUTPUT\n' + request.command], {
108
+ cwd: request.scope, detached: true, env: { PATH: '/usr/local/bin:/usr/bin:/bin', LANG: 'C.UTF-8', ...request.secrets }, stdio: ['pipe', 'pipe', 'pipe'],
109
+ });
110
+ child.stdin.on('error', () => { });
111
+ child.stdin.end(JSON.stringify(request.input) + '\0');
112
+ let stdout = '', stderr = '', failed = false;
113
+ const kill = () => { if (child.pid) {
114
+ try {
115
+ process.kill(-child.pid, 'SIGKILL');
116
+ }
117
+ catch (error) {
118
+ if (error.code !== 'ESRCH')
119
+ throw error;
120
+ }
121
+ } };
122
+ stop = () => { failed = true; controller.abort(); kill(); };
123
+ for (const [stream, name] of [[child.stdout, 'stdout'], [child.stderr, 'stderr']])
124
+ stream.setEncoding('utf8').on('data', (data) => {
125
+ if (name === 'stdout')
126
+ stdout += data.toString();
127
+ else
128
+ stderr += data.toString();
129
+ });
130
+ child.on('error', reject);
131
+ child.on('exit', kill);
132
+ child.on('close', code => failed ? reject(new Error('Shell stopped')) : resolveResult({ stdout, stderr, exitCode: code ?? 128 }));
133
+ });
134
+ }
135
+ function compile(code, inputType, outputType, names) {
136
+ if (code.length > LIMIT)
137
+ throw new Error('Code limit exceeded');
138
+ const source = `declare const input: ${inputType};\ndeclare const secrets: {${names.map(name => `${JSON.stringify(name)}: string`).join(';')}};\ndeclare const fs: { readText(path: string): Promise<string>; writeText(path: string, text: string): Promise<void>; mkdir(path: string): Promise<void> };\ndeclare function fetch(url: string, options?: {method?: string; headers?: Record<string,string>; body?: string}): Promise<{status: number; ok: boolean; body: string; text(): Promise<string>; json(): Promise<unknown>}>;\nasync function main(): Promise<${outputType}> {\n${code}\n}\nmain();`;
139
+ const file = ts.createSourceFile('/guest.ts', source, ts.ScriptTarget.ES2020, true);
140
+ const visit = (node) => {
141
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node) || ts.isImportEqualsDeclaration(node) || ts.isImportTypeNode(node) || node.kind === ts.SyntaxKind.ImportKeyword)
142
+ throw new Error('Imports are not supported');
143
+ ts.forEachChild(node, visit);
144
+ };
145
+ visit(file);
146
+ const options = { strict: true, target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.None, types: [], noEmitOnError: true, skipLibCheck: true };
147
+ let javascript = '';
148
+ const host = {
149
+ getSourceFile: path => path === '/guest.ts' ? file : libraries[path.replace(/^\//, '')] === undefined ? undefined : ts.createSourceFile(path, libraries[path.replace(/^\//, '')], ts.ScriptTarget.ES2020, true),
150
+ getDefaultLibFileName: () => '/lib.es2020.d.ts', writeFile: (_path, text) => { javascript = text; }, getCurrentDirectory: () => '/', getDirectories: () => [], fileExists: path => path === '/guest.ts' || libraries[path.replace(/^\//, '')] !== undefined,
151
+ readFile: path => libraries[path.replace(/^\//, '')], getCanonicalFileName: path => path, useCaseSensitiveFileNames: () => true, getNewLine: () => '\n',
152
+ };
153
+ const program = ts.createProgram(['/guest.ts'], options, host);
154
+ const errors = ts.getPreEmitDiagnostics(program);
155
+ if (errors.length)
156
+ throw new Error(ts.flattenDiagnosticMessageText(errors[0].messageText, '\n'));
157
+ program.emit();
158
+ return javascript;
159
+ }
160
+ async function guest(request) {
161
+ const deadline = Date.now() + request.timeout;
162
+ const redactError = (value) => {
163
+ if (typeof value === 'string') {
164
+ let text = value;
165
+ for (const secret of Object.values(request.secrets))
166
+ if (secret)
167
+ text = text.split(secret).join('[REDACTED]');
168
+ return text;
169
+ }
170
+ if (Array.isArray(value))
171
+ return value.map(redactError);
172
+ if (value && typeof value === 'object')
173
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [redactError(key), redactError(item)]));
174
+ return value;
175
+ };
176
+ const errorText = (value) => JSON.stringify(redactError(value)) ?? 'Guest execution failed';
177
+ const code = compile(request.code, request.inputType, request.outputType, Object.keys(request.secrets));
178
+ const root = realpathSync(request.scope);
179
+ const descriptors = process.platform === 'linux' ? '/proc/self/fd' : '/dev/fd';
180
+ const scoped = (path, createDirectories, use) => {
181
+ if (!path || isAbsolute(path) || path.includes('\0'))
182
+ throw new Error('Path must be Scope-relative');
183
+ const rel = relative(root, resolve(root, path));
184
+ if (rel === '..' || rel.startsWith('../') || isAbsolute(rel))
185
+ throw new Error('Path escapes Scope');
186
+ const parts = rel.split('/').filter(Boolean);
187
+ const leaf = createDirectories ? '.' : parts.pop() ?? '.';
188
+ let fd = openSync(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
189
+ try {
190
+ for (const part of parts) {
191
+ const next = `${descriptors}/${fd}/${part}`;
192
+ if (createDirectories) {
193
+ try {
194
+ mkdirSync(next, { mode: 0o700 });
195
+ }
196
+ catch (error) {
197
+ if (error.code !== 'EEXIST')
198
+ throw error;
199
+ }
200
+ }
201
+ const child = openSync(next, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
202
+ closeSync(fd);
203
+ fd = child;
204
+ }
205
+ return use(`${descriptors}/${fd}/${leaf}`);
206
+ }
207
+ finally {
208
+ closeSync(fd);
209
+ }
210
+ };
211
+ const operations = {
212
+ readText: async (path) => {
213
+ const fd = scoped(path, false, target => openSync(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK));
214
+ try {
215
+ if (!fstatSync(fd).isFile())
216
+ throw new Error('Only regular files can be read');
217
+ return readFileSync(fd, 'utf8');
218
+ }
219
+ finally {
220
+ closeSync(fd);
221
+ }
222
+ },
223
+ writeText: async (path, text) => {
224
+ if (typeof text !== 'string')
225
+ throw new Error('File content must be text');
226
+ const fd = scoped(path, false, target => openSync(target, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600));
227
+ try {
228
+ writeFileSync(fd, text);
229
+ }
230
+ finally {
231
+ closeSync(fd);
232
+ }
233
+ },
234
+ mkdir: async (path) => { scoped(path, true, () => { }); },
235
+ fetch: async (address, options = {}) => {
236
+ let url = new URL(address);
237
+ for (let redirects = 0; redirects <= 5; redirects++) {
238
+ if (!['http:', 'https:'].includes(url.protocol))
239
+ throw new Error('Only HTTP(S) is supported');
240
+ const response = await fetch(url, { ...options, redirect: 'manual', signal: controller.signal });
241
+ if ([301, 302, 303, 307, 308].includes(response.status) && response.headers.has('location')) {
242
+ await response.body?.cancel();
243
+ const next = new URL(response.headers.get('location'), url);
244
+ if (next.origin !== url.origin)
245
+ options = { ...options, headers: {} };
246
+ if (response.status === 303 || ((response.status === 301 || response.status === 302) && options.method === 'POST')) {
247
+ options = { ...options, method: 'GET' };
248
+ delete options.body;
249
+ }
250
+ url = next;
251
+ continue;
252
+ }
253
+ const chunks = [];
254
+ if (response.body)
255
+ for await (const chunk of response.body) {
256
+ chunks.push(chunk);
257
+ }
258
+ return { status: response.status, body: Buffer.concat(chunks).toString() };
259
+ }
260
+ throw new Error('Redirect limit exceeded');
261
+ },
262
+ };
263
+ const module = await getQuickJS();
264
+ const runtime = module.newRuntime();
265
+ runtime.setMemoryLimit(32 * 1024 * 1024);
266
+ runtime.setMaxStackSize(512 * 1024);
267
+ runtime.setInterruptHandler(() => controller.signal.aborted || Date.now() > deadline);
268
+ const vm = runtime.newContext();
269
+ const pending = new Set();
270
+ let calls = 0;
271
+ const bridge = vm.newFunction('__call', (name, args) => {
272
+ if (++calls > 1000 || pending.size >= 32 || controller.signal.aborted)
273
+ throw new Error('Operation limit exceeded');
274
+ const operation = Object.hasOwn(operations, vm.getString(name)) ? operations[vm.getString(name)] : undefined;
275
+ if (!operation)
276
+ throw new Error('Unknown operation');
277
+ const encoded = vm.getString(args);
278
+ const values = JSON.parse(encoded);
279
+ if (!Array.isArray(values))
280
+ throw new Error('Operation arguments must be an array');
281
+ const promise = vm.newPromise();
282
+ const work = Promise.resolve().then(() => { controller.signal.throwIfAborted(); return operation(...values); }).then(value => {
283
+ const handle = vm.newString(JSON.stringify(value ?? null));
284
+ promise.resolve(handle);
285
+ handle.dispose();
286
+ }, error => { const handle = vm.newError(String(error)); promise.reject(handle); handle.dispose(); }).finally(() => { pending.delete(work); promise.dispose(); });
287
+ pending.add(work);
288
+ return promise.handle;
289
+ });
290
+ vm.setProp(vm.global, '__call', bridge);
291
+ bridge.dispose();
292
+ try {
293
+ const setup = vm.evalCode(`const input = JSON.parse(${JSON.stringify(JSON.stringify(request.input))}); const secrets = JSON.parse(${JSON.stringify(JSON.stringify(request.secrets))}); const fs = Object.freeze(Object.fromEntries(['readText','writeText','mkdir'].map(name => [name, async (...args) => JSON.parse(await __call(name, JSON.stringify(args)))]))); const fetch = async (...args) => { const result = JSON.parse(await __call('fetch', JSON.stringify(args))); return Object.freeze({ ...result, ok: result.status >= 200 && result.status < 300, text: async () => result.body, json: async () => JSON.parse(result.body) }); };`);
294
+ vm.unwrapResult(setup).dispose();
295
+ const result = vm.unwrapResult(vm.evalCode(code));
296
+ try {
297
+ while (true) {
298
+ controller.signal.throwIfAborted();
299
+ const jobs = runtime.executePendingJobs();
300
+ if (jobs.error) {
301
+ const error = vm.dump(jobs.error);
302
+ jobs.error.dispose();
303
+ throw new Error(errorText(error));
304
+ }
305
+ const state = vm.getPromiseState(result);
306
+ if (state.type === 'fulfilled') {
307
+ const stringify = vm.unwrapResult(vm.evalCode('(value) => { const text = JSON.stringify(value, (_key, item) => { if (item === undefined || typeof item === "function" || typeof item === "symbol" || typeof item === "bigint" || (typeof item === "number" && !Number.isFinite(item))) throw Error("Output must be JSON"); return item; }); if (text === undefined) throw Error("Output must be JSON"); return text; }'));
308
+ try {
309
+ const encoded = vm.unwrapResult(vm.callFunction(stringify, vm.undefined, state.value));
310
+ try {
311
+ const text = vm.getString(encoded);
312
+ return JSON.parse(text);
313
+ }
314
+ finally {
315
+ encoded.dispose();
316
+ }
317
+ }
318
+ finally {
319
+ stringify.dispose();
320
+ state.value.dispose();
321
+ }
322
+ }
323
+ if (state.type === 'rejected') {
324
+ const error = vm.dump(state.error);
325
+ state.error.dispose();
326
+ throw new Error(errorText(error));
327
+ }
328
+ if (!pending.size)
329
+ throw new Error('Guest promise cannot settle');
330
+ await Promise.race(pending);
331
+ }
332
+ }
333
+ finally {
334
+ result.dispose();
335
+ }
336
+ }
337
+ finally {
338
+ controller.abort();
339
+ await Promise.allSettled(pending);
340
+ vm.dispose();
341
+ runtime.dispose();
342
+ }
343
+ }