@volter/twin-world 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@volter/twin-world",
3
+ "version": "0.1.0",
4
+ "description": "World configs for twins: boot named local runtimes, allocate ports, generate world.env/instance.json, and run apps against fake-key twin worlds.",
5
+ "keywords": [
6
+ "twin",
7
+ "world",
8
+ "local",
9
+ "fixtures",
10
+ "testing",
11
+ "sdk",
12
+ "api",
13
+ "localstack"
14
+ ],
15
+ "author": "Volter (https://github.com/volter-ai)",
16
+ "license": "Apache-2.0",
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "files": [
21
+ "src",
22
+ "client",
23
+ "test-fixtures",
24
+ "README.md",
25
+ "LICENSE",
26
+ "!test-fixtures/*.SOURCE.md",
27
+ "!src/host-fault-fixture.ts",
28
+ "!**/*.test.ts",
29
+ "!**/*.test.tsx"
30
+ ],
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/volter-ai/twin.git",
34
+ "directory": "packages/twin/world-runtime"
35
+ },
36
+ "homepage": "https://github.com/volter-ai/twin/tree/main/packages/twin/world-runtime#readme",
37
+ "type": "module",
38
+ "exports": {
39
+ ".": "./src/index.ts"
40
+ },
41
+ "bin": {
42
+ "volter-world": "src/cli.ts",
43
+ "volter-world-browser-proxy": "src/browser-proxy-cli.ts",
44
+ "volter-world-host": "src/host-cli.ts"
45
+ },
46
+ "scripts": {
47
+ "test": "bun test src/*.test.ts",
48
+ "typecheck": "tsc --noEmit"
49
+ },
50
+ "dependencies": {
51
+ "@volter/twin": "0.1.0"
52
+ },
53
+ "devDependencies": {
54
+ "@types/bun": "^1.2.20",
55
+ "@types/node": "^24.0.0",
56
+ "typescript": "^5.9.0"
57
+ },
58
+ "engines": {
59
+ "bun": ">=1.2.0"
60
+ }
61
+ }
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env bun
2
+ // @ts-nocheck
3
+ // Browser proxy launcher for fullstack app worlds. This is APP/WORLD orchestration glue
4
+ // (it wires specific app vendors + app URLs from env), so it lives in @volter/twin-world,
5
+ // NOT in the vendor-agnostic kernel — control-plane must never name a vendor (A2). The kernel
6
+ // only exports the vendor-INDEPENDENT `createTwinProxy` utility; choosing which vendors a given
7
+ // app world proxies is the orchestrator's job.
8
+ import { createTwinProxy } from '@volter/twin';
9
+
10
+ const port = Number(process.env.PORT || 0);
11
+ const target = process.env.TARGET_URL;
12
+ if (!target) throw new Error('TARGET_URL is required');
13
+
14
+ const map = {};
15
+ if (process.env.CLERK_TWIN_URL) {
16
+ map.clerk = {
17
+ origin: process.env.CLERK_TWIN_URL,
18
+ apiPathPrefix: '/v1/',
19
+ loaderHost: 'https://api.clerk.com',
20
+ };
21
+ map.clerkLoader = {
22
+ origin: process.env.CLERK_TWIN_URL,
23
+ apiPathPrefix: '/npm/',
24
+ };
25
+ }
26
+ if (process.env.RUNHUMAN_API_URL || process.env.API_URL) {
27
+ map.runhumanApi = {
28
+ origin: process.env.RUNHUMAN_API_URL || process.env.API_URL,
29
+ apiPathPrefix: '/api',
30
+ };
31
+ }
32
+
33
+ const redirectOrigins = [
34
+ process.env.RUNHUMAN_WEB_URL,
35
+ process.env.RUNHUMAN_LEARN_URL,
36
+ process.env.RUNHUMAN_STATIC_URL,
37
+ process.env.RUNHUMAN_API_URL,
38
+ process.env.API_URL,
39
+ ].filter(Boolean);
40
+
41
+ const proxy = createTwinProxy({ target, map, redirectOrigins, port });
42
+ process.stdout.write(`[browser-proxy] http://127.0.0.1:${proxy.port} -> ${target} (${Object.keys(map).join(', ') || 'no browser vendors'})\n`);
43
+ await new Promise(() => {});
package/src/cli.ts ADDED
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env bun
2
+ import { activateScript, checkPrerequisites, doctorWorld, downWorld, formatPrerequisiteChecks, listWorlds, runWithWorldEnv, runWorld, shareWorldServices, shellWorld, statusWorld, unshareWorld, upWorld, urlsWorld } from './index.ts';
3
+ import type { PrerequisiteId } from './index.ts';
4
+
5
+ function optionValue(args: string[], name: string, fallback = ''): string {
6
+ const index = args.indexOf(name);
7
+ return index >= 0 && index + 1 < args.length ? args[index + 1]! : fallback;
8
+ }
9
+
10
+ function printHelp(): void {
11
+ process.stdout.write(`Usage:
12
+ volter-world up <config> --env-file <path> [--name <name>] [--mode local|share|sealed] [--isolation process|colocated|worker] [--root <repo>]
13
+ volter-world down <name> [--grace-ms <ms>] [--purge] [--root <repo>] # SIGTERM, then SIGKILL survivors after the grace (default 5000ms)
14
+ # --purge: after teardown, delete the instance dir (and per-service twin data) too — see docs/DATA_AT_REST.md
15
+ volter-world status <name> [--json] [--root <repo>]
16
+ volter-world doctor <name> [--verify-public] [--json] [--root <repo>]
17
+ volter-world doctor-prereqs --require docker [--json] [--quiet]
18
+ volter-world urls <name> [--json] [--root <repo>]
19
+ volter-world list [--root <repo>]
20
+ volter-world env <name> -- <command...>
21
+ volter-world activate <name> # eval "$(volter-world activate <name>)" — a virtualenv for vendor APIs
22
+ volter-world shell <name> # drop into a subshell with the world active (any CLI hits the twins)
23
+ volter-world run <config> --env-file <path> [--name <name>] [--mode local|share|sealed] [--keep] -- <command...>
24
+ volter-world share <name> [--service app] [--verify /health|--no-verify] [--command <cmd> [-- <args…>]] # {url} in args = the service's local URL
25
+ volter-world unshare <name> [--service app]
26
+
27
+ Configs are stable JSON files, resolved from worlds/configs/<config>.json unless a path is passed.
28
+ `);
29
+ }
30
+
31
+ function printReady(instance: Awaited<ReturnType<typeof upWorld>>): void {
32
+ process.stdout.write(`World ${instance.name} is ready (${instance.config})
33
+
34
+ Services:
35
+ ${Object.values(instance.services).map((service) => ` ${service.id}: ${service.url}`).join('\n')}
36
+
37
+ Env:
38
+ ${instance.envFile}
39
+
40
+ Instance:
41
+ ${instance.dirs.instance}/instance.json
42
+
43
+ Stop:
44
+ volter-world down ${instance.name}
45
+ `);
46
+ }
47
+
48
+ async function main(): Promise<void> {
49
+ const [cmd, subject, ...rest] = process.argv.slice(2);
50
+ const root = optionValue(rest, '--root', process.cwd());
51
+ if (!cmd || cmd === '--help' || cmd === '-h') {
52
+ printHelp();
53
+ return;
54
+ }
55
+
56
+ if (cmd === 'up') {
57
+ if (!subject) throw new Error('volter-world up: missing config');
58
+ const envFile = optionValue(rest, '--env-file');
59
+ if (!envFile) throw new Error('volter-world up: missing required --env-file <path>');
60
+ const name = optionValue(rest, '--name') || undefined;
61
+ const mode = optionValue(rest, '--mode', 'local') as 'local' | 'share' | 'sealed';
62
+ const isolationArg = optionValue(rest, '--isolation');
63
+ if (isolationArg && isolationArg !== 'process' && isolationArg !== 'colocated' && isolationArg !== 'worker') {
64
+ throw new Error(`volter-world up: invalid --isolation "${isolationArg}" (want process|colocated|worker)`);
65
+ }
66
+ const isolation = (isolationArg || undefined) as 'process' | 'colocated' | 'worker' | undefined;
67
+ const instance = await upWorld(subject, { name, root, mode, envFile, ...(isolation ? { isolation } : {}) });
68
+ printReady(instance);
69
+ return;
70
+ }
71
+
72
+ if (cmd === 'down') {
73
+ if (!subject) throw new Error('volter-world down: missing world name');
74
+ const graceArg = optionValue(rest, '--grace-ms');
75
+ if (graceArg && !(Number(graceArg) >= 0)) throw new Error(`volter-world down: invalid --grace-ms "${graceArg}" (want a non-negative number)`);
76
+ const purge = rest.includes('--purge');
77
+ const result = await downWorld(subject, root, {
78
+ ...(graceArg ? { graceMs: Number(graceArg) } : {}),
79
+ ...(purge ? { purge: true } : {}),
80
+ });
81
+ process.stdout.write(`Stopped world ${result.name}${result.stopped.length ? `: ${result.stopped.join(', ')}` : ''}\n`);
82
+ if (result.escalated.length) process.stdout.write(`Escalated to SIGKILL (ignored SIGTERM past the grace): ${result.escalated.join(', ')}\n`);
83
+ if (result.externalErrors.length) {
84
+ for (const message of result.externalErrors) process.stderr.write(`External teardown failed: ${message}\n`);
85
+ }
86
+ if (result.purged) {
87
+ process.stdout.write(`Purged instance data: ${result.purged}\n`);
88
+ } else if (purge && result.externalErrors.length) {
89
+ process.stdout.write(`Refused to purge instance data: an external service's teardown failed (see above) — its down command/discovered env must survive.\n`);
90
+ }
91
+ // Honest exit code (TWIN-61): a silent 0 here is exactly the gap a failed `supabase stop` +
92
+ // `--purge` exploited — a still-running external, a deleted stop recipe, and a green exit.
93
+ if (result.externalErrors.length) process.exitCode = 1;
94
+ return;
95
+ }
96
+
97
+ if (cmd === 'status') {
98
+ if (!subject) throw new Error('volter-world status: missing world name');
99
+ const status = statusWorld(subject, root);
100
+ if (rest.includes('--json')) process.stdout.write(`${JSON.stringify(status, null, 2)}\n`);
101
+ else {
102
+ process.stdout.write(`World ${status.name}: ${status.running ? 'running' : 'stopped'} (${status.config})\n`);
103
+ for (const service of Object.values(status.services)) process.stdout.write(` ${service.id}: ${service.url}\n`);
104
+ }
105
+ return;
106
+ }
107
+
108
+ if (cmd === 'doctor') {
109
+ if (!subject) throw new Error('volter-world doctor: missing world name');
110
+ const report = await doctorWorld(subject, { root, verifyPublic: rest.includes('--verify-public') });
111
+ if (rest.includes('--json')) {
112
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
113
+ } else {
114
+ process.stdout.write(`World ${report.name}: ${report.ok ? 'ok' : 'failed'}\n`);
115
+ for (const check of report.checks) process.stdout.write(` ${check.ok ? 'ok' : 'fail'} ${check.id}: ${check.message}\n`);
116
+ }
117
+ if (!report.ok) process.exit(1);
118
+ return;
119
+ }
120
+
121
+ if (cmd === 'doctor-prereqs') {
122
+ const required = rest.flatMap((arg, index) => arg === '--require' ? [rest[index + 1]] : [])
123
+ .filter(Boolean) as PrerequisiteId[];
124
+ const checks = checkPrerequisites(required.length ? required : ['docker']);
125
+ const ok = checks.every((check) => check.ok);
126
+ if (rest.includes('--json')) {
127
+ process.stdout.write(`${JSON.stringify({ ok, checks }, null, 2)}\n`);
128
+ } else if (!rest.includes('--quiet')) {
129
+ const output = formatPrerequisiteChecks(checks);
130
+ process[ok ? 'stdout' : 'stderr'].write(`${output}\n`);
131
+ }
132
+ if (!ok) process.exit(1);
133
+ return;
134
+ }
135
+
136
+ if (cmd === 'urls') {
137
+ if (!subject) throw new Error('volter-world urls: missing world name');
138
+ const urls = urlsWorld(subject, root);
139
+ if (rest.includes('--json')) {
140
+ process.stdout.write(`${JSON.stringify(urls, null, 2)}\n`);
141
+ } else {
142
+ process.stdout.write(`World ${urls.name} (${urls.mode})\n`);
143
+ for (const [serviceId, service] of Object.entries(urls.services)) {
144
+ process.stdout.write(` ${serviceId}: ${service.localUrl}${service.publicUrl ? ` public=${service.publicUrl}` : ''}\n`);
145
+ }
146
+ }
147
+ return;
148
+ }
149
+
150
+ if (cmd === 'list') {
151
+ for (const world of listWorlds(root)) {
152
+ process.stdout.write(`${world.name}\t${world.running ? 'running' : 'stopped'}\t${world.config ?? ''}\n`);
153
+ }
154
+ return;
155
+ }
156
+
157
+ if (cmd === 'env') {
158
+ if (!subject) throw new Error('volter-world env: missing world name');
159
+ const split = rest.indexOf('--');
160
+ if (split < 0) throw new Error('volter-world env: pass command after --');
161
+ const exitCode = runWithWorldEnv(subject, rest.slice(split + 1), root);
162
+ process.exit(exitCode);
163
+ }
164
+
165
+ if (cmd === 'activate') {
166
+ if (!subject) throw new Error('volter-world activate: missing world name');
167
+ process.stdout.write(activateScript(subject, root));
168
+ return;
169
+ }
170
+
171
+ if (cmd === 'shell') {
172
+ if (!subject) throw new Error('volter-world shell: missing world name');
173
+ process.exit(await shellWorld(subject, root));
174
+ }
175
+
176
+ if (cmd === 'run') {
177
+ if (!subject) throw new Error('volter-world run: missing config');
178
+ const split = rest.indexOf('--');
179
+ if (split < 0) throw new Error('volter-world run: pass command after --');
180
+ const envFile = optionValue(rest, '--env-file');
181
+ if (!envFile) throw new Error('volter-world run: missing required --env-file <path>');
182
+ const name = optionValue(rest, '--name') || undefined;
183
+ const mode = optionValue(rest, '--mode', 'local') as 'local' | 'share' | 'sealed';
184
+ const result = await runWorld(subject, rest.slice(split + 1), { root, name, mode, envFile, keep: rest.includes('--keep') });
185
+ process.exit(result.exitCode);
186
+ }
187
+
188
+ if (cmd === 'share') {
189
+ if (!subject) throw new Error('volter-world share: missing world name');
190
+ const service = optionValue(rest, '--service') || undefined;
191
+ const verifyPath = rest.includes('--no-verify')
192
+ ? false
193
+ : rest.includes('--verify')
194
+ ? optionValue(rest, '--verify', '/health')
195
+ : undefined;
196
+ const split = rest.indexOf('--');
197
+ const command = optionValue(rest, '--command') || undefined;
198
+ if (split >= 0 && !command) throw new Error('volter-world share: -- <args> requires --command <cmd>');
199
+ const args = command && split >= 0 ? rest.slice(split + 1) : undefined;
200
+ const instance = await shareWorldServices(subject, { root, service, verifyPath, command, args });
201
+ const serviceIds = service ? [service] : Object.values(instance.services)
202
+ .filter((candidate) => candidate.publicUrl)
203
+ .map((candidate) => candidate.id);
204
+ for (const serviceId of serviceIds) {
205
+ const shared = instance.services[serviceId];
206
+ process.stdout.write(`${shared?.publicReady ? 'Shared' : 'Shared (unverified)'} ${subject}/${serviceId}: ${shared?.publicUrl}\n`);
207
+ }
208
+ return;
209
+ }
210
+
211
+ if (cmd === 'unshare') {
212
+ if (!subject) throw new Error('volter-world unshare: missing world name');
213
+ const service = optionValue(rest, '--service') || undefined;
214
+ const result = unshareWorld(subject, { root, service });
215
+ process.stdout.write(`Unshared world ${subject}${service ? `/${service}` : ''}\n`);
216
+ if (result.escalated.length) process.stdout.write(`Escalated to SIGKILL (tunnel ignored SIGTERM past the grace): ${result.escalated.join(', ')}\n`);
217
+ return;
218
+ }
219
+
220
+ throw new Error(`Unknown command: ${cmd}`);
221
+ }
222
+
223
+ main().catch((error) => {
224
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
225
+ process.exit(1);
226
+ });
package/src/configs.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { assertWorldConfig, type WorldConfig } from './schema.ts';
4
+
5
+ export function resolveConfigPath(config: string, root = process.cwd()): string {
6
+ const candidates = config.includes('/') || config.endsWith('.json')
7
+ ? [resolve(root, config)]
8
+ : [
9
+ resolve(root, 'worlds/configs', `${config}.json`),
10
+ resolve(root, 'worlds/configs', config, 'world.config.json'),
11
+ resolve(root, `${config}.world.config.json`),
12
+ ];
13
+ const found = candidates.find((candidate) => existsSync(candidate));
14
+ if (!found) {
15
+ throw new Error(`World config not found: ${config}\nTried:\n${candidates.map((candidate) => ` ${candidate}`).join('\n')}`);
16
+ }
17
+ return found;
18
+ }
19
+
20
+ export function loadWorldConfig(config: string, root = process.cwd()): { path: string; config: WorldConfig } {
21
+ const path = resolveConfigPath(config, root);
22
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as unknown;
23
+ return { path, config: assertWorldConfig(parsed, path) };
24
+ }
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env bun
2
+ // volter-world-host: run a set of twins co-located in this single process. The world
3
+ // runtime spawns ONE of these (instead of one bin per twin) when a world selects
4
+ // 'colocated'/'worker' isolation. Each twin is named by a module specifier + export so
5
+ // this stays vendor-agnostic (no pack imports here — dynamic import() resolves them).
6
+ //
7
+ // volter-world-host --isolation worker \
8
+ // --spec stripe|@volter/twin-stripe|createStripeTwinServer|12111|/data/stripe \
9
+ // --spec github|@volter/twin-github|createGithubTwinServer|12112|/data/github
10
+ //
11
+ // Prints one `ready id=<id> port=<port>` line per twin, then `host ready (<n> twins)`.
12
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
13
+ import { dirname, join } from 'node:path';
14
+ import { startColocatedHost, type ColocatedTwinSpec, type HostIsolation } from './host.ts';
15
+
16
+ const argv = process.argv.slice(2);
17
+ const opt = (name: string, fb = ''): string => { const i = argv.indexOf(name); return i >= 0 && argv[i + 1] ? argv[i + 1]! : fb; };
18
+
19
+ const isolation = (opt('--isolation', 'shared') as HostIsolation);
20
+ if (isolation !== 'shared' && isolation !== 'worker') {
21
+ process.stderr.write(`invalid --isolation "${isolation}" (want shared|worker)\n`);
22
+ process.exit(2);
23
+ }
24
+
25
+ const specs: ColocatedTwinSpec[] = [];
26
+ for (let i = 0; i < argv.length; i++) {
27
+ if (argv[i] !== '--spec') continue;
28
+ const raw = argv[i + 1] ?? '';
29
+ const [id, module, exportName, port, root, ro] = raw.split('|');
30
+ if (!id || !module || !exportName || !port || !root) {
31
+ process.stderr.write(`bad --spec "${raw}" (want id|module|export|port|root[|ro])\n`);
32
+ process.exit(2);
33
+ }
34
+ specs.push({ id, module, export: exportName, port: Number(port), root, readOnly: ro === 'ro' });
35
+ }
36
+ if (specs.length === 0) { process.stderr.write('no --spec given\n'); process.exit(2); }
37
+
38
+ // A worker give-up (host.ts fires it on the first crash — never restarted) must be discoverable
39
+ // AFTER the fact, not just as a
40
+ // stdout line — this process IS the world's `instance.json` host child, but it is a SEPARATE OS
41
+ // process from the runtime that wrote instance.json, so it must not rewrite that file directly
42
+ // (the parent may still be mid-write, or rewrite it later — share/unshare both call
43
+ // saveWorldInstance). Instead it writes a small sidecar (`host-gaveup.json`) next to instance.json
44
+ // in the SAME instance dir (already created by upWorld before this child is spawned); `readWorldInstance`
45
+ // merges the sidecar into `services[<id>].workerGaveUp` so every reader (doctor, status, tests) sees
46
+ // the record as if it were in instance.json, without any cross-process write contention.
47
+ // The instance file path is threaded in via VOLTER_WORLD_INSTANCE (set by upWorld for every co-located
48
+ // child). Absent it (e.g. this CLI driven standalone in a unit test), give-up persistence is a no-op —
49
+ // host.test.ts covers shared mode in-process; the give-up mechanics themselves (worker crash →
50
+ // `gaveup` event, never respawned) are covered by the host-isolation / colocated-world integration
51
+ // tests, which spawn this CLI and observe it from the outside.
52
+ const instanceFile = process.env.VOLTER_WORLD_INSTANCE;
53
+ const gaveUpSidecar = instanceFile ? join(dirname(instanceFile), 'host-gaveup.json') : undefined;
54
+
55
+ function recordGaveUp(twin: string, exits: number, detail: string): void {
56
+ if (!gaveUpSidecar) return;
57
+ let all: Record<string, { at: string; exits: number; detail: string }> = {};
58
+ try {
59
+ if (existsSync(gaveUpSidecar)) all = JSON.parse(readFileSync(gaveUpSidecar, 'utf8'));
60
+ } catch {
61
+ // A torn/partial read (e.g. we crashed mid-write previously) — start fresh rather than
62
+ // let a corrupt sidecar wedge future give-ups from ever being recorded.
63
+ }
64
+ all[twin] = { at: new Date().toISOString(), exits, detail };
65
+ // Atomic publish (temp→rename in the SAME dir), the same discipline the kernel/instance.json
66
+ // writers use — a reader never observes a partially-written sidecar.
67
+ mkdirSync(dirname(gaveUpSidecar), { recursive: true });
68
+ const tmp = `${gaveUpSidecar}.${process.pid}.tmp`;
69
+ writeFileSync(tmp, `${JSON.stringify(all, null, 2)}\n`);
70
+ renameSync(tmp, gaveUpSidecar);
71
+ }
72
+
73
+ const host = await startColocatedHost(specs, {
74
+ isolation,
75
+ onEvent: (e) => {
76
+ process.stdout.write(`event twin=${e.twin} kind=${e.kind}${e.detail ? ` detail=${e.detail}` : ''}\n`);
77
+ if (e.kind === 'gaveup') recordGaveUp(e.twin, e.exits ?? 0, e.detail ?? '');
78
+ },
79
+ });
80
+ for (const [id, port] of Object.entries(host.ports)) process.stdout.write(`ready id=${id} port=${port}\n`);
81
+ process.stdout.write(`host ready (${specs.length} twins, isolation=${isolation})\n`);
82
+
83
+ const shutdown = async () => { await host.stop(); process.exit(0); };
84
+ process.on('SIGTERM', shutdown);
85
+ process.on('SIGINT', shutdown);
86
+ await new Promise(() => {});
@@ -0,0 +1,22 @@
1
+ // Worker entry for 'worker' isolation: one Worker thread per twin. It owns its event
2
+ // loop + heap, so a CPU hog / leak / hard crash here is contained to this thread — the
3
+ // host does NOT restart it: it gives up on the worker (fires a `gaveup` event → doctor
4
+ // red) without disturbing sibling twins. Posts {type:'ready'} once listening.
5
+ import { parentPort, workerData } from 'node:worker_threads';
6
+ import type { ColocatedTwinSpec } from './host.ts';
7
+
8
+ const spec = workerData as ColocatedTwinSpec;
9
+
10
+ type TwinServer = { port: number; stop: () => void };
11
+ type TwinServerFactory = (opts: { port?: number; root?: string; readOnly?: boolean }) => TwinServer;
12
+
13
+ const mod = (await import(spec.module)) as Record<string, unknown>;
14
+ const factory = mod[spec.export] as TwinServerFactory | undefined;
15
+ if (typeof factory !== 'function') {
16
+ throw new Error(`Twin "${spec.id}": ${spec.module} has no factory export "${spec.export}"`);
17
+ }
18
+
19
+ const server = factory({ port: spec.port, root: spec.root, readOnly: spec.readOnly });
20
+ parentPort?.postMessage({ type: 'ready', port: server.port });
21
+
22
+ // The Bun.serve listener keeps this worker's event loop alive; nothing else to do.