@worldlabsai/cli 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/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # World Labs CLI
2
+
3
+ Use the World Labs Developer API from a terminal or coding agent with a manually issued API key. The published package has zero npm runtime dependencies; the public SDK is bundled.
4
+
5
+ With Node 24 or newer, install the CLI and configure your key:
6
+
7
+ ```sh
8
+ npm install -g @worldlabsai/cli && worldlabs setup
9
+ ```
10
+
11
+ On Windows, run these commands in Command Prompt.
12
+
13
+ `setup` opens the API keys page, prompts you to paste a new key without echoing it, validates it with `assets.list`, and saves it in a plaintext file in your user configuration directory. It can also install the general skill for Codex or Claude Code; you can skip skill installation. Use `worldlabs setup --help` for options.
14
+
15
+ ## Onboarding
16
+
17
+ ```mermaid
18
+ flowchart TD
19
+ A[Install CLI] --> B[worldlabs setup]
20
+ B --> C[Create API key on website]
21
+ C --> D[Paste key into hidden prompt]
22
+ D --> E[Validate with assets.list]
23
+ E --> F[Save credentials file]
24
+ F --> G[Optionally install Codex or Claude Code skill]
25
+ F --> H[Upload assets and run tasks]
26
+ ```
27
+
28
+ On the API keys page, choose only the scopes required for your work: task submission, asset upload, operation polling, and asset download. The available choices and descriptions appear in the key creation form. The key belongs to the selected project. Store it as a secret; revoke it from the website if it is exposed or no longer needed.
29
+
30
+ ## Commands
31
+
32
+ | Command | Purpose |
33
+ | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
34
+ | `setup [--client codex\|claude-code]` | Configure the API key and optionally install the agent skill. Without `--client`, noninteractive setup skips skill installation. |
35
+ | `auth login [--no-browser]` | Open the API keys page, or print its URL for manual opening. |
36
+ | `auth status` | Check the key through `assets.list` without printing it. This does not validate every generation scope. |
37
+ | `auth logout` | Remove the locally stored key. Revoke the key on the website to invalidate it. |
38
+ | `tasks list` | List tasks available through the public SDK. |
39
+ | `tasks run <name> --request file.json [--idempotency-key key] [--wait] [--timeout seconds]` | Submit a task request; optionally wait for its operation. Some SDK tasks require beta entitlement. |
40
+ | `assets upload file [--mime type]` | Upload a local file. |
41
+ | `assets download id --out file` | Download an asset to a local path. |
42
+ | `assets list [--page-token token]` | List accessible assets. |
43
+ | `operations get id` | Read an operation. |
44
+ | `operations wait id [--timeout seconds]` | Poll an operation until it finishes or the timeout expires. The default timeout is 600 seconds. |
45
+ | `skills install\|uninstall --client codex\|claude-code` | Install or remove the general agent skill. |
46
+
47
+ Use `--request -` to read task JSON from standard input. Results go to stdout; diagnostics go to stderr, so a result can be saved without mixing in progress messages:
48
+
49
+ ```sh
50
+ worldlabs tasks run atlasGenerate --request - --wait --json < request.json > result.json
51
+ ```
52
+
53
+ Use `--json` for machine-readable output. Task submission generates an idempotency key and prints it to stderr before sending the request. Save that value and pass it back with `--idempotency-key` to retry an uncertain submission. The bundled `@worldlabsai/client-next` SDK handles API retries and operation polling.
54
+
55
+ Skill updates and removal refuse to change a directory with local edits or unrelated files. Move a customized `worldlabs` skill aside before reinstalling.
56
+
57
+ The installed skill includes task descriptions and an upload/submit/result example. It points to
58
+ [How To Use Atlas](https://marble5.worldlabs.ai/docs/how-to-use-atlas) for maintained guidance on model inputs, cameras, and task combinations.
59
+
60
+ ## Configuration
61
+
62
+ The CLI uses `https://api.atlas-beta.worldlabs.ai` by default. Saved keys live in separate files per API origin under `~/.config/worldlabs/credentials/`. On macOS/Linux, new directories use mode `700` and new files use mode `600`. On Windows, files inherit the directory permissions. Keys are plaintext, so programs running as your user can read them. `auth status` shows the saved file location.
63
+
64
+ Set `WORLDLABS_CONFIG_DIR` to use another configuration directory, such as a temporary directory for tests. Keep it outside repositories. `WLT_API_KEY` takes precedence over saved keys for automation. Generated Windows skill commands use PowerShell.
65
+
66
+ For development or a nonproduction deployment, set `WORLDLABS_API_ORIGIN` and, when needed, `WORLDLABS_API_KEYS_URL`. The key page defaults to `https://atlas-beta.worldlabs.ai/api-keys`. Do not commit credentials, client IDs, or nonproduction hostnames.
67
+
68
+ See the [World Labs CLI skill](skills/worldlabs/SKILL.md).
package/dist/index.js ADDED
@@ -0,0 +1,963 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { readFileSync } from "node:fs";
5
+ import { parseArgs as parseArgs2 } from "node:util";
6
+
7
+ // ../client/dist/core/sleep.js
8
+ var sleep = async (ms, signal) => {
9
+ if (signal?.aborted) {
10
+ return;
11
+ }
12
+ await new Promise((resolve) => {
13
+ const finish = () => {
14
+ clearTimeout(timer);
15
+ signal?.removeEventListener("abort", finish);
16
+ resolve();
17
+ };
18
+ const timer = setTimeout(finish, ms);
19
+ signal?.addEventListener("abort", finish, { once: true });
20
+ });
21
+ };
22
+
23
+ // ../client/dist/core/transport.js
24
+ var errorDetail = (body) => {
25
+ if (typeof body !== "object" || body === null) {
26
+ return void 0;
27
+ }
28
+ for (const key of ["detail", "message"]) {
29
+ const value = Reflect.get(body, key);
30
+ if (typeof value === "string" && value !== "") {
31
+ return value;
32
+ }
33
+ }
34
+ return void 0;
35
+ };
36
+ var ApiError = class extends Error {
37
+ name = "ApiError";
38
+ /** HTTP status and headers. The response body has already been consumed. */
39
+ response;
40
+ /**
41
+ * Parsed JSON or text for API failures; raw text for upload failures.
42
+ * Empty API response bodies are `undefined`.
43
+ */
44
+ body;
45
+ constructor(response, body) {
46
+ const where = response.url === "" ? "" : ` for ${response.url}`;
47
+ super(`${response.status} ${errorDetail(body) ?? response.statusText}${where}`);
48
+ this.response = response;
49
+ this.body = body;
50
+ }
51
+ };
52
+ var fillPath = (path, params) => path.replaceAll(/\{(?<name>\w+)\}/gu, (_, name) => {
53
+ const value = params[name];
54
+ if (value === void 0) {
55
+ throw new Error(`Missing path parameter "${name}" for ${path}`);
56
+ }
57
+ return encodeURIComponent(value);
58
+ });
59
+ var compose = (middleware, fetch2) => {
60
+ let next = fetch2;
61
+ for (const layer of middleware.toReversed()) {
62
+ const inner = next;
63
+ next = async (request) => await layer(request, inner);
64
+ }
65
+ return next;
66
+ };
67
+ var parseBody = async (response) => {
68
+ const text2 = await response.text();
69
+ if (text2 === "") {
70
+ return void 0;
71
+ }
72
+ try {
73
+ return JSON.parse(text2);
74
+ } catch {
75
+ return text2;
76
+ }
77
+ };
78
+ var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
79
+ var retryDelay = (error, attempt) => {
80
+ const backoff = 1e3 * 2 ** attempt * (0.5 + Math.random() / 2);
81
+ const value = error instanceof ApiError ? error.response.headers.get("retry-after")?.trim() : void 0;
82
+ if (!value) {
83
+ return backoff;
84
+ }
85
+ const delay = /^\d+$/u.test(value) ? Number(value) * 1e3 : Date.parse(value) - Date.now();
86
+ return Math.max(backoff, Number.isFinite(delay) ? delay : 0);
87
+ };
88
+ var createTransport = (options) => {
89
+ const fetch2 = options.fetch ?? (async (request) => await globalThis.fetch(request));
90
+ const send = compose(options.middleware ?? [], fetch2);
91
+ const baseUrl = String(options.baseUrl).replace(/\/+$/u, "");
92
+ const boundParams = options.pathParams ?? {};
93
+ return {
94
+ fetch: fetch2,
95
+ send,
96
+ request: async (path, { body, params, query, retry = false, ...init } = {}) => {
97
+ const url = new URL(baseUrl + fillPath(path, { ...boundParams, ...params }));
98
+ for (const [key, value] of Object.entries(query ?? {})) {
99
+ if (value !== void 0 && value !== null) {
100
+ url.searchParams.set(key, String(value));
101
+ }
102
+ }
103
+ const headers = new Headers(init.headers);
104
+ if (body !== void 0) {
105
+ headers.set("content-type", "application/json");
106
+ }
107
+ const request = new Request(url, {
108
+ ...init,
109
+ headers,
110
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
111
+ });
112
+ let networkError;
113
+ const sendRequest = retry ? compose(options.middleware ?? [], async (attempt) => {
114
+ try {
115
+ return await fetch2(attempt);
116
+ } catch (error) {
117
+ networkError = error;
118
+ throw error;
119
+ }
120
+ }) : send;
121
+ for (let attempt = 0; ; attempt += 1) {
122
+ request.signal.throwIfAborted();
123
+ networkError = void 0;
124
+ try {
125
+ const response = await sendRequest(retry ? request.clone() : request);
126
+ let parsed;
127
+ try {
128
+ parsed = await parseBody(response);
129
+ } catch (error) {
130
+ if (!response.ok) {
131
+ throw new ApiError(response, void 0);
132
+ }
133
+ networkError = error;
134
+ throw error;
135
+ }
136
+ if (!response.ok) {
137
+ throw new ApiError(response, parsed);
138
+ }
139
+ return parsed;
140
+ } catch (error) {
141
+ request.signal.throwIfAborted();
142
+ const transient = error instanceof ApiError ? RETRYABLE_STATUS_CODES.has(error.response.status) : error instanceof TypeError && error === networkError;
143
+ if (!retry || attempt >= 3 || !transient) {
144
+ throw error;
145
+ }
146
+ await sleep(retryDelay(error, attempt), request.signal);
147
+ }
148
+ }
149
+ }
150
+ };
151
+ };
152
+ var withHeader = (request, name, value) => {
153
+ const headers = new Headers(request.headers);
154
+ headers.set(name, value);
155
+ return new Request(request, { headers });
156
+ };
157
+ var apiKeyAuth = (apiKey) => async (request, next) => {
158
+ const key = typeof apiKey === "function" ? await apiKey() : apiKey;
159
+ if (!key)
160
+ throw new Error("No API key is available for the Developer API request");
161
+ return await next(withHeader(request, "WLT-Api-Key", key));
162
+ };
163
+
164
+ // ../client/dist/core/assets.js
165
+ var assetId = (asset) => asset.id;
166
+ var toBlob = (data, mimeType) => {
167
+ if (data instanceof Blob) {
168
+ return mimeType === void 0 || mimeType === data.type ? data : new Blob([data], { type: mimeType });
169
+ }
170
+ return new Blob([data], { type: mimeType ?? "" });
171
+ };
172
+ var createAssets = (transport, assetsPath2) => {
173
+ const itemPath = `${assetsPath2}/{asset}`;
174
+ const create = async (asset, signal) => await transport.request(assetsPath2, {
175
+ body: { asset },
176
+ method: "POST",
177
+ ...signal ? { signal } : {}
178
+ });
179
+ const completeUpload = async (id, body = {}, options = {}) => await transport.request(`${itemPath}:completeUpload`, {
180
+ body,
181
+ method: "POST",
182
+ params: { asset: id },
183
+ ...options
184
+ });
185
+ return {
186
+ /**
187
+ * Finalize an asset after its bytes have been uploaded.
188
+ * @param id - Asset ID from {@link assetId}.
189
+ * @returns The updated asset resource.
190
+ */
191
+ completeUpload,
192
+ /** Create an asset record. Use `upload` to create and upload a single file in one call. */
193
+ create: async (asset, options = {}) => await create(asset, options.signal),
194
+ /**
195
+ * Create a temporary signed URL for reading an asset's stored bytes.
196
+ * @param id - Asset ID from {@link assetId}.
197
+ */
198
+ createReadUrl: async (id, options = {}) => await transport.request(`${itemPath}:createReadUrl`, {
199
+ method: "POST",
200
+ params: { asset: id },
201
+ ...options
202
+ }),
203
+ /**
204
+ * Soft-delete an asset.
205
+ * @param id - Asset ID from {@link assetId}.
206
+ */
207
+ delete: async (id, options = {}) => {
208
+ await transport.request(itemPath, { method: "DELETE", params: { asset: id }, ...options });
209
+ },
210
+ /**
211
+ * Fetch asset metadata.
212
+ * @param id - Asset ID from {@link assetId}.
213
+ */
214
+ get: async (id, options = {}) => await transport.request(itemPath, { params: { asset: id }, ...options }),
215
+ /** Return one page of assets. Pass the response's `nextPageToken` to retrieve the next page. */
216
+ list: async ({ pageSize, pageToken, state, ...options } = {}) => await transport.request(assetsPath2, {
217
+ query: { pageSize, pageToken, state },
218
+ ...options
219
+ }),
220
+ /**
221
+ * Create an asset, upload the bytes, and mark the upload complete.
222
+ *
223
+ * @param data - Bytes to upload. A `Blob` supplies its own MIME type when present.
224
+ * @param options - Display name, MIME type, and cancellation settings.
225
+ * @returns The completed asset. Pass it to {@link assetRef} to use it in a task.
226
+ * @throws {Error} If neither `mimeType` nor the input `Blob` supplies a MIME type.
227
+ * @throws {ApiError} If an API request or storage upload fails with a non-2xx status.
228
+ */
229
+ upload: async (data, { displayName, mimeType, signal }) => {
230
+ const blob = toBlob(data, mimeType);
231
+ if (blob.type === "") {
232
+ throw new Error("upload needs a mimeType when the data does not carry one");
233
+ }
234
+ const init = signal ? { signal } : {};
235
+ const created = await create({ displayName }, signal);
236
+ const id = assetId(created);
237
+ const ticket = await transport.request(`${itemPath}:createUploadUrl`, {
238
+ body: { contentLength: blob.size, contentType: blob.type },
239
+ method: "POST",
240
+ params: { asset: id },
241
+ ...init
242
+ });
243
+ const stored = await transport.fetch(new Request(ticket.uploadUrl, {
244
+ body: blob,
245
+ headers: ticket.headers ?? {},
246
+ method: ticket.method,
247
+ ...init
248
+ }));
249
+ if (!stored.ok) {
250
+ throw new ApiError(stored, await stored.text());
251
+ }
252
+ return await completeUpload(id, { sizeBytes: blob.size }, init);
253
+ }
254
+ };
255
+ };
256
+
257
+ // ../client/dist/core/operations.js
258
+ var DEFAULT_POLL_INTERVAL_MS = 1e3;
259
+ var waitForOperation = async (fetchOperation, { pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, signal } = {}) => {
260
+ for (; ; ) {
261
+ signal?.throwIfAborted();
262
+ const operation = await fetchOperation(signal);
263
+ if (operation.done) {
264
+ return { ...operation, done: true };
265
+ }
266
+ await sleep(pollIntervalMs, signal);
267
+ }
268
+ };
269
+ var createOperations = (transport, operationPath2) => {
270
+ const get = async (operationId, { signal, wait } = {}) => await transport.request(operationPath2, {
271
+ params: { operation: operationId },
272
+ query: { wait },
273
+ ...signal ? { signal } : {}
274
+ });
275
+ return {
276
+ /** Fetch the current state of an operation by its id. */
277
+ get: async (operationId, options = {}) => await get(operationId, options),
278
+ /**
279
+ * Poll until an operation is done. The returned operation keeps the response type
280
+ * associated with the task that created it.
281
+ *
282
+ * An operation can finish with an API-reported task error; inspect `error` before
283
+ * reading `response`. Aborting stops local waiting without canceling the task.
284
+ * HTTP 502, 503, and 504 polling failures are retried up to three times in a row;
285
+ * a successful poll resets the retry count.
286
+ *
287
+ * @param operation - Operation returned by task submission. Completed operations return immediately.
288
+ * @param options - Polling interval and abort signal; no overall timeout by default.
289
+ * @throws {ApiError} If polling fails with an unretried status or exhausts gateway retries.
290
+ */
291
+ wait: async (operation, options) => {
292
+ options?.signal?.throwIfAborted();
293
+ if (operation.done) {
294
+ return { ...operation, done: true };
295
+ }
296
+ let gatewayErrors = 0;
297
+ return await waitForOperation(async (signal) => {
298
+ try {
299
+ const current = await get(operation.id, {
300
+ ...signal ? { signal } : {},
301
+ wait: true
302
+ });
303
+ gatewayErrors = 0;
304
+ return current;
305
+ } catch (error) {
306
+ gatewayErrors += 1;
307
+ if (!(error instanceof ApiError) || ![502, 503, 504].includes(error.response.status) || gatewayErrors > 3) {
308
+ throw error;
309
+ }
310
+ return operation;
311
+ }
312
+ }, options);
313
+ }
314
+ };
315
+ };
316
+
317
+ // ../client/dist/core/tasks.js
318
+ var submitTask = async (transport, path, body, { idempotencyKey = crypto.randomUUID(), signal, wait } = {}) => {
319
+ if (idempotencyKey.trim() === "") {
320
+ throw new Error("Idempotency key must not be empty");
321
+ }
322
+ return await transport.request(path, {
323
+ body,
324
+ headers: { "Idempotency-Key": idempotencyKey },
325
+ method: "POST",
326
+ query: { wait },
327
+ retry: true,
328
+ ...signal ? { signal } : {}
329
+ });
330
+ };
331
+
332
+ // ../client/dist/generated/tasks.gen.js
333
+ var operationPath = "/api/v2/operations/{operation}";
334
+ var assetsPath = "/api/v2/assets";
335
+ var createTasks = (transport) => ({
336
+ /**
337
+ * Submit the atlasChisel task
338
+ * Retries network failures and HTTP 429/502/503/504 up to three times with the same key and body.
339
+ *
340
+ * @param body - Task inputs and settings.
341
+ * @param options - Abort signal, idempotency key, and server-wait preference.
342
+ * @returns An operation to pass to `client.operations.wait` for the typed result.
343
+ * Check the completed operation's `error` before reading its `response`.
344
+ * @throws {ApiError} If the API rejects the submission or retries are exhausted.
345
+ * @beta Requires beta access for your account.
346
+ */
347
+ atlasChisel: async (body, options) => await submitTask(transport, "/api/v2/tasks:atlasChisel", body, options),
348
+ /**
349
+ * Submit the atlasGenerate task
350
+ * Retries network failures and HTTP 429/502/503/504 up to three times with the same key and body.
351
+ *
352
+ * @param body - Task inputs and settings.
353
+ * @param options - Abort signal, idempotency key, and server-wait preference.
354
+ * @returns An operation to pass to `client.operations.wait` for the typed result.
355
+ * Check the completed operation's `error` before reading its `response`.
356
+ * @throws {ApiError} If the API rejects the submission or retries are exhausted.
357
+ * @beta Requires beta access for your account.
358
+ */
359
+ atlasGenerate: async (body, options) => await submitTask(transport, "/api/v2/tasks:atlasGenerate", body, options),
360
+ /**
361
+ * Submit the atlasMasked task
362
+ * Retries network failures and HTTP 429/502/503/504 up to three times with the same key and body.
363
+ *
364
+ * @param body - Task inputs and settings.
365
+ * @param options - Abort signal, idempotency key, and server-wait preference.
366
+ * @returns An operation to pass to `client.operations.wait` for the typed result.
367
+ * Check the completed operation's `error` before reading its `response`.
368
+ * @throws {ApiError} If the API rejects the submission or retries are exhausted.
369
+ * @beta Requires beta access for your account.
370
+ */
371
+ atlasMasked: async (body, options) => await submitTask(transport, "/api/v2/tasks:atlasMasked", body, options),
372
+ /**
373
+ * Submit the atlasTextToImage task
374
+ * Retries network failures and HTTP 429/502/503/504 up to three times with the same key and body.
375
+ *
376
+ * @param body - Task inputs and settings.
377
+ * @param options - Abort signal, idempotency key, and server-wait preference.
378
+ * @returns An operation to pass to `client.operations.wait` for the typed result.
379
+ * Check the completed operation's `error` before reading its `response`.
380
+ * @throws {ApiError} If the API rejects the submission or retries are exhausted.
381
+ * @beta Requires beta access for your account.
382
+ */
383
+ atlasTextToImage: async (body, options) => await submitTask(transport, "/api/v2/tasks:atlasTextToImage", body, options),
384
+ /**
385
+ * Submit the images2PosedRGBD task
386
+ * Retries network failures and HTTP 429/502/503/504 up to three times with the same key and body.
387
+ *
388
+ * @param body - Task inputs and settings.
389
+ * @param options - Abort signal, idempotency key, and server-wait preference.
390
+ * @returns An operation to pass to `client.operations.wait` for the typed result.
391
+ * Check the completed operation's `error` before reading its `response`.
392
+ * @throws {ApiError} If the API rejects the submission or retries are exhausted.
393
+ * @beta Requires beta access for your account.
394
+ */
395
+ images2PosedRGBD: async (body, options) => await submitTask(transport, "/api/v2/tasks:images2PosedRGBD", body, options),
396
+ /**
397
+ * Submit the splats2Mesh task
398
+ * Retries network failures and HTTP 429/502/503/504 up to three times with the same key and body.
399
+ *
400
+ * @param body - Task inputs and settings.
401
+ * @param options - Abort signal, idempotency key, and server-wait preference.
402
+ * @returns An operation to pass to `client.operations.wait` for the typed result.
403
+ * Check the completed operation's `error` before reading its `response`.
404
+ * @throws {ApiError} If the API rejects the submission or retries are exhausted.
405
+ * @beta Requires beta access for your account.
406
+ */
407
+ splats2Mesh: async (body, options) => await submitTask(transport, "/api/v2/tasks:splats2Mesh", body, options)
408
+ });
409
+
410
+ // ../client/dist/client.js
411
+ var DEFAULT_BASE_URL = "https://api.atlas-beta.worldlabs.ai";
412
+ var createClient = (options) => {
413
+ const middleware = [
414
+ ...options.apiKey === void 0 ? [] : [apiKeyAuth(options.apiKey)],
415
+ ...options.middleware ?? []
416
+ ];
417
+ if (middleware.length === 0) {
418
+ throw new Error("createClient needs an apiKey or middleware that authenticates requests");
419
+ }
420
+ const transport = createTransport({
421
+ baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
422
+ ...options.fetch ? { fetch: options.fetch } : {},
423
+ middleware
424
+ });
425
+ return {
426
+ assets: createAssets(transport, assetsPath),
427
+ operations: createOperations(transport, operationPath),
428
+ tasks: createTasks(transport)
429
+ };
430
+ };
431
+
432
+ // src/config.ts
433
+ var CliError = class extends Error {
434
+ name = "CliError";
435
+ };
436
+ function configuration(env = process.env) {
437
+ const api = checkedUrl(env.WORLDLABS_API_ORIGIN ?? DEFAULT_BASE_URL);
438
+ if (api.pathname !== "/" || api.search || api.hash) {
439
+ throw new CliError(
440
+ "WORLDLABS_API_ORIGIN must be an origin without a path, query, or fragment."
441
+ );
442
+ }
443
+ return {
444
+ apiOrigin: api.origin,
445
+ apiKeysUrl: checkedUrl(env.WORLDLABS_API_KEYS_URL ?? "https://atlas-beta.worldlabs.ai/api-keys").href
446
+ };
447
+ }
448
+ function checkedUrl(value) {
449
+ const url = new URL(value);
450
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
451
+ if (url.username || url.password || url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
452
+ throw new CliError(
453
+ "Use HTTPS, or HTTP on a loopback address for local testing. URL credentials are not allowed."
454
+ );
455
+ }
456
+ return url;
457
+ }
458
+
459
+ // src/credentials.ts
460
+ import { createHash, randomUUID } from "node:crypto";
461
+ import { constants } from "node:fs";
462
+ import { lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
463
+ import { homedir } from "node:os";
464
+ import nodePath from "node:path";
465
+ function credentialPath(apiOrigin) {
466
+ const config = process.env.WORLDLABS_CONFIG_DIR ?? nodePath.join(homedir(), ".config", "worldlabs");
467
+ const name = createHash("sha256").update(apiOrigin).digest("hex");
468
+ return nodePath.join(config, "credentials", `${name}.key`);
469
+ }
470
+ async function readApiKey(apiOrigin) {
471
+ let file;
472
+ try {
473
+ file = await open(
474
+ credentialPath(apiOrigin),
475
+ process.platform === "win32" ? constants.O_RDONLY : constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
476
+ );
477
+ } catch (error) {
478
+ if (error.code === "ENOENT") return void 0;
479
+ throw new CliError("Cannot open saved credentials. Check the file location and permissions.");
480
+ }
481
+ try {
482
+ const stat = await file.stat();
483
+ if (!stat.isFile()) {
484
+ throw new CliError("Saved credentials must be a regular file.");
485
+ }
486
+ const contents = await file.readFile("utf8");
487
+ return contents.trim() || void 0;
488
+ } finally {
489
+ await file.close();
490
+ }
491
+ }
492
+ async function saveApiKey(apiOrigin, apiKey) {
493
+ const path = credentialPath(apiOrigin);
494
+ const directory = nodePath.dirname(path);
495
+ await mkdir(directory, { recursive: true, mode: 448 });
496
+ const stat = await lstat(directory);
497
+ if (!stat.isDirectory()) {
498
+ throw new CliError("The credentials path must be a directory and must not be a symlink.");
499
+ }
500
+ const temporary = nodePath.join(directory, `.${randomUUID()}.tmp`);
501
+ try {
502
+ await writeFile(temporary, `${apiKey}
503
+ `, { mode: 384, flag: "wx" });
504
+ await rename(temporary, path);
505
+ } finally {
506
+ await rm(temporary, { force: true });
507
+ }
508
+ }
509
+ async function removeApiKey(apiOrigin) {
510
+ await rm(credentialPath(apiOrigin), { force: true });
511
+ }
512
+
513
+ // src/terminal.ts
514
+ import { spawn } from "node:child_process";
515
+ import { createInterface } from "node:readline/promises";
516
+ import { Writable } from "node:stream";
517
+ async function prompt(message, hidden = false) {
518
+ if (!process.stdin.isTTY || !process.stderr.isTTY) {
519
+ throw new CliError("Run this command in your terminal. For automation, set WLT_API_KEY.");
520
+ }
521
+ const muted = new Writable({
522
+ write(_chunk, _encoding, callback) {
523
+ callback();
524
+ }
525
+ });
526
+ const reader = createInterface({
527
+ input: process.stdin,
528
+ output: hidden ? muted : process.stderr,
529
+ terminal: true
530
+ });
531
+ const controller = new AbortController();
532
+ reader.once("SIGINT", () => controller.abort());
533
+ process.stderr.write(message);
534
+ try {
535
+ const answer = await reader.question("", { signal: controller.signal });
536
+ return answer.trim();
537
+ } catch {
538
+ throw new CliError("Cancelled.");
539
+ } finally {
540
+ reader.close();
541
+ if (hidden) process.stderr.write("\n");
542
+ }
543
+ }
544
+ async function openBrowser(url) {
545
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer.exe" : "xdg-open";
546
+ await new Promise((resolve) => {
547
+ const child = spawn(command, [url], { detached: true, stdio: "ignore" });
548
+ child.once("error", () => resolve());
549
+ child.once("spawn", () => {
550
+ child.unref();
551
+ resolve();
552
+ });
553
+ });
554
+ }
555
+
556
+ // src/auth.ts
557
+ async function authenticatedClient() {
558
+ const { apiOrigin } = configuration();
559
+ let apiKey = process.env.WLT_API_KEY?.trim();
560
+ if (!apiKey) {
561
+ apiKey = await readApiKey(apiOrigin);
562
+ }
563
+ if (!apiKey) throw new CliError("Run worldlabs auth login or set WLT_API_KEY.");
564
+ return createClient({ apiKey, baseUrl: apiOrigin });
565
+ }
566
+ async function authStatus() {
567
+ const client = await authenticatedClient();
568
+ await client.assets.list({ pageSize: 1, signal: AbortSignal.timeout(3e4) });
569
+ return {
570
+ authenticated: true,
571
+ apiOrigin: configuration().apiOrigin,
572
+ source: process.env.WLT_API_KEY?.trim() ? "environment" : "file",
573
+ ...process.env.WLT_API_KEY?.trim() ? {} : { credentialFile: credentialPath(configuration().apiOrigin) }
574
+ };
575
+ }
576
+ async function login(noBrowser) {
577
+ if (process.env.WLT_API_KEY?.trim()) return await authStatus();
578
+ const { apiOrigin, apiKeysUrl } = configuration();
579
+ if (!process.stdin.isTTY || !process.stderr.isTTY) {
580
+ throw new CliError(
581
+ "Run worldlabs auth login in your own terminal to paste a key privately. Agents should never ask for keys in chat."
582
+ );
583
+ }
584
+ process.stderr.write(
585
+ `API: ${apiOrigin}
586
+ Create a key for your project at ${apiKeysUrl}
587
+ Select task submission, operation reads, and asset upload/read permissions. Usage is billed to that API project.
588
+ The key will be saved in plaintext at ${credentialPath(apiOrigin)}.
589
+ `
590
+ );
591
+ if (!noBrowser) await openBrowser(apiKeysUrl);
592
+ const apiKey = await prompt("Paste API key (hidden): ", true);
593
+ if (!apiKey) throw new CliError("No key entered.");
594
+ await createClient({ apiKey, baseUrl: apiOrigin }).assets.list({
595
+ pageSize: 1,
596
+ signal: AbortSignal.timeout(3e4)
597
+ });
598
+ await saveApiKey(apiOrigin, apiKey);
599
+ return {
600
+ authenticated: true,
601
+ apiOrigin,
602
+ source: "file",
603
+ credentialFile: credentialPath(apiOrigin)
604
+ };
605
+ }
606
+ async function logout() {
607
+ const { apiOrigin } = configuration();
608
+ await removeApiKey(apiOrigin);
609
+ return {
610
+ apiOrigin,
611
+ message: "Saved key removed from this computer. Revoke it on the API keys page to disable it everywhere.",
612
+ environmentKeyActive: Boolean(process.env.WLT_API_KEY?.trim())
613
+ };
614
+ }
615
+
616
+ // src/commands.ts
617
+ import { randomUUID as randomUUID2 } from "node:crypto";
618
+ import { openAsBlob } from "node:fs";
619
+ import { open as open2, readFile, rm as rm2 } from "node:fs/promises";
620
+ import nodePath2 from "node:path";
621
+ import { text } from "node:stream/consumers";
622
+ import { pipeline } from "node:stream/promises";
623
+ import { parseArgs } from "node:util";
624
+ var mimeTypes = {
625
+ ".jpg": "image/jpeg",
626
+ ".jpeg": "image/jpeg",
627
+ ".png": "image/png",
628
+ ".webp": "image/webp",
629
+ ".mp4": "video/mp4",
630
+ ".ply": "application/octet-stream",
631
+ ".spz": "application/octet-stream"
632
+ };
633
+ function timeout(value) {
634
+ const seconds = value === void 0 ? 600 : Number(value);
635
+ if (!Number.isFinite(seconds) || seconds <= 0 || seconds > 86400) {
636
+ throw new CliError("--timeout must be between 0 and 86400 seconds (exclusive of 0).");
637
+ }
638
+ return AbortSignal.timeout(Math.ceil(seconds * 1e3));
639
+ }
640
+ async function runApiCommand(args2) {
641
+ const [command, action, ...rest] = args2;
642
+ if (command === "tasks" && action === "list" && !rest.length) {
643
+ return Object.keys(createClient({ apiKey: "unused" }).tasks);
644
+ }
645
+ if (command === "tasks" && action === "run") {
646
+ const { values, positionals } = parseArgs({
647
+ args: rest,
648
+ allowPositionals: true,
649
+ options: {
650
+ request: { type: "string" },
651
+ "idempotency-key": { type: "string" },
652
+ wait: { type: "boolean" },
653
+ timeout: { type: "string" }
654
+ }
655
+ });
656
+ const [name] = positionals;
657
+ if (!name || positionals.length !== 1 || !values.request) {
658
+ throw new CliError(
659
+ "Usage: tasks run <name> --request <file|-> [--wait] [--idempotency-key <key>] [--timeout <seconds>]"
660
+ );
661
+ }
662
+ const signal = timeout(values.timeout);
663
+ const client = await authenticatedClient();
664
+ if (!Object.hasOwn(client.tasks, name)) {
665
+ throw new CliError("Unknown task. Run worldlabs tasks list.");
666
+ }
667
+ const body = JSON.parse(
668
+ values.request === "-" ? await text(process.stdin) : await readFile(values.request, "utf8")
669
+ );
670
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
671
+ throw new CliError("Task request must be a JSON object.");
672
+ }
673
+ const idempotencyKey = values["idempotency-key"] ?? randomUUID2();
674
+ if (!idempotencyKey.trim() || /[\r\n]/u.test(idempotencyKey)) {
675
+ throw new CliError("Invalid idempotency key.");
676
+ }
677
+ process.stderr.write(
678
+ `Idempotency key: ${idempotencyKey}
679
+ Reuse this key and request if submission is interrupted.
680
+ `
681
+ );
682
+ const submit = client.tasks[name];
683
+ const operation = await submit(body, { idempotencyKey, signal });
684
+ if (!values.wait) return operation;
685
+ process.stderr.write(`Operation: ${operation.id}
686
+ `);
687
+ return await client.operations.wait(operation, { signal });
688
+ }
689
+ if (command === "operations" && (action === "get" || action === "wait")) {
690
+ const { values, positionals } = parseArgs({
691
+ args: rest,
692
+ allowPositionals: true,
693
+ options: { timeout: { type: "string" } }
694
+ });
695
+ const [id] = positionals;
696
+ if (!id || positionals.length !== 1) {
697
+ throw new CliError("Usage: operations get|wait <id> [--timeout <seconds>]");
698
+ }
699
+ const signal = timeout(values.timeout);
700
+ const client = await authenticatedClient();
701
+ const operation = await client.operations.get(id, { signal });
702
+ return action === "wait" ? await client.operations.wait(operation, { signal }) : operation;
703
+ }
704
+ if (command === "assets" && action === "upload") {
705
+ const { values, positionals } = parseArgs({
706
+ args: rest,
707
+ allowPositionals: true,
708
+ options: { mime: { type: "string" } }
709
+ });
710
+ const [file] = positionals;
711
+ if (!file || positionals.length !== 1) {
712
+ throw new CliError("Usage: assets upload <file> [--mime <type>]");
713
+ }
714
+ const type = values.mime ?? mimeTypes[nodePath2.extname(file).toLowerCase()];
715
+ if (!type) throw new CliError("Unknown file type. Pass --mime <type>.");
716
+ const blob = await openAsBlob(file, { type });
717
+ const client = await authenticatedClient();
718
+ return await client.assets.upload(blob, {
719
+ displayName: nodePath2.basename(file),
720
+ signal: timeout()
721
+ });
722
+ }
723
+ if (command === "assets" && action === "download") {
724
+ const { values, positionals } = parseArgs({
725
+ args: rest,
726
+ allowPositionals: true,
727
+ options: { out: { type: "string" } }
728
+ });
729
+ const [id] = positionals;
730
+ if (!id || positionals.length !== 1 || !values.out) {
731
+ throw new CliError("Usage: assets download <id> --out <file>");
732
+ }
733
+ const client = await authenticatedClient();
734
+ const signal = timeout();
735
+ const { readUrl } = await client.assets.createReadUrl(id, { signal });
736
+ const response = await fetch(readUrl, { signal });
737
+ if (!response.ok || !response.body) {
738
+ throw new CliError(`Asset download failed (HTTP ${response.status}).`);
739
+ }
740
+ const file = await open2(values.out, "wx", 384);
741
+ try {
742
+ await pipeline(response.body, file.createWriteStream());
743
+ } catch (error) {
744
+ await rm2(values.out, { force: true });
745
+ throw error;
746
+ } finally {
747
+ await file.close();
748
+ }
749
+ return { assetId: id, path: values.out };
750
+ }
751
+ if (command === "assets" && action === "list") {
752
+ const { values } = parseArgs({ args: rest, options: { "page-token": { type: "string" } } });
753
+ const client = await authenticatedClient();
754
+ return await client.assets.list({
755
+ ...values["page-token"] ? { pageToken: values["page-token"] } : {},
756
+ signal: timeout()
757
+ });
758
+ }
759
+ throw new CliError("Unknown command or arguments. Run worldlabs --help.");
760
+ }
761
+
762
+ // src/skills.ts
763
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
764
+ import { cp, lstat as lstat2, mkdir as mkdir2, readFile as readFile2, readdir, rename as rename2, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
765
+ import { homedir as homedir2 } from "node:os";
766
+ import nodePath3 from "node:path";
767
+ import { fileURLToPath } from "node:url";
768
+ var marker = ".worldlabs-install.json";
769
+ var source = fileURLToPath(new URL("../skills/worldlabs/", import.meta.url));
770
+ function skillTarget(client) {
771
+ if (client === "codex") {
772
+ return nodePath3.join(
773
+ process.env.CODEX_HOME ?? nodePath3.join(homedir2(), ".codex"),
774
+ "skills",
775
+ "worldlabs"
776
+ );
777
+ }
778
+ if (client === "claude-code") return nodePath3.join(homedir2(), ".claude", "skills", "worldlabs");
779
+ throw new CliError("Choose --client codex or --client claude-code.");
780
+ }
781
+ async function fingerprint(root) {
782
+ const hash = createHash2("sha256");
783
+ async function visit(relative) {
784
+ if (relative === marker) return;
785
+ const path = nodePath3.join(root, relative);
786
+ const stat = await lstat2(path);
787
+ hash.update(`${relative}\0`);
788
+ if (stat.isDirectory()) {
789
+ const names = await readdir(path);
790
+ for (const name of names.toSorted()) await visit(nodePath3.join(relative, name));
791
+ } else if (stat.isFile()) {
792
+ hash.update(await readFile2(path));
793
+ } else {
794
+ throw new CliError(`Refusing a skill containing symlinks or special files: ${path}`);
795
+ }
796
+ }
797
+ await visit("");
798
+ return hash.digest("hex");
799
+ }
800
+ async function manageSkills(action, target) {
801
+ const parent = nodePath3.dirname(target);
802
+ const lock = `${target}.lock`;
803
+ await mkdir2(parent, { recursive: true });
804
+ try {
805
+ await mkdir2(lock);
806
+ } catch {
807
+ throw new CliError(
808
+ `Skill installation is locked at ${lock}. Remove the lock only if no installer is running.`
809
+ );
810
+ }
811
+ const staging = nodePath3.join(parent, `.worldlabs-${randomUUID3()}`);
812
+ const backup = `${staging}-backup`;
813
+ try {
814
+ let exists = false;
815
+ try {
816
+ await lstat2(target);
817
+ exists = true;
818
+ } catch (error) {
819
+ if (error.code !== "ENOENT") throw error;
820
+ }
821
+ if (exists) {
822
+ const actual = await fingerprint(target);
823
+ let expected;
824
+ try {
825
+ expected = JSON.parse(await readFile2(nodePath3.join(target, marker), "utf8"));
826
+ } catch {
827
+ throw new CliError(`Refusing to replace an unowned skill: ${target}`);
828
+ }
829
+ if (actual !== expected) {
830
+ throw new CliError(`Skill has local changes. Move it aside before continuing: ${target}`);
831
+ }
832
+ }
833
+ if (action === "uninstall") {
834
+ if (exists) await rm3(target, { recursive: true });
835
+ return { path: target, removed: exists };
836
+ }
837
+ await cp(source, staging, { recursive: true });
838
+ const entry = fileURLToPath(
839
+ new URL(import.meta.url.endsWith(".ts") ? "index.ts" : "index.js", import.meta.url)
840
+ );
841
+ const windows = process.platform === "win32";
842
+ const shell = windows ? "powershell" : "sh";
843
+ const quote = (value) => `'${value.replaceAll("'", windows ? "''" : String.raw`'\''`)}'`;
844
+ const command = `${windows ? "& " : ""}${quote(process.execPath)} ${quote(entry)}`;
845
+ for (const name of await readdir(staging, { recursive: true })) {
846
+ const path = nodePath3.join(staging, name);
847
+ const stat = await lstat2(path);
848
+ if (stat.isFile()) {
849
+ const content = await readFile2(path, "utf8");
850
+ await writeFile2(
851
+ path,
852
+ content.replaceAll("{{CLI}}", () => command).replaceAll("{{SHELL}}", shell)
853
+ );
854
+ }
855
+ }
856
+ await writeFile2(nodePath3.join(staging, marker), JSON.stringify(await fingerprint(staging)));
857
+ if (exists) await rename2(target, backup);
858
+ try {
859
+ await rename2(staging, target);
860
+ } catch (error) {
861
+ if (exists) await rename2(backup, target);
862
+ throw error;
863
+ }
864
+ await rm3(backup, { recursive: true, force: true });
865
+ return { path: target, next: "Start a new agent session to load the worldlabs skill." };
866
+ } finally {
867
+ await rm3(staging, { recursive: true, force: true });
868
+ await rm3(lock, { recursive: true, force: true });
869
+ }
870
+ }
871
+
872
+ // src/setup.ts
873
+ async function setup(client, noBrowser) {
874
+ let target;
875
+ if (client !== void 0) {
876
+ target = skillTarget(client);
877
+ } else if (process.stdin.isTTY && process.stderr.isTTY) {
878
+ const choice = await prompt("Install agent skill: 1) Codex 2) Claude Code 3) Skip [3]: ");
879
+ if (choice === "1" || choice === "2") {
880
+ target = skillTarget(choice === "1" ? "codex" : "claude-code");
881
+ } else if (choice && choice !== "3") {
882
+ throw new CliError("Choose 1, 2, or 3.");
883
+ }
884
+ }
885
+ const auth = await login(noBrowser);
886
+ const skill = target ? await manageSkills("install", target) : void 0;
887
+ return {
888
+ ...auth,
889
+ ...skill ? { skill } : {},
890
+ next: "Run worldlabs tasks list to see the available tasks."
891
+ };
892
+ }
893
+
894
+ // src/index.ts
895
+ var { version } = JSON.parse(
896
+ readFileSync(new URL("../package.json", import.meta.url), "utf8")
897
+ );
898
+ var help = `worldlabs - World Labs Developer API CLI
899
+
900
+ Usage: worldlabs [--json] <command>
901
+ setup [--client codex|claude-code] [--no-browser]
902
+ skills install|uninstall --client codex|claude-code
903
+ auth login [--no-browser]
904
+ auth status
905
+ auth logout
906
+ config show
907
+ tasks list
908
+ tasks run <name> --request <file|-> [--wait] [--idempotency-key <key>] [--timeout <seconds>]
909
+ assets upload <file> [--mime <type>]
910
+ assets download <id> --out <file>
911
+ assets list [--page-token <token>]
912
+ operations get|wait <id> [--timeout <seconds>]
913
+ --version
914
+ --help
915
+
916
+ Use --request - to read task JSON from standard input.
917
+
918
+ Saved login uses a plaintext file in your user configuration directory. Automation can set WLT_API_KEY.
919
+ `;
920
+ async function main(args2) {
921
+ if (args2.length === 0 || args2.includes("--help")) return help;
922
+ if (args2.length === 1 && args2[0] === "--version") return version;
923
+ const [command, action, ...rest] = args2;
924
+ if (command === "setup") {
925
+ const { values } = parseArgs2({
926
+ args: args2.slice(1),
927
+ options: { client: { type: "string" }, "no-browser": { type: "boolean" } }
928
+ });
929
+ return await setup(values.client, Boolean(values["no-browser"]));
930
+ }
931
+ if (command === "skills" && (action === "install" || action === "uninstall")) {
932
+ const { values } = parseArgs2({ args: rest, options: { client: { type: "string" } } });
933
+ return await manageSkills(action, skillTarget(values.client));
934
+ }
935
+ if (command === "config" && action === "show" && !rest.length) return configuration();
936
+ if (command === "auth") {
937
+ if (action === "login") {
938
+ const { values } = parseArgs2({ args: rest, options: { "no-browser": { type: "boolean" } } });
939
+ return await login(Boolean(values["no-browser"]));
940
+ }
941
+ if (action === "status" && !rest.length) return await authStatus();
942
+ if (action === "logout" && !rest.length) return await logout();
943
+ }
944
+ if (["tasks", "assets", "operations"].includes(command ?? "")) return await runApiCommand(args2);
945
+ throw new CliError("Unknown command or arguments. Run worldlabs --help.");
946
+ }
947
+ var args = process.argv.slice(2);
948
+ var json = args.includes("--json");
949
+ try {
950
+ const result = await main(args.filter((arg) => arg !== "--json"));
951
+ if (result && typeof result === "object" && "done" in result && result.done && "error" in result && result.error) {
952
+ process.exitCode = 1;
953
+ }
954
+ process.stdout.write(
955
+ `${typeof result === "string" && !json ? result : JSON.stringify(result, null, json ? void 0 : 2)}
956
+ `
957
+ );
958
+ } catch (error) {
959
+ const message = error instanceof ApiError ? `API request failed (HTTP ${error.response.status}). Check the API key, its permissions, and project access.` : error instanceof Error ? error.message : "Command failed.";
960
+ process.stderr.write(`${json ? JSON.stringify({ error: message }) : message}
961
+ `);
962
+ process.exitCode = 1;
963
+ }
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@worldlabsai/cli",
3
+ "version": "0.1.0",
4
+ "description": "World Labs command line interface",
5
+ "license": "Apache-2.0",
6
+ "bin": {
7
+ "worldlabs": "./dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist/index.js",
11
+ "skills",
12
+ "LICENSE"
13
+ ],
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=24"
17
+ },
18
+ "publishConfig": {
19
+ "access": "restricted",
20
+ "registry": "https://registry.npmjs.org/",
21
+ "tag": "next"
22
+ }
23
+ }
@@ -0,0 +1,43 @@
1
+ ---
2
+ name: worldlabs
3
+ description: Generate and edit scene images, estimate cameras and depth, or extract meshes with the World Labs CLI.
4
+ ---
5
+
6
+ # World Labs
7
+
8
+ Use `{{CLI}}` for the Developer API. Run commands in `{{SHELL}}`. Run `{{CLI}} --help` for command syntax.
9
+
10
+ ## Choose a task
11
+
12
+ | Task | Purpose |
13
+ | --- | --- |
14
+ | `atlasTextToImage` | Generate starting images from a description of an environment. |
15
+ | `images2PosedRGBD` | Estimate cameras and depth from images of a scene. |
16
+ | `atlasGenerate` | Generate new viewpoints using posed RGBD context. |
17
+ | `atlasChisel` | Generate posed images from a prompt and optional depth layouts. |
18
+ | `atlasMasked` | Fill masked regions across posed images. |
19
+ | `splats2Mesh` | Extract a mesh from a Gaussian splat scene. |
20
+
21
+ Read [How To Use Atlas](https://marble5.worldlabs.ai/docs/how-to-use-atlas) before choosing model inputs, calculating cameras, or chaining tasks. It explains scene data, model behavior, and the requirements that affect results. Follow its task or camera links when you need exact fields or geometry calculations. `{{CLI}} tasks list` reports SDK task names; account access can differ.
22
+
23
+ ## Submit and inspect
24
+
25
+ Upload a local image:
26
+
27
+ ```{{SHELL}}
28
+ {{CLI}} assets upload photo.jpg --json > asset.json
29
+ ```
30
+
31
+ Write `request.json` as `{"frames":[{"imageAsset":{"assetId":"<id>"}}]}`, replacing `<id>` with the uploaded asset's `id` from `asset.json`.
32
+
33
+ ```{{SHELL}}
34
+ {{CLI}} tasks run images2PosedRGBD --request request.json --wait --json > result.json
35
+ ```
36
+
37
+ Use `--request -` to read JSON from stdin. Results go to stdout; diagnostics and the submission's idempotency key go to stderr. Preserve the key and reuse it with `--idempotency-key <key>` and the same request if submission is interrupted.
38
+
39
+ A timeout stops local waiting, not server work. Resume with `{{CLI}} operations wait <operation-id> --json`. Check a completed operation's `error` before reading `response`. Download returned assets with `{{CLI}} assets download <asset-id> --out result.png`. Inspect the outputs before using them in another task; keep each image, camera, depth, and confidence together.
40
+
41
+ ## Authentication
42
+
43
+ Check `{{CLI}} auth status`. If login is needed, have the user run `{{CLI}} auth login` in their own terminal and enter the key privately. Never request keys in chat or put them in command arguments. Automation can supply `WLT_API_KEY`. The key selects the API project and billing; a successful status check verifies asset access, not every task permission.